diff --git a/dev/index.html b/dev/index.html index f1fbafe2..f109b139 100644 --- a/dev/index.html +++ b/dev/index.html @@ -451,253 +451,248 @@ While `django_components.component_shorthand_formatter` al HELLO_FROM_SLOT_2 {% endfill %} {% endcomponent %} -
These behave same way as regular components. You pass it the same args, kwargs, and slots as you would to the component that you want to render.
The only exception is that also you supply 1-2 additional inputs: - is
- Required - The component name or a component class to render - registry
- Optional - The ComponentRegistry
that will be searched if is
is a component name. If omitted, ALL registries are searched.
By default, the dynamic component is registered under the name "dynamic"
. In case of a conflict, you can change the name used for the dynamic components by defining the COMPONENTS.dynamic_component_name
setting.
If you need to use the dynamic components in Python, you can also import it from django_components
:
from django_components import DynamicComponent
-
-comp = SimpleTableComp if is_readonly else TableComp
-
-output = DynamicComponent.render(
- kwargs={
- "is": comp,
- # Other kwargs...
- },
- # args: [...],
- # slots: {...},
-)
-
In previous examples you could repeatedly see us using @register()
to "register" the components. In this section we dive deeper into what it actually means and how you can manage (add or remove) components.
As a reminder, we may have a component like this:
or in case you use the django_components.component_shorthand_formatter
tag formatter:
{% dynamic is=component_name title="Cat Museu" %}
+ {% fill "content" %}
+ HELLO_FROM_SLOT_1
+ {% endfill %}
+ {% fill "sidebar" %}
+ HELLO_FROM_SLOT_2
+ {% endfill %}
+{% enddynamic %}
+
These behave same way as regular components. You pass it the same args, kwargs, and slots as you would to the component that you want to render.
The only exception is that also you supply 1-2 additional inputs: - is
- Required - The component name or a component class to render - registry
- Optional - The ComponentRegistry
that will be searched if is
is a component name. If omitted, ALL registries are searched.
By default, the dynamic component is registered under the name "dynamic"
. In case of a conflict, you can change the name used for the dynamic components by defining the COMPONENTS.dynamic_component_name
setting.
If you need to use the dynamic components in Python, you can also import it from django_components
:
from django_components import DynamicComponent
-@register("calendar")
-class Calendar(Component):
- template_name = "template.html"
-
- # This component takes one parameter, a date string to show in the template
- def get_context_data(self, date):
- return {
- "date": date,
- }
-
which we then render in the template as:
As you can see, @register
links up the component class with the {% component %}
template tag. So when the template tag comes across a component called "calendar"
, it can look up it's class and instantiate it.
The @register
decorator is a shortcut for working with the ComponentRegistry
.
ComponentRegistry
manages which components can be used in the template tags.
Each ComponentRegistry
instance is associated with an instance of Django's Library
. And Libraries are inserted into Django template using the {% load %}
tags.
The @register
decorator accepts an optional kwarg registry
, which specifies, the ComponentRegistry
to register components into. If omitted, the default ComponentRegistry
instance defined in django_components is used.
my_registry = ComponentRegistry()
-
-@register(registry=my_registry)
-class MyComponent(Component):
- ...
-
The default ComponentRegistry
is associated with the Library
that you load when you call {% load component_tags %}
inside your template, or when you add django_components.templatetags.component_tags
to the template builtins.
So when you register or unregister a component to/from a component registry, then behind the scenes the registry automatically adds/removes the component's template tags to/from the Library, so you can call the component from within the templates such as {% component "my_comp" %}
.
The default ComponentRegistry
instance can be imported as:
You can use the registry to manually add/remove/get components:
from django_components import registry
-
-# Register components
-registry.register("button", ButtonComponent)
-registry.register("card", CardComponent)
-
-# Get all or single
-registry.all() # {"button": ButtonComponent, "card": CardComponent}
-registry.get("card") # CardComponent
-
-# Unregister single component
-registry.unregister("card")
-
-# Unregister all components
-registry.clear()
-
If you are writing a component library to be shared with others, you may want to manage your own instance of ComponentRegistry
and register components onto a different Library
instance than the default one.
The Library
instance can be set at instantiation of ComponentRegistry
. If omitted, then the default Library instance from django_components is used.
from django.template import Library
-from django_components import ComponentRegistry
-
-my_library = Library(...)
-my_registry = ComponentRegistry(library=my_library)
-
When you have defined your own ComponentRegistry
, you can either register the components with my_registry.register()
, or pass the registry to the @component.register()
decorator via the registry
kwarg:
from path.to.my.registry import my_registry
-
-@register("my_component", registry=my_registry)
-class MyComponent(Component):
- ...
-
NOTE: The Library instance can be accessed under library
attribute of ComponentRegistry
.
When you are creating an instance of ComponentRegistry
, you can define the components' behavior within the template.
The registry accepts these settings: - CONTEXT_BEHAVIOR
- TAG_FORMATTER
from django.template import Library
-from django_components import ComponentRegistry, RegistrySettings
-
-register = library = django.template.Library()
-comp_registry = ComponentRegistry(
- library=library,
- settings=RegistrySettings(
- CONTEXT_BEHAVIOR="isolated",
- TAG_FORMATTER="django_components.component_formatter",
- ),
-)
-
These settings are the same as the ones you can set for django_components.
In fact, when you set COMPONENT.tag_formatter
or COMPONENT.context_behavior
, these are forwarded to the default ComponentRegistry
.
This makes it possible to have multiple registries with different settings in one projects, and makes sharing of component libraries possible.
Every component that you want to use in the template with the {% component %}
tag needs to be registered with the ComponentRegistry. Normally, we use the @register
decorator for that:
from django_components import Component, register
-
-@register("calendar")
-class Calendar(Component):
- ...
-
But for the component to be registered, the code needs to be executed - the file needs to be imported as a module.
One way to do that is by importing all your components in apps.py
:
from django.apps import AppConfig
+comp = SimpleTableComp if is_readonly else TableComp
+
+output = DynamicComponent.render(
+ kwargs={
+ "is": comp,
+ # Other kwargs...
+ },
+ # args: [...],
+ # slots: {...},
+)
+
In previous examples you could repeatedly see us using @register()
to "register" the components. In this section we dive deeper into what it actually means and how you can manage (add or remove) components.
As a reminder, we may have a component like this:
from django_components import Component, register
+
+@register("calendar")
+class Calendar(Component):
+ template_name = "template.html"
+
+ # This component takes one parameter, a date string to show in the template
+ def get_context_data(self, date):
+ return {
+ "date": date,
+ }
+
which we then render in the template as:
As you can see, @register
links up the component class with the {% component %}
template tag. So when the template tag comes across a component called "calendar"
, it can look up it's class and instantiate it.
The @register
decorator is a shortcut for working with the ComponentRegistry
.
ComponentRegistry
manages which components can be used in the template tags.
Each ComponentRegistry
instance is associated with an instance of Django's Library
. And Libraries are inserted into Django template using the {% load %}
tags.
The @register
decorator accepts an optional kwarg registry
, which specifies, the ComponentRegistry
to register components into. If omitted, the default ComponentRegistry
instance defined in django_components is used.
my_registry = ComponentRegistry()
+
+@register(registry=my_registry)
+class MyComponent(Component):
+ ...
+
The default ComponentRegistry
is associated with the Library
that you load when you call {% load component_tags %}
inside your template, or when you add django_components.templatetags.component_tags
to the template builtins.
So when you register or unregister a component to/from a component registry, then behind the scenes the registry automatically adds/removes the component's template tags to/from the Library, so you can call the component from within the templates such as {% component "my_comp" %}
.
The default ComponentRegistry
instance can be imported as:
You can use the registry to manually add/remove/get components:
from django_components import registry
+
+# Register components
+registry.register("button", ButtonComponent)
+registry.register("card", CardComponent)
+
+# Get all or single
+registry.all() # {"button": ButtonComponent, "card": CardComponent}
+registry.get("card") # CardComponent
+
+# Unregister single component
+registry.unregister("card")
+
+# Unregister all components
+registry.clear()
+
If you are writing a component library to be shared with others, you may want to manage your own instance of ComponentRegistry
and register components onto a different Library
instance than the default one.
The Library
instance can be set at instantiation of ComponentRegistry
. If omitted, then the default Library instance from django_components is used.
from django.template import Library
+from django_components import ComponentRegistry
+
+my_library = Library(...)
+my_registry = ComponentRegistry(library=my_library)
+
When you have defined your own ComponentRegistry
, you can either register the components with my_registry.register()
, or pass the registry to the @component.register()
decorator via the registry
kwarg:
from path.to.my.registry import my_registry
+
+@register("my_component", registry=my_registry)
+class MyComponent(Component):
+ ...
+
NOTE: The Library instance can be accessed under library
attribute of ComponentRegistry
.
When you are creating an instance of ComponentRegistry
, you can define the components' behavior within the template.
The registry accepts these settings: - CONTEXT_BEHAVIOR
- TAG_FORMATTER
from django.template import Library
+from django_components import ComponentRegistry, RegistrySettings
+
+register = library = django.template.Library()
+comp_registry = ComponentRegistry(
+ library=library,
+ settings=RegistrySettings(
+ CONTEXT_BEHAVIOR="isolated",
+ TAG_FORMATTER="django_components.component_formatter",
+ ),
+)
+
These settings are the same as the ones you can set for django_components.
In fact, when you set COMPONENT.tag_formatter
or COMPONENT.context_behavior
, these are forwarded to the default ComponentRegistry
.
This makes it possible to have multiple registries with different settings in one projects, and makes sharing of component libraries possible.
Every component that you want to use in the template with the {% component %}
tag needs to be registered with the ComponentRegistry. Normally, we use the @register
decorator for that:
from django_components import Component, register
-class MyAppConfig(AppConfig):
- name = "my_app"
-
- def ready(self) -> None:
- from components.card.card import Card
- from components.list.list import List
- from components.menu.menu import Menu
- from components.button.button import Button
- ...
-
However, there's a simpler way!
By default, the Python files in the COMPONENTS.dirs
directories (or app-level [app]/components/
) are auto-imported in order to auto-register the components.
Autodiscovery occurs when Django is loaded, during the ready
hook of the apps.py
file.
If you are using autodiscovery, keep a few points in mind:
components
dir, that you would not want to run anyway.@register()
.py
, and module name should follow PEP-8.Autodiscovery can be disabled in the settings.
Autodiscovery can be also triggered manually as a function call. This is useful if you want to run autodiscovery at a custom point of the lifecycle:
from django_components import autodiscover
+@register("calendar")
+class Calendar(Component):
+ ...
+
But for the component to be registered, the code needs to be executed - the file needs to be imported as a module.
One way to do that is by importing all your components in apps.py
:
New in version 0.26:
slot
tag now serves only to declare new slots inside the component template.fill
tag instead.required
option 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. This behavior is similar to slots in Vue.
In the example below we introduce two block tags that work hand in hand to make this work. These are...
{% slot <name> %}
/{% endslot %}
: Declares a new slot in the component template.{% fill <name> %}
/{% endfill %}
: (Used inside a component
tag pair.) Fills a declared slot with the specified content.Let's update our calendar component to support more customization. We'll add slot
tag pairs to its template, template.html.
<div class="calendar-component">
- <div class="header">
- {% slot "header" %}Calendar header{% endslot %}
- </div>
- <div class="body">
- {% slot "body" %}Today's date is <span>{{ date }}</span>{% endslot %}
- </div>
-</div>
-
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:
{% component "calendar" date="2020-06-06" %}
- {% fill "body" %}Can you believe it's already <span>{{ date }}</span>??{% endfill %}
-{% endcomponent %}
-
Since the 'header' fill is unspecified, it's taken from the base template. If you put this in a template, and pass in date=2020-06-06
, this is what gets rendered:
<div class="calendar-component">
- <div class="header">
- Calendar header
- </div>
- <div class="body">
- Can you believe it's already <span>2020-06-06</span>??
- </div>
-</div>
-
Added in version 0.28
As you can see, component slots lets you write reusable containers that you fill in when you use a component. This makes for highly reusable components that can be used in different circumstances.
It can become tedious to use fill
tags everywhere, especially when you're using a component that declares only one slot. To make things easier, slot
tags can be marked with an optional keyword: default
. When added to the end of the tag (as shown below), this option lets you pass filling content directly in the body of a component
tag pair – without using a fill
tag. Choose carefully, though: a component template may contain at most one slot that is marked as default
. The default
option can be combined with other slot options, e.g. required
.
Here's the same example as before, except with default slots and implicit filling.
The template:
<div class="calendar-component">
+class MyAppConfig(AppConfig):
+ name = "my_app"
+
+ def ready(self) -> None:
+ from components.card.card import Card
+ from components.list.list import List
+ from components.menu.menu import Menu
+ from components.button.button import Button
+ ...
+
However, there's a simpler way!
By default, the Python files in the COMPONENTS.dirs
directories (or app-level [app]/components/
) are auto-imported in order to auto-register the components.
Autodiscovery occurs when Django is loaded, during the ready
hook of the apps.py
file.
If you are using autodiscovery, keep a few points in mind:
components
dir, that you would not want to run anyway.@register()
.py
, and module name should follow PEP-8.Autodiscovery can be disabled in the settings.
Autodiscovery can be also triggered manually as a function call. This is useful if you want to run autodiscovery at a custom point of the lifecycle:
New in version 0.26:
slot
tag now serves only to declare new slots inside the component template.fill
tag instead.required
option 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. This behavior is similar to slots in Vue.
In the example below we introduce two block tags that work hand in hand to make this work. These are...
{% slot <name> %}
/{% endslot %}
: Declares a new slot in the component template.{% fill <name> %}
/{% endfill %}
: (Used inside a component
tag pair.) Fills a declared slot with the specified content.Let's update our calendar component to support more customization. We'll add slot
tag pairs to its template, template.html.
<div class="calendar-component">
+ <div class="header">
+ {% slot "header" %}Calendar header{% endslot %}
+ </div>
+ <div class="body">
+ {% slot "body" %}Today's date is <span>{{ date }}</span>{% endslot %}
+ </div>
+</div>
+
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:
{% component "calendar" date="2020-06-06" %}
+ {% fill "body" %}Can you believe it's already <span>{{ date }}</span>??{% endfill %}
+{% endcomponent %}
+
Since the 'header' fill is unspecified, it's taken from the base template. If you put this in a template, and pass in date=2020-06-06
, this is what gets rendered:
<div class="calendar-component">
<div class="header">
- {% slot "header" %}Calendar header{% endslot %}
+ Calendar header
</div>
<div class="body">
- {% slot "body" default %}Today's date is <span>{{ date }}</span>{% endslot %}
+ Can you believe it's already <span>2020-06-06</span>??
</div>
</div>
-
Including the component (notice how the fill
tag is omitted):
{% component "calendar" date="2020-06-06" %}
- Can you believe it's already <span>{{ date }}</span>??
-{% endcomponent %}
-
The rendered result (exactly the same as before):
<div class="calendar-component">
- <div class="header">Calendar header</div>
- <div class="body">Can you believe it's already <span>2020-06-06</span>??</div>
-</div>
-
You may be tempted to combine implicit fills with explicit fill
tags. This will not work. The following component template will raise an error when compiled.
{# DON'T DO THIS #}
-{% component "calendar" date="2020-06-06" %}
- {% fill "header" %}Totally new header!{% endfill %}
- Can you believe it's already <span>{{ date }}</span>??
-{% endcomponent %}
-
By contrast, it is permitted to use fill
tags in nested components, e.g.:
{% component "calendar" date="2020-06-06" %}
- {% component "beautiful-box" %}
- {% fill "content" %} Can you believe it's already <span>{{ date }}</span>?? {% endfill %}
- {% endcomponent %}
+
Added in version 0.28
As you can see, component slots lets you write reusable containers that you fill in when you use a component. This makes for highly reusable components that can be used in different circumstances.
It can become tedious to use fill
tags everywhere, especially when you're using a component that declares only one slot. To make things easier, slot
tags can be marked with an optional keyword: default
. When added to the end of the tag (as shown below), this option lets you pass filling content directly in the body of a component
tag pair – without using a fill
tag. Choose carefully, though: a component template may contain at most one slot that is marked as default
. The default
option can be combined with other slot options, e.g. required
.
Here's the same example as before, except with default slots and implicit filling.
The template:
<div class="calendar-component">
+ <div class="header">
+ {% slot "header" %}Calendar header{% endslot %}
+ </div>
+ <div class="body">
+ {% slot "body" default %}Today's date is <span>{{ date }}</span>{% endslot %}
+ </div>
+</div>
+
Including the component (notice how the fill
tag is omitted):
{% component "calendar" date="2020-06-06" %}
+ Can you believe it's already <span>{{ date }}</span>??
+{% endcomponent %}
+
The rendered result (exactly the same as before):
<div class="calendar-component">
+ <div class="header">Calendar header</div>
+ <div class="body">Can you believe it's already <span>2020-06-06</span>??</div>
+</div>
+
You may be tempted to combine implicit fills with explicit fill
tags. This will not work. The following component template will raise an error when compiled.
{# DON'T DO THIS #}
+{% component "calendar" date="2020-06-06" %}
+ {% fill "header" %}Totally new header!{% endfill %}
+ Can you believe it's already <span>{{ date }}</span>??
{% endcomponent %}
-
This is fine too:
{% component "calendar" date="2020-06-06" %}
- {% fill "header" %}
- {% component "calendar-header" %}
- Super Special Calendar Header
- {% endcomponent %}
- {% endfill %}
-{% endcomponent %}
-
Added in version 0.70
You can render the same content in multiple places by defining multiple slots with identical names:
<div class="calendar-component">
- <div class="header">
- {% slot "image" %}Image here{% endslot %}
- </div>
- <div class="body">
- {% slot "image" %}Image here{% endslot %}
- </div>
-</div>
-
So if used like:
{% component "calendar" date="2020-06-06" %}
- {% fill "image" %}
- <img src="..." />
- {% endfill %}
-{% endcomponent %}
-
This renders:
By contrast, it is permitted to use fill
tags in nested components, e.g.:
{% component "calendar" date="2020-06-06" %}
+ {% component "beautiful-box" %}
+ {% fill "content" %} Can you believe it's already <span>{{ date }}</span>?? {% endfill %}
+ {% endcomponent %}
+{% endcomponent %}
+
This is fine too:
{% component "calendar" date="2020-06-06" %}
+ {% fill "header" %}
+ {% component "calendar-header" %}
+ Super Special Calendar Header
+ {% endcomponent %}
+ {% endfill %}
+{% endcomponent %}
+
Added in version 0.70
You can render the same content in multiple places by defining multiple slots with identical names:
<div class="calendar-component">
+ <div class="header">
+ {% slot "image" %}Image here{% endslot %}
+ </div>
+ <div class="body">
+ {% slot "image" %}Image here{% endslot %}
+ </div>
+</div>
+
So if used like:
{% component "calendar" date="2020-06-06" %}
+ {% fill "image" %}
<img src="..." />
- </div>
- <div class="body">
- <img src="..." />
- </div>
-</div>
-
If you use a slot multiple times, you can still mark the slot as default
or required
. For that, you must mark ONLY ONE of the identical slots.
We recommend to mark the first occurence for consistency, e.g.:
This renders:
<div class="calendar-component">
<div class="header">
- {% slot "image" default required %}Image here{% endslot %}
+ <img src="..." />
</div>
<div class="body">
- {% slot "image" %}Image here{% endslot %}
+ <img src="..." />
</div>
</div>
-
Which you can then use are regular default slot:
Added in version 0.26
NOTE: In version 0.77, the syntax was changed from
to
Sometimes you may want to keep the original slot, but only wrap or prepend/append content to it. To do so, you can access the default slot via the default
kwarg.
Similarly to the data
attribute, you specify the variable name through which the default slot will be made available.
For instance, let's say you're filling a slot called 'body'. To render the original slot, assign it to a variable using the 'default'
keyword. You then render this variable to insert the default content:
{% component "calendar" date="2020-06-06" %}
- {% fill "body" default="body_default" %}
- {{ body_default }}. Have a great day!
- {% endfill %}
-{% endcomponent %}
-
This produces:
<div class="calendar-component">
- <div class="header">
- Calendar header
- </div>
- <div class="body">
- Today's date is <span>2020-06-06</span>. Have a great day!
- </div>
-</div>
-
Added in version 0.26.
NOTE: In version 0.70,
{% if_filled %}
tags were replaced with{{ component_vars.is_filled }}
variables. If your slot name contained special characters, see the section Accessingis_filled
of slot names with special characters.
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:
If you use a slot multiple times, you can still mark the slot as default
or required
. For that, you must mark ONLY ONE of the identical slots.
We recommend to mark the first occurence for consistency, e.g.:
<div class="calendar-component">
+ <div class="header">
+ {% slot "image" default required %}Image here{% endslot %}
+ </div>
+ <div class="body">
+ {% slot "image" %}Image here{% endslot %}
+ </div>
+</div>
+
Which you can then use are regular default slot:
Added in version 0.26
NOTE: In version 0.77, the syntax was changed from
to
Sometimes you may want to keep the original slot, but only wrap or prepend/append content to it. To do so, you can access the default slot via the default
kwarg.
Similarly to the data
attribute, you specify the variable name through which the default slot will be made available.
For instance, let's say you're filling a slot called 'body'. To render the original slot, assign it to a variable using the 'default'
keyword. You then render this variable to insert the default content:
{% component "calendar" date="2020-06-06" %}
+ {% fill "body" default="body_default" %}
+ {{ body_default }}. Have a great day!
+ {% endfill %}
+{% endcomponent %}
+
This produces:
<div class="calendar-component">
+ <div class="header">
+ Calendar header
</div>
- <div class="subtitle">
- {% slot "subtitle" %}{# Optional subtitle #}{% endslot %}
+ <div class="body">
+ Today's date is <span>2020-06-06</span>. Have a great day!
</div>
</div>
-
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:
<div class="frontmatter-component">
- <div class="title">Title</div>
- <div class="subtitle"></div>
-</div>
-
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 {{ component_vars.is_filled.<name> }}
variable. You can use this together with Django's {% if/elif/else/endif %}
tags to 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 component_vars.is_filled
.
<div class="frontmatter-component">
- <div class="title">
- {% slot "title" %}Title{% endslot %}
- </div>
- {% if component_vars.is_filled.subtitle %}
- <div class="subtitle">
- {% slot "subtitle" %}{# Optional subtitle #}{% endslot %}
- </div>
- {% endif %}
-</div>
-
-Here's our example with more complex branching.
-
-```htmldjango
-<div class="frontmatter-component">
- <div class="title">
- {% slot "title" %}Title{% endslot %}
- </div>
- {% if component_vars.is_filled.subtitle %}
- <div class="subtitle">
- {% slot "subtitle" %}{# Optional subtitle #}{% endslot %}
- </div>
- {% elif component_vars.is_filled.title %}
- ...
- {% elif component_vars.is_filled.<name> %}
- ...
- {% endif %}
-</div>
-
Sometimes you're not interested in whether a slot is filled, but rather that it isn't. To negate the meaning of component_vars.is_filled
, simply treat it as boolean and negate it with not
:
{% if not component_vars.is_filled.subtitle %}
-<div class="subtitle">
- {% slot "subtitle" / %}
-</div>
-{% endif %}
-
is_filled
of slot names with special characters¤To be able to access a slot name via component_vars.is_filled
, the slot name needs to be composed of only alphanumeric characters and underscores (e.g. this__isvalid_123
).
However, you can still define slots with other special characters. In such case, the slot name in component_vars.is_filled
is modified to replace all invalid characters into _
.
So a slot named "my super-slot :)"
will be available as component_vars.is_filled.my_super_slot___
.
Added in version 0.76:
Consider a component with slot(s). This component may do some processing on the inputs, and then use the processed variable in the slot's default template:
@register("my_comp")
-class MyComp(Component):
- template = """
- <div>
- {% slot "content" default %}
- input: {{ input }}
- {% endslot %}
- </div>
- """
-
- def get_context_data(self, input):
- processed_input = do_something(input)
- return {"input": processed_input}
-
You may want to design a component so that users of your component can still access the input
variable, so they don't have to recompute it.
This behavior is called "scoped slots". This is inspired by Vue scoped slots and scoped slots of django-web-components.
Using scoped slots consists of two steps:
slot
tagfill
tagTo pass the data to the slot
tag, simply pass them as keyword attributes (key=value
):
Added in version 0.26.
NOTE: In version 0.70,
{% if_filled %}
tags were replaced with{{ component_vars.is_filled }}
variables. If your slot name contained special characters, see the section Accessingis_filled
of slot names with special characters.
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:
<div class="frontmatter-component">
+ <div class="title">
+ {% slot "title" %}Title{% endslot %}
+ </div>
+ <div class="subtitle">
+ {% slot "subtitle" %}{# Optional subtitle #}{% endslot %}
+ </div>
+</div>
+
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:
<div class="frontmatter-component">
+ <div class="title">Title</div>
+ <div class="subtitle"></div>
+</div>
+
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 {{ component_vars.is_filled.<name> }}
variable. You can use this together with Django's {% if/elif/else/endif %}
tags to 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 component_vars.is_filled
.
<div class="frontmatter-component">
+ <div class="title">
+ {% slot "title" %}Title{% endslot %}
+ </div>
+ {% if component_vars.is_filled.subtitle %}
+ <div class="subtitle">
+ {% slot "subtitle" %}{# Optional subtitle #}{% endslot %}
+ </div>
+ {% endif %}
+</div>
+
+Here's our example with more complex branching.
+
+```htmldjango
+<div class="frontmatter-component">
+ <div class="title">
+ {% slot "title" %}Title{% endslot %}
+ </div>
+ {% if component_vars.is_filled.subtitle %}
+ <div class="subtitle">
+ {% slot "subtitle" %}{# Optional subtitle #}{% endslot %}
+ </div>
+ {% elif component_vars.is_filled.title %}
+ ...
+ {% elif component_vars.is_filled.<name> %}
+ ...
+ {% endif %}
+</div>
+
Sometimes you're not interested in whether a slot is filled, but rather that it isn't. To negate the meaning of component_vars.is_filled
, simply treat it as boolean and negate it with not
:
{% if not component_vars.is_filled.subtitle %}
+<div class="subtitle">
+ {% slot "subtitle" / %}
+</div>
+{% endif %}
+
is_filled
of slot names with special characters¤To be able to access a slot name via component_vars.is_filled
, the slot name needs to be composed of only alphanumeric characters and underscores (e.g. this__isvalid_123
).
However, you can still define slots with other special characters. In such case, the slot name in component_vars.is_filled
is modified to replace all invalid characters into _
.
So a slot named "my super-slot :)"
will be available as component_vars.is_filled.my_super_slot___
.
Added in version 0.76:
Consider a component with slot(s). This component may do some processing on the inputs, and then use the processed variable in the slot's default template:
@register("my_comp")
class MyComp(Component):
template = """
<div>
- {% slot "content" default input=input %}
+ {% slot "content" default %}
input: {{ input }}
{% endslot %}
</div>
@@ -705,322 +700,335 @@ While `django_components.component_shorthand_formatter` al
def get_context_data(self, input):
processed_input = do_something(input)
- return {
- "input": processed_input,
- }
-
Next, we head over to where we define a fill for this slot. Here, to access the slot data we set the data
attribute to the name of the variable through which we want to access the slot data. In the example below, we set it to data
:
{% component "my_comp" %}
- {% fill "content" data="data" %}
- {{ data.input }}
- {% endfill %}
-{% endcomponent %}
-
To access slot data on a default slot, you have to explictly define the {% fill %}
tags.
So this works:
You may want to design a component so that users of your component can still access the input
variable, so they don't have to recompute it.
This behavior is called "scoped slots". This is inspired by Vue scoped slots and scoped slots of django-web-components.
Using scoped slots consists of two steps:
slot
tagfill
tagTo pass the data to the slot
tag, simply pass them as keyword attributes (key=value
):
@register("my_comp")
+class MyComp(Component):
+ template = """
+ <div>
+ {% slot "content" default input=input %}
+ input: {{ input }}
+ {% endslot %}
+ </div>
+ """
+
+ def get_context_data(self, input):
+ processed_input = do_something(input)
+ return {
+ "input": processed_input,
+ }
+
Next, we head over to where we define a fill for this slot. Here, to access the slot data we set the data
attribute to the name of the variable through which we want to access the slot data. In the example below, we set it to data
:
{% component "my_comp" %}
{% fill "content" data="data" %}
{{ data.input }}
{% endfill %}
{% endcomponent %}
-
While this does not:
Note: You cannot set the data
attribute and default
attribute) to the same name. This raises an error:
{% component "my_comp" %}
- {% fill "content" data="slot_var" default="slot_var" %}
- {{ slot_var.input }}
- {% endfill %}
-{% endcomponent %}
-
Until now, we were declaring slot and fill names statically, as a string literal, e.g.
However, sometimes you may want to generate slots based on the given input. One example of this is a table component like that of Vuetify, which creates a header and an item slots for each user-defined column.
In django_components you can achieve the same, simply by using a variable (or a template expression) instead of a string literal:
<table>
- <tr>
- {% for header in headers %}
- <th>
- {% slot "header-{{ header.key }}" value=header.title %}
- {{ header.title }}
- {% endslot %}
- </th>
- {% endfor %}
- </tr>
-</table>
-
When using the component, you can either set the fill explicitly:
{% component "table" headers=headers items=items %}
- {% fill "header-name" data="data" %}
- <b>{{ data.value }}</b>
- {% endfill %}
-{% endcomponent %}
-
Or also use a variable:
{% component "table" headers=headers items=items %}
- {# Make only the active column bold #}
- {% fill "header-{{ active_header_name }}" data="data" %}
- <b>{{ data.value }}</b>
- {% endfill %}
-{% endcomponent %}
-
NOTE: It's better to use static slot names whenever possible for clarity. The dynamic slot names should be reserved for advanced use only.
Lastly, in rare cases, you can also pass the slot name via the spread operator. This is possible, because the slot name argument is actually a shortcut for a name
keyword argument.
So this:
is the same as:
So it's possible to define a name
key on a dictionary, and then spread that onto the slot tag:
When you call Component.render
or Component.render_to_response
, the inputs to these methods can be accessed from within the instance under self.input
.
This means that you can use self.input
inside: - get_context_data
- get_template_name
- get_template
self.input
is only defined during the execution of Component.render
, and raises a RuntimeError
when called outside of this context.
self.input
has the same fields as the input to Component.render
:
class TestComponent(Component):
- def get_context_data(self, var1, var2, variable, another, **attrs):
- assert self.input.args == (123, "str")
- assert self.input.kwargs == {"variable": "test", "another": 1}
- assert self.input.slots == {"my_slot": "MY_SLOT"}
- assert isinstance(self.input.context, Context)
-
- return {
- "variable": variable,
- }
-
-rendered = TestComponent.render(
- kwargs={"variable": "test", "another": 1},
- args=(123, "str"),
- slots={"my_slot": "MY_SLOT"},
-)
-
New in version 0.74:
You can use the html_attrs
tag to render HTML attributes, given a dictionary of values.
So if you have a template:
You can simplify it with html_attrs
tag:
To access slot data on a default slot, you have to explictly define the {% fill %}
tags.
So this works:
{% component "my_comp" %}
+ {% fill "content" data="data" %}
+ {{ data.input }}
+ {% endfill %}
+{% endcomponent %}
+
While this does not:
Note: You cannot set the data
attribute and default
attribute) to the same name. This raises an error:
{% component "my_comp" %}
+ {% fill "content" data="slot_var" default="slot_var" %}
+ {{ slot_var.input }}
+ {% endfill %}
+{% endcomponent %}
+
Until now, we were declaring slot and fill names statically, as a string literal, e.g.
However, sometimes you may want to generate slots based on the given input. One example of this is a table component like that of Vuetify, which creates a header and an item slots for each user-defined column.
In django_components you can achieve the same, simply by using a variable (or a template expression) instead of a string literal:
<table>
+ <tr>
+ {% for header in headers %}
+ <th>
+ {% slot "header-{{ header.key }}" value=header.title %}
+ {{ header.title }}
+ {% endslot %}
+ </th>
+ {% endfor %}
+ </tr>
+</table>
+
When using the component, you can either set the fill explicitly:
{% component "table" headers=headers items=items %}
+ {% fill "header-name" data="data" %}
+ <b>{{ data.value }}</b>
+ {% endfill %}
+{% endcomponent %}
+
Or also use a variable:
{% component "table" headers=headers items=items %}
+ {# Make only the active column bold #}
+ {% fill "header-{{ active_header_name }}" data="data" %}
+ <b>{{ data.value }}</b>
+ {% endfill %}
+{% endcomponent %}
+
NOTE: It's better to use static slot names whenever possible for clarity. The dynamic slot names should be reserved for advanced use only.
Lastly, in rare cases, you can also pass the slot name via the spread operator. This is possible, because the slot name argument is actually a shortcut for a name
keyword argument.
So this:
is the same as:
So it's possible to define a name
key on a dictionary, and then spread that onto the slot tag:
When you call Component.render
or Component.render_to_response
, the inputs to these methods can be accessed from within the instance under self.input
.
This means that you can use self.input
inside: - get_context_data
- get_template_name
- get_template
self.input
is only defined during the execution of Component.render
, and raises a RuntimeError
when called outside of this context.
self.input
has the same fields as the input to Component.render
:
class TestComponent(Component):
+ def get_context_data(self, var1, var2, variable, another, **attrs):
+ assert self.input.args == (123, "str")
+ assert self.input.kwargs == {"variable": "test", "another": 1}
+ assert self.input.slots == {"my_slot": "MY_SLOT"}
+ assert isinstance(self.input.context, Context)
+
+ return {
+ "variable": variable,
+ }
+
+rendered = TestComponent.render(
+ kwargs={"variable": "test", "another": 1},
+ args=(123, "str"),
+ slots={"my_slot": "MY_SLOT"},
+)
+
New in version 0.74:
You can use the html_attrs
tag to render HTML attributes, given a dictionary of values.
So if you have a template:
where attrs
is:
This feature is inspired by merge_attrs
tag of django-web-components and "fallthrough attributes" feature of Vue.
Attributes that are set to None
or False
are NOT rendered.
So given this input:
And template:
Then this renders:
In HTML, boolean attributes are usually rendered with no value. Consider the example below where the first button is disabled and the second is not:
HTML rendering with html_attrs
tag or attributes_to_string
works the same way, where key=True
is rendered simply as key
, and key=False
is not render at all.
So given this input:
And template:
Then this renders:
Sometimes you may want to specify default values for attributes. You can pass a second argument (or kwarg defaults
) to set the defaults.
In the example above, if attrs
contains e.g. the class
key, html_attrs
will render:
class="{{ attrs.class }}"
Otherwise, html_attrs
will render:
class="{{ defaults.class }}"
For the class
HTML attribute, it's common that we want to join multiple values, instead of overriding them. For example, if you're authoring a component, you may want to ensure that the component will ALWAYS have a specific class. Yet, you may want to allow users of your component to supply their own classes.
We can achieve this by adding extra kwargs. These values will be appended, instead of overwriting the previous value.
So if we have a variable attrs
:
And on html_attrs
tag, we set the key class
:
Then these will be merged and rendered as:
To simplify merging of variables, you can supply the same key multiple times, and these will be all joined together:
{# my_var = "class-from-var text-red" #}
-<div {% html_attrs attrs class="some-class another-class" class=my_var %}>
-</div>
-
Renders:
html_attrs
¤attrs
and defaults
can be passed as positional args{% html_attrs attrs defaults key=val %}
or as kwargs
{% html_attrs key=val defaults=defaults attrs=attrs %}
Both attrs
and defaults
are optional (can be omitted)
Both attrs
and defaults
are dictionaries, and we can define them the same way we define dictionaries for the component
tag. So either as attrs=attrs
or attrs:key=value
.
All other kwargs are appended and can be repeated.
html_attrs
¤Assuming that:
class_from_var = "from-var"
-
-attrs = {
- "class": "from-attrs",
- "type": "submit",
-}
-
-defaults = {
- "class": "from-defaults",
- "role": "button",
-}
-
Then:
{% html_attr %}
renders (empty string):
{% html_attr class="some-class" class=class_from_var data-id="123" %}
renders:
class="some-class from-var" data-id="123"
{% html_attr attrs %}
renders:
class="from-attrs" type="submit"
{% html_attr attrs=attrs %}
renders:
class="from-attrs" type="submit"
{% html_attr defaults=defaults %}
renders:
class="from-defaults" role="button"
prefix:key=value
construct {% html_attr attrs:class="from-attrs" attrs:type="submit" %}
renders:
class="from-attrs" type="submit"
prefix:key=value
construct {% html_attr defaults:class="from-defaults" %}
renders:
class="from-defaults" role="button"
{% html_attrs attrs defaults class="added_class" class=class_from_var data-id=123 %}
renders:
class="from-attrs added_class from-var" type="submit" role="button" data-id=123
{% html_attrs class="added_class" class=class_from_var data-id=123 attrs=attrs defaults=defaults %}
renders:
class="from-attrs added_class from-var" type="submit" role="button" data-id=123
{% html_attrs attrs defaults:class="default-class" class="added_class" class=class_from_var data-id=123 %}
renders:
class="from-attrs added_class from-var" type="submit" data-id=123
html_attrs
¤@register("my_comp")
-class MyComp(Component):
- template: t.django_html = """
- <div
- {% html_attrs attrs
- defaults:class="pa-4 text-red"
- class="my-comp-date"
- class=class_from_var
- data-id="123"
- %}
- >
- Today's date is <span>{{ date }}</span>
- </div>
- """
-
- def get_context_data(self, date: Date, attrs: dict):
- return {
- "date": date,
- "attrs": attrs,
- "class_from_var": "extra-class"
- }
-
-@register("parent")
-class Parent(Component):
- template: t.django_html = """
- {% component "my_comp"
- date=date
- attrs:class="pa-0 border-solid border-red"
- attrs:data-json=json_data
- attrs:@click="(e) => onClick(e, 'from_parent')"
- / %}
- """
-
- def get_context_data(self, date: Date):
- return {
- "date": datetime.now(),
- "json_data": json.dumps({"value": 456})
- }
-
Note: For readability, we've split the tags across multiple lines.
Inside MyComp
, we defined a default attribute
defaults:class="pa-4 text-red"
So if attrs
includes key class
, the default above will be ignored.
MyComp
also defines class
key twice. It means that whether the class
attribute is taken from attrs
or defaults
, the two class
values will be appended to it.
So by default, MyComp
renders:
Next, let's consider what will be rendered when we call MyComp
from Parent
component.
MyComp
accepts a attrs
dictionary, that is passed to html_attrs
, so the contents of that dictionary are rendered as the HTML attributes.
In Parent
, we make use of passing dictionary key-value pairs as kwargs to define individual attributes as if they were regular kwargs.
So all kwargs that start with attrs:
will be collected into an attrs
dict.
attrs:class="pa-0 border-solid border-red"
- attrs:data-json=json_data
- attrs:@click="(e) => onClick(e, 'from_parent')"
-
And get_context_data
of MyComp
will receive attrs
input with following keys:
attrs = {
- "class": "pa-0 border-solid",
- "data-json": '{"value": 456}',
- "@click": "(e) => onClick(e, 'from_parent')",
-}
-
attrs["class"]
overrides the default value for class
, whereas other keys will be merged.
So in the end MyComp
will render:
<div
- class="pa-0 border-solid my-comp-date extra-class"
- data-id="123"
- data-json='{"value": 456}'
- @click="(e) => onClick(e, 'from_parent')"
->
- ...
-</div>
-
If you need to use serialize HTML attributes outside of Django template and the html_attrs
tag, you can use attributes_to_string
:
from django_components.attributes import attributes_to_string
-
-attrs = {
- "class": "my-class text-red pa-4",
- "data-id": 123,
- "required": True,
- "disabled": False,
- "ignored-attr": None,
-}
-
-attributes_to_string(attrs)
-# 'class="my-class text-red pa-4" data-id="123" required'
-
All template tags in django_component, like {% component %}
or {% slot %}
, and so on, support extra syntax that makes it possible to write components like in Vue or React (JSX).
When you have a tag like {% component %}
or {% slot %}
, but it has no content, you can simply append a forward slash /
at the end, instead of writing out the closing tags like {% endcomponent %}
or {% endslot %}
:
So this:
becomes
New in version 0.71:
Keyword arguments can contain special characters # @ . - _
, so keywords like so are still valid:
<body>
- {% component "calendar" my-date="2015-06-19" @click.native=do_something #some_id=True / %}
-</body>
-
These can then be accessed inside get_context_data
so:
@register("calendar")
-class Calendar(Component):
- # Since # . @ - are not valid identifiers, we have to
- # use `**kwargs` so the method can accept these args.
- def get_context_data(self, **kwargs):
- return {
- "date": kwargs["my-date"],
- "id": kwargs["#some_id"],
- "on_click": kwargs["@click.native"]
- }
-
New in version 0.93:
Instead of passing keyword arguments one-by-one:
You can use a spread operator ...dict
to apply key-value pairs from a dictionary:
This behaves similar to JSX's spread operator or Vue's v-bind
.
Spread operators are treated as keyword arguments, which means that: 1. Spread operators must come after positional arguments. 2. You cannot use spread operators for positional-only arguments.
Other than that, you can use spread operators multiple times, and even put keyword arguments in-between or after them:
In a case of conflicts, the values added later (right-most) overwrite previous values.
New in version 0.93
When passing data around, sometimes you may need to do light transformations, like negating booleans or filtering lists.
Normally, what you would have to do is to define ALL the variables inside get_context_data()
. But this can get messy if your components contain a lot of logic.
@register("calendar")
-class Calendar(Component):
- def get_context_data(self, id: str, editable: bool):
- return {
- "editable": editable,
- "readonly": not editable,
- "input_id": f"input-{id}",
- "icon_id": f"icon-{id}",
- ...
- }
-
Instead, template tags in django_components ({% component %}
, {% slot %}
, {% provide %}
, etc) allow you to treat literal string values as templates:
{% component 'blog_post'
- "As positional arg {# yay #}"
- title="{{ person.first_name }} {{ person.last_name }}"
- id="{% random_int 10 20 %}"
- readonly="{{ editable|not }}"
- author="John Wick {# TODO: parametrize #}"
-/ %}
-
In the example above: - Component test
receives a positional argument with value "As positional arg "
. The comment is omitted. - Kwarg title
is passed as a string, e.g. John Doe
- Kwarg id
is passed as int
, e.g. 15
- Kwarg readonly
is passed as bool
, e.g. False
- Kwarg author
is passed as a string, e.g. John Wick
(Comment omitted)
This is inspired by django-cotton.
Sometimes you may want to use the template tags to transform or generate the data that is then passed to the component.
The data doesn't necessarily have to be strings. In the example above, the kwarg id
was passed as an integer, NOT a string.
Although the string literals for components inputs are treated as regular Django templates, there is one special case:
When the string literal contains only a single template tag, with no extra text, then the value is passed as the original type instead of a string.
Here, page
is an integer:
Here, page
is a string:
And same applies to the {{ }}
variable tags:
Here, items
is a list:
Here, items
is a string:
You can even go a step further and have a similar experience to Vue or React, where you can evaluate arbitrary code expressions:
Similar is possible with django-expr
, which adds an expr
tag and filter that you can use to evaluate Python expressions from within the template:
Note: Never use this feature to mix business logic and template logic. Business logic should still be in the view!
New in version 0.74:
Sometimes, a component may expect a dictionary as one of its inputs.
Most commonly, this happens when a component accepts a dictionary of HTML attributes (usually called attrs
) to pass to the underlying template.
In such cases, we may want to define some HTML attributes statically, and other dynamically. But for that, we need to define this dictionary on Python side:
@register("my_comp")
-class MyComp(Component):
- template = """
- {% component "other" attrs=attrs / %}
- """
-
- def get_context_data(self, some_id: str):
- attrs = {
- "class": "pa-4 flex",
- "data-some-id": some_id,
- "@click.stop": "onClickHandler",
- }
- return {"attrs": attrs}
-
But as you can see in the case above, the event handler @click.stop
and styling pa-4 flex
are disconnected from the template. If the component grew in size and we moved the HTML to a separate file, we would have hard time reasoning about the component's template.
Luckily, there's a better way.
When we want to pass a dictionary to a component, we can define individual key-value pairs as component kwargs, so we can keep all the relevant information in the template. For that, we prefix the key with the name of the dict and :
. So key class
of input attrs
becomes attrs:class
. And our example becomes:
You can simplify it with html_attrs
tag:
where attrs
is:
This feature is inspired by merge_attrs
tag of django-web-components and "fallthrough attributes" feature of Vue.
Attributes that are set to None
or False
are NOT rendered.
So given this input:
And template:
Then this renders:
In HTML, boolean attributes are usually rendered with no value. Consider the example below where the first button is disabled and the second is not:
HTML rendering with html_attrs
tag or attributes_to_string
works the same way, where key=True
is rendered simply as key
, and key=False
is not render at all.
So given this input:
And template:
Then this renders:
Sometimes you may want to specify default values for attributes. You can pass a second argument (or kwarg defaults
) to set the defaults.
In the example above, if attrs
contains e.g. the class
key, html_attrs
will render:
class="{{ attrs.class }}"
Otherwise, html_attrs
will render:
class="{{ defaults.class }}"
For the class
HTML attribute, it's common that we want to join multiple values, instead of overriding them. For example, if you're authoring a component, you may want to ensure that the component will ALWAYS have a specific class. Yet, you may want to allow users of your component to supply their own classes.
We can achieve this by adding extra kwargs. These values will be appended, instead of overwriting the previous value.
So if we have a variable attrs
:
And on html_attrs
tag, we set the key class
:
Then these will be merged and rendered as:
To simplify merging of variables, you can supply the same key multiple times, and these will be all joined together:
{# my_var = "class-from-var text-red" #}
+<div {% html_attrs attrs class="some-class another-class" class=my_var %}>
+</div>
+
Renders:
html_attrs
¤attrs
and defaults
can be passed as positional args{% html_attrs attrs defaults key=val %}
or as kwargs
{% html_attrs key=val defaults=defaults attrs=attrs %}
Both attrs
and defaults
are optional (can be omitted)
Both attrs
and defaults
are dictionaries, and we can define them the same way we define dictionaries for the component
tag. So either as attrs=attrs
or attrs:key=value
.
All other kwargs are appended and can be repeated.
html_attrs
¤Assuming that:
class_from_var = "from-var"
+
+attrs = {
+ "class": "from-attrs",
+ "type": "submit",
+}
+
+defaults = {
+ "class": "from-defaults",
+ "role": "button",
+}
+
Then:
{% html_attr %}
renders (empty string):
{% html_attr class="some-class" class=class_from_var data-id="123" %}
renders:
class="some-class from-var" data-id="123"
{% html_attr attrs %}
renders:
class="from-attrs" type="submit"
{% html_attr attrs=attrs %}
renders:
class="from-attrs" type="submit"
{% html_attr defaults=defaults %}
renders:
class="from-defaults" role="button"
prefix:key=value
construct {% html_attr attrs:class="from-attrs" attrs:type="submit" %}
renders:
class="from-attrs" type="submit"
prefix:key=value
construct {% html_attr defaults:class="from-defaults" %}
renders:
class="from-defaults" role="button"
{% html_attrs attrs defaults class="added_class" class=class_from_var data-id=123 %}
renders:
class="from-attrs added_class from-var" type="submit" role="button" data-id=123
{% html_attrs class="added_class" class=class_from_var data-id=123 attrs=attrs defaults=defaults %}
renders:
class="from-attrs added_class from-var" type="submit" role="button" data-id=123
{% html_attrs attrs defaults:class="default-class" class="added_class" class=class_from_var data-id=123 %}
renders:
class="from-attrs added_class from-var" type="submit" data-id=123
html_attrs
¤@register("my_comp")
+class MyComp(Component):
+ template: t.django_html = """
+ <div
+ {% html_attrs attrs
+ defaults:class="pa-4 text-red"
+ class="my-comp-date"
+ class=class_from_var
+ data-id="123"
+ %}
+ >
+ Today's date is <span>{{ date }}</span>
+ </div>
+ """
+
+ def get_context_data(self, date: Date, attrs: dict):
+ return {
+ "date": date,
+ "attrs": attrs,
+ "class_from_var": "extra-class"
+ }
+
+@register("parent")
+class Parent(Component):
+ template: t.django_html = """
+ {% component "my_comp"
+ date=date
+ attrs:class="pa-0 border-solid border-red"
+ attrs:data-json=json_data
+ attrs:@click="(e) => onClick(e, 'from_parent')"
+ / %}
+ """
+
+ def get_context_data(self, date: Date):
+ return {
+ "date": datetime.now(),
+ "json_data": json.dumps({"value": 456})
+ }
+
Note: For readability, we've split the tags across multiple lines.
Inside MyComp
, we defined a default attribute
defaults:class="pa-4 text-red"
So if attrs
includes key class
, the default above will be ignored.
MyComp
also defines class
key twice. It means that whether the class
attribute is taken from attrs
or defaults
, the two class
values will be appended to it.
So by default, MyComp
renders:
Next, let's consider what will be rendered when we call MyComp
from Parent
component.
MyComp
accepts a attrs
dictionary, that is passed to html_attrs
, so the contents of that dictionary are rendered as the HTML attributes.
In Parent
, we make use of passing dictionary key-value pairs as kwargs to define individual attributes as if they were regular kwargs.
So all kwargs that start with attrs:
will be collected into an attrs
dict.
attrs:class="pa-0 border-solid border-red"
+ attrs:data-json=json_data
+ attrs:@click="(e) => onClick(e, 'from_parent')"
+
And get_context_data
of MyComp
will receive attrs
input with following keys:
attrs = {
+ "class": "pa-0 border-solid",
+ "data-json": '{"value": 456}',
+ "@click": "(e) => onClick(e, 'from_parent')",
+}
+
attrs["class"]
overrides the default value for class
, whereas other keys will be merged.
So in the end MyComp
will render:
<div
+ class="pa-0 border-solid my-comp-date extra-class"
+ data-id="123"
+ data-json='{"value": 456}'
+ @click="(e) => onClick(e, 'from_parent')"
+>
+ ...
+</div>
+
If you need to use serialize HTML attributes outside of Django template and the html_attrs
tag, you can use attributes_to_string
:
from django_components.attributes import attributes_to_string
+
+attrs = {
+ "class": "my-class text-red pa-4",
+ "data-id": 123,
+ "required": True,
+ "disabled": False,
+ "ignored-attr": None,
+}
+
+attributes_to_string(attrs)
+# 'class="my-class text-red pa-4" data-id="123" required'
+
All template tags in django_component, like {% component %}
or {% slot %}
, and so on, support extra syntax that makes it possible to write components like in Vue or React (JSX).
When you have a tag like {% component %}
or {% slot %}
, but it has no content, you can simply append a forward slash /
at the end, instead of writing out the closing tags like {% endcomponent %}
or {% endslot %}
:
So this:
becomes
New in version 0.71:
Keyword arguments can contain special characters # @ . - _
, so keywords like so are still valid:
<body>
+ {% component "calendar" my-date="2015-06-19" @click.native=do_something #some_id=True / %}
+</body>
+
These can then be accessed inside get_context_data
so:
@register("calendar")
+class Calendar(Component):
+ # Since # . @ - are not valid identifiers, we have to
+ # use `**kwargs` so the method can accept these args.
+ def get_context_data(self, **kwargs):
+ return {
+ "date": kwargs["my-date"],
+ "id": kwargs["#some_id"],
+ "on_click": kwargs["@click.native"]
+ }
+
New in version 0.93:
Instead of passing keyword arguments one-by-one:
You can use a spread operator ...dict
to apply key-value pairs from a dictionary:
This behaves similar to JSX's spread operator or Vue's v-bind
.
Spread operators are treated as keyword arguments, which means that: 1. Spread operators must come after positional arguments. 2. You cannot use spread operators for positional-only arguments.
Other than that, you can use spread operators multiple times, and even put keyword arguments in-between or after them:
In a case of conflicts, the values added later (right-most) overwrite previous values.
New in version 0.93
When passing data around, sometimes you may need to do light transformations, like negating booleans or filtering lists.
Normally, what you would have to do is to define ALL the variables inside get_context_data()
. But this can get messy if your components contain a lot of logic.
@register("calendar")
+class Calendar(Component):
+ def get_context_data(self, id: str, editable: bool):
+ return {
+ "editable": editable,
+ "readonly": not editable,
+ "input_id": f"input-{id}",
+ "icon_id": f"icon-{id}",
+ ...
+ }
+
Instead, template tags in django_components ({% component %}
, {% slot %}
, {% provide %}
, etc) allow you to treat literal string values as templates:
{% component 'blog_post'
+ "As positional arg {# yay #}"
+ title="{{ person.first_name }} {{ person.last_name }}"
+ id="{% random_int 10 20 %}"
+ readonly="{{ editable|not }}"
+ author="John Wick {# TODO: parametrize #}"
+/ %}
+
In the example above: - Component test
receives a positional argument with value "As positional arg "
. The comment is omitted. - Kwarg title
is passed as a string, e.g. John Doe
- Kwarg id
is passed as int
, e.g. 15
- Kwarg readonly
is passed as bool
, e.g. False
- Kwarg author
is passed as a string, e.g. John Wick
(Comment omitted)
This is inspired by django-cotton.
Sometimes you may want to use the template tags to transform or generate the data that is then passed to the component.
The data doesn't necessarily have to be strings. In the example above, the kwarg id
was passed as an integer, NOT a string.
Although the string literals for components inputs are treated as regular Django templates, there is one special case:
When the string literal contains only a single template tag, with no extra text, then the value is passed as the original type instead of a string.
Here, page
is an integer:
Here, page
is a string:
And same applies to the {{ }}
variable tags:
Here, items
is a list:
Here, items
is a string:
You can even go a step further and have a similar experience to Vue or React, where you can evaluate arbitrary code expressions:
Similar is possible with django-expr
, which adds an expr
tag and filter that you can use to evaluate Python expressions from within the template:
Note: Never use this feature to mix business logic and template logic. Business logic should still be in the view!
New in version 0.74:
Sometimes, a component may expect a dictionary as one of its inputs.
Most commonly, this happens when a component accepts a dictionary of HTML attributes (usually called attrs
) to pass to the underlying template.
In such cases, we may want to define some HTML attributes statically, and other dynamically. But for that, we need to define this dictionary on Python side:
@register("my_comp")
class MyComp(Component):
template = """
- {% component "other"
- attrs:class="pa-4 flex"
- attrs:data-some-id=some_id
- attrs:@click.stop="onClickHandler"
- / %}
- """
-
- def get_context_data(self, some_id: str):
- return {"some_id": some_id}
-
Sweet! Now all the relevant HTML is inside the template, and we can move it to a separate file with confidence:
{% component "other"
- attrs:class="pa-4 flex"
- attrs:data-some-id=some_id
- attrs:@click.stop="onClickHandler"
-/ %}
-
Note: It is NOT possible to define nested dictionaries, so
attrs:my_key:two=2
would be interpreted as:
By default, Django expects a template tag to be defined on a single line.
However, this can become unwieldy if you have a component with a lot of inputs:
{% component "card" title="Joanne Arc" subtitle="Head of Kitty Relations" date_last_active="2024-09-03" ... %}
-
Instead, when you install django_components, it automatically configures Django to suport multi-line tags.
So we can rewrite the above as:
{% component "card"
- title="Joanne Arc"
- subtitle="Head of Kitty Relations"
- date_last_active="2024-09-03"
- ...
-%}
-
Much better!
To disable this behavior, set COMPONENTS.multiline_tag
to False
New in version 0.80:
Django components supports dependency injection with the combination of:
{% provide %}
taginject()
method of the Component
classProp drilling refers to a scenario in UI development where you need to pass data through many layers of a component tree to reach the nested components that actually need the data.
Normally, you'd use props to send data from a parent component to its children. However, this straightforward method becomes cumbersome and inefficient if the data has to travel through many levels or if several components scattered at different depths all need the same piece of information.
This results in a situation where the intermediate components, which don't need the data for their own functioning, end up having to manage and pass along these props. This clutters the component tree and makes the code verbose and harder to manage.
A neat solution to avoid prop drilling is using the "provide and inject" technique, AKA dependency injection.
With dependency injection, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.
This feature is inspired by Vue's Provide / Inject and React's Context / useContext.
As the name suggest, using provide / inject consists of 2 steps
For examples of advanced uses of provide / inject, see this discussion.
{% provide %}
tag¤First we use the {% provide %}
tag to define the data we want to "provide" (make available).
{% provide "my_data" key="hi" another=123 %}
- {% component "child" / %} <--- Can access "my_data"
-{% endprovide %}
-
-{% component "child" / %} <--- Cannot access "my_data"
-
Notice that the provide
tag REQUIRES a name as a first argument. This is the key by which we can then access the data passed to this tag.
provide
tag name must resolve to a valid identifier (AKA a valid Python variable name).
Once you've set the name, you define the data you want to "provide" by passing it as keyword arguments. This is similar to how you pass data to the {% with %}
tag.
NOTE: Kwargs passed to
{% provide %}
are NOT added to the context. In the example below, the{{ key }}
won't render anything:{% provide "my_data" key="hi" another=123 %} - {{ key }} + {% component "other" attrs=attrs / %} + """ + + def get_context_data(self, some_id: str): + attrs = { + "class": "pa-4 flex", + "data-some-id": some_id, + "@click.stop": "onClickHandler", + } + return {"attrs": attrs} +
But as you can see in the case above, the event handler
@click.stop
and stylingpa-4 flex
are disconnected from the template. If the component grew in size and we moved the HTML to a separate file, we would have hard time reasoning about the component's template.Luckily, there's a better way.
When we want to pass a dictionary to a component, we can define individual key-value pairs as component kwargs, so we can keep all the relevant information in the template. For that, we prefix the key with the name of the dict and
:
. So keyclass
of inputattrs
becomesattrs:class
. And our example becomes:@register("my_comp") +class MyComp(Component): + template = """ + {% component "other" + attrs:class="pa-4 flex" + attrs:data-some-id=some_id + attrs:@click.stop="onClickHandler" + / %} + """ + + def get_context_data(self, some_id: str): + return {"some_id": some_id} +
Sweet! Now all the relevant HTML is inside the template, and we can move it to a separate file with confidence:
{% component "other" + attrs:class="pa-4 flex" + attrs:data-some-id=some_id + attrs:@click.stop="onClickHandler" +/ %} +
Note: It is NOT possible to define nested dictionaries, so
attrs:my_key:two=2
would be interpreted as:Multi-line tags¤
By default, Django expects a template tag to be defined on a single line.
However, this can become unwieldy if you have a component with a lot of inputs:
{% component "card" title="Joanne Arc" subtitle="Head of Kitty Relations" date_last_active="2024-09-03" ... %} +
Instead, when you install django_components, it automatically configures Django to suport multi-line tags.
So we can rewrite the above as:
{% component "card" + title="Joanne Arc" + subtitle="Head of Kitty Relations" + date_last_active="2024-09-03" + ... +%} +
Much better!
To disable this behavior, set
COMPONENTS.multiline_tag
toFalse
Prop drilling and dependency injection (provide / inject)¤
New in version 0.80:
Django components supports dependency injection with the combination of:
{% provide %}
taginject()
method of theComponent
classWhat is "dependency injection" and "prop drilling"?¤
Prop drilling refers to a scenario in UI development where you need to pass data through many layers of a component tree to reach the nested components that actually need the data.
Normally, you'd use props to send data from a parent component to its children. However, this straightforward method becomes cumbersome and inefficient if the data has to travel through many levels or if several components scattered at different depths all need the same piece of information.
This results in a situation where the intermediate components, which don't need the data for their own functioning, end up having to manage and pass along these props. This clutters the component tree and makes the code verbose and harder to manage.
A neat solution to avoid prop drilling is using the "provide and inject" technique, AKA dependency injection.
With dependency injection, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.
This feature is inspired by Vue's Provide / Inject and React's Context / useContext.
How to use provide / inject¤
As the name suggest, using provide / inject consists of 2 steps
- Providing data
- Injecting provided data
For examples of advanced uses of provide / inject, see this discussion.
Using
{% provide %}
tag¤First we use the
{% provide %}
tag to define the data we want to "provide" (make available).
Similarly to slots and fills, also provide's name argument can be set dynamically via a variable, a template expression, or a spread operator:
inject()
method¤To "inject" (access) the data defined on the provide
tag, you can use the inject()
method inside of get_context_data()
.
For a component to be able to "inject" some data, the component ({% component %}
tag) must be nested inside the {% provide %}
tag.
In the example from previous section, we've defined two kwargs: key="hi" another=123
. That means that if we now inject "my_data"
, we get an object with 2 attributes - key
and another
.
class ChildComponent(Component):
- def get_context_data(self):
- my_data = self.inject("my_data")
- print(my_data.key) # hi
- print(my_data.another) # 123
- return {}
-
First argument to inject
is the key (or name) of the provided data. This must match the string that you used in the provide
tag. If no provider with given key is found, inject
raises a KeyError
.
To avoid the error, you can pass a second argument to inject
to which will act as a default value, similar to dict.get(key, default)
:
Notice that the provide
tag REQUIRES a name as a first argument. This is the key by which we can then access the data passed to this tag.
provide
tag name must resolve to a valid identifier (AKA a valid Python variable name).
Once you've set the name, you define the data you want to "provide" by passing it as keyword arguments. This is similar to how you pass data to the {% with %}
tag.
NOTE: Kwargs passed to
{% provide %}
are NOT added to the context. In the example below, the{{ key }}
won't render anything:
Similarly to slots and fills, also provide's name argument can be set dynamically via a variable, a template expression, or a spread operator:
inject()
method¤To "inject" (access) the data defined on the provide
tag, you can use the inject()
method inside of get_context_data()
.
For a component to be able to "inject" some data, the component ({% component %}
tag) must be nested inside the {% provide %}
tag.
In the example from previous section, we've defined two kwargs: key="hi" another=123
. That means that if we now inject "my_data"
, we get an object with 2 attributes - key
and another
.
class ChildComponent(Component):
def get_context_data(self):
- my_data = self.inject("invalid_key", DEFAULT_DATA)
- assert my_data == DEFAUKT_DATA
- return {}
-
The instance returned from inject()
is a subclass of NamedTuple
, so the instance is immutable. This ensures that the data returned from inject
will always have all the keys that were passed to the provide
tag.
NOTE:
inject()
works strictly only inget_context_data
. If you try to call it from elsewhere, it will raise an error.
@register("child")
-class ChildComponent(Component):
- template = """
- <div> {{ my_data.key }} </div>
- <div> {{ my_data.another }} </div>
- """
-
- def get_context_data(self):
- my_data = self.inject("my_data", "default")
- return {"my_data": my_data}
-
-template_str = """
- {% load component_tags %}
- {% provide "my_data" key="hi" another=123 %}
- {% component "child" / %}
- {% endprovide %}
-"""
-
renders:
New in version 0.96
Component hooks are functions that allow you to intercept the rendering process at specific positions.
on_render_before
def on_render_before(
- self: Component,
- context: Context,
- template: Template
-) -> None:
+ my_data = self.inject("my_data")
+ print(my_data.key) # hi
+ print(my_data.another) # 123
+ return {}
+
First argument to inject
is the key (or name) of the provided data. This must match the string that you used in the provide
tag. If no provider with given key is found, inject
raises a KeyError
.
To avoid the error, you can pass a second argument to inject
to which will act as a default value, similar to dict.get(key, default)
:
class ChildComponent(Component):
+ def get_context_data(self):
+ my_data = self.inject("invalid_key", DEFAULT_DATA)
+ assert my_data == DEFAUKT_DATA
+ return {}
+
The instance returned from inject()
is a subclass of NamedTuple
, so the instance is immutable. This ensures that the data returned from inject
will always have all the keys that were passed to the provide
tag.
NOTE:
inject()
works strictly only inget_context_data
. If you try to call it from elsewhere, it will raise an error.
@register("child")
+class ChildComponent(Component):
+ template = """
+ <div> {{ my_data.key }} </div>
+ <div> {{ my_data.another }} </div>
+ """
+
+ def get_context_data(self):
+ my_data = self.inject("my_data", "default")
+ return {"my_data": my_data}
+
+template_str = """
+ {% load component_tags %}
+ {% provide "my_data" key="hi" another=123 %}
+ {% component "child" / %}
+ {% endprovide %}
+"""
+
renders:
New in version 0.96
Component hooks are functions that allow you to intercept the rendering process at specific positions.
on_render_before
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template:
@@ -1033,12 +1041,12 @@ While `django_components.component_shorthand_formatter` al
# Append text into the Template
template.nodelist.append(TextNode("FROM_ON_BEFORE"))
```
-
on_render_after
def on_render_after(
- self: Component,
- context: Context,
- template: Template,
- content: str
-) -> None | str | SafeString:
+
on_render_after
def on_render_after(
+ self: Component,
+ context: Context,
+ template: Template,
+ content: str
+) -> None | str | SafeString:
Hook that runs just after the component's template was rendered.
It receives the rendered output as the last argument.
@@ -1052,60 +1060,60 @@ def on_render_after(self, context, template, content):
# Prepend text to the rendered content
return "Chocolate cookie recipe: " + content
```
-
You can use hooks together with provide / inject to create components that accept a list of items via a slot.
In the example below, each tab_item
component will be rendered on a separate tab page, but they are all defined in the default slot of the tabs
component.
{% component "tabs" %}
- {% component "tab_item" header="Tab 1" %}
- <p>
- hello from tab 1
- </p>
- {% component "button" %}
- Click me!
- {% endcomponent %}
- {% endcomponent %}
-
- {% component "tab_item" header="Tab 2" %}
- Hello this is tab 2
- {% endcomponent %}
-{% endcomponent %}
-
By default, context variables are passed down the template as in regular Django - deeper scopes can access the variables from the outer scopes. So if you have several nested forloops, then inside the deep-most loop you can access variables defined by all previous loops.
With this in mind, the {% component %}
tag behaves similarly to {% include %}
tag - inside the component tag, you can access all variables that were defined outside of it.
And just like with {% include %}
, if you don't want a specific component template to have access to the parent context, add only
to the {% component %}
tag:
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.
If you find yourself using the only
modifier often, you can set the context_behavior option to "isolated"
, which automatically applies the only
modifier. This is useful if you want to make sure that components don't accidentally access the outer context.
Components can also access the outer context in their context methods like get_context_data
by accessing the property self.outer_context
.
Assuming that the rendering context has variables such as date
, you can use self.outer_context
to access them from within get_context_data
. Here's how you might implement it:
class Calender(Component):
-
- ...
-
- def get_context_data(self):
- outer_field = self.outer_context["date"]
- return {
- "date": outer_fields,
- }
-
However, as a best practice, it’s recommended not to rely on accessing the outer context directly through self.outer_context
. Instead, explicitly pass the variables to the component. For instance, continue passing the variables in the component tag as shown in the previous examples.
Here is a list of all variables that are automatically available from within the component's template and on_render_before
/ on_render_after
hooks.
component_vars.is_filled
New in version 0.70
Dictonary describing which slots are filled (True
) or are not (False
).
Example:
New in version 0.89
By default, components are rendered using the pair of {% component %}
/ {% endcomponent %}
template tags:
{% component "button" href="..." disabled %}
-Click me!
-{% endcomponent %}
-
-{# or #}
-
-{% component "button" href="..." disabled / %}
-
You can change this behaviour in the settings under the COMPONENTS.tag_formatter
.
For example, if you set the tag formatter to django_components.component_shorthand_formatter
, the components will use their name as the template tags:
You can use hooks together with provide / inject to create components that accept a list of items via a slot.
In the example below, each tab_item
component will be rendered on a separate tab page, but they are all defined in the default slot of the tabs
component.
{% component "tabs" %}
+ {% component "tab_item" header="Tab 1" %}
+ <p>
+ hello from tab 1
+ </p>
+ {% component "button" %}
+ Click me!
+ {% endcomponent %}
+ {% endcomponent %}
+
+ {% component "tab_item" header="Tab 2" %}
+ Hello this is tab 2
+ {% endcomponent %}
+{% endcomponent %}
+
By default, context variables are passed down the template as in regular Django - deeper scopes can access the variables from the outer scopes. So if you have several nested forloops, then inside the deep-most loop you can access variables defined by all previous loops.
With this in mind, the {% component %}
tag behaves similarly to {% include %}
tag - inside the component tag, you can access all variables that were defined outside of it.
And just like with {% include %}
, if you don't want a specific component template to have access to the parent context, add only
to the {% component %}
tag:
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.
If you find yourself using the only
modifier often, you can set the context_behavior option to "isolated"
, which automatically applies the only
modifier. This is useful if you want to make sure that components don't accidentally access the outer context.
Components can also access the outer context in their context methods like get_context_data
by accessing the property self.outer_context
.
Assuming that the rendering context has variables such as date
, you can use self.outer_context
to access them from within get_context_data
. Here's how you might implement it:
class Calender(Component):
+
+ ...
+
+ def get_context_data(self):
+ outer_field = self.outer_context["date"]
+ return {
+ "date": outer_fields,
+ }
+
However, as a best practice, it’s recommended not to rely on accessing the outer context directly through self.outer_context
. Instead, explicitly pass the variables to the component. For instance, continue passing the variables in the component tag as shown in the previous examples.
Here is a list of all variables that are automatically available from within the component's template and on_render_before
/ on_render_after
hooks.
component_vars.is_filled
New in version 0.70
Dictonary describing which slots are filled (True
) or are not (False
).
Example:
New in version 0.89
By default, components are rendered using the pair of {% component %}
/ {% endcomponent %}
template tags:
{% component "button" href="..." disabled %}
+Click me!
+{% endcomponent %}
{# or #}
-{% button href="..." disabled / %}
-
django_components provides following predefined TagFormatters:
ComponentFormatter
(django_components.component_formatter
)
Default
Uses the component
and endcomponent
tags, and the component name is gives as the first positional argument.
Example as block:
{% component "button" href="..." %}
- {% fill "content" %}
- ...
- {% endfill %}
-{% endcomponent %}
-
Example as inlined tag:
ShorthandComponentFormatter
(django_components.component_shorthand_formatter
)
Uses the component name as start tag, and end<component_name>
as an end tag.
Example as block:
Example as inlined tag:
You can change this behaviour in the settings under the COMPONENTS.tag_formatter
.
For example, if you set the tag formatter to django_components.component_shorthand_formatter
, the components will use their name as the template tags:
{% button href="..." disabled %}
+ Click me!
+{% endbutton %}
+
+{# or #}
+
+{% button href="..." disabled / %}
+
django_components provides following predefined TagFormatters:
ComponentFormatter
(django_components.component_formatter
)
Default
Uses the component
and endcomponent
tags, and the component name is gives as the first positional argument.
Example as block:
{% component "button" href="..." %}
+ {% fill "content" %}
+ ...
+ {% endfill %}
+{% endcomponent %}
+
Example as inlined tag:
ShorthandComponentFormatter
(django_components.component_shorthand_formatter
)
Uses the component name as start tag, and end<component_name>
as an end tag.
Example as block:
Example as inlined tag:
First, let's discuss how TagFormatters work, and how components are rendered in django_components.
When you render a component with {% component %}
(or your own tag), the following happens: 1. component
must be registered as a Django's template tag 2. Django triggers django_components's tag handler for tag component
. 3. The tag handler passes the tag contents for pre-processing to TagFormatter.parse()
.
So if you render this:
```django
{% component "button" href="..." disabled %}
@@ -1116,467 +1124,467 @@ def on_render_after(self, context, template, content):
```py
["component", '"button"', 'href="..."', 'disabled']
```
-
TagFormatter
extracts the component name and the remaining input.
So, given the above, TagFormatter.parse()
returns the following:
TagFormatter
. So, continuing the example, at this point the tag handler practically behaves as if you rendered:
6. Tag handler looks up the componentbutton
, and passes the args, kwargs, and slots to it. TagFormatter
handles following parts of the process above: - Generates start/end tags, given a component. This is what you then call from within your template as {% component %}
.
{% component %}
, tag formatter pre-processes the tag contents, so it can link back the custom template tag to the right component.To do so, subclass from TagFormatterABC
and implement following method: - start_tag
- end_tag
- parse
For example, this is the implementation of ShorthandComponentFormatter
class ShorthandComponentFormatter(TagFormatterABC):
- # Given a component name, generate the start template tag
- def start_tag(self, name: str) -> str:
- return name # e.g. 'button'
-
- # Given a component name, generate the start template tag
- def end_tag(self, name: str) -> str:
- return f"end{name}" # e.g. 'endbutton'
-
- # Given a tag, e.g.
- # `{% button href="..." disabled %}`
- #
- # The parser receives:
- # `['button', 'href="..."', 'disabled']`
- def parse(self, tokens: List[str]) -> TagResult:
- tokens = [*tokens]
- name = tokens.pop(0)
- return TagResult(
- name, # e.g. 'button'
- tokens # e.g. ['href="..."', 'disabled']
- )
-
That's it! And once your TagFormatter
is ready, don't forget to update the settings!
django_component's management of files builds on top of Django's Media
class.
To be familiar with how Django handles static files, we recommend reading also:
As seen in the getting started example, to associate HTML/JS/CSS files with a component, you set them as template_name
, Media.js
and Media.css
respectively:
# In a file [project root]/components/calendar/calendar.py
-from django_components import Component, register
-
-@register("calendar")
-class Calendar(Component):
- template_name = "template.html"
-
- class Media:
- css = "style.css"
- js = "script.js"
-
In the example above, the files are defined relative to the directory where component.py
is.
Alternatively, you can specify the file paths relative to the directories set in COMPONENTS.dirs
or COMPONENTS.app_dirs
.
Assuming that COMPONENTS.dirs
contains path [project root]/components
, we can rewrite the example as:
TagFormatter
extracts the component name and the remaining input.
So, given the above, TagFormatter.parse()
returns the following:
TagFormatter
. So, continuing the example, at this point the tag handler practically behaves as if you rendered:
6. Tag handler looks up the componentbutton
, and passes the args, kwargs, and slots to it. TagFormatter
handles following parts of the process above: - Generates start/end tags, given a component. This is what you then call from within your template as {% component %}
.
{% component %}
, tag formatter pre-processes the tag contents, so it can link back the custom template tag to the right component.To do so, subclass from TagFormatterABC
and implement following method: - start_tag
- end_tag
- parse
For example, this is the implementation of ShorthandComponentFormatter
class ShorthandComponentFormatter(TagFormatterABC):
+ # Given a component name, generate the start template tag
+ def start_tag(self, name: str) -> str:
+ return name # e.g. 'button'
+
+ # Given a component name, generate the start template tag
+ def end_tag(self, name: str) -> str:
+ return f"end{name}" # e.g. 'endbutton'
+
+ # Given a tag, e.g.
+ # `{% button href="..." disabled %}`
+ #
+ # The parser receives:
+ # `['button', 'href="..."', 'disabled']`
+ def parse(self, tokens: List[str]) -> TagResult:
+ tokens = [*tokens]
+ name = tokens.pop(0)
+ return TagResult(
+ name, # e.g. 'button'
+ tokens # e.g. ['href="..."', 'disabled']
+ )
+
That's it! And once your TagFormatter
is ready, don't forget to update the settings!
django_component's management of files builds on top of Django's Media
class.
To be familiar with how Django handles static files, we recommend reading also:
As seen in the getting started example, to associate HTML/JS/CSS files with a component, you set them as template_name
, Media.js
and Media.css
respectively:
# In a file [project root]/components/calendar/calendar.py
from django_components import Component, register
@register("calendar")
class Calendar(Component):
- template_name = "calendar/template.html"
+ template_name = "template.html"
class Media:
- css = "calendar/style.css"
- js = "calendar/script.js"
-
NOTE: In case of conflict, the preference goes to resolving the files relative to the component's directory.
Each component can have only a single template. However, you can define as many JS or CSS files as you want using a list.
class MyComponent(Component):
- class Media:
- js = ["path/to/script1.js", "path/to/script2.js"]
- css = ["path/to/style1.css", "path/to/style2.css"]
-
You can define which stylesheets will be associated with which CSS Media types. You do so by defining CSS files as a dictionary.
See the corresponding Django Documentation.
Again, you can set either a single file or a list of files per media type:
In the example above, the files are defined relative to the directory where component.py
is.
Alternatively, you can specify the file paths relative to the directories set in COMPONENTS.dirs
or COMPONENTS.app_dirs
.
Assuming that COMPONENTS.dirs
contains path [project root]/components
, we can rewrite the example as:
# In a file [project root]/components/calendar/calendar.py
+from django_components import Component, register
+
+@register("calendar")
+class Calendar(Component):
+ template_name = "calendar/template.html"
+
+ class Media:
+ css = "calendar/style.css"
+ js = "calendar/script.js"
+
NOTE: In case of conflict, the preference goes to resolving the files relative to the component's directory.
Each component can have only a single template. However, you can define as many JS or CSS files as you want using a list.
class MyComponent(Component):
class Media:
- css = {
- "all": "path/to/style1.css",
- "print": "path/to/style2.css",
- }
-
class MyComponent(Component):
+ js = ["path/to/script1.js", "path/to/script2.js"]
+ css = ["path/to/style1.css", "path/to/style2.css"]
+
You can define which stylesheets will be associated with which CSS Media types. You do so by defining CSS files as a dictionary.
See the corresponding Django Documentation.
Again, you can set either a single file or a list of files per media type:
class MyComponent(Component):
class Media:
css = {
- "all": ["path/to/style1.css", "path/to/style2.css"],
- "print": ["path/to/style3.css", "path/to/style4.css"],
+ "all": "path/to/style1.css",
+ "print": "path/to/style2.css",
}
-
NOTE: When you define CSS as a string or a list, the all
media type is implied.
File paths can be any of:
str
bytes
PathLike
(__fspath__
method)SafeData
(__html__
method)Callable
that returns any of the above, evaluated at class creation (__new__
)from pathlib import Path
-
-from django.utils.safestring import mark_safe
-
-class SimpleComponent(Component):
- class Media:
- css = [
- mark_safe('<link href="/static/calendar/style.css" rel="stylesheet" />'),
- Path("calendar/style1.css"),
- "calendar/style2.css",
- b"calendar/style3.css",
- lambda: "calendar/style4.css",
- ]
- js = [
- mark_safe('<script src="/static/calendar/script.js"></script>'),
- Path("calendar/script1.js"),
- "calendar/script2.js",
- b"calendar/script3.js",
- lambda: "calendar/script4.js",
- ]
-
In the example above, you could see that when we used mark_safe
to mark a string as a SafeString
, we had to define the full <script>
/<link>
tag.
This is an extension of Django's Paths as objects feature, where "safe" strings are taken as is, and accessed only at render time.
Because of that, the paths defined as "safe" strings are NEVER resolved, neither relative to component's directory, nor relative to COMPONENTS.dirs
.
"Safe" strings can be used to lazily resolve a path, or to customize the <script>
or <link>
tag for individual paths:
class LazyJsPath:
- def __init__(self, static_path: str) -> None:
- self.static_path = static_path
+
class MyComponent(Component):
+ class Media:
+ css = {
+ "all": ["path/to/style1.css", "path/to/style2.css"],
+ "print": ["path/to/style3.css", "path/to/style4.css"],
+ }
+
NOTE: When you define CSS as a string or a list, the all
media type is implied.
File paths can be any of:
str
bytes
PathLike
(__fspath__
method)SafeData
(__html__
method)Callable
that returns any of the above, evaluated at class creation (__new__
)from pathlib import Path
+
+from django.utils.safestring import mark_safe
- def __html__(self):
- full_path = static(self.static_path)
- return format_html(
- f'<script type="module" src="{full_path}"></script>'
- )
-
-@register("calendar")
-class Calendar(Component):
- template_name = "calendar/template.html"
-
- def get_context_data(self, date):
- return {
- "date": date,
- }
-
- class Media:
- css = "calendar/style.css"
- js = [
- # <script> tag constructed by Media class
- "calendar/script1.js",
- # Custom <script> tag
- LazyJsPath("calendar/script2.js"),
- ]
-
media_class
¤Sometimes you may need to change how all CSS <link>
or JS <script>
tags are rendered for a given component. You can achieve this by providing your own subclass of Django's Media
class to component's media_class
attribute.
Normally, the JS and CSS paths are passed to Media
class, which decides how the paths are resolved and how the <link>
and <script>
tags are constructed.
To change how the tags are constructed, you can override the Media.render_js
and Media.render_css
methods:
from django.forms.widgets import Media
-from django_components import Component, register
-
-class MyMedia(Media):
- # Same as original Media.render_js, except
- # the `<script>` tag has also `type="module"`
- def render_js(self):
- tags = []
- for path in self._js:
- if hasattr(path, "__html__"):
- tag = path.__html__()
- else:
- tag = format_html(
- '<script type="module" src="{}"></script>',
- self.absolute_path(path)
- )
- return tags
-
-@register("calendar")
-class Calendar(Component):
- template_name = "calendar/template.html"
-
- class Media:
- css = "calendar/style.css"
- js = "calendar/script.js"
-
- # Override the behavior of Media class
- media_class = MyMedia
-
NOTE: The instance of the Media
class (or it's subclass) is available under Component.media
after the class creation (__new__
).
The JS and CSS files included in components are not automatically rendered. Instead, use the following tags to specify where to render the dependencies:
component_dependencies
- Renders both JS and CSScomponent_js_dependencies
- Renders only JScomponent_css_dependencies
- Reneders only CSSJS files are rendered as <script>
tags.
CSS files are rendered as <style>
tags.
ComponentDependencyMiddleware
¤ComponentDependencyMiddleware
is a Django middleware designed to manage and inject CSS/JS dependencies for rendered components dynamically. It ensures that only the necessary stylesheets and scripts are loaded in your HTML responses, based on the components used in your Django templates.
To set it up, add the middleware to your MIDDLEWARE
in settings.py:
MIDDLEWARE = [
- # ... other middleware classes ...
- 'django_components.middleware.ComponentDependencyMiddleware'
- # ... other middleware classes ...
-]
-
Then, enable RENDER_DEPENDENCIES
in setting.py:
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.
Here's overview of all available settings and their defaults:
COMPONENTS = {
- "autodiscover": True,
- "context_behavior": "django", # "django" | "isolated"
- "dirs": [BASE_DIR / "components"], # Root-level "components" dirs, e.g. `/path/to/proj/components/`
- "app_dirs": ["components"], # App-level "components" dirs, e.g. `[app]/components/`
- "dynamic_component_name": "dynamic",
- "libraries": [], # ["mysite.components.forms", ...]
- "multiline_tags": True,
- "reload_on_template_change": False,
- "static_files_allowed": [
- ".css",
- ".js",
- # Images
- ".apng", ".png", ".avif", ".gif", ".jpg",
- ".jpeg", ".jfif", ".pjpeg", ".pjp", ".svg",
- ".webp", ".bmp", ".ico", ".cur", ".tif", ".tiff",
- # Fonts
- ".eot", ".ttf", ".woff", ".otf", ".svg",
- ],
- "static_files_forbidden": [
- ".html", ".django", ".dj", ".tpl",
- # Python files
- ".py", ".pyc",
- ],
- "tag_formatter": "django_components.component_formatter",
- "template_cache_size": 128,
-}
-
libraries
- Load component modules¤Configure the locations 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.
COMPONENTS = {
- "libraries": [
- "mysite.components.forms",
- "mysite.components.buttons",
- "mysite.components.cards",
- ],
-}
-
Where mysite/components/forms.py
may look like this:
@register("form_simple")
-class FormSimple(Component):
- template = """
- <form>
- ...
- </form>
- """
-
-@register("form_other")
-class FormOther(Component):
- template = """
- <form>
- ...
- </form>
- """
-
In the rare cases when you need to manually trigger the import of libraries, you can use the import_libraries
function:
autodiscover
- Toggle 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.
dirs
¤Specify the directories that contain your components.
Directories must be full paths, same as with STATICFILES_DIRS.
These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as a separate file.
COMPONENTS = {
- "dirs": [BASE_DIR / "components"],
+class SimpleComponent(Component):
+ class Media:
+ css = [
+ mark_safe('<link href="/static/calendar/style.css" rel="stylesheet" />'),
+ Path("calendar/style1.css"),
+ "calendar/style2.css",
+ b"calendar/style3.css",
+ lambda: "calendar/style4.css",
+ ]
+ js = [
+ mark_safe('<script src="/static/calendar/script.js"></script>'),
+ Path("calendar/script1.js"),
+ "calendar/script2.js",
+ b"calendar/script3.js",
+ lambda: "calendar/script4.js",
+ ]
+
In the example above, you could see that when we used mark_safe
to mark a string as a SafeString
, we had to define the full <script>
/<link>
tag.
This is an extension of Django's Paths as objects feature, where "safe" strings are taken as is, and accessed only at render time.
Because of that, the paths defined as "safe" strings are NEVER resolved, neither relative to component's directory, nor relative to COMPONENTS.dirs
.
"Safe" strings can be used to lazily resolve a path, or to customize the <script>
or <link>
tag for individual paths:
class LazyJsPath:
+ def __init__(self, static_path: str) -> None:
+ self.static_path = static_path
+
+ def __html__(self):
+ full_path = static(self.static_path)
+ return format_html(
+ f'<script type="module" src="{full_path}"></script>'
+ )
+
+@register("calendar")
+class Calendar(Component):
+ template_name = "calendar/template.html"
+
+ def get_context_data(self, date):
+ return {
+ "date": date,
+ }
+
+ class Media:
+ css = "calendar/style.css"
+ js = [
+ # <script> tag constructed by Media class
+ "calendar/script1.js",
+ # Custom <script> tag
+ LazyJsPath("calendar/script2.js"),
+ ]
+
media_class
¤Sometimes you may need to change how all CSS <link>
or JS <script>
tags are rendered for a given component. You can achieve this by providing your own subclass of Django's Media
class to component's media_class
attribute.
Normally, the JS and CSS paths are passed to Media
class, which decides how the paths are resolved and how the <link>
and <script>
tags are constructed.
To change how the tags are constructed, you can override the Media.render_js
and Media.render_css
methods:
from django.forms.widgets import Media
+from django_components import Component, register
+
+class MyMedia(Media):
+ # Same as original Media.render_js, except
+ # the `<script>` tag has also `type="module"`
+ def render_js(self):
+ tags = []
+ for path in self._js:
+ if hasattr(path, "__html__"):
+ tag = path.__html__()
+ else:
+ tag = format_html(
+ '<script type="module" src="{}"></script>',
+ self.absolute_path(path)
+ )
+ return tags
+
+@register("calendar")
+class Calendar(Component):
+ template_name = "calendar/template.html"
+
+ class Media:
+ css = "calendar/style.css"
+ js = "calendar/script.js"
+
+ # Override the behavior of Media class
+ media_class = MyMedia
+
NOTE: The instance of the Media
class (or it's subclass) is available under Component.media
after the class creation (__new__
).
The JS and CSS files included in components are not automatically rendered. Instead, use the following tags to specify where to render the dependencies:
component_dependencies
- Renders both JS and CSScomponent_js_dependencies
- Renders only JScomponent_css_dependencies
- Reneders only CSSJS files are rendered as <script>
tags.
CSS files are rendered as <style>
tags.
ComponentDependencyMiddleware
¤ComponentDependencyMiddleware
is a Django middleware designed to manage and inject CSS/JS dependencies for rendered components dynamically. It ensures that only the necessary stylesheets and scripts are loaded in your HTML responses, based on the components used in your Django templates.
To set it up, add the middleware to your MIDDLEWARE
in settings.py:
MIDDLEWARE = [
+ # ... other middleware classes ...
+ 'django_components.middleware.ComponentDependencyMiddleware'
+ # ... other middleware classes ...
+]
+
Then, enable RENDER_DEPENDENCIES
in setting.py:
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.
Here's overview of all available settings and their defaults:
COMPONENTS = {
+ "autodiscover": True,
+ "context_behavior": "django", # "django" | "isolated"
+ "dirs": [BASE_DIR / "components"], # Root-level "components" dirs, e.g. `/path/to/proj/components/`
+ "app_dirs": ["components"], # App-level "components" dirs, e.g. `[app]/components/`
+ "dynamic_component_name": "dynamic",
+ "libraries": [], # ["mysite.components.forms", ...]
+ "multiline_tags": True,
+ "reload_on_template_change": False,
+ "static_files_allowed": [
+ ".css",
+ ".js",
+ # Images
+ ".apng", ".png", ".avif", ".gif", ".jpg",
+ ".jpeg", ".jfif", ".pjpeg", ".pjp", ".svg",
+ ".webp", ".bmp", ".ico", ".cur", ".tif", ".tiff",
+ # Fonts
+ ".eot", ".ttf", ".woff", ".otf", ".svg",
+ ],
+ "static_files_forbidden": [
+ ".html", ".django", ".dj", ".tpl",
+ # Python files
+ ".py", ".pyc",
+ ],
+ "tag_formatter": "django_components.component_formatter",
+ "template_cache_size": 128,
+}
+
libraries
- Load component modules¤Configure the locations 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.
COMPONENTS = {
+ "libraries": [
+ "mysite.components.forms",
+ "mysite.components.buttons",
+ "mysite.components.cards",
+ ],
+}
+
Where mysite/components/forms.py
may look like this:
@register("form_simple")
+class FormSimple(Component):
+ template = """
+ <form>
+ ...
+ </form>
+ """
+
+@register("form_other")
+class FormOther(Component):
+ template = """
+ <form>
+ ...
+ </form>
+ """
+
In the rare cases when you need to manually trigger the import of libraries, you can use the import_libraries
function:
autodiscover
- Toggle 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.
app_dirs
¤Specify the app-level directories that contain your components.
Directories must be relative to app, e.g.:
dirs
¤Specify the directories that contain your components.
Directories must be full paths, same as with STATICFILES_DIRS.
These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as a separate file.
These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as a separate file.
Each app will be searched for these directories.
Set to empty list to disable app-level components:
app_dirs
¤Specify the app-level directories that contain your components.
Directories must be relative to app, e.g.:
dynamic_component_name
¤By default, the dynamic component is registered under the name "dynamic"
. In case of a conflict, use this setting to change the name used for the dynamic components.
These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as a separate file.
Each app will be searched for these directories.
Set to empty list to disable app-level components:
multiline_tags
- Enable/Disable multiline support¤If True
, template tags can span multiple lines. Default: True
dynamic_component_name
¤By default, the dynamic component is registered under the name "dynamic"
. In case of a conflict, use this setting to change the name used for the dynamic components.
static_files_allowed
¤A list of regex patterns (as strings) that define which files within COMPONENTS.dirs
and COMPONENTS.app_dirs
are treated as static files.
If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running collectstatic
, and can be accessed under the static file endpoint.
You can also pass in compiled regexes (re.Pattern
) for more advanced patterns.
By default, JS, CSS, and common image and font file formats are considered static files:
COMPONENTS = {
- "static_files_allowed": [
- "css",
- "js",
- # Images
- ".apng", ".png",
- ".avif",
- ".gif",
- ".jpg", ".jpeg", ".jfif", ".pjpeg", ".pjp", # JPEG
- ".svg",
- ".webp", ".bmp",
- ".ico", ".cur", # ICO
- ".tif", ".tiff",
- # Fonts
- ".eot", ".ttf", ".woff", ".otf", ".svg",
- ],
-}
-
static_files_forbidden
¤A list of suffixes that define which files within COMPONENTS.dirs
and COMPONENTS.app_dirs
will NEVER be treated as static files.
If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in COMPONENTS.static_files_allowed
.
Use this setting together with COMPONENTS.static_files_allowed
for a fine control over what files will be exposed.
You can also pass in compiled regexes (re.Pattern
) for more advanced patterns.
By default, any HTML and Python are considered NOT static files:
COMPONENTS = {
- "static_files_forbidden": [
- ".html", ".django", ".dj", ".tpl", ".py", ".pyc",
- ],
-}
-
template_cache_size
- 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
.
If you want add templates to the cache yourself, you can use cached_template()
:
from django_components import cached_template
-
-cached_template("Variable: {{ variable }}")
-
-# You can optionally specify Template class, and other Template inputs:
-class MyTemplate(Template):
- pass
-
-cached_template(
- "Variable: {{ variable }}",
- template_cls=MyTemplate,
- name=...
- origin=...
- engine=...
-)
-
context_behavior
- Make components isolated (or not)¤NOTE:
context_behavior
andslot_context_behavior
options were merged in v0.70.If you are migrating from BEFORE v0.67, set
context_behavior
to"django"
. From v0.67 to v0.78 (incl) the default value was"isolated"
.For v0.79 and later, the default is again
"django"
. See the rationale for change here.
You can configure what variables are available inside the {% fill %}
tags. See Component context and scope.
This has two modes:
"django"
- Default - The default Django template behavior.Inside the {% fill %}
tag, the context variables you can access are a union of:
Data returned from get_context_data()
of the component that wraps the fill tag.
"isolated"
- Similar behavior to Vue or React, this is useful if you want to make sure that components don't accidentally access variables defined outside of the component.
Inside the {% fill %}
tag, you can ONLY access variables from 2 places:
get_context_data()
of the component which defined the template (AKA the "root" component){% for ... %}
) that the {% fill %}
tag is part of.Given this template:
class RootComp(Component):
- template = """
- {% with cheese="feta" %}
- {% component 'my_comp' %}
- {{ my_var }} # my_var
- {{ cheese }} # cheese
- {% endcomponent %}
- {% endwith %}
- """
- def get_context_data(self):
- return { "my_var": 123 }
-
Then if get_context_data()
of the component "my_comp"
returns following data:
Then the template will be rendered as:
Because "my_comp"
overshadows the variable "my_var"
, so {{ my_var }}
equals 456
.
And variable "cheese"
equals feta
, because the fill CAN access all the data defined in the outer layers, like the {% with %}
tag.
Given this template:
class RootComp(Component):
- template = """
- {% with cheese="feta" %}
- {% component 'my_comp' %}
- {{ my_var }} # my_var
- {{ cheese }} # cheese
- {% endcomponent %}
- {% endwith %}
- """
- def get_context_data(self):
- return { "my_var": 123 }
-
Then if get_context_data()
of the component "my_comp"
returns following data:
Then the template will be rendered as:
Because variables "my_var"
and "cheese"
are searched only inside RootComponent.get_context_data()
. But since "cheese"
is not defined there, it's empty.
Notice that the variables defined with the {% with %}
tag are ignored inside the {% fill %}
tag with the "isolated"
mode.
reload_on_template_change
- Reload dev server on component file changes¤If True
, configures Django to reload on component files. See Reload dev server on component file changes.
NOTE: This setting should be enabled only for the dev environment!
tag_formatter
- Change how components are used in templates¤Sets the TagFormatter
instance. See the section Customizing component tags with TagFormatter.
Can be set either as direct reference, or as an import string;
Or
from django_components import component_formatter
-
-COMPONENTS = {
- "tag_formatter": component_formatter
-}
-
This is relevant if you are using the project structure as shown in our examples, where HTML, JS, CSS and Python are separate and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change comoponent files.
From relevant StackOverflow thread:
TL;DR is that the server won't reload if it thinks the changed file is in a templates directory, or in a nested sub directory of a templates directory. This is by design.
To make the dev server reload on all component files, set reload_on_template_change
to True
. This configures Django to watch for component files too.
NOTE: This setting should be enabled only for the dev environment!
Django components supports logging with Django. This can help with troubleshooting.
To configure logging for Django components, set the django_components
logger in LOGGING
in settings.py
(below).
Also see the settings.py
file in sampleproject for a real-life example.
import logging
-import sys
-
-LOGGING = {
- 'version': 1,
- 'disable_existing_loggers': False,
- "handlers": {
- "console": {
- 'class': 'logging.StreamHandler',
- 'stream': sys.stdout,
- },
- },
- "loggers": {
- "django_components": {
- "level": logging.DEBUG,
- "handlers": ["console"],
- },
- },
-}
-
You can use the built-in management command startcomponent
to create a django component. The command accepts the following arguments and options:
name
: The name of the component to create. This is a required argument.
--path
: The path to the components directory. This is an optional argument. If not provided, the command will use the BASE_DIR
setting from your Django settings.
--js
: The name of the JavaScript file. This is an optional argument. The default value is script.js
.
--css
: The name of the CSS file. This is an optional argument. The default value is style.css
.
--template
: The name of the template file. This is an optional argument. The default value is template.html
.
--force
: This option allows you to overwrite existing files if they exist. This is an optional argument.
--verbose
: This option allows the command to print additional information during component creation. This is an optional argument.
--dry-run
: This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False
.
To use the command, run the following command in your terminal:
python manage.py startcomponent <name> --path <path> --js <js_filename> --css <css_filename> --template <template_filename> --force --verbose --dry-run
-
Replace <name>
, <path>
, <js_filename>
, <css_filename>
, and <template_filename>
with your desired values.
Here are some examples of how you can use the command:
To create a component with the default settings, you only need to provide the name of the component:
This will create a new component named my_component
in the components
directory of your Django project. The JavaScript, CSS, and template files will be named script.js
, style.css
, and template.html
, respectively.
You can also create a component with custom settings by providing additional arguments:
python manage.py startcomponent new_component --path my_components --js my_script.js --css my_style.css --template my_template.html
-
This will create a new component named new_component
in the my_components
directory. The JavaScript, CSS, and template files will be named my_script.js
, my_style.css
, and my_template.html
, respectively.
If you want to overwrite an existing component, you can use the --force
option:
This will overwrite the existing my_component
if it exists.
If you want to simulate the creation of a component without actually creating any files, you can use the --dry-run
option:
This will simulate the creation of my_component
without creating any files.
You can publish and share your components for others to use. Here are the steps to do so:
Create a Django project with the following structure:
Create custom Library
and ComponentRegistry
instances in mytags.py
This will be the entrypoint for using the components inside Django templates.
Remember that Django requires the Library
instance to be accessible under the register
variable (See Django docs):
from django.template import Library
-from django_components import ComponentRegistry, RegistrySettings
-
-register = library = django.template.Library()
-comp_registry = ComponentRegistry(
- library=library,
- settings=RegistrySettings(
- CONTEXT_BEHAVIOR="isolated",
- TAG_FORMATTER="django_components.component_formatter",
- ),
-)
-
As you can see above, this is also the place where we configure how our components should behave, using the settings
argument. If omitted, default settings are used.
For library authors, we recommend setting CONTEXT_BEHAVIOR
to "isolated"
, so that the state cannot leak into the components, and so the components' behavior is configured solely through the inputs. This means that the components will be more predictable and easier to debug.
Next, you can decide how will others use your components by settingt the TAG_FORMATTER
options.
If omitted or set to "django_components.component_formatter"
, your components will be used like this:
Or you can use "django_components.component_shorthand_formatter"
to use components like so:
Or you can define a custom TagFormatter.
Either way, these settings will be scoped only to your components. So, in the user code, there may be components side-by-side that use different formatters:
Write your components and register them with your instance of ComponentRegistry
There's one difference when you are writing components that are to be shared, and that's that the components must be explicitly registered with your instance of ComponentRegistry
from the previous step.
For better user experience, you can also define the types for the args, kwargs, slots and data.
It's also a good idea to have a common prefix for your components, so they can be easily distinguished from users' components. In the example below, we use the prefix my_
/ My
.
multiline_tags
- Enable/Disable multiline support¤If True
, template tags can span multiple lines. Default: True
static_files_allowed
¤A list of regex patterns (as strings) that define which files within COMPONENTS.dirs
and COMPONENTS.app_dirs
are treated as static files.
If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running collectstatic
, and can be accessed under the static file endpoint.
You can also pass in compiled regexes (re.Pattern
) for more advanced patterns.
By default, JS, CSS, and common image and font file formats are considered static files:
COMPONENTS = {
+ "static_files_allowed": [
+ "css",
+ "js",
+ # Images
+ ".apng", ".png",
+ ".avif",
+ ".gif",
+ ".jpg", ".jpeg", ".jfif", ".pjpeg", ".pjp", # JPEG
+ ".svg",
+ ".webp", ".bmp",
+ ".ico", ".cur", # ICO
+ ".tif", ".tiff",
+ # Fonts
+ ".eot", ".ttf", ".woff", ".otf", ".svg",
+ ],
+}
+
static_files_forbidden
¤A list of suffixes that define which files within COMPONENTS.dirs
and COMPONENTS.app_dirs
will NEVER be treated as static files.
If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in COMPONENTS.static_files_allowed
.
Use this setting together with COMPONENTS.static_files_allowed
for a fine control over what files will be exposed.
You can also pass in compiled regexes (re.Pattern
) for more advanced patterns.
By default, any HTML and Python are considered NOT static files:
COMPONENTS = {
+ "static_files_forbidden": [
+ ".html", ".django", ".dj", ".tpl", ".py", ".pyc",
+ ],
+}
+
template_cache_size
- 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
.
If you want add templates to the cache yourself, you can use cached_template()
:
from django_components import cached_template
+
+cached_template("Variable: {{ variable }}")
+
+# You can optionally specify Template class, and other Template inputs:
+class MyTemplate(Template):
+ pass
+
+cached_template(
+ "Variable: {{ variable }}",
+ template_cls=MyTemplate,
+ name=...
+ origin=...
+ engine=...
+)
+
context_behavior
- Make components isolated (or not)¤NOTE:
context_behavior
andslot_context_behavior
options were merged in v0.70.If you are migrating from BEFORE v0.67, set
context_behavior
to"django"
. From v0.67 to v0.78 (incl) the default value was"isolated"
.For v0.79 and later, the default is again
"django"
. See the rationale for change here.
You can configure what variables are available inside the {% fill %}
tags. See Component context and scope.
This has two modes:
"django"
- Default - The default Django template behavior.Inside the {% fill %}
tag, the context variables you can access are a union of:
Data returned from get_context_data()
of the component that wraps the fill tag.
"isolated"
- Similar behavior to Vue or React, this is useful if you want to make sure that components don't accidentally access variables defined outside of the component.
Inside the {% fill %}
tag, you can ONLY access variables from 2 places:
get_context_data()
of the component which defined the template (AKA the "root" component){% for ... %}
) that the {% fill %}
tag is part of.Given this template:
class RootComp(Component):
+ template = """
+ {% with cheese="feta" %}
+ {% component 'my_comp' %}
+ {{ my_var }} # my_var
+ {{ cheese }} # cheese
+ {% endcomponent %}
+ {% endwith %}
+ """
+ def get_context_data(self):
+ return { "my_var": 123 }
+
Then if get_context_data()
of the component "my_comp"
returns following data:
Then the template will be rendered as:
Because "my_comp"
overshadows the variable "my_var"
, so {{ my_var }}
equals 456
.
And variable "cheese"
equals feta
, because the fill CAN access all the data defined in the outer layers, like the {% with %}
tag.
Given this template:
class RootComp(Component):
+ template = """
+ {% with cheese="feta" %}
+ {% component 'my_comp' %}
+ {{ my_var }} # my_var
+ {{ cheese }} # cheese
+ {% endcomponent %}
+ {% endwith %}
+ """
+ def get_context_data(self):
+ return { "my_var": 123 }
+
Then if get_context_data()
of the component "my_comp"
returns following data:
Then the template will be rendered as:
Because variables "my_var"
and "cheese"
are searched only inside RootComponent.get_context_data()
. But since "cheese"
is not defined there, it's empty.
Notice that the variables defined with the {% with %}
tag are ignored inside the {% fill %}
tag with the "isolated"
mode.
reload_on_template_change
- Reload dev server on component file changes¤If True
, configures Django to reload on component files. See Reload dev server on component file changes.
NOTE: This setting should be enabled only for the dev environment!
tag_formatter
- Change how components are used in templates¤Sets the TagFormatter
instance. See the section Customizing component tags with TagFormatter.
Can be set either as direct reference, or as an import string;
Or
from django_components import component_formatter
+
+COMPONENTS = {
+ "tag_formatter": component_formatter
+}
+
This is relevant if you are using the project structure as shown in our examples, where HTML, JS, CSS and Python are separate and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change comoponent files.
From relevant StackOverflow thread:
TL;DR is that the server won't reload if it thinks the changed file is in a templates directory, or in a nested sub directory of a templates directory. This is by design.
To make the dev server reload on all component files, set reload_on_template_change
to True
. This configures Django to watch for component files too.
NOTE: This setting should be enabled only for the dev environment!
Django components supports logging with Django. This can help with troubleshooting.
To configure logging for Django components, set the django_components
logger in LOGGING
in settings.py
(below).
Also see the settings.py
file in sampleproject for a real-life example.
import logging
+import sys
+
+LOGGING = {
+ 'version': 1,
+ 'disable_existing_loggers': False,
+ "handlers": {
+ "console": {
+ 'class': 'logging.StreamHandler',
+ 'stream': sys.stdout,
+ },
+ },
+ "loggers": {
+ "django_components": {
+ "level": logging.DEBUG,
+ "handlers": ["console"],
+ },
+ },
+}
+
You can use the built-in management command startcomponent
to create a django component. The command accepts the following arguments and options:
name
: The name of the component to create. This is a required argument.
--path
: The path to the components directory. This is an optional argument. If not provided, the command will use the BASE_DIR
setting from your Django settings.
--js
: The name of the JavaScript file. This is an optional argument. The default value is script.js
.
--css
: The name of the CSS file. This is an optional argument. The default value is style.css
.
--template
: The name of the template file. This is an optional argument. The default value is template.html
.
--force
: This option allows you to overwrite existing files if they exist. This is an optional argument.
--verbose
: This option allows the command to print additional information during component creation. This is an optional argument.
--dry-run
: This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False
.
To use the command, run the following command in your terminal:
python manage.py startcomponent <name> --path <path> --js <js_filename> --css <css_filename> --template <template_filename> --force --verbose --dry-run
+
Replace <name>
, <path>
, <js_filename>
, <css_filename>
, and <template_filename>
with your desired values.
Here are some examples of how you can use the command:
To create a component with the default settings, you only need to provide the name of the component:
This will create a new component named my_component
in the components
directory of your Django project. The JavaScript, CSS, and template files will be named script.js
, style.css
, and template.html
, respectively.
You can also create a component with custom settings by providing additional arguments:
python manage.py startcomponent new_component --path my_components --js my_script.js --css my_style.css --template my_template.html
+
This will create a new component named new_component
in the my_components
directory. The JavaScript, CSS, and template files will be named my_script.js
, my_style.css
, and my_template.html
, respectively.
If you want to overwrite an existing component, you can use the --force
option:
This will overwrite the existing my_component
if it exists.
If you want to simulate the creation of a component without actually creating any files, you can use the --dry-run
option:
This will simulate the creation of my_component
without creating any files.
You can publish and share your components for others to use. Here are the steps to do so:
Create a Django project with the following structure:
Create custom Library
and ComponentRegistry
instances in mytags.py
This will be the entrypoint for using the components inside Django templates.
Remember that Django requires the Library
instance to be accessible under the register
variable (See Django docs):
from django.template import Library
+from django_components import ComponentRegistry, RegistrySettings
+
+register = library = django.template.Library()
+comp_registry = ComponentRegistry(
+ library=library,
+ settings=RegistrySettings(
+ CONTEXT_BEHAVIOR="isolated",
+ TAG_FORMATTER="django_components.component_formatter",
+ ),
+)
+
As you can see above, this is also the place where we configure how our components should behave, using the settings
argument. If omitted, default settings are used.
For library authors, we recommend setting CONTEXT_BEHAVIOR
to "isolated"
, so that the state cannot leak into the components, and so the components' behavior is configured solely through the inputs. This means that the components will be more predictable and easier to debug.
Next, you can decide how will others use your components by settingt the TAG_FORMATTER
options.
If omitted or set to "django_components.component_formatter"
, your components will be used like this:
Or you can use "django_components.component_shorthand_formatter"
to use components like so:
Or you can define a custom TagFormatter.
Either way, these settings will be scoped only to your components. So, in the user code, there may be components side-by-side that use different formatters:
{% load mytags %}
-from django_components import Component, SlotFunc, register, types
-
-from myapp.templatetags.mytags import comp_registry
+{# Component from your library "mytags", using the "shorthand" formatter #}
+{% table items=items headers=header %}
+{% endtable %}
-# Define the types
-class EmptyDict(TypedDict):
- pass
-
-type MyMenuArgs = Tuple[int, str]
-
-class MyMenuSlots(TypedDict):
- default: NotRequired[Optional[SlotFunc[EmptyDict]]]
-
-class MyMenuProps(TypedDict):
- vertical: NotRequired[bool]
- klass: NotRequired[str]
- style: NotRequired[str]
-
-# Define the component
-# NOTE: Don't forget to set the `registry`!
-@register("my_menu", registry=comp_registry)
-class MyMenu(Component[MyMenuArgs, MyMenuProps, MyMenuSlots, Any]):
- def get_context_data(
- self,
- *args,
- attrs: Optional[Dict] = None,
- ):
- return {
- "attrs": attrs,
- }
-
- template: types.django_html = """
- {# Load django_components template tags #}
- {% load component_tags %}
-
- <div {% html_attrs attrs class="my-menu" %}>
- <div class="my-menu__content">
- {% slot "default" default / %}
- </div>
- </div>
- """
-
Import the components in apps.py
Normally, users rely on autodiscovery and COMPONENTS.dirs
to load the component files.
Since you, as the library author, are not in control of the file system, it is recommended to load the components manually.
We recommend doing this in the AppConfig.ready()
hook of your apps.py
:
Write your components and register them with your instance of ComponentRegistry
There's one difference when you are writing components that are to be shared, and that's that the components must be explicitly registered with your instance of ComponentRegistry
from the previous step.
For better user experience, you can also define the types for the args, kwargs, slots and data.
It's also a good idea to have a common prefix for your components, so they can be easily distinguished from users' components. In the example below, we use the prefix my_
/ My
.
from typing import Dict, NotRequired, Optional, Tuple, TypedDict
-class MyAppConfig(AppConfig):
- default_auto_field = "django.db.models.BigAutoField"
- name = "myapp"
+from django_components import Component, SlotFunc, register, types
+
+from myapp.templatetags.mytags import comp_registry
- # This is the code that gets run when user adds myapp
- # to Django's INSTALLED_APPS
- def ready(self) -> None:
- # Import the components that you want to make available
- # inside the templates.
- from myapp.templates import (
- menu,
- table,
- )
-
Note that you can also include any other startup logic within AppConfig.ready()
.
And that's it! The next step is to publish it.
Once you are ready to share your library, you need to build a distribution and then publish it to PyPI.
django_components uses the build
utility to build a distribution:
And to publish to PyPI, you can use twine
(See Python user guide)
Notes on publishing: - The user of the package NEEDS to have installed and configured django_components
. - If you use components where the HTML / CSS / JS files are separate, you may need to define MANIFEST.in
to include those files with the distribution (see user guide).
After the package has been published, all that remains is to install it in other django projects:
Install the package:
Add the package to INSTALLED_APPS
Optionally add the template tags to the builtins
, so you don't have to call {% load mytags %}
in every template:
And, at last, you can use the components in your own project!
One of our goals with django-components
is to make it easy to share components between projects. If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.
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:
To quickly run the tests install the local dependencies by running:
Now you can run the tests to make sure everything works as expected:
The library is also tested across many versions of Python and Django. To run tests that way:
pyenv install -s 3.8
-pyenv install -s 3.9
-pyenv install -s 3.10
-pyenv install -s 3.11
-pyenv install -s 3.12
-pyenv local 3.8 3.9 3.10 3.11 3.12
-tox -p
-
We use Playwright for end-to-end tests. You will therefore need to install Playwright to be able to run these tests.
Luckily, Playwright makes it very easy:
After Playwright is ready, simply run the tests with tox
:
How do you check that your changes to django-components project will work in an actual Django project?
Use the sampleproject demo project to validate the changes:
NOTE: The path (in this case ..
) must point to the directory that has the setup.py
file.
Once the server is up, it should be available at http://127.0.0.1:8000.
To display individual components, add them to the urls.py
, like in the case of http://127.0.0.1:8000/greeting
django_components uses a bit of JS code to: - Manage the loading of JS and CSS files used by the components - Allow to pass data from Python to JS
When you make changes to this JS code, you also need to compile it:
src/django_components_js
:The script will combine all JS/TS code into a single .js
file, minify it, and copy it to django_components/static/django_components/django_components.min.js
.
To package the library into a distribution that can be published to PyPI, run:
# Install pypa/build
-python -m pip install build --user
-# Build a binary wheel and a source tarball
-python -m build --sdist --wheel --outdir dist/ .
-
To publish the package to PyPI, use twine
(See Python user guide):
twine upload --repository pypi dist/* -u __token__ -p <PyPI_TOKEN>
+# Define the types
+class EmptyDict(TypedDict):
+ pass
+
+type MyMenuArgs = Tuple[int, str]
+
+class MyMenuSlots(TypedDict):
+ default: NotRequired[Optional[SlotFunc[EmptyDict]]]
+
+class MyMenuProps(TypedDict):
+ vertical: NotRequired[bool]
+ klass: NotRequired[str]
+ style: NotRequired[str]
+
+# Define the component
+# NOTE: Don't forget to set the `registry`!
+@register("my_menu", registry=comp_registry)
+class MyMenu(Component[MyMenuArgs, MyMenuProps, MyMenuSlots, Any]):
+ def get_context_data(
+ self,
+ *args,
+ attrs: Optional[Dict] = None,
+ ):
+ return {
+ "attrs": attrs,
+ }
+
+ template: types.django_html = """
+ {# Load django_components template tags #}
+ {% load component_tags %}
+
+ <div {% html_attrs attrs class="my-menu" %}>
+ <div class="my-menu__content">
+ {% slot "default" default / %}
+ </div>
+ </div>
+ """
+
Import the components in apps.py
Normally, users rely on autodiscovery and COMPONENTS.dirs
to load the component files.
Since you, as the library author, are not in control of the file system, it is recommended to load the components manually.
We recommend doing this in the AppConfig.ready()
hook of your apps.py
:
from django.apps import AppConfig
+
+class MyAppConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "myapp"
+
+ # This is the code that gets run when user adds myapp
+ # to Django's INSTALLED_APPS
+ def ready(self) -> None:
+ # Import the components that you want to make available
+ # inside the templates.
+ from myapp.templates import (
+ menu,
+ table,
+ )
+
Note that you can also include any other startup logic within AppConfig.ready()
.
And that's it! The next step is to publish it.
Once you are ready to share your library, you need to build a distribution and then publish it to PyPI.
django_components uses the build
utility to build a distribution:
And to publish to PyPI, you can use twine
(See Python user guide)
Notes on publishing: - The user of the package NEEDS to have installed and configured django_components
. - If you use components where the HTML / CSS / JS files are separate, you may need to define MANIFEST.in
to include those files with the distribution (see user guide).
After the package has been published, all that remains is to install it in other django projects:
Install the package:
Add the package to INSTALLED_APPS
Optionally add the template tags to the builtins
, so you don't have to call {% load mytags %}
in every template:
And, at last, you can use the components in your own project!
One of our goals with django-components
is to make it easy to share components between projects. If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.
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:
To quickly run the tests install the local dependencies by running:
Now you can run the tests to make sure everything works as expected:
The library is also tested across many versions of Python and Django. To run tests that way:
pyenv install -s 3.8
+pyenv install -s 3.9
+pyenv install -s 3.10
+pyenv install -s 3.11
+pyenv install -s 3.12
+pyenv local 3.8 3.9 3.10 3.11 3.12
+tox -p
+
We use Playwright for end-to-end tests. You will therefore need to install Playwright to be able to run these tests.
Luckily, Playwright makes it very easy:
After Playwright is ready, simply run the tests with tox
:
How do you check that your changes to django-components project will work in an actual Django project?
Use the sampleproject demo project to validate the changes:
NOTE: The path (in this case ..
) must point to the directory that has the setup.py
file.
Once the server is up, it should be available at http://127.0.0.1:8000.
To display individual components, add them to the urls.py
, like in the case of http://127.0.0.1:8000/greeting
django_components uses a bit of JS code to: - Manage the loading of JS and CSS files used by the components - Allow to pass data from Python to JS
When you make changes to this JS code, you also need to compile it:
src/django_components_js
:The script will combine all JS/TS code into a single .js
file, minify it, and copy it to django_components/static/django_components/django_components.min.js
.
To package the library into a distribution that can be published to PyPI, run:
# Install pypa/build
+python -m pip install build --user
+# Build a binary wheel and a source tarball
+python -m build --sdist --wheel --outdir dist/ .
+
To publish the package to PyPI, use twine
(See Python user guide):