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: {...},
-)
-

Registering components¤

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
+

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:

{% component "calendar" date="1970-01-01" %}
-{% endcomponent %}
-

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.

What is ComponentRegistry¤

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" %}.

Working with ComponentRegistry¤

The default ComponentRegistry instance can be imported as:

from django_components import registry
-

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()
-

Registering components to custom ComponentRegistry¤

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.

ComponentRegistry settings¤

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.

Autodiscovery¤

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: {...},
+)
+

Registering components¤

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:

{% component "calendar" date="1970-01-01" %}
+{% endcomponent %}
+

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.

What is ComponentRegistry¤

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" %}.

Working with ComponentRegistry¤

The default ComponentRegistry instance can be imported as:

from django_components import registry
+

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()
+

Registering components to custom ComponentRegistry¤

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.

ComponentRegistry settings¤

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.

Autodiscovery¤

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:

Autodiscovery can be disabled in the settings.

Manually trigger autodiscovery¤

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:

from django.apps import AppConfig
 
-autodiscover()
-

Using slots in templates¤

New in version 0.26:


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...

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>
-

Default slot¤

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:

Autodiscovery can be disabled in the settings.

Manually trigger autodiscovery¤

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
+
+autodiscover()
+

Using slots in templates¤

New in version 0.26:


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...

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 %}
+

Default slot¤

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 %}
-

Render fill in multiple places¤

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:

<div class="calendar-component">
-    <div class="header">
+

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 %}
+

Render fill in multiple places¤

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>
-

Default and required slots¤

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">
+    {% endfill %}
+{% endcomponent %}
+

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:

{% component "calendar" date="2020-06-06" %}
-    <img src="..." />
-{% endcomponent %}
-

Accessing original content of slots¤

Added in version 0.26

NOTE: In version 0.77, the syntax was changed from

{% fill "my_slot" as "alias" %} {{ alias.default }}
-

to

{% fill "my_slot" default="slot_default" %} {{ slot_default }}
-

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>
-

Conditional slots¤

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 Accessing is_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 %}
+

Default and required slots¤

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:

{% component "calendar" date="2020-06-06" %}
+    <img src="..." />
+{% endcomponent %}
+

Accessing original content of slots¤

Added in version 0.26

NOTE: In version 0.77, the syntax was changed from

{% fill "my_slot" as "alias" %} {{ alias.default }}
+

to

{% fill "my_slot" default="slot_default" %} {{ slot_default }}
+

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 %}
-

Accessing 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___.

Scoped slots¤

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:

  1. Passing data to slot tag
  2. Accessing data in fill tag

Passing data to slots¤

To pass the data to the slot tag, simply pass them as keyword attributes (key=value):

@register("my_comp")
+

Conditional slots¤

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 Accessing is_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 %}
+

Accessing 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___.

Scoped slots¤

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,
-        }
-

Accessing slot data in fill¤

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:

{% component "my_comp" %}
+        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:

  1. Passing data to slot tag
  2. Accessing data in fill tag

Passing data to slots¤

To 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,
+        }
+

Accessing slot data in fill¤

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:

{% component "my_comp" data="data" %}
-    {{ data.input }}
-{% endcomponent %}
-

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 %}
-

Dynamic slots and fills¤

Until now, we were declaring slot and fill names statically, as a string literal, e.g.

{% slot "content" / %}
-

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:

{% slot "content" / %}
-

is the same as:

{% slot name="content" / %}
-

So it's possible to define a name key on a dictionary, and then spread that onto the slot tag:

{# slot_props = {"name": "content"} #}
-{% slot ...slot_props / %}
-

Accessing data passed to the component¤

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"},
-)
-

Rendering HTML attributes¤

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:

<div class="{{ classes }}" data-id="{{ my_id }}">
-</div>
-

You can simplify it with html_attrs tag:

<div {% html_attrs attrs %}>
+

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:

{% component "my_comp" data="data" %}
+    {{ data.input }}
+{% endcomponent %}
+

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 %}
+

Dynamic slots and fills¤

Until now, we were declaring slot and fill names statically, as a string literal, e.g.

{% slot "content" / %}
+

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:

{% slot "content" / %}
+

is the same as:

{% slot name="content" / %}
+

So it's possible to define a name key on a dictionary, and then spread that onto the slot tag:

{# slot_props = {"name": "content"} #}
+{% slot ...slot_props / %}
+

Accessing data passed to the component¤

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"},
+)
+

Rendering HTML attributes¤

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:

<div class="{{ classes }}" data-id="{{ my_id }}">
 </div>
-

where attrs is:

attrs = {
-    "class": classes,
-    "data-id": my_id,
-}
-

This feature is inspired by merge_attrs tag of django-web-components and "fallthrough attributes" feature of Vue.

Removing atttributes¤

Attributes that are set to None or False are NOT rendered.

So given this input:

attrs = {
-    "class": "text-green",
-    "required": False,
-    "data-id": None,
-}
-

And template:

<div {% html_attrs attrs %}>
-</div>
-

Then this renders:

<div class="text-green"></div>
-

Boolean attributes¤

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:

<button disabled>Click me!</button> <button>Click me!</button>
-

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:

attrs = {
-    "disabled": True,
-    "autofocus": False,
-}
-

And template:

<div {% html_attrs attrs %}>
-</div>
-

Then this renders:

<div disabled></div>
-

Default attributes¤

Sometimes you may want to specify default values for attributes. You can pass a second argument (or kwarg defaults) to set the defaults.

<div {% html_attrs attrs defaults %}>
-    ...
-</div>
-

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 }}"

Appending attributes¤

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:

attrs = {
-    "class": "my-class pa-4",
-}
-

And on html_attrs tag, we set the key class:

<div {% html_attrs attrs class="some-class" %}>
-</div>
-

Then these will be merged and rendered as:

<div data-value="my-class pa-4 some-class"></div>
-

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:

<div
-  data-value="my-class pa-4 some-class another-class class-from-var text-red"
-></div>
-

Rules for html_attrs¤

  1. Both 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 %}

  1. Both attrs and defaults are optional (can be omitted)

  2. 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.

  3. All other kwargs are appended and can be repeated.

Examples for html_attrs¤

Assuming that:

class_from_var = "from-var"
-
-attrs = {
-    "class": "from-attrs",
-    "type": "submit",
-}
-
-defaults = {
-    "class": "from-defaults",
-    "role": "button",
-}
-

Then:

renders (empty string):

renders:
class="some-class from-var" data-id="123"

renders:
class="from-attrs" type="submit"

renders:
class="from-attrs" type="submit"

renders:
class="from-defaults" role="button"

renders:
class="from-attrs" type="submit"

renders:
class="from-defaults" role="button"

renders:
class="from-attrs added_class from-var" type="submit" role="button" data-id=123

renders:
class="from-attrs added_class from-var" type="submit" role="button" data-id=123

renders:
class="from-attrs added_class from-var" type="submit" data-id=123

Full example for 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:

<div class="pa-4 text-red my-comp-date extra-class" data-id="123">...</div>
-

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>
-

Rendering HTML attributes outside of templates¤

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'
-

Template tag syntax¤

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).

Self-closing tags¤

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:

{% component "button" %}{% endcomponent %}
-

becomes

{% component "button" / %}
-

Special characters¤

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"]
-        }
-

Spread operator¤

New in version 0.93:

Instead of passing keyword arguments one-by-one:

{% component "calendar" title="How to abc" date="2015-06-19" author="John Wick" / %}
-

You can use a spread operator ...dict to apply key-value pairs from a dictionary:

post_data = {
-    "title": "How to...",
-    "date": "2015-06-19",
-    "author": "John Wick",
-}
-
{% component "calendar" ...post_data / %}
-

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:

{% component "calendar" ...post_data id=post.id ...extra / %}
-

In a case of conflicts, the values added later (right-most) overwrite previous values.

Use template tags inside component inputs¤

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.

Passing data as string vs original values¤

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:

{% component 'blog_post' page="{% random_int 10 20 %}" / %}
-

Here, page is a string:

{% component 'blog_post' page=" {% random_int 10 20 %} " / %}
-

And same applies to the {{ }} variable tags:

Here, items is a list:

{% component 'cat_list' items="{{ cats|slice:':2' }}" / %}
-

Here, items is a string:

{% component 'cat_list' items="{{ cats|slice:':2' }} See more" / %}
-

Evaluating Python expressions in template¤

You can even go a step further and have a similar experience to Vue or React, where you can evaluate arbitrary code expressions:

<MyForm
-  value={ isEnabled ? inputValue : null }
-/>
-

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:

{% component "my_form"
-  value="{% expr 'input_value if is_enabled else None' %}"
-/ %}
-

Note: Never use this feature to mix business logic and template logic. Business logic should still be in the view!

Pass dictonary by its key-value pairs¤

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:

@register("my_comp")
+

You can simplify it with html_attrs tag:

<div {% html_attrs attrs %}>
+</div>
+

where attrs is:

attrs = {
+    "class": classes,
+    "data-id": my_id,
+}
+

This feature is inspired by merge_attrs tag of django-web-components and "fallthrough attributes" feature of Vue.

Removing atttributes¤

Attributes that are set to None or False are NOT rendered.

So given this input:

attrs = {
+    "class": "text-green",
+    "required": False,
+    "data-id": None,
+}
+

And template:

<div {% html_attrs attrs %}>
+</div>
+

Then this renders:

<div class="text-green"></div>
+

Boolean attributes¤

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:

<button disabled>Click me!</button> <button>Click me!</button>
+

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:

attrs = {
+    "disabled": True,
+    "autofocus": False,
+}
+

And template:

<div {% html_attrs attrs %}>
+</div>
+

Then this renders:

<div disabled></div>
+

Default attributes¤

Sometimes you may want to specify default values for attributes. You can pass a second argument (or kwarg defaults) to set the defaults.

<div {% html_attrs attrs defaults %}>
+    ...
+</div>
+

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 }}"

Appending attributes¤

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:

attrs = {
+    "class": "my-class pa-4",
+}
+

And on html_attrs tag, we set the key class:

<div {% html_attrs attrs class="some-class" %}>
+</div>
+

Then these will be merged and rendered as:

<div data-value="my-class pa-4 some-class"></div>
+

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:

<div
+  data-value="my-class pa-4 some-class another-class class-from-var text-red"
+></div>
+

Rules for html_attrs¤

  1. Both 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 %}

  1. Both attrs and defaults are optional (can be omitted)

  2. 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.

  3. All other kwargs are appended and can be repeated.

Examples for html_attrs¤

Assuming that:

class_from_var = "from-var"
+
+attrs = {
+    "class": "from-attrs",
+    "type": "submit",
+}
+
+defaults = {
+    "class": "from-defaults",
+    "role": "button",
+}
+

Then:

renders (empty string):

renders:
class="some-class from-var" data-id="123"

renders:
class="from-attrs" type="submit"

renders:
class="from-attrs" type="submit"

renders:
class="from-defaults" role="button"

renders:
class="from-attrs" type="submit"

renders:
class="from-defaults" role="button"

renders:
class="from-attrs added_class from-var" type="submit" role="button" data-id=123

renders:
class="from-attrs added_class from-var" type="submit" role="button" data-id=123

renders:
class="from-attrs added_class from-var" type="submit" data-id=123

Full example for 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:

<div class="pa-4 text-red my-comp-date extra-class" data-id="123">...</div>
+

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>
+

Rendering HTML attributes outside of templates¤

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'
+

Template tag syntax¤

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).

Self-closing tags¤

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:

{% component "button" %}{% endcomponent %}
+

becomes

{% component "button" / %}
+

Special characters¤

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"]
+        }
+

Spread operator¤

New in version 0.93:

Instead of passing keyword arguments one-by-one:

{% component "calendar" title="How to abc" date="2015-06-19" author="John Wick" / %}
+

You can use a spread operator ...dict to apply key-value pairs from a dictionary:

post_data = {
+    "title": "How to...",
+    "date": "2015-06-19",
+    "author": "John Wick",
+}
+
{% component "calendar" ...post_data / %}
+

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:

{% component "calendar" ...post_data id=post.id ...extra / %}
+

In a case of conflicts, the values added later (right-most) overwrite previous values.

Use template tags inside component inputs¤

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.

Passing data as string vs original values¤

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:

{% component 'blog_post' page="{% random_int 10 20 %}" / %}
+

Here, page is a string:

{% component 'blog_post' page=" {% random_int 10 20 %} " / %}
+

And same applies to the {{ }} variable tags:

Here, items is a list:

{% component 'cat_list' items="{{ cats|slice:':2' }}" / %}
+

Here, items is a string:

{% component 'cat_list' items="{{ cats|slice:':2' }} See more" / %}
+

Evaluating Python expressions in template¤

You can even go a step further and have a similar experience to Vue or React, where you can evaluate arbitrary code expressions:

<MyForm
+  value={ isEnabled ? inputValue : null }
+/>
+

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:

{% component "my_form"
+  value="{% expr 'input_value if is_enabled else None' %}"
+/ %}
+

Note: Never use this feature to mix business logic and template logic. Business logic should still be in the view!

Pass dictonary by its key-value pairs¤

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:

{"attrs": {"my_key:two": 2}}
-

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 to False

Prop drilling and dependency injection (provide / inject)¤

New in version 0.80:

Django components supports dependency injection with the combination of:

  1. {% provide %} tag
  2. inject() method of the Component class

What 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

  1. Providing data
  2. 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).

{% 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 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:

@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:

{"attrs": {"my_key:two": 2}}
+

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 to False

Prop drilling and dependency injection (provide / inject)¤

New in version 0.80:

Django components supports dependency injection with the combination of:

  1. {% provide %} tag
  2. inject() method of the Component class

What 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

  1. Providing data
  2. 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).

{% provide "my_data" key="hi" another=123 %}
+    {% component "child" / %}  <--- Can access "my_data"
 {% endprovide %}
-

Similarly to slots and fills, also provide's name argument can be set dynamically via a variable, a template expression, or a spread operator:

{% provide name=name ... %}
-    ...
-{% provide %}
-</table>
-

Using 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):

class ChildComponent(Component):
+
+{% 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 }}
+{% endprovide %}
+

Similarly to slots and fills, also provide's name argument can be set dynamically via a variable, a template expression, or a spread operator:

{% provide name=name ... %}
+    ...
+{% provide %}
+</table>
+

Using 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 in get_context_data. If you try to call it from elsewhere, it will raise an error.

Full example¤

@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:

<div>hi</div>
-<div>123</div>
-

Component hooks¤

New in version 0.96

Component hooks are functions that allow you to intercept the rendering process at specific positions.

Available hooks¤

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 in get_context_data. If you try to call it from elsewhere, it will raise an error.

Full example¤

@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:

<div>hi</div>
+<div>123</div>
+

Component hooks¤

New in version 0.96

Component hooks are functions that allow you to intercept the rendering process at specific positions.

Available hooks¤

def on_render_before(
+    self: Component,
+    context: Context,
+    template: Template
+) -> None:
 
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"))
 ```
-
def on_render_after(
-    self: Component,
-    context: Context,
-    template: Template,
-    content: str
-) -> None | str | SafeString:
+
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
 ```
-

Component hooks example¤

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.

See here for how it was done

{% 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 %}
-

Component context and scope¤

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:

{% component "calendar" date="2015-06-19" only / %}
-

NOTE: {% csrf_token %} tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the only modifier.

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.

Example of Accessing Outer Context¤

<div>
-  {% component "calender" / %}
-</div>
-

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.

Pre-defined template variables¤

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.

Customizing component tags with TagFormatter¤

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:

{% button href="..." disabled %}
-  Click me!
-{% endbutton %}
+

Component hooks example¤

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.

See here for how it was done

{% 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 %}
+

Component context and scope¤

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:

{% component "calendar" date="2015-06-19" only / %}
+

NOTE: {% csrf_token %} tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the only modifier.

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.

Example of Accessing Outer Context¤

<div>
+  {% component "calender" / %}
+</div>
+

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.

Pre-defined template variables¤

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.

Customizing component tags with TagFormatter¤

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 / %}
-

Available TagFormatters¤

django_components provides following predefined TagFormatters: