%global _empty_manifest_terminate_build 0
Name: python-django-components
Version: 0.27.2
Release: 1
Summary: A way to create simple reusable template components in Django.
License: MIT
URL: https://github.com/EmilStenstrom/django-components/
Source0: https://mirrors.nju.edu.cn/pypi/web/packages/92/ae/071f0e48846dded3ee83f7fa1bd966fadda927dc940addde70d9a29a1f8a/django_components-0.27.2.tar.gz
BuildArch: noarch
Requires: python3-Django
%description
# django-components
A way to create simple reusable template components in Django.
It lets you create "template components", that contains both the template, the Javascript and the CSS needed to generate the front end code you need for a modern app. Components look like this:
```htmldjango
{% component "calendar" date="2015-06-19" %}
```
And this is what gets rendered (plus the CSS and Javascript you've specified):
```html
Today's date is 2015-06-19
```
Read on to learn about the details!
# Release notes
*Version 0.27* includes an additional installable app *django_components.safer_staticfiles*. It provides the same behavior as *django.contrib.staticfiles* but with extra security guarantees (more info below in Security Notes).
*Version 0.26* changes the syntax for `{% slot %}` tags. From now on, we separate defining a slot (`{% slot %}`) from filling a slot with content (`{% fill %}`). This means you will likely need to change a lot of slot tags to fill. We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice feature to have access to. Hoping that this will feel worth it!
*Version 0.22* starts autoimporting all files inside components subdirectores, to simplify setup. An existing project might start to get AlreadyRegistered-errors because of this. To solve this, either remove your custom loading of components, or set "autodiscover": False in settings.COMPONENTS.
*Version 0.17* renames `Component.context` and `Component.template` to `get_context_data` and `get_template_name`. The old methods still work, but emit a deprecation warning. This change was done to sync naming with Django's class based views, and make using django-components more familiar to Django users. `Component.context` and `Component.template` will be removed when version 1.0 is released.
# Security notes 🚨
*You are advised to read this section before using django-components in production.*
## Static files
Components can be organized however you prefer.
That said, our prefered way is to keep the files of a component close together by bundling them in the same directory.
This means that files containing backend logic, such as Python modules and HTML templates, live in the same directory as static files, e.g. JS and CSS.
If your are using _django.contrib.staticfiles_ to collect static files, no distinction is made between the different kinds of files.
As a result, your Python code and templates may inadvertently become available on your static file server.
You probably don't want this, as parts of your backend logic will be exposed, posing a __potential security vulnerability__.
As of *v0.27*, django-components ships with an additional installable app *django_components.__safer_staticfiles__*.
It is a drop-in replacement for *django.contrib.staticfiles*.
Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server.
To use it, add it to INSTALLED_APPS and remove _django.contrib.staticfiles_.
```python
INSTALLED_APPS = [
# django.contrib.staticfiles # <-- REMOVE
"django_components",
"django_components.safer_staticfiles" # <-- ADD
]
```
If you are on an older version of django-components, your alternatives are a) passing `--ignore ` options to the _collecstatic_ CLI command, or b) defining a subclass of StaticFilesConfig.
Both routes are described in the official [docs of the _staticfiles_ app](https://docs.djangoproject.com/en/4.2/ref/contrib/staticfiles/#customizing-the-ignored-pattern-list).
# Installation
Install the app into your environment:
> ```pip install django_components```
Then add the app into INSTALLED_APPS in settings.py
```python
INSTALLED_APPS = [
...,
"django_components",
]
```
Modify `TEMPLATES` section of settings.py as follows:
- *Remove `'APP_DIRS': True,`*
- add `loaders` to `OPTIONS` list and set it to following value:
```python
TEMPLATES = [
{
...,
'OPTIONS': {
'context_processors': [
...
],
'loaders':[(
'django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
'django_components.template_loader.Loader',
]
)],
},
},
]
```
Modify STATICFILES_DIRS (or add it if you don't have it) so django can find your static JS and CSS files:
```python
STATICFILES_DIRS = [
...,
BASE_DIR / "components",
]
```
## Optional
To avoid loading the app in each template using ``` {% load django_components %} ```, you can add the tag as a 'builtin' in settings.py
```python
TEMPLATES = [
{
...,
'OPTIONS': {
'context_processors': [
...
],
'builtins': [
'django_components.templatetags.component_tags',
]
},
},
]
```
Read on to find out how to build your first component!
# Compatiblity
Django-components supports all officially supported versions of Django and Python.
| Python version | Django version |
|----------------|--------------------------|
| 3.6 | 3.2 |
| 3.7 | 3.2 |
| 3.8 | 3.2, 4.0 |
| 3.9 | 3.2, 4.0 |
| 3.10 | 4.0 |
# Create your first component
A component in django-components is the combination of four things: CSS, Javascript, a Django template, and some Python code to put them all together.

Start by creating empty files in the structure above.
First you need a CSS file. Be sure to prefix all rules with a unique class so they don't clash with other rules.
```css
/* In a file called [project root]/components/calendar/style.css */
.calendar-component { width: 200px; background: pink; }
.calendar-component span { font-weight: bold; }
```
Then you need a javascript file that specifies how you interact with this component. You are free to use any javascript framework you want. A good way to make sure this component doesn't clash with other components is to define all code inside an anonymous function that calls itself. This makes all variables defined only be defined inside this component and not affect other components.
```js
/* In a file called [project root]/components/calendar/script.js */
(function(){
if (document.querySelector(".calendar-component")) {
document.querySelector(".calendar-component").onclick = function(){ alert("Clicked calendar!"); };
}
})()
```
Now you need a Django template for your component. Feel free to define more variables like `date` in this example. When creating an instance of this component we will send in the values for these variables. The template will be rendered with whatever template backend you've specified in your Django settings file.
```htmldjango
{# In a file called [project root]/components/calendar/calendar.html #}
Today's date is {{ date }}
```
Finally, we use django-components to tie this together. Start by creating a file called `calendar.py` in your component calendar directory. It will be auto-detected and loaded by the app.
Inside this file we create a Component by inheriting from the Component class and specifying the context method. We also register the global component registry so that we easily can render it anywhere in our templates.
```python
# In a file called [project root]/components/calendar/calendar.py
from django_components import component
@component.register("calendar")
class Calendar(component.Component):
# Templates inside `[your apps]/components` dir and `[project root]/components` dir will be automatically found. To customize which template to use based on context
# you can override def get_template_name() instead of specifying the below variable.
template_name = "calendar/calendar.html"
# This component takes one parameter, a date string to show in the template
def get_context_data(self, date):
return {
"date": date,
}
class Media:
css = "calendar/calendar.css"
js = "calendar/calendar.js"
```
And voilá!! We've created our first component.
# Use the component in a template
First load the `component_tags` tag library, then use the `component_[js/css]_dependencies` and `component` tags to render the component to the page.
```htmldjango
{% load component_tags %}
My example calendar
{% component_css_dependencies %}
{% component "calendar" date="2015-06-19" %}
{% component_js_dependencies %}
```
The output from the above template will be:
```html
My example calendar
Today's date is 2015-06-19
```
This makes it possible to organize your front-end around reusable components. Instead of relying on template tags and keeping your CSS and Javascript in the static directory.
# Using slots in templates
_New in version 0.26_:
- The `slot` tag now serves only to declare new slots inside the component template.
- To override the content of a declared slot, use the newly introduced `fill` tag instead.
- Whereas unfilled slots used to raise a warning, filling a slot is now optional by default.
- To indicate that a slot must be filled, the new keyword `required` should be added at the end of the `slot` tag.
Components support something called 'slots'.
When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content.
This mechanism makes components more reusable and composable.
In the example below we introduce two block tags that work hand in hand to make this work. These are...
- `{% slot %}`/`{% endslot %}`: Declares a new slot in the component template.
- `{% fill %}`/`{% endfill %}`: (Used inside a component block.) Fills a declared slot with the specified content.
Let's update our calendar component to support more customization by updating our calendar.html template.
```htmldjango
{% slot "header" %}Calendar header{% endslot %}
{% slot "body" %}Today's date is {{ date }}{% endslot %}
```
When using the component, you specify which slots you want to fill and where you want to use the defaults from the template. It looks like this:
```htmldjango
{% component_block "calendar" date="2020-06-06" %}
{% fill "body" %}Can you believe it's already {{ date }}??{% endfill %}
{% endcomponent_block %}
```
Since the header block is unspecified, it's taken from the base template. If you put this in a template, and send in date=2020-06-06, this is what's rendered:
```htmldjango
Calendar header
Can you believe it's already 2020-06-06??
```
As you can see, component slots lets you write reusable containers, that you fill out when you use a component. This makes for highly reusable components, that can be used in different circumstances.
Certain properties of a slot can be accessed from within a 'fill' context. They are provided as attributes on a user-defined alias of the targeted slot. For instance, let's say you're filling a slot called 'body'. To access properties of this slot, alias it using the 'as' keyword to a new name -- or keep the original name. With the new slot alias, you can call `.default` to insert the default content.
```htmldjango
{% component_block "calendar" date="2020-06-06" %}
{% fill "body" as "body" %}{{ body.default }}. Have a great day!{% endslot %}
{% endcomponent_block %}
```
Produces:
```htmldjango
Calendar header
Today's date is 2020-06-06. Have a great day!
```
## Advanced
### Conditional slots
_Added in version 0.26._
In certain circumstances, you may want the behavior of slot filling to depend on
whether or not a particular slot is filled.
For example, suppose we have the following component template:
```htmldjango
```
By default the slot named 'subtitle' is empty. Yet when the component is used without
explicit fills, the div containing the slot is still rendered, as shown below:
```html
Title
```
This may not be what you want. What if instead the outer 'subtitle' div should only
be included when the inner slot is in fact filled?
The answer is to use the `{% if_filled %}` tag. Together with `{% endif_filled %}`,
these define a block whose contents will be rendered only if the component slot with
the corresponding 'name' is filled.
This is what our example looks like with an 'if_filled' tag.
```htmldjango
```
Just as Django's builtin 'if' tag has 'elif' and 'else' counterparts, so does 'if_filled'
include additional tags for more complex branching. These tags are 'elif_filled' and
'else_filled'. Here's what our example looks like with them.
```htmldjango
```
Sometimes you're not interested in whether a slot is filled, but rather that it _isn't_.
To negate the meaning of 'if_filled' in this way, an optional boolean can be passed to
the 'if_filled' and 'elif_filled' tags.
In the example below we use `False` to indicate that the content should be rendered
only if the slot 'subtitle' is _not_ filled.
```htmldjango
{% if_filled subtitle False %}
{% slot "subtitle" %}{% endslot %}
{% endif_filled %}
```
# Component context and scope
By default, components can access context variables from the parent template, just like templates that are included with the `{% include %}` tag. Just like with `{% include %}`, if you don't want the component template to have access to the parent context, add `only` to the end of the `{% component %}` (or `{% component_block %}` tag):
```htmldjango
{% component "calendar" date="2015-06-19" only %}
```
NOTE: `{% csrf_token %}` tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the `only` modifier.
Components can also access the outer context in their context methods by accessing the property `outer_context`.
# Available settings
All library settings are handled from a global COMPONENTS variable that is read from settings.py. By default you don't need it set, there are resonable defaults.
## Configure the module where components are loaded from
Configure the location where components are loaded. To do this, add a COMPONENTS variable to you settings.py with a list of python paths to load. This allows you to build a structure of components that are independent from your apps.
```python
COMPONENTS = {
"libraries": [
"mysite.components.forms",
"mysite.components.buttons",
"mysite.components.cards",
],
}
```
## Disable autodiscovery
If you specify all the component locations with the setting above and have a lot of apps, you can (very) slightly speed things up by disabling autodiscovery.
```python
COMPONENTS = {
"autodiscover": False,
}
```
## Tune the template cache
Each time a template is rendered it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up. By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are using the `template` method of a component to render lots of dynamic templates, you can increase this number. To remove the cache limit altogether and cache everything, set template_cache_size to `None`.
```python
COMPONENTS = {
"template_cache_size": 256,
}
```
# Install locally and run the tests
Start by forking the project by clicking the **Fork button** up in the right corner in the GitHub . This makes a copy of the repository in your own name. Now you can clone this repository locally and start adding features:
```sh
git clone https://github.com//django-components.git
```
To quickly run the tests install the local dependencies by running:
```sh
pip install -r requirements-dev.txt
```
Now you can run the tests to make sure everything works as expected:
```sh
pytest
```
The library is also tested across many versions of Python and Django. To run tests that way:
```sh
pyenv install 3.6.9
pyenv install 3.7.9
pyenv install 3.8.9
pyenv install 3.9.4
pyenv install 3.10.5
pyenv local 3.6.9 3.7.9 3.8.9 3.9.4 3.10.5
tox -p
```
%package -n python3-django-components
Summary: A way to create simple reusable template components in Django.
Provides: python-django-components
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-django-components
# django-components
A way to create simple reusable template components in Django.
It lets you create "template components", that contains both the template, the Javascript and the CSS needed to generate the front end code you need for a modern app. Components look like this:
```htmldjango
{% component "calendar" date="2015-06-19" %}
```
And this is what gets rendered (plus the CSS and Javascript you've specified):
```html
Today's date is 2015-06-19
```
Read on to learn about the details!
# Release notes
*Version 0.27* includes an additional installable app *django_components.safer_staticfiles*. It provides the same behavior as *django.contrib.staticfiles* but with extra security guarantees (more info below in Security Notes).
*Version 0.26* changes the syntax for `{% slot %}` tags. From now on, we separate defining a slot (`{% slot %}`) from filling a slot with content (`{% fill %}`). This means you will likely need to change a lot of slot tags to fill. We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice feature to have access to. Hoping that this will feel worth it!
*Version 0.22* starts autoimporting all files inside components subdirectores, to simplify setup. An existing project might start to get AlreadyRegistered-errors because of this. To solve this, either remove your custom loading of components, or set "autodiscover": False in settings.COMPONENTS.
*Version 0.17* renames `Component.context` and `Component.template` to `get_context_data` and `get_template_name`. The old methods still work, but emit a deprecation warning. This change was done to sync naming with Django's class based views, and make using django-components more familiar to Django users. `Component.context` and `Component.template` will be removed when version 1.0 is released.
# Security notes 🚨
*You are advised to read this section before using django-components in production.*
## Static files
Components can be organized however you prefer.
That said, our prefered way is to keep the files of a component close together by bundling them in the same directory.
This means that files containing backend logic, such as Python modules and HTML templates, live in the same directory as static files, e.g. JS and CSS.
If your are using _django.contrib.staticfiles_ to collect static files, no distinction is made between the different kinds of files.
As a result, your Python code and templates may inadvertently become available on your static file server.
You probably don't want this, as parts of your backend logic will be exposed, posing a __potential security vulnerability__.
As of *v0.27*, django-components ships with an additional installable app *django_components.__safer_staticfiles__*.
It is a drop-in replacement for *django.contrib.staticfiles*.
Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server.
To use it, add it to INSTALLED_APPS and remove _django.contrib.staticfiles_.
```python
INSTALLED_APPS = [
# django.contrib.staticfiles # <-- REMOVE
"django_components",
"django_components.safer_staticfiles" # <-- ADD
]
```
If you are on an older version of django-components, your alternatives are a) passing `--ignore ` options to the _collecstatic_ CLI command, or b) defining a subclass of StaticFilesConfig.
Both routes are described in the official [docs of the _staticfiles_ app](https://docs.djangoproject.com/en/4.2/ref/contrib/staticfiles/#customizing-the-ignored-pattern-list).
# Installation
Install the app into your environment:
> ```pip install django_components```
Then add the app into INSTALLED_APPS in settings.py
```python
INSTALLED_APPS = [
...,
"django_components",
]
```
Modify `TEMPLATES` section of settings.py as follows:
- *Remove `'APP_DIRS': True,`*
- add `loaders` to `OPTIONS` list and set it to following value:
```python
TEMPLATES = [
{
...,
'OPTIONS': {
'context_processors': [
...
],
'loaders':[(
'django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
'django_components.template_loader.Loader',
]
)],
},
},
]
```
Modify STATICFILES_DIRS (or add it if you don't have it) so django can find your static JS and CSS files:
```python
STATICFILES_DIRS = [
...,
BASE_DIR / "components",
]
```
## Optional
To avoid loading the app in each template using ``` {% load django_components %} ```, you can add the tag as a 'builtin' in settings.py
```python
TEMPLATES = [
{
...,
'OPTIONS': {
'context_processors': [
...
],
'builtins': [
'django_components.templatetags.component_tags',
]
},
},
]
```
Read on to find out how to build your first component!
# Compatiblity
Django-components supports all officially supported versions of Django and Python.
| Python version | Django version |
|----------------|--------------------------|
| 3.6 | 3.2 |
| 3.7 | 3.2 |
| 3.8 | 3.2, 4.0 |
| 3.9 | 3.2, 4.0 |
| 3.10 | 4.0 |
# Create your first component
A component in django-components is the combination of four things: CSS, Javascript, a Django template, and some Python code to put them all together.

Start by creating empty files in the structure above.
First you need a CSS file. Be sure to prefix all rules with a unique class so they don't clash with other rules.
```css
/* In a file called [project root]/components/calendar/style.css */
.calendar-component { width: 200px; background: pink; }
.calendar-component span { font-weight: bold; }
```
Then you need a javascript file that specifies how you interact with this component. You are free to use any javascript framework you want. A good way to make sure this component doesn't clash with other components is to define all code inside an anonymous function that calls itself. This makes all variables defined only be defined inside this component and not affect other components.
```js
/* In a file called [project root]/components/calendar/script.js */
(function(){
if (document.querySelector(".calendar-component")) {
document.querySelector(".calendar-component").onclick = function(){ alert("Clicked calendar!"); };
}
})()
```
Now you need a Django template for your component. Feel free to define more variables like `date` in this example. When creating an instance of this component we will send in the values for these variables. The template will be rendered with whatever template backend you've specified in your Django settings file.
```htmldjango
{# In a file called [project root]/components/calendar/calendar.html #}
Today's date is {{ date }}
```
Finally, we use django-components to tie this together. Start by creating a file called `calendar.py` in your component calendar directory. It will be auto-detected and loaded by the app.
Inside this file we create a Component by inheriting from the Component class and specifying the context method. We also register the global component registry so that we easily can render it anywhere in our templates.
```python
# In a file called [project root]/components/calendar/calendar.py
from django_components import component
@component.register("calendar")
class Calendar(component.Component):
# Templates inside `[your apps]/components` dir and `[project root]/components` dir will be automatically found. To customize which template to use based on context
# you can override def get_template_name() instead of specifying the below variable.
template_name = "calendar/calendar.html"
# This component takes one parameter, a date string to show in the template
def get_context_data(self, date):
return {
"date": date,
}
class Media:
css = "calendar/calendar.css"
js = "calendar/calendar.js"
```
And voilá!! We've created our first component.
# Use the component in a template
First load the `component_tags` tag library, then use the `component_[js/css]_dependencies` and `component` tags to render the component to the page.
```htmldjango
{% load component_tags %}
My example calendar
{% component_css_dependencies %}
{% component "calendar" date="2015-06-19" %}
{% component_js_dependencies %}
```
The output from the above template will be:
```html
My example calendar
Today's date is 2015-06-19
```
This makes it possible to organize your front-end around reusable components. Instead of relying on template tags and keeping your CSS and Javascript in the static directory.
# Using slots in templates
_New in version 0.26_:
- The `slot` tag now serves only to declare new slots inside the component template.
- To override the content of a declared slot, use the newly introduced `fill` tag instead.
- Whereas unfilled slots used to raise a warning, filling a slot is now optional by default.
- To indicate that a slot must be filled, the new keyword `required` should be added at the end of the `slot` tag.
Components support something called 'slots'.
When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content.
This mechanism makes components more reusable and composable.
In the example below we introduce two block tags that work hand in hand to make this work. These are...
- `{% slot %}`/`{% endslot %}`: Declares a new slot in the component template.
- `{% fill %}`/`{% endfill %}`: (Used inside a component block.) Fills a declared slot with the specified content.
Let's update our calendar component to support more customization by updating our calendar.html template.
```htmldjango
{% slot "header" %}Calendar header{% endslot %}
{% slot "body" %}Today's date is {{ date }}{% endslot %}
```
When using the component, you specify which slots you want to fill and where you want to use the defaults from the template. It looks like this:
```htmldjango
{% component_block "calendar" date="2020-06-06" %}
{% fill "body" %}Can you believe it's already {{ date }}??{% endfill %}
{% endcomponent_block %}
```
Since the header block is unspecified, it's taken from the base template. If you put this in a template, and send in date=2020-06-06, this is what's rendered:
```htmldjango
Calendar header
Can you believe it's already 2020-06-06??
```
As you can see, component slots lets you write reusable containers, that you fill out when you use a component. This makes for highly reusable components, that can be used in different circumstances.
Certain properties of a slot can be accessed from within a 'fill' context. They are provided as attributes on a user-defined alias of the targeted slot. For instance, let's say you're filling a slot called 'body'. To access properties of this slot, alias it using the 'as' keyword to a new name -- or keep the original name. With the new slot alias, you can call `.default` to insert the default content.
```htmldjango
{% component_block "calendar" date="2020-06-06" %}
{% fill "body" as "body" %}{{ body.default }}. Have a great day!{% endslot %}
{% endcomponent_block %}
```
Produces:
```htmldjango
Calendar header
Today's date is 2020-06-06. Have a great day!
```
## Advanced
### Conditional slots
_Added in version 0.26._
In certain circumstances, you may want the behavior of slot filling to depend on
whether or not a particular slot is filled.
For example, suppose we have the following component template:
```htmldjango
```
By default the slot named 'subtitle' is empty. Yet when the component is used without
explicit fills, the div containing the slot is still rendered, as shown below:
```html
Title
```
This may not be what you want. What if instead the outer 'subtitle' div should only
be included when the inner slot is in fact filled?
The answer is to use the `{% if_filled %}` tag. Together with `{% endif_filled %}`,
these define a block whose contents will be rendered only if the component slot with
the corresponding 'name' is filled.
This is what our example looks like with an 'if_filled' tag.
```htmldjango
```
Just as Django's builtin 'if' tag has 'elif' and 'else' counterparts, so does 'if_filled'
include additional tags for more complex branching. These tags are 'elif_filled' and
'else_filled'. Here's what our example looks like with them.
```htmldjango
```
Sometimes you're not interested in whether a slot is filled, but rather that it _isn't_.
To negate the meaning of 'if_filled' in this way, an optional boolean can be passed to
the 'if_filled' and 'elif_filled' tags.
In the example below we use `False` to indicate that the content should be rendered
only if the slot 'subtitle' is _not_ filled.
```htmldjango
{% if_filled subtitle False %}
{% slot "subtitle" %}{% endslot %}
{% endif_filled %}
```
# Component context and scope
By default, components can access context variables from the parent template, just like templates that are included with the `{% include %}` tag. Just like with `{% include %}`, if you don't want the component template to have access to the parent context, add `only` to the end of the `{% component %}` (or `{% component_block %}` tag):
```htmldjango
{% component "calendar" date="2015-06-19" only %}
```
NOTE: `{% csrf_token %}` tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the `only` modifier.
Components can also access the outer context in their context methods by accessing the property `outer_context`.
# Available settings
All library settings are handled from a global COMPONENTS variable that is read from settings.py. By default you don't need it set, there are resonable defaults.
## Configure the module where components are loaded from
Configure the location where components are loaded. To do this, add a COMPONENTS variable to you settings.py with a list of python paths to load. This allows you to build a structure of components that are independent from your apps.
```python
COMPONENTS = {
"libraries": [
"mysite.components.forms",
"mysite.components.buttons",
"mysite.components.cards",
],
}
```
## Disable autodiscovery
If you specify all the component locations with the setting above and have a lot of apps, you can (very) slightly speed things up by disabling autodiscovery.
```python
COMPONENTS = {
"autodiscover": False,
}
```
## Tune the template cache
Each time a template is rendered it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up. By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are using the `template` method of a component to render lots of dynamic templates, you can increase this number. To remove the cache limit altogether and cache everything, set template_cache_size to `None`.
```python
COMPONENTS = {
"template_cache_size": 256,
}
```
# Install locally and run the tests
Start by forking the project by clicking the **Fork button** up in the right corner in the GitHub . This makes a copy of the repository in your own name. Now you can clone this repository locally and start adding features:
```sh
git clone https://github.com//django-components.git
```
To quickly run the tests install the local dependencies by running:
```sh
pip install -r requirements-dev.txt
```
Now you can run the tests to make sure everything works as expected:
```sh
pytest
```
The library is also tested across many versions of Python and Django. To run tests that way:
```sh
pyenv install 3.6.9
pyenv install 3.7.9
pyenv install 3.8.9
pyenv install 3.9.4
pyenv install 3.10.5
pyenv local 3.6.9 3.7.9 3.8.9 3.9.4 3.10.5
tox -p
```
%package help
Summary: Development documents and examples for django-components
Provides: python3-django-components-doc
%description help
# django-components
A way to create simple reusable template components in Django.
It lets you create "template components", that contains both the template, the Javascript and the CSS needed to generate the front end code you need for a modern app. Components look like this:
```htmldjango
{% component "calendar" date="2015-06-19" %}
```
And this is what gets rendered (plus the CSS and Javascript you've specified):
```html
Today's date is 2015-06-19
```
Read on to learn about the details!
# Release notes
*Version 0.27* includes an additional installable app *django_components.safer_staticfiles*. It provides the same behavior as *django.contrib.staticfiles* but with extra security guarantees (more info below in Security Notes).
*Version 0.26* changes the syntax for `{% slot %}` tags. From now on, we separate defining a slot (`{% slot %}`) from filling a slot with content (`{% fill %}`). This means you will likely need to change a lot of slot tags to fill. We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice feature to have access to. Hoping that this will feel worth it!
*Version 0.22* starts autoimporting all files inside components subdirectores, to simplify setup. An existing project might start to get AlreadyRegistered-errors because of this. To solve this, either remove your custom loading of components, or set "autodiscover": False in settings.COMPONENTS.
*Version 0.17* renames `Component.context` and `Component.template` to `get_context_data` and `get_template_name`. The old methods still work, but emit a deprecation warning. This change was done to sync naming with Django's class based views, and make using django-components more familiar to Django users. `Component.context` and `Component.template` will be removed when version 1.0 is released.
# Security notes 🚨
*You are advised to read this section before using django-components in production.*
## Static files
Components can be organized however you prefer.
That said, our prefered way is to keep the files of a component close together by bundling them in the same directory.
This means that files containing backend logic, such as Python modules and HTML templates, live in the same directory as static files, e.g. JS and CSS.
If your are using _django.contrib.staticfiles_ to collect static files, no distinction is made between the different kinds of files.
As a result, your Python code and templates may inadvertently become available on your static file server.
You probably don't want this, as parts of your backend logic will be exposed, posing a __potential security vulnerability__.
As of *v0.27*, django-components ships with an additional installable app *django_components.__safer_staticfiles__*.
It is a drop-in replacement for *django.contrib.staticfiles*.
Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server.
To use it, add it to INSTALLED_APPS and remove _django.contrib.staticfiles_.
```python
INSTALLED_APPS = [
# django.contrib.staticfiles # <-- REMOVE
"django_components",
"django_components.safer_staticfiles" # <-- ADD
]
```
If you are on an older version of django-components, your alternatives are a) passing `--ignore ` options to the _collecstatic_ CLI command, or b) defining a subclass of StaticFilesConfig.
Both routes are described in the official [docs of the _staticfiles_ app](https://docs.djangoproject.com/en/4.2/ref/contrib/staticfiles/#customizing-the-ignored-pattern-list).
# Installation
Install the app into your environment:
> ```pip install django_components```
Then add the app into INSTALLED_APPS in settings.py
```python
INSTALLED_APPS = [
...,
"django_components",
]
```
Modify `TEMPLATES` section of settings.py as follows:
- *Remove `'APP_DIRS': True,`*
- add `loaders` to `OPTIONS` list and set it to following value:
```python
TEMPLATES = [
{
...,
'OPTIONS': {
'context_processors': [
...
],
'loaders':[(
'django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
'django_components.template_loader.Loader',
]
)],
},
},
]
```
Modify STATICFILES_DIRS (or add it if you don't have it) so django can find your static JS and CSS files:
```python
STATICFILES_DIRS = [
...,
BASE_DIR / "components",
]
```
## Optional
To avoid loading the app in each template using ``` {% load django_components %} ```, you can add the tag as a 'builtin' in settings.py
```python
TEMPLATES = [
{
...,
'OPTIONS': {
'context_processors': [
...
],
'builtins': [
'django_components.templatetags.component_tags',
]
},
},
]
```
Read on to find out how to build your first component!
# Compatiblity
Django-components supports all officially supported versions of Django and Python.
| Python version | Django version |
|----------------|--------------------------|
| 3.6 | 3.2 |
| 3.7 | 3.2 |
| 3.8 | 3.2, 4.0 |
| 3.9 | 3.2, 4.0 |
| 3.10 | 4.0 |
# Create your first component
A component in django-components is the combination of four things: CSS, Javascript, a Django template, and some Python code to put them all together.

Start by creating empty files in the structure above.
First you need a CSS file. Be sure to prefix all rules with a unique class so they don't clash with other rules.
```css
/* In a file called [project root]/components/calendar/style.css */
.calendar-component { width: 200px; background: pink; }
.calendar-component span { font-weight: bold; }
```
Then you need a javascript file that specifies how you interact with this component. You are free to use any javascript framework you want. A good way to make sure this component doesn't clash with other components is to define all code inside an anonymous function that calls itself. This makes all variables defined only be defined inside this component and not affect other components.
```js
/* In a file called [project root]/components/calendar/script.js */
(function(){
if (document.querySelector(".calendar-component")) {
document.querySelector(".calendar-component").onclick = function(){ alert("Clicked calendar!"); };
}
})()
```
Now you need a Django template for your component. Feel free to define more variables like `date` in this example. When creating an instance of this component we will send in the values for these variables. The template will be rendered with whatever template backend you've specified in your Django settings file.
```htmldjango
{# In a file called [project root]/components/calendar/calendar.html #}
Today's date is {{ date }}
```
Finally, we use django-components to tie this together. Start by creating a file called `calendar.py` in your component calendar directory. It will be auto-detected and loaded by the app.
Inside this file we create a Component by inheriting from the Component class and specifying the context method. We also register the global component registry so that we easily can render it anywhere in our templates.
```python
# In a file called [project root]/components/calendar/calendar.py
from django_components import component
@component.register("calendar")
class Calendar(component.Component):
# Templates inside `[your apps]/components` dir and `[project root]/components` dir will be automatically found. To customize which template to use based on context
# you can override def get_template_name() instead of specifying the below variable.
template_name = "calendar/calendar.html"
# This component takes one parameter, a date string to show in the template
def get_context_data(self, date):
return {
"date": date,
}
class Media:
css = "calendar/calendar.css"
js = "calendar/calendar.js"
```
And voilá!! We've created our first component.
# Use the component in a template
First load the `component_tags` tag library, then use the `component_[js/css]_dependencies` and `component` tags to render the component to the page.
```htmldjango
{% load component_tags %}
My example calendar
{% component_css_dependencies %}
{% component "calendar" date="2015-06-19" %}
{% component_js_dependencies %}
```
The output from the above template will be:
```html
My example calendar
Today's date is 2015-06-19
```
This makes it possible to organize your front-end around reusable components. Instead of relying on template tags and keeping your CSS and Javascript in the static directory.
# Using slots in templates
_New in version 0.26_:
- The `slot` tag now serves only to declare new slots inside the component template.
- To override the content of a declared slot, use the newly introduced `fill` tag instead.
- Whereas unfilled slots used to raise a warning, filling a slot is now optional by default.
- To indicate that a slot must be filled, the new keyword `required` should be added at the end of the `slot` tag.
Components support something called 'slots'.
When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content.
This mechanism makes components more reusable and composable.
In the example below we introduce two block tags that work hand in hand to make this work. These are...
- `{% slot %}`/`{% endslot %}`: Declares a new slot in the component template.
- `{% fill %}`/`{% endfill %}`: (Used inside a component block.) Fills a declared slot with the specified content.
Let's update our calendar component to support more customization by updating our calendar.html template.
```htmldjango
{% slot "header" %}Calendar header{% endslot %}
{% slot "body" %}Today's date is {{ date }}{% endslot %}
```
When using the component, you specify which slots you want to fill and where you want to use the defaults from the template. It looks like this:
```htmldjango
{% component_block "calendar" date="2020-06-06" %}
{% fill "body" %}Can you believe it's already {{ date }}??{% endfill %}
{% endcomponent_block %}
```
Since the header block is unspecified, it's taken from the base template. If you put this in a template, and send in date=2020-06-06, this is what's rendered:
```htmldjango
Calendar header
Can you believe it's already 2020-06-06??
```
As you can see, component slots lets you write reusable containers, that you fill out when you use a component. This makes for highly reusable components, that can be used in different circumstances.
Certain properties of a slot can be accessed from within a 'fill' context. They are provided as attributes on a user-defined alias of the targeted slot. For instance, let's say you're filling a slot called 'body'. To access properties of this slot, alias it using the 'as' keyword to a new name -- or keep the original name. With the new slot alias, you can call `.default` to insert the default content.
```htmldjango
{% component_block "calendar" date="2020-06-06" %}
{% fill "body" as "body" %}{{ body.default }}. Have a great day!{% endslot %}
{% endcomponent_block %}
```
Produces:
```htmldjango
Calendar header
Today's date is 2020-06-06. Have a great day!
```
## Advanced
### Conditional slots
_Added in version 0.26._
In certain circumstances, you may want the behavior of slot filling to depend on
whether or not a particular slot is filled.
For example, suppose we have the following component template:
```htmldjango
```
By default the slot named 'subtitle' is empty. Yet when the component is used without
explicit fills, the div containing the slot is still rendered, as shown below:
```html
Title
```
This may not be what you want. What if instead the outer 'subtitle' div should only
be included when the inner slot is in fact filled?
The answer is to use the `{% if_filled %}` tag. Together with `{% endif_filled %}`,
these define a block whose contents will be rendered only if the component slot with
the corresponding 'name' is filled.
This is what our example looks like with an 'if_filled' tag.
```htmldjango
```
Just as Django's builtin 'if' tag has 'elif' and 'else' counterparts, so does 'if_filled'
include additional tags for more complex branching. These tags are 'elif_filled' and
'else_filled'. Here's what our example looks like with them.
```htmldjango
```
Sometimes you're not interested in whether a slot is filled, but rather that it _isn't_.
To negate the meaning of 'if_filled' in this way, an optional boolean can be passed to
the 'if_filled' and 'elif_filled' tags.
In the example below we use `False` to indicate that the content should be rendered
only if the slot 'subtitle' is _not_ filled.
```htmldjango
{% if_filled subtitle False %}
{% slot "subtitle" %}{% endslot %}
{% endif_filled %}
```
# Component context and scope
By default, components can access context variables from the parent template, just like templates that are included with the `{% include %}` tag. Just like with `{% include %}`, if you don't want the component template to have access to the parent context, add `only` to the end of the `{% component %}` (or `{% component_block %}` tag):
```htmldjango
{% component "calendar" date="2015-06-19" only %}
```
NOTE: `{% csrf_token %}` tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the `only` modifier.
Components can also access the outer context in their context methods by accessing the property `outer_context`.
# Available settings
All library settings are handled from a global COMPONENTS variable that is read from settings.py. By default you don't need it set, there are resonable defaults.
## Configure the module where components are loaded from
Configure the location where components are loaded. To do this, add a COMPONENTS variable to you settings.py with a list of python paths to load. This allows you to build a structure of components that are independent from your apps.
```python
COMPONENTS = {
"libraries": [
"mysite.components.forms",
"mysite.components.buttons",
"mysite.components.cards",
],
}
```
## Disable autodiscovery
If you specify all the component locations with the setting above and have a lot of apps, you can (very) slightly speed things up by disabling autodiscovery.
```python
COMPONENTS = {
"autodiscover": False,
}
```
## Tune the template cache
Each time a template is rendered it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up. By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are using the `template` method of a component to render lots of dynamic templates, you can increase this number. To remove the cache limit altogether and cache everything, set template_cache_size to `None`.
```python
COMPONENTS = {
"template_cache_size": 256,
}
```
# Install locally and run the tests
Start by forking the project by clicking the **Fork button** up in the right corner in the GitHub . This makes a copy of the repository in your own name. Now you can clone this repository locally and start adding features:
```sh
git clone https://github.com//django-components.git
```
To quickly run the tests install the local dependencies by running:
```sh
pip install -r requirements-dev.txt
```
Now you can run the tests to make sure everything works as expected:
```sh
pytest
```
The library is also tested across many versions of Python and Django. To run tests that way:
```sh
pyenv install 3.6.9
pyenv install 3.7.9
pyenv install 3.8.9
pyenv install 3.9.4
pyenv install 3.10.5
pyenv local 3.6.9 3.7.9 3.8.9 3.9.4 3.10.5
tox -p
```
%prep
%autosetup -n django-components-0.27.2
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-django-components -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Wed May 17 2023 Python_Bot - 0.27.2-1
- Package Spec generated