Skip to content

Release notes¤

🚨📢 Version 0.100 - BREAKING CHANGE: - django_components.safer_staticfiles app was removed. It is no longer needed. - Installation changes: - Instead of defining component directories in STATICFILES_DIRS, set them to COMPONENTS.dirs. - You now must define STATICFILES_FINDERS - See here how to migrate your settings.py - Beside the top-level /components directory, you can now define also app-level components dirs, e.g. [app]/components (See COMPONENTS.app_dirs). - When you call as_view() on a component instance, that instance will be passed to View.as_view()

Version 0.97 - Fixed template caching. You can now also manually create cached templates with cached_template() - The previously undocumented get_template was made private. - In it's place, there's a new get_template, which supersedes get_template_string (will be removed in v1). The new get_template is the same as get_template_string, except it allows to return either a string or a Template instance. - You now must use only one of template, get_template, template_name, or get_template_name.

Version 0.96 - Run-time type validation for Python 3.11+ - If the Component class is typed, e.g. Component[Args, Kwargs, ...], the args, kwargs, slots, and data are validated against the given types. (See Runtime input validation with types) - Render hooks - Set on_render_before and on_render_after methods on Component to intercept or modify the template or context before rendering, or the rendered result afterwards. (See Component hooks) - component_vars.is_filled context variable can be accessed from within on_render_before and on_render_after hooks as self.is_filled.my_slot

Version 0.95 - Added support for dynamic components, where the component name is passed as a variable. (See Dynamic components) - Changed Component.input to raise RuntimeError if accessed outside of render context. Previously it returned None if unset.

Version 0.94 - django_components now automatically configures Django to support multi-line tags. (See Multi-line tags) - New setting reload_on_template_change. Set this to True to reload the dev server on changes to component template files. (See Reload dev server on component file changes)

Version 0.93 - Spread operator ...dict inside template tags. (See Spread operator) - Use template tags inside string literals in component inputs. (See Use template tags inside component inputs) - Dynamic slots, fills and provides - The name argument for these can now be a variable, a template expression, or via spread operator - Component library authors can now configure CONTEXT_BEHAVIOR and TAG_FORMATTER settings independently from user settings.

🚨📢 Version 0.92 - BREAKING CHANGE: Component class is no longer a subclass of View. To configure the View class, set the Component.View nested class. HTTP methods like get or post can still be defined directly on Component class, and Component.as_view() internally calls Component.View.as_view(). (See Modifying the View class)

  • The inputs (args, kwargs, slots, context, ...) that you pass to Component.render() can be accessed from within get_context_data, get_template and get_template_name via self.input. (See Accessing data passed to the component)

  • Typing: Component class supports generics that specify types for Component.render (See Adding type hints with Generics)

Version 0.90 - All tags (component, slot, fill, ...) now support "self-closing" or "inline" form, where you can omit the closing tag:

{# Before #}
{% component "button" %}{% endcomponent %}
{# After #}
{% component "button" / %}
- All tags now support the "dictionary key" or "aggregate" syntax (kwarg:key=val):
{% component "button" attrs:class="hidden" %}
- You can change how the components are written in the template with TagFormatter.

The default is `django_components.component_formatter`:
```django
{% component "button" href="..." disabled %}
    Click me!
{% endcomponent %}
```

While `django_components.shorthand_component_formatter` allows you to write components like so:

```django
{% button href="..." disabled %}
    Click me!
{% endbutton %}

🚨📢 Version 0.85 Autodiscovery module resolution changed. Following undocumented behavior was removed:

  • Previously, autodiscovery also imported any [app]/components.py files, and used SETTINGS_MODULE to search for component dirs.
  • To migrate from:
    • [app]/components.py - Define each module in COMPONENTS.libraries setting, or import each module inside the AppConfig.ready() hook in respective apps.py files.
    • SETTINGS_MODULE - Define component dirs using STATICFILES_DIRS
  • Previously, autodiscovery handled relative files in STATICFILES_DIRS. To align with Django, STATICFILES_DIRS now must be full paths (Django docs).

🚨📢 Version 0.81 Aligned the render_to_response method with the (now public) render method of Component class. Moreover, slots passed to these can now be rendered also as functions.

  • BREAKING CHANGE: The order of arguments to render_to_response has changed.

Version 0.80 introduces dependency injection with the {% provide %} tag and inject() method.

🚨📢 Version 0.79

  • BREAKING CHANGE: Default value for the COMPONENTS.context_behavior setting was changes from "isolated" to "django". If you did not set this value explicitly before, this may be a breaking change. See the rationale for change here.

🚨📢 Version 0.77 CHANGED the syntax for accessing default slot content.

  • Previously, the syntax was {% fill "my_slot" as "alias" %} and {{ alias.default }}.
  • Now, the syntax is {% fill "my_slot" default="alias" %} and {{ alias }}.

Version 0.74 introduces html_attrs tag and prefix:key=val construct for passing dicts to components.

🚨📢 Version 0.70

  • {% if_filled "my_slot" %} tags were replaced with {{ component_vars.is_filled.my_slot }} variables.
  • Simplified settings - slot_context_behavior and context_behavior were merged. See the documentation for more details.

Version 0.67 CHANGED the default way how context variables are resolved in slots. See the documentation for more details.

🚨📢 Version 0.5 CHANGES THE SYNTAX for components. component_block is now component, and component blocks need an ending endcomponent tag. The new python manage.py upgradecomponent command can be used to upgrade a directory (use --path argument to point to each dir) of templates that use components to the new syntax automatically.

This change is done to simplify the API in anticipation of a 1.0 release of django_components. After 1.0 we intend to be stricter with big changes like this in point releases.

Version 0.34 adds components as views, which allows you to handle requests and render responses from within a component. See the documentation for more details.

Version 0.28 introduces 'implicit' slot filling and the default option for slot tags.

Version 0.27 adds a second installable app: django_components.safer_staticfiles. It provides the same behavior as django.contrib.staticfiles but with extra security guarantees (more info below in Security Notes).

Version 0.26 changes the syntax for {% slot %} tags. From now on, we separate defining a slot ({% slot %}) from filling a slot with content ({% fill %}). This means you will likely need to change a lot of slot tags to fill. We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice featuPpre to have access to. Hoping that this will feel worth it!

Version 0.22 starts autoimporting all files inside components subdirectores, to simplify setup. An existing project might start to get AlreadyRegistered-errors because of this. To solve this, either remove your custom loading of components, or set "autodiscover": False in settings.COMPONENTS.

Version 0.17 renames Component.context and Component.template to get_context_data and get_template_name. The old methods still work, but emit a deprecation warning. This change was done to sync naming with Django's class based views, and make using django-components more familiar to Django users. Component.context and Component.template will be removed when version 1.0 is released.

Static files

Components can be organized however you prefer. That said, our prefered way is to keep the files of a component close together by bundling them in the same directory.

This means that files containing backend logic, such as Python modules and HTML templates, live in the same directory as static files, e.g. JS and CSS.

From v0.100 onwards, we keep component files (as defined by COMPONENTS.dirs and COMPONENTS.app_dirs) separate from the rest of the static files (defined by STATICFILES_DIRS). That way, the Python and HTML files are NOT exposed by the server. Only the static JS, CSS, and other common formats.

NOTE: If you need to expose different file formats, you can configure these with COMPONENTS.static_files_allowed and COMPONENTS.static_files_forbidden.

Installation¤

  1. Install django_components into your environment:

pip install django_components

  1. Load django_components into Django by adding it into INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
   ...,
   'django_components',
]
  1. BASE_DIR setting is required. Ensure that it is defined in settings.py:
BASE_DIR = Path(__file__).resolve().parent.parent
  1. Add / modify COMPONENTS.dirs and / or COMPONENTS.app_dirs so django_components knows where to find component HTML, JS and CSS files:
COMPONENTS = {
    "dirs": [
         ...,
         os.path.join(BASE_DIR, "components"),
     ],
}

If COMPONENTS.dirs is omitted, django-components will by default look for a top-level /components directory, {BASE_DIR}/components.

In addition to COMPONENTS.dirs, django_components will also load components from app-level directories, such as my-app/components/. The directories within apps are configured with COMPONENTS.app_dirs, and the default is [app]/components.

NOTE: The input to COMPONENTS.dirs is the same as for STATICFILES_DIRS, and the paths must be full paths. See Django docs.

  1. Next, to make Django load component HTML files as Django templates, modify TEMPLATES section of settings.py as follows:

  2. Remove 'APP_DIRS': True,

  3. Add loaders to OPTIONS list and set it to following value:
TEMPLATES = [
   {
      ...,
      'OPTIONS': {
            'context_processors': [
               ...
            ],
            'loaders':[(
               'django.template.loaders.cached.Loader', [
                  # Default Django loader
                  'django.template.loaders.filesystem.Loader',
                  # Inluding this is the same as APP_DIRS=True
                  'django.template.loaders.app_directories.Loader',
                  # Components loader
                  'django_components.template_loader.Loader',
               ]
            )],
      },
   },
]
  1. Lastly, be able to serve the component JS and CSS files as static files, modify STATICFILES_FINDERS section of settings.py as follows:
STATICFILES_FINDERS = [
    # Default finders
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
    # Django components
    "django_components.finders.ComponentsFileSystemFinder",
]

Compatibility¤

Django-components supports all supported combinations versions of Django and Python.

Python version Django version
3.8 4.2
3.9 4.2
3.10 4.2, 5.0
3.11 4.2, 5.0
3.12 4.2, 5.0

Using single-file components

Components can also be defined in a single file, which is useful for small components. To do this, you can use the template, js, and css class attributes instead of the template_name and Media. For example, here's the calendar component from above, defined in a single file:

[project root]/components/calendar.py
## In a file called [project root]/components/calendar.py
from django_components import Component, register, types

@register("calendar")
class Calendar(Component):
    def get_context_data(self, date):
        return {
            "date": date,
        }

    template: types.django_html = """
        <div class="calendar-component">Today's date is <span>{{ date }}</span></div>
    """

    css: types.css = """
        .calendar-component { width: 200px; background: pink; }
        .calendar-component span { font-weight: bold; }
    """

    js: types.js = """
        (function(){
            if (document.querySelector(".calendar-component")) {
                document.querySelector(".calendar-component").onclick = function(){ alert("Clicked calendar!"); };
            }
        })()
    """

This makes it easy to create small components without having to create a separate template, CSS, and JS file.

VSCode¤

Note, in the above example, that the t.django_html, t.css, and t.js types are used to specify the type of the template, CSS, and JS files, respectively. This is not necessary, but if you're using VSCode with the Python Inline Source Syntax Highlighting extension, it will give you syntax highlighting for the template, CSS, and JS.

Use components in templates¤

First load the component_tags tag library, then use the component_[js/css]_dependencies and component tags to render the component to the page.

{% load component_tags %}
<!DOCTYPE html>
<html>
<head>
    <title>My example calendar</title>
    {% component_css_dependencies %}
</head>
<body>
    {% component "calendar" date="2015-06-19" %}{% endcomponent %}
    {% component_js_dependencies %}
</body>
<html>

NOTE: Instead of writing {% endcomponent %} at the end, you can use a self-closing tag:

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

The output from the above template will be:

<!DOCTYPE html>
<html>
  <head>
    <title>My example calendar</title>
    <link
      href="/static/calendar/style.css"
      type="text/css"
      media="all"
      rel="stylesheet"
    />
  </head>
  <body>
    <div class="calendar-component">
      Today's date is <span>2015-06-19</span>
    </div>
    <script src="/static/calendar/script.js"></script>
  </body>
  <html></html>
</html>

This makes it possible to organize your front-end around reusable components. Instead of relying on template tags and keeping your CSS and Javascript in the static directory.

Inputs of render and render_to_response

Both render and render_to_response accept the same input:

Component.render(
    context: Mapping | django.template.Context | None = None,
    args: List[Any] | None = None,
    kwargs: Dict[str, Any] | None = None,
    slots: Dict[str, str | SafeString | SlotFunc] | None = None,
    escape_slots_content: bool = True
) -> str:
  • args - Positional args for the component. This is the same as calling the component as {% component "my_comp" arg1 arg2 ... %}

  • kwargs - Keyword args for the component. This is the same as calling the component as {% component "my_comp" key1=val1 key2=val2 ... %}

  • slots - Component slot fills. This is the same as pasing {% fill %} tags to the component. Accepts a dictionary of { slot_name: slot_content } where slot_content can be a string or SlotFunc.

  • escape_slots_content - Whether the content from slots should be escaped. True by default to prevent XSS attacks. If you disable escaping, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.

  • context - A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template.

  • NOTE: In "isolated" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs.

Response class of render_to_response¤

While render method returns a plain string, render_to_response wraps the rendered content in a "Response" class. By default, this is django.http.HttpResponse.

If you want to use a different Response class in render_to_response, set the Component.response_class attribute:

class MyResponse(HttpResponse):
   def __init__(self, *args, **kwargs) -> None:
      super().__init__(*args, **kwargs)
      # Configure response
      self.headers = ...
      self.status = ...

class SimpleComponent(Component):
   response_class = MyResponse
   template: types.django_html = "HELLO"

response = SimpleComponent.render_to_response()
assert isinstance(response, MyResponse)

Component as view example

Here's an example of a calendar component defined as a view:

## In a file called [project root]/components/calendar.py
from django_components import Component, ComponentView, register

@register("calendar")
class Calendar(Component):

    template = """
        <div class="calendar-component">
            <div class="header">
                {% slot "header" / %}
            </div>
            <div class="body">
                Today's date is <span>{{ date }}</span>
            </div>
        </div>
    """

    # Handle GET requests
    def get(self, request, *args, **kwargs):
        context = {
            "date": request.GET.get("date", "2020-06-06"),
        }
        slots = {
            "header": "Calendar header",
        }
        # Return HttpResponse with the rendered content
        return self.render_to_response(
            context=context,
            slots=slots,
        )

Then, to use this component as a view, you should create a urls.py file in your components directory, and add a path to the component's view:

## In a file called [project root]/components/urls.py
from django.urls import path
from components.calendar.calendar import Calendar

urlpatterns = [
    path("calendar/", Calendar.as_view()),
]

Component.as_view() is a shorthand for calling View.as_view() and passing the component instance as one of the arguments.

Remember to add __init__.py to your components directory, so that Django can find the urls.py file.

Finally, include the component's urls in your project's urls.py file:

## In a file called [project root]/urls.py
from django.urls import include, path

urlpatterns = [
    path("components/", include("components.urls")),
]

Note: Slots content are automatically escaped by default to prevent XSS attacks. To disable escaping, set escape_slots_content=False in the render_to_response method. If you do so, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.

If you're planning on passing an HTML string, check Django's use of format_html and mark_safe.

Typing and validating components¤

Usage for Python <3.11¤

On Python 3.8-3.10, use typing_extensions

from typing_extensions import TypedDict, NotRequired

Additionally on Python 3.8-3.9, also import annotations:

from __future__ import annotations

Moreover, on 3.10 and less, you may not be able to use NotRequired, and instead you will need to mark either all keys are required, or all keys as optional, using TypeDict's total kwarg.

See PEP-655 for more info.

Handling no args or no kwargs¤

To declare that a component accepts no Args, Kwargs, etc, you can use EmptyTuple and EmptyDict types:

from django_components import Component, EmptyDict, EmptyTuple

Args = EmptyTuple
Kwargs = Data = Slots = EmptyDict

class Button(Component[Args, Kwargs, Data, Slots]):
    ...

Pre-defined components¤

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.

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

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.

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

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

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

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

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

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

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

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

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>

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

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.

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>

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

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

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.

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!

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

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.

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

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>

Available hooks

  • on_render_before
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:

```py
def on_render_before(self, context, template) -> None:
    # Insert value into the Context
    context["from_on_before"] = ":)"

    # 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:
Hook that runs just after the component's template was rendered.
It receives the rendered output as the last argument.

You can use this hook to access the context or the template, but modifying
them won't have any effect.

To override the content that gets rendered, you can return a string or SafeString from this hook:

```py
def on_render_after(self, context, template, content):
    # Prepend text to the rendered content
    return "Chocolate cookie recipe: " + content
```

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.

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.

  • component_vars.is_filled

    New in version 0.70

    Dictonary describing which slots are filled (True) or are not (False).

    Example:

    {% if component_vars.is_filled.my_slot %}
        {% slot "my_slot" / %}
    {% endif %}
    

Available TagFormatters

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:

    {% component "button" href="..." / %}
    

  • ShorthandComponentFormatter (django_components.shorthand_component_formatter)

    Uses the component name as start tag, and end<component_name> as an end tag.

    Example as block:

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

    Example as inlined tag:

    {% button href="..." / %}
    

Background¤

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

Then `TagFormatter.parse()` will receive a following input:
```py
["component", '"button"', 'href="..."', 'disabled']
```
  1. TagFormatter extracts the component name and the remaining input.

    So, given the above, TagFormatter.parse() returns the following:

    TagResult(
        component_name="button",
        tokens=['href="..."', 'disabled']
    )
    
    5. The tag handler resumes, using the tokens returned from TagFormatter.

    So, continuing the example, at this point the tag handler practically behaves as if you rendered:

    {% component href="..." disabled %}
    
    6. Tag handler looks up the component button, and passes the args, kwargs, and slots to it.

Defining HTML/JS/CSS files¤

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:

Defining multiple paths¤

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

Supported types for file paths¤

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

Customize how paths are rendered into HTML tags with 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__).

Setting Up 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:

COMPONENTS = {
    "RENDER_DEPENDENCIES": True,
    # ... other component settings ...
}

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:

from django_components import import_libraries

import_libraries()

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

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.

COMPONENTS = {
    "dynamic_component_name": "new_dynamic",
}

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

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.

COMPONENTS = {
    "template_cache_size": 256,
}

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

Example "django"¤

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:

{ "my_var": 456 }

Then the template will be rendered as:

456   # my_var
feta  # cheese

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.

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!

Running with development server¤

Logging and debugging¤

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

Management Command Usage

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.

Creating a Component with Default Settings¤

To create a component with the default settings, you only need to provide the name of the component:

python manage.py startcomponent my_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.

Overwriting an Existing Component¤

If you want to overwrite an existing component, you can use the --force option:

python manage.py startcomponent my_component --force

This will overwrite the existing my_component if it exists.

Writing and sharing component libraries¤

You can publish and share your components for others to use. Here are the steps to do so:

Publishing component libraries¤

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:

python -m build --sdist --wheel --outdir dist/ .

And to publish to PyPI, you can use twine (See Python user guide)

twine upload --repository pypi dist/* -u __token__ -p <PyPI_TOKEN>

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

Community examples¤

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.

Install locally and run the tests

Start by forking the project by clicking the Fork button up in the right corner in the GitHub . This makes a copy of the repository in your own name. Now you can clone this repository locally and start adding features:

git clone https://github.com/<your GitHub username>/django-components.git

To quickly run the tests install the local dependencies by running:

pip install -r requirements-dev.txt

Now you can run the tests to make sure everything works as expected:

pytest

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

Developing against live Django app¤

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:

  1. Navigate to sampleproject directory:
cd sampleproject
  1. Install dependencies from the requirements.txt file:
pip install -r requirements.txt
  1. Link to your local version of django-components:
pip install -e ..

NOTE: The path (in this case ..) must point to the directory that has the setup.py file.

  1. Start Django server
    python manage.py runserver
    

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

Packaging and publishing¤

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>

See the full workflow here.

¤