diff --git a/dev/getting_started/adding_js_and_css/index.html b/dev/getting_started/adding_js_and_css/index.html index dea567cf..985e8842 100644 --- a/dev/getting_started/adding_js_and_css/index.html +++ b/dev/getting_started/adding_js_and_css/index.html @@ -97,7 +97,7 @@ a component is rendered on the page. This is not true for JS and CSS defined in `Media.js/css`, where the linked JS / CSS are rendered as is. --->

Your components may depend on third-party packages or styling, or other shared logic. To load these additional dependencies, you can use a nested Media class.

This Media class behaves similarly to Django's Media class, with a few differences:

  1. Our Media class accepts various formats for the JS and CSS files: either a single file, a list, or (CSS-only) a dictonary (see below).
  2. Individual JS / CSS files can be any of str, bytes, Path, SafeString, or a function.
  3. Individual JS / CSS files can be glob patterns, e.g. *.js or styles/**/*.css.
  4. If you set Media.extend to a list, it should be a list of Component classes.

Learn more about using Media.

[project root]/components/calendar/calendar.py
from django_components import Component
+-->  

Your components may depend on third-party packages or styling, or other shared logic. To load these additional dependencies, you can use a nested Media class.

This Media class behaves similarly to Django's Media class, with a few differences:

  1. Our Media class accepts various formats for the JS and CSS files: either a single file, a list, or (CSS-only) a dictonary (see below).
  2. Individual JS / CSS files can be any of str, bytes, Path, SafeString, or a function.
  3. Individual JS / CSS files can be glob patterns, e.g. *.js or styles/**/*.css.
  4. If you set Media.extend to a list, it should be a list of Component classes.

Learn more about using Media.

[project root]/components/calendar/calendar.py
from django_components import Component
 
 class Calendar(Component):
     template_file = "calendar.html"
@@ -172,4 +172,4 @@
     </script>
   </body>
 </html>
-

Now that we have a fully-defined component, next let's use it in a Django template ➡️.

\ No newline at end of file +

Now that we have a fully-defined component, next let's use it in a Django template ➡️.

\ No newline at end of file diff --git a/dev/reference/api/index.html b/dev/reference/api/index.html index 3ae524e1..b0a54c7b 100644 --- a/dev/reference/api/index.html +++ b/dev/reference/api/index.html @@ -761,7 +761,7 @@ assert self.kwargs["page"] == 123 assert self.kwargs["per_page"] == 10

media class-attribute instance-attribute ¤

media: Optional[Media] = None
-

See source code

Normalized definition of JS and CSS media files associated with this component. None if Component.Media is not defined.

This field is generated from Component.media_class.

Read more on Accessing component's HTML / JS / CSS.

Example:

class MyComponent(Component):
+

See source code

Normalized definition of JS and CSS media files associated with this component. None if Component.Media is not defined.

This field is generated from Component.media_class.

Read more on Accessing component's Media JS / CSS.

Example:

class MyComponent(Component):
     class Media:
         js = "path/to/script.js"
         css = "path/to/style.css"
@@ -771,7 +771,7 @@
 # <script src="/static/path/to/script.js"></script>
 # <link href="/static/path/to/style.css" media="all" rel="stylesheet">
 

media_class class-attribute ¤

media_class: Type[Media] = Media
-

See source code

Set the Media class that will be instantiated with the JS and CSS media files from Component.Media.

This is useful when you want to customize the behavior of the media files, like customizing how the JS or CSS files are rendered into <script> or <link> HTML tags.

Read more in Defining HTML / JS / CSS files.

Example:

class MyTable(Component):
+

See source code

Set the Media class that will be instantiated with the JS and CSS media files from Component.Media.

This is useful when you want to customize the behavior of the media files, like customizing how the JS or CSS files are rendered into <script> or <link> HTML tags.

Read more in Media class.

Example:

class MyTable(Component):
     class Media:
         js = "path/to/script.js"
         css = "path/to/style.css"
@@ -2579,7 +2579,7 @@
 

See source code

Specify the app-level directories that contain your components.

Defaults to ["components"]. That is, for each Django app, we search <app>/components/ for components.

The paths must be relative to app, e.g.:

COMPONENTS = ComponentsSettings(
     app_dirs=["my_comps"],
 )
-

To search for <app>/my_comps/.

These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.

Set to empty list to disable app-level components:

COMPONENTS = ComponentsSettings(
+

To search for <app>/my_comps/.

These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.

Set to empty list to disable app-level components:

COMPONENTS = ComponentsSettings(
     app_dirs=[],
 )
 

autodiscover class-attribute instance-attribute ¤

autodiscover: Optional[bool] = None
@@ -2603,7 +2603,7 @@
     debug_highlight_slots=True,
 )
 

dirs class-attribute instance-attribute ¤

See source code

Specify the directories that contain your components.

Defaults to [Path(settings.BASE_DIR) / "components"]. That is, the root components/ app.

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

COMPONENTS = ComponentsSettings(
+

See source code

Specify the directories that contain your components.

Defaults to [Path(settings.BASE_DIR) / "components"]. That is, the root components/ app.

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

COMPONENTS = ComponentsSettings(
     dirs=[BASE_DIR / "components"],
 )
 

Set to empty list to disable global components directories:

COMPONENTS = ComponentsSettings(
diff --git a/dev/reference/settings/index.html b/dev/reference/settings/index.html
index 9039e2b7..824db5f9 100644
--- a/dev/reference/settings/index.html
+++ b/dev/reference/settings/index.html
@@ -51,7 +51,7 @@
 

See source code

Specify the app-level directories that contain your components.

Defaults to ["components"]. That is, for each Django app, we search <app>/components/ for components.

The paths must be relative to app, e.g.:

COMPONENTS = ComponentsSettings(
     app_dirs=["my_comps"],
 )
-

To search for <app>/my_comps/.

These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.

Set to empty list to disable app-level components:

COMPONENTS = ComponentsSettings(
+

To search for <app>/my_comps/.

These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.

Set to empty list to disable app-level components:

COMPONENTS = ComponentsSettings(
     app_dirs=[],
 )
 

autodiscover ¤

autodiscover: Optional[bool] = None
@@ -75,7 +75,7 @@
     debug_highlight_slots=True,
 )
 

dirs ¤

See source code

Specify the directories that contain your components.

Defaults to [Path(settings.BASE_DIR) / "components"]. That is, the root components/ app.

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

COMPONENTS = ComponentsSettings(
+

See source code

Specify the directories that contain your components.

Defaults to [Path(settings.BASE_DIR) / "components"]. That is, the root components/ app.

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

COMPONENTS = ComponentsSettings(
     dirs=[BASE_DIR / "components"],
 )
 

Set to empty list to disable global components directories:

COMPONENTS = ComponentsSettings(
diff --git a/dev/search/search_index.json b/dev/search/search_index.json
index d51befe3..8360c2d1 100644
--- a/dev/search/search_index.json
+++ b/dev/search/search_index.json
@@ -1 +1 @@
-{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Welcome to Django Components","text":"

django-components combines Django's templating system with the modularity seen in modern frontend frameworks like Vue or React.

With django-components you can support Django projects small and large without leaving the Django ecosystem.

"},{"location":"#quickstart","title":"Quickstart","text":"

A component in django-components can be as simple as a Django template and Python code to declare the component:

components/calendar/calendar.html
<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n
components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n

Or a combination of Django template, Python, CSS, and Javascript:

components/calendar/calendar.html
<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n
components/calendar/calendar.css
.calendar {\n  width: 200px;\n  background: pink;\n}\n
components/calendar/calendar.js
document.querySelector(\".calendar\").onclick = () => {\n  alert(\"Clicked calendar!\");\n};\n
components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    js_file = \"calendar.js\"\n    css_file = \"calendar.css\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\"date\": kwargs[\"date\"]}\n

Use the component like this:

{% component \"calendar\" date=\"2024-11-06\" %}{% endcomponent %}\n

And this is what gets rendered:

<div class=\"calendar-component\">\n  Today's date is <span>2024-11-06</span>\n</div>\n

Read on to learn about all the exciting details and configuration possibilities!

(If you instead prefer to jump right into the code, check out the example project)

"},{"location":"#features","title":"Features","text":""},{"location":"#modern-and-modular-ui","title":"Modern and modular UI","text":"
  • Create self-contained, reusable UI elements.
  • Each component can include its own HTML, CSS, and JS, or additional third-party JS and CSS.
  • HTML, CSS, and JS can be defined on the component class, or loaded from files.
from django_components import Component\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template = \"\"\"\n        <div class=\"calendar\">\n            Today's date is\n            <span>{{ date }}</span>\n        </div>\n    \"\"\"\n\n    css = \"\"\"\n        .calendar {\n            width: 200px;\n            background: pink;\n        }\n    \"\"\"\n\n    js = \"\"\"\n        document.querySelector(\".calendar\")\n            .addEventListener(\"click\", () => {\n                alert(\"Clicked calendar!\");\n            });\n    \"\"\"\n\n    # Additional JS and CSS\n    class Media:\n        js = [\"https://cdn.jsdelivr.net/npm/htmx.org@2/dist/htmx.min.js\"]\n        css = [\"bootstrap/dist/css/bootstrap.min.css\"]\n\n    # Variables available in the template\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"date\"]\n        }\n
"},{"location":"#composition-with-slots","title":"Composition with slots","text":"
  • Render components inside templates with {% component %} tag.
  • Compose them with {% slot %} and {% fill %} tags.
  • Vue-like slot system, including scoped slots.
{% component \"Layout\"\n    bookmarks=bookmarks\n    breadcrumbs=breadcrumbs\n%}\n    {% fill \"header\" %}\n        <div class=\"flex justify-between gap-x-12\">\n            <div class=\"prose\">\n                <h3>{{ project.name }}</h3>\n            </div>\n            <div class=\"font-semibold text-gray-500\">\n                {{ project.start_date }} - {{ project.end_date }}\n            </div>\n        </div>\n    {% endfill %}\n\n    {# Access data passed to `{% slot %}` with `data` #}\n    {% fill \"tabs\" data=\"tabs_data\" %}\n        {% component \"TabItem\" header=\"Project Info\" %}\n            {% component \"ProjectInfo\"\n                project=project\n                project_tags=project_tags\n                attrs:class=\"py-5\"\n                attrs:width=tabs_data.width\n            / %}\n        {% endcomponent %}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"#extended-template-tags","title":"Extended template tags","text":"

django-components is designed for flexibility, making working with templates a breeze.

It extends Django's template tags syntax with:

  • Literal lists and dictionaries in the template
  • Self-closing tags {% mytag / %}
  • Multi-line template tags
  • Spread operator ... to dynamically pass args or kwargs into the template tag
  • Template tags inside literal strings like \"{{ first_name }} {{ last_name }}\"
  • Pass dictonaries by their key-value pairs attr:key=val
{% component \"table\"\n    ...default_attrs\n    title=\"Friend list for {{ user.name }}\"\n    headers=[\"Name\", \"Age\", \"Email\"]\n    data=[\n        {\n            \"name\": \"John\"|upper,\n            \"age\": 30|add:1,\n            \"email\": \"john@example.com\",\n            \"hobbies\": [\"reading\"],\n        },\n        {\n            \"name\": \"Jane\"|upper,\n            \"age\": 25|add:1,\n            \"email\": \"jane@example.com\",\n            \"hobbies\": [\"reading\", \"coding\"],\n        },\n    ],\n    attrs:class=\"py-4 ma-2 border-2 border-gray-300 rounded-md\"\n/ %}\n

You too can define template tags with these features by using @template_tag() or BaseNode.

Read more on Custom template tags.

"},{"location":"#full-programmatic-access","title":"Full programmatic access","text":"

When you render a component, you can access everything about the component:

  • Component input: args, kwargs, slots and context
  • Component's template, CSS and JS
  • Django's context processors
  • Unique render ID
class Table(Component):\n    js_file = \"table.js\"\n    css_file = \"table.css\"\n\n    template = \"\"\"\n        <div class=\"table\">\n            <span>{{ variable }}</span>\n        </div>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        # Access component's ID\n        assert self.id == \"djc1A2b3c\"\n\n        # Access component's inputs and slots\n        assert self.args == [123, \"str\"]\n        assert self.kwargs == {\"variable\": \"test\", \"another\": 1}\n        footer_slot = self.slots[\"footer\"]\n        some_var = self.context[\"some_var\"]\n\n        # Access the request object and Django's context processors, if available\n        assert self.request.GET == {\"query\": \"something\"}\n        assert self.context_processors_data['user'].username == \"admin\"\n\n        return {\n            \"variable\": kwargs[\"variable\"],\n        }\n\n# Access component's HTML / JS / CSS\nTable.template\nTable.js\nTable.css\n\n# Render the component\nrendered = Table.render(\n    kwargs={\"variable\": \"test\", \"another\": 1},\n    args=(123, \"str\"),\n    slots={\"footer\": \"MY_FOOTER\"},\n)\n
"},{"location":"#granular-html-attributes","title":"Granular HTML attributes","text":"

Use the {% html_attrs %} template tag to render HTML attributes.

It supports:

  • Defining attributes as whole dictionaries or keyword arguments
  • Merging attributes from multiple sources
  • Boolean attributes
  • Appending attributes
  • Removing attributes
  • Defining default attributes
<div\n    {% html_attrs\n        attrs\n        defaults:class=\"default-class\"\n        class=\"extra-class\"\n    %}\n>\n

{% html_attrs %} offers a Vue-like granular control for class and style HTML attributes, where you can use a dictionary to manage each class name or style property separately.

{% html_attrs\n    class=\"foo bar\"\n    class={\n        \"baz\": True,\n        \"foo\": False,\n    }\n    class=\"extra\"\n%}\n
{% html_attrs\n    style=\"text-align: center; background-color: blue;\"\n    style={\n        \"background-color\": \"green\",\n        \"color\": None,\n        \"width\": False,\n    }\n    style=\"position: absolute; height: 12px;\"\n%}\n

Read more about HTML attributes.

"},{"location":"#html-fragment-support","title":"HTML fragment support","text":"

django-components makes integration with HTMX, AlpineJS or jQuery easy by allowing components to be rendered as HTML fragments:

  • Components's JS and CSS files are loaded automatically when the fragment is inserted into the DOM.

  • Components can be exposed as Django Views with get(), post(), put(), patch(), delete() methods

  • Automatically create an endpoint for a component with Component.View.public

# components/calendar/calendar.py\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n\n    class View:\n        # Register Component with `urlpatterns`\n        public = True\n\n        # Define handlers\n        def get(self, request, *args, **kwargs):\n            page = request.GET.get(\"page\", 1)\n            return self.component.render_to_response(\n                request=request,\n                kwargs={\n                    \"page\": page,\n                },\n            )\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"page\": kwargs[\"page\"],\n        }\n\n# Get auto-generated URL for the component\nurl = get_component_url(Calendar)\n\n# Or define explicit URL in urls.py\npath(\"calendar/\", Calendar.as_view())\n
"},{"location":"#provide-inject","title":"Provide / Inject","text":"

django-components supports the provide / inject pattern, similarly to React's Context Providers or Vue's provide / inject:

  • Use the {% provide %} tag to provide data to the component tree
  • Use the Component.inject() method to inject data into the component

Read more about Provide / Inject.

<body>\n    {% provide \"theme\" variant=\"light\" %}\n        {% component \"header\" / %}\n    {% endprovide %}\n</body>\n
@register(\"header\")\nclass Header(Component):\n    template = \"...\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        theme = self.inject(\"theme\").variant\n        return {\n            \"theme\": theme,\n        }\n
"},{"location":"#input-validation-and-static-type-hints","title":"Input validation and static type hints","text":"

Avoid needless errors with type hints and runtime input validation.

To opt-in to input validation, define types for component's args, kwargs, slots:

from typing import NamedTuple, Optional\nfrom django.template import Context\nfrom django_components import Component, Slot, SlotInput\n\nclass Button(Component):\n    class Args(NamedTuple):\n        size: int\n        text: str\n\n    class Kwargs(NamedTuple):\n        variable: str\n        another: int\n        maybe_var: Optional[int] = None  # May be omitted\n\n    class Slots(NamedTuple):\n        my_slot: Optional[SlotInput] = None\n        another_slot: SlotInput\n\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        args.size  # int\n        kwargs.variable  # str\n        slots.my_slot  # Slot[MySlotData]\n

To have type hints when calling Button.render() or Button.render_to_response(), wrap the inputs in their respective Args, Kwargs, and Slots classes:

Button.render(\n    # Error: First arg must be `int`, got `float`\n    args=Button.Args(\n        size=1.25,\n        text=\"abc\",\n    ),\n    # Error: Key \"another\" is missing\n    kwargs=Button.Kwargs(\n        variable=\"text\",\n    ),\n)\n
"},{"location":"#extensions","title":"Extensions","text":"

Django-components functionality can be extended with Extensions. Extensions allow for powerful customization and integrations. They can:

  • Tap into lifecycle events, such as when a component is created, deleted, or registered
  • Add new attributes and methods to the components
  • Add custom CLI commands
  • Add custom URLs

Some of the extensions include:

  • Component caching
  • Django View integration
  • Component defaults
  • Pydantic integration (input validation)

Some of the planned extensions include:

  • AlpineJS integration
  • Storybook integration
  • Component-level benchmarking with asv
"},{"location":"#caching","title":"Caching","text":"
  • Components can be cached using Django's cache framework.
  • Caching rules can be configured on a per-component basis.
  • Components are cached based on their input. Or you can write custom caching logic.
from django_components import Component\n\nclass MyComponent(Component):\n    class Cache:\n        enabled = True\n        ttl = 60 * 60 * 24  # 1 day\n\n        def hash(self, *args, **kwargs):\n            return hash(f\"{json.dumps(args)}:{json.dumps(kwargs)}\")\n
"},{"location":"#simple-testing","title":"Simple testing","text":"
  • Write tests for components with @djc_test decorator.
  • The decorator manages global state, ensuring that tests don't leak.
  • If using pytest, the decorator allows you to parametrize Django or Components settings.
  • The decorator also serves as a stand-in for Django's @override_settings.
from django_components.testing import djc_test\n\nfrom components.my_table import MyTable\n\n@djc_test\ndef test_my_table():\n    rendered = MyTable.render(\n        kwargs={\n            \"title\": \"My table\",\n        },\n    )\n    assert rendered == \"<table>My table</table>\"\n
"},{"location":"#debugging-features","title":"Debugging features","text":"
  • Visual component inspection: Highlight components and slots directly in your browser.
  • Detailed tracing logs to supply AI-agents with context: The logs include component and slot names and IDs, and their position in the tree.
"},{"location":"#sharing-components","title":"Sharing components","text":"
  • Install and use third-party components from PyPI
  • Or publish your own \"component registry\"
  • Highly customizable - Choose how the components are called in the template (and more):

    {% component \"calendar\" date=\"2024-11-06\" %}\n{% endcomponent %}\n\n{% calendar date=\"2024-11-06\" %}\n{% endcalendar %}\n
"},{"location":"#performance","title":"Performance","text":"

Our aim is to be at least as fast as Django templates.

As of 0.130, django-components is ~4x slower than Django templates.

Render time django 68.9\u00b10.6ms django-components 259\u00b14ms

See the full performance breakdown for more information.

"},{"location":"#release-notes","title":"Release notes","text":"

Read the Release Notes to see the latest features and fixes.

"},{"location":"#community-examples","title":"Community examples","text":"

One of our goals with django-components is to make it easy to share components between projects. Head over to the Community examples to see some examples.

"},{"location":"#contributing-and-development","title":"Contributing and development","text":"

Get involved or sponsor this project - See here

Running django-components locally for development - See here

"},{"location":"migrating_from_safer_staticfiles/","title":"Migrating from safer_staticfiles","text":"

This guide is for you if you're upgrating django_components to v0.100 or later from older versions.

In version 0.100, we changed how components' static JS and CSS files are handled. See more in the \"Static files\" section.

Migration steps:

  1. Remove django_components.safer_staticfiles from INSTALLED_APPS in your settings.py, and replace it with django.contrib.staticfiles.

Before:

INSTALLED_APPS = [\n   \"django.contrib.admin\",\n   ...\n   # \"django.contrib.staticfiles\",  # <-- ADD\n   \"django_components\",\n   \"django_components.safer_staticfiles\",  # <-- REMOVE\n]\n

After:

INSTALLED_APPS = [\n   \"django.contrib.admin\",\n   ...\n   \"django.contrib.staticfiles\",\n   \"django_components\",\n]\n
  1. Add STATICFILES_FINDERS to settings.py, and add django_components.finders.ComponentsFileSystemFinder:
STATICFILES_FINDERS = [\n   # Default finders\n   \"django.contrib.staticfiles.finders.FileSystemFinder\",\n   \"django.contrib.staticfiles.finders.AppDirectoriesFinder\",\n   # Django components\n   \"django_components.finders.ComponentsFileSystemFinder\",  # <-- ADDED\n]\n
  1. Add COMPONENTS.dirs to settings.py.

If you previously defined STATICFILES_DIRS, move only those directories from STATICFILES_DIRS that point to components directories, and keep the rest.

E.g. if you have STATICFILES_DIRS like this:

STATICFILES_DIRS = [\n   BASE_DIR / \"components\",  # <-- MOVE\n   BASE_DIR / \"myapp\" / \"components\",  # <-- MOVE\n   BASE_DIR / \"assets\",\n]\n

Then first two entries point to components dirs, whereas /assets points to non-component static files. In this case move only the first two paths:

COMPONENTS = {\n   \"dirs\": [\n      BASE_DIR / \"components\",  # <-- MOVED\n      BASE_DIR / \"myapp\" / \"components\",  # <-- MOVED\n   ],\n}\n\nSTATICFILES_DIRS = [\n   BASE_DIR / \"assets\",\n]\n

Moreover, if you defined app-level component directories in STATICFILES_DIRS before, you can now define as a RELATIVE path in app_dirs:

COMPONENTS = {\n   \"dirs\": [\n      # Search top-level \"/components/\" dir\n      BASE_DIR / \"components\",\n   ],\n   \"app_dirs\": [\n      # Search \"/[app]/components/\" dirs\n      \"components\",\n   ],\n}\n\nSTATICFILES_DIRS = [\n   BASE_DIR / \"assets\",\n]\n
"},{"location":"release_notes/","title":"Release notes","text":""},{"location":"release_notes/#v01412","title":"v0.141.2","text":""},{"location":"release_notes/#fix","title":"Fix","text":"
  • Fix bug where JS and CSS were missing when {% component %} tag was inside {% include %} tag (#1296)
"},{"location":"release_notes/#v01411","title":"v0.141.1","text":""},{"location":"release_notes/#fix_1","title":"Fix","text":"
  • Components' JS and CSS scripts (e.g. from Component.js or Component.js_file) are now cached at class creation time.

    This means that when you now restart the server while having a page opened in the browser, the JS / CSS files are immediately available.

    Previously, the JS/CSS were cached only after the components were rendered. So you had to reload the page to trigger the rendering, in order to make the JS/CSS files available.

  • Fix the default cache for JS / CSS scripts to be unbounded.

    Previously, the default cache for the JS/CSS scripts (LocMemCache) was accidentally limited to 300 entries (~150 components).

  • Do not send template_rendered signal when rendering a component with no template. (#1277)

"},{"location":"release_notes/#v01410","title":"v0.141.0","text":""},{"location":"release_notes/#feat","title":"Feat","text":"
  • New extension hooks on_template_loaded, on_js_loaded, on_css_loaded, and on_template_compiled

    The first 3 hooks are called when Component's template / JS / CSS is loaded as a string.

    The on_template_compiled hook is called when Component's template is compiled to a Template.

    The on_xx_loaded hooks can modify the content by returning the new value.

    class MyExtension(ComponentExtension):\n    def on_template_loaded(self, ctx: OnTemplateLoadedContext) -> Optional[str]:\n        return ctx.content + \"<!-- Hello! -->\"\n\n    def on_js_loaded(self, ctx: OnJsLoadedContext) -> Optional[str]:\n        return ctx.content + \"// Hello!\"\n\n    def on_css_loaded(self, ctx: OnCssLoadedContext) -> Optional[str]:\n        return ctx.content + \"/* Hello! */\"\n

    See all Extension hooks.

"},{"location":"release_notes/#fix_2","title":"Fix","text":"
  • Subclassing - Previously, if a parent component defined Component.template or Component.template_file, it's subclass would use the same Template instance.

    This could lead to unexpected behavior, where a change to the template of the subclass would also change the template of the parent class.

    Now, each subclass has it's own Template instance, and changes to the template of the subclass do not affect the template of the parent class.

  • Fix Django failing to restart due to \"TypeError: 'Dynamic' object is not iterable\" (#1232)

  • Fix bug when error formatting failed when error value was not a string.

"},{"location":"release_notes/#refactor","title":"Refactor","text":"
  • components ext run CLI command now allows to call only those extensions that actually have subcommands.
"},{"location":"release_notes/#v01401","title":"v0.140.1","text":""},{"location":"release_notes/#fix_3","title":"Fix","text":"
  • Fix typo preventing benchmarking (#1235)
"},{"location":"release_notes/#v01400","title":"\ud83d\udea8\ud83d\udce2 v0.140.0","text":"

\u26a0\ufe0f Major release \u26a0\ufe0f - Please test thoroughly before / after upgrading.

This is the biggest step towards v1. While this version introduces many small API changes, we don't expect to make further changes to the affected parts before v1.

For more details see #433.

Summary:

  • Overhauled typing system
  • Middleware removed, no longer needed
  • get_template_data() is the new canonical way to define template data. get_context_data() is now deprecated but will remain until v2.
  • Slots API polished and prepared for v1.
  • Merged Component.Url with Component.View
  • Added Component.args, Component.kwargs, Component.slots, Component.context
  • Added {{ component_vars.args }}, {{ component_vars.kwargs }}, {{ component_vars.slots }}
  • You should no longer instantiate Component instances. Instead, call Component.render() or Component.render_to_response() directly.
  • Component caching can now consider slots (opt-in)
  • And lot more...
"},{"location":"release_notes/#breaking-changes","title":"\ud83d\udea8\ud83d\udce2 BREAKING CHANGES","text":"

Middleware

  • The middleware ComponentDependencyMiddleware was removed as it is no longer needed.

    The middleware served one purpose - to render the JS and CSS dependencies of components when you rendered templates with Template.render() or django.shortcuts.render() and those templates contained {% component %} tags.

    • NOTE: If you rendered HTML with Component.render() or Component.render_to_response(), the JS and CSS were already rendered.

    Now, the JS and CSS dependencies of components are automatically rendered, even when you render Templates with Template.render() or django.shortcuts.render().

    To disable this behavior, set the DJC_DEPS_STRATEGY context key to \"ignore\" when rendering the template:

    # With `Template.render()`:\ntemplate = Template(template_str)\nrendered = template.render(Context({\"DJC_DEPS_STRATEGY\": \"ignore\"}))\n\n# Or with django.shortcuts.render():\nfrom django.shortcuts import render\nrendered = render(\n    request,\n    \"my_template.html\",\n    context={\"DJC_DEPS_STRATEGY\": \"ignore\"},\n)\n

    In fact, you can set the DJC_DEPS_STRATEGY context key to any of the strategies:

    • \"document\"
    • \"fragment\"
    • \"simple\"
    • \"prepend\"
    • \"append\"
    • \"ignore\"

    See Dependencies rendering for more info.

Typing

  • Component typing no longer uses generics. Instead, the types are now defined as class attributes of the component class.

    Before:

    Args = Tuple[float, str]\n\nclass Button(Component[Args]):\n    pass\n

    After:

    class Button(Component):\n    class Args(NamedTuple):\n        size: float\n        text: str\n

    See Migrating from generics to class attributes for more info. - Removed EmptyTuple and EmptyDict types. Instead, there is now a single Empty type.

    from django_components import Component, Empty\n\nclass Button(Component):\n    template = \"Hello\"\n\n    Args = Empty\n    Kwargs = Empty\n

Component API

  • The interface of the not-yet-released get_js_data() and get_css_data() methods has changed to match get_template_data().

    Before:

    def get_js_data(self, *args, **kwargs):\ndef get_css_data(self, *args, **kwargs):\n

    After:

    def get_js_data(self, args, kwargs, slots, context):\ndef get_css_data(self, args, kwargs, slots, context):\n
  • Arguments in Component.render_to_response() have changed to match that of Component.render().

    Please ensure that you pass the parameters as kwargs, not as positional arguments, to avoid breaking changes.

    The signature changed, moving the args and kwargs parameters to 2nd and 3rd position.

    Next, the render_dependencies parameter was added to match Component.render().

    Lastly:

    • Previously, any extra ARGS and KWARGS were passed to the response_class.
    • Now, only extra KWARGS will be passed to the response_class.

    Before:

      def render_to_response(\n      cls,\n      context: Optional[Union[Dict[str, Any], Context]] = None,\n      slots: Optional[SlotsType] = None,\n      escape_slots_content: bool = True,\n      args: Optional[ArgsType] = None,\n      kwargs: Optional[KwargsType] = None,\n      deps_strategy: DependenciesStrategy = \"document\",\n      request: Optional[HttpRequest] = None,\n      *response_args: Any,\n      **response_kwargs: Any,\n  ) -> HttpResponse:\n

    After:

    def render_to_response(\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    args: Optional[Any] = None,\n    kwargs: Optional[Any] = None,\n    slots: Optional[Any] = None,\n    deps_strategy: DependenciesStrategy = \"document\",\n    type: Optional[DependenciesStrategy] = None,  # Deprecated, use `deps_strategy`\n    render_dependencies: bool = True,  # Deprecated, use `deps_strategy=\"ignore\"`\n    outer_context: Optional[Context] = None,\n    request: Optional[HttpRequest] = None,\n    registry: Optional[ComponentRegistry] = None,\n    registered_name: Optional[str] = None,\n    node: Optional[ComponentNode] = None,\n    **response_kwargs: Any,\n) -> HttpResponse:\n
  • Component.render() and Component.render_to_response() NO LONGER accept escape_slots_content kwarg.

    Instead, slots are now always escaped.

    To disable escaping, wrap the result of slots in mark_safe().

    Before:

    html = component.render(\n    slots={\"my_slot\": \"CONTENT\"},\n    escape_slots_content=False,\n)\n

    After:

    html = component.render(\n    slots={\"my_slot\": mark_safe(\"CONTENT\")}\n)\n
  • Component.template no longer accepts a Template instance, only plain string.

    Before:

    class MyComponent(Component):\n    template = Template(\"{{ my_var }}\")\n

    Instead, either:

    1. Set Component.template to a plain string.

      class MyComponent(Component):\n    template = \"{{ my_var }}\"\n
    2. Move the template to it's own HTML file and set Component.template_file.

      class MyComponent(Component):\n    template_file = \"my_template.html\"\n
    3. Or, if you dynamically created the template, render the template inside Component.on_render().

      class MyComponent(Component):\n    def on_render(self, context, template):\n        dynamic_template = do_something_dynamic()\n        return dynamic_template.render(context)\n
  • Subclassing of components with None values has changed:

    Previously, when a child component's template / JS / CSS attributes were set to None, the child component still inherited the parent's template / JS / CSS.

    Now, the child component will not inherit the parent's template / JS / CSS if it sets the attribute to None.

    Before:

    class Parent(Component):\n    template = \"parent.html\"\n\nclass Child(Parent):\n    template = None\n\n# Child still inherited parent's template\nassert Child.template == Parent.template\n

    After:

    class Parent(Component):\n    template = \"parent.html\"\n\nclass Child(Parent):\n    template = None\n\n# Child does not inherit parent's template\nassert Child.template is None\n
  • The Component.Url class was merged with Component.View.

    Instead of Component.Url.public, use Component.View.public.

    If you imported ComponentUrl from django_components, you need to update your import to ComponentView.

    Before:

    class MyComponent(Component):\n    class Url:\n        public = True\n\n    class View:\n        def get(self, request):\n            return self.render_to_response()\n

    After:

    class MyComponent(Component):\n    class View:\n        public = True\n\n        def get(self, request):\n            return self.render_to_response()\n
  • Caching - The function signatures of Component.Cache.get_cache_key() and Component.Cache.hash() have changed to enable passing slots.

    Args and kwargs are no longer spread, but passed as a list and a dict, respectively.

    Before:

    def get_cache_key(self, *args: Any, **kwargs: Any) -> str:\n\ndef hash(self, *args: Any, **kwargs: Any) -> str:\n

    After:

    def get_cache_key(self, args: Any, kwargs: Any, slots: Any) -> str:\n\ndef hash(self, args: Any, kwargs: Any) -> str:\n

Template tags

  • Component name in the {% component %} tag can no longer be set as a kwarg.

    Instead, the component name MUST be the first POSITIONAL argument only.

    Before, it was possible to set the component name as a kwarg and put it anywhere in the {% component %} tag:

    {% component rows=rows headers=headers name=\"my_table\" ... / %}\n

    Now, the component name MUST be the first POSITIONAL argument:

    {% component \"my_table\" rows=rows headers=headers ... / %}\n

    Thus, the name kwarg can now be used as a regular input.

    {% component \"profile\" name=\"John\" job=\"Developer\" / %}\n

Slots

  • If you instantiated Slot class with kwargs, you should now use contents instead of content_func.

    Before:

    slot = Slot(content_func=lambda *a, **kw: \"CONTENT\")\n

    After:

    slot = Slot(contents=lambda ctx: \"CONTENT\")\n

    Alternatively, pass the function / content as first positional argument:

    slot = Slot(lambda ctx: \"CONTENT\")\n
  • The undocumented Slot.escaped attribute was removed.

    Instead, slots are now always escaped.

    To disable escaping, wrap the result of slots in mark_safe().

  • Slot functions behavior has changed. See the new Slots docs for more info.

    • Function signature:

      1. All parameters are now passed under a single ctx argument.

        You can still access all the same parameters via ctx.context, ctx.data, and ctx.fallback.

      2. context and fallback now may be None if the slot function was called outside of {% slot %} tag.

      Before:

      def slot_fn(context: Context, data: Dict, slot_ref: SlotRef):\n    isinstance(context, Context)\n    isinstance(data, Dict)\n    isinstance(slot_ref, SlotRef)\n\n    return \"CONTENT\"\n

      After:

      def slot_fn(ctx: SlotContext):\n    assert isinstance(ctx.context, Context) # May be None\n    assert isinstance(ctx.data, Dict)\n    assert isinstance(ctx.fallback, SlotFallback) # May be None\n\n    return \"CONTENT\"\n
    • Calling slot functions:

      1. Rather than calling the slot functions directly, you should now call the Slot instances.

      2. All parameters are now optional.

      3. The order of parameters has changed.

      Before:

      def slot_fn(context: Context, data: Dict, slot_ref: SlotRef):\n    return \"CONTENT\"\n\nhtml = slot_fn(context, data, slot_ref)\n

      After:

      def slot_fn(ctx: SlotContext):\n    return \"CONTENT\"\n\nslot = Slot(slot_fn)\nhtml = slot()\nhtml = slot({\"data1\": \"abc\", \"data2\": \"hello\"})\nhtml = slot({\"data1\": \"abc\", \"data2\": \"hello\"}, fallback=\"FALLBACK\")\n
    • Usage in components:

      Before:

      class MyComponent(Component):\n    def get_context_data(self, *args, **kwargs):\n        slots = self.input.slots\n        slot_fn = slots[\"my_slot\"]\n        html = slot_fn(context, data, slot_ref)\n        return {\n            \"html\": html,\n        }\n

      After:

      class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        slot_fn = slots[\"my_slot\"]\n        html = slot_fn(data)\n        return {\n            \"html\": html,\n        }\n

Miscellaneous

  • The second argument to render_dependencies() is now strategy instead of type.

    Before:

    render_dependencies(content, type=\"document\")\n

    After:

    render_dependencies(content, strategy=\"document\")\n
"},{"location":"release_notes/#deprecation","title":"\ud83d\udea8\ud83d\udce2 Deprecation","text":"

Component API

  • Component.get_context_data() is now deprecated. Use Component.get_template_data() instead.

    get_template_data() behaves the same way, but has a different function signature to accept also slots and context.

    Since get_context_data() is widely used, it will remain available until v2.

  • Component.get_template_name() and Component.get_template() are now deprecated. Use Component.template, Component.template_file or Component.on_render() instead.

    Component.get_template_name() and Component.get_template() will be removed in v1.

    In v1, each Component will have at most one static template. This is needed to enable support for Markdown, Pug, or other pre-processing of templates by extensions.

    If you are using the deprecated methods to point to different templates, there's 2 ways to migrate:

    1. Split the single Component into multiple Components, each with its own template. Then switch between them in Component.on_render():

      class MyComponentA(Component):\n    template_file = \"a.html\"\n\nclass MyComponentB(Component):\n    template_file = \"b.html\"\n\nclass MyComponent(Component):\n    def on_render(self, context, template):\n        if context[\"a\"]:\n            return MyComponentA.render(context)\n        else:\n            return MyComponentB.render(context)\n
    2. Alternatively, use Component.on_render() with Django's get_template() to dynamically render different templates:

      from django.template.loader import get_template\n\nclass MyComponent(Component):\n    def on_render(self, context, template):\n        if context[\"a\"]:\n            template_name = \"a.html\"\n        else:\n            template_name = \"b.html\"\n\n        actual_template = get_template(template_name)\n        return actual_template.render(context)\n

    Read more in django-components#1204.

  • The type kwarg in Component.render() and Component.render_to_response() is now deprecated. Use deps_strategy instead. The type kwarg will be removed in v1.

    Before:

    Calendar.render_to_response(type=\"fragment\")\n

    After:

    Calendar.render_to_response(deps_strategy=\"fragment\")\n
  • The render_dependencies kwarg in Component.render() and Component.render_to_response() is now deprecated. Use deps_strategy=\"ignore\" instead. The render_dependencies kwarg will be removed in v1.

    Before:

    Calendar.render_to_response(render_dependencies=False)\n

    After:

    Calendar.render_to_response(deps_strategy=\"ignore\")\n
  • Support for Component constructor kwargs registered_name, outer_context, and registry is deprecated, and will be removed in v1.

    Before, you could instantiate a standalone component, and then call render() on the instance:

    comp = MyComponent(\n    registered_name=\"my_component\",\n    outer_context=my_context,\n    registry=my_registry,\n)\ncomp.render(\n    args=[1, 2, 3],\n    kwargs={\"a\": 1, \"b\": 2},\n    slots={\"my_slot\": \"CONTENT\"},\n)\n

    Now you should instead pass all that data to Component.render() / Component.render_to_response():

    MyComponent.render(\n    args=[1, 2, 3],\n    kwargs={\"a\": 1, \"b\": 2},\n    slots={\"my_slot\": \"CONTENT\"},\n    # NEW\n    registered_name=\"my_component\",\n    outer_context=my_context,\n    registry=my_registry,\n)\n
  • Component.input (and its type ComponentInput) is now deprecated. The input property will be removed in v1.

    Instead, use attributes directly on the Component instance.

    Before:

    class MyComponent(Component):\n    def on_render(self, context, template):\n        assert self.input.args == [1, 2, 3]\n        assert self.input.kwargs == {\"a\": 1, \"b\": 2}\n        assert self.input.slots == {\"my_slot\": \"CONTENT\"}\n        assert self.input.context == {\"my_slot\": \"CONTENT\"}\n        assert self.input.deps_strategy == \"document\"\n        assert self.input.type == \"document\"\n        assert self.input.render_dependencies == True\n

    After:

    class MyComponent(Component):\n    def on_render(self, context, template):\n        assert self.args == [1, 2, 3]\n        assert self.kwargs == {\"a\": 1, \"b\": 2}\n        assert self.slots == {\"my_slot\": \"CONTENT\"}\n        assert self.context == {\"my_slot\": \"CONTENT\"}\n        assert self.deps_strategy == \"document\"\n        assert (self.deps_strategy != \"ignore\") is True\n
  • Component method on_render_after was updated to receive also error field.

    For backwards compatibility, the error field can be omitted until v1.

    Before:

    def on_render_after(\n    self,\n    context: Context,\n    template: Template,\n    html: str,\n) -> None:\n    pass\n

    After:

    def on_render_after(\n    self,\n    context: Context,\n    template: Template,\n    html: Optional[str],\n    error: Optional[Exception],\n) -> None:\n    pass\n
  • If you are using the Components as views, the way to access the component class is now different.

    Instead of self.component, use self.component_cls. self.component will be removed in v1.

    Before:

    class MyView(View):\n    def get(self, request):\n        return self.component.render_to_response(request=request)\n

    After:

    class MyView(View):\n    def get(self, request):\n        return self.component_cls.render_to_response(request=request)\n

Extensions

  • In the on_component_data() extension hook, the context_data field of the context object was superseded by template_data.

    The context_data field will be removed in v1.0.

    Before:

    class MyExtension(ComponentExtension):\n    def on_component_data(self, ctx: OnComponentDataContext) -> None:\n        ctx.context_data[\"my_template_var\"] = \"my_value\"\n

    After:

    class MyExtension(ComponentExtension):\n    def on_component_data(self, ctx: OnComponentDataContext) -> None:\n        ctx.template_data[\"my_template_var\"] = \"my_value\"\n
  • When creating extensions, the ComponentExtension.ExtensionClass attribute was renamed to ComponentConfig.

    The old name is deprecated and will be removed in v1.

    Before:

    from django_components import ComponentExtension\n\nclass MyExtension(ComponentExtension):\n    class ExtensionClass(ComponentExtension.ExtensionClass):\n        pass\n

    After:

    from django_components import ComponentExtension, ExtensionComponentConfig\n\nclass MyExtension(ComponentExtension):\n    class ComponentConfig(ExtensionComponentConfig):\n        pass\n
  • When creating extensions, to access the Component class from within the methods of the extension nested classes, use component_cls.

    Previously this field was named component_class. The old name is deprecated and will be removed in v1.

ComponentExtension.ExtensionClass attribute was renamed to ComponentConfig.

The old name is deprecated and will be removed in v1.\n\nBefore:\n\n```py\nfrom django_components import ComponentExtension, ExtensionComponentConfig\n\nclass LoggerExtension(ComponentExtension):\n    name = \"logger\"\n\n    class ComponentConfig(ExtensionComponentConfig):\n        def log(self, msg: str) -> None:\n            print(f\"{self.component_class.__name__}: {msg}\")\n```\n\nAfter:\n\n```py\nfrom django_components import ComponentExtension, ExtensionComponentConfig\n\nclass LoggerExtension(ComponentExtension):\n    name = \"logger\"\n\n    class ComponentConfig(ExtensionComponentConfig):\n        def log(self, msg: str) -> None:\n            print(f\"{self.component_cls.__name__}: {msg}\")\n```\n

Slots

  • SlotContent was renamed to SlotInput. The old name is deprecated and will be removed in v1.

  • SlotRef was renamed to SlotFallback. The old name is deprecated and will be removed in v1.

  • The default kwarg in {% fill %} tag was renamed to fallback. The old name is deprecated and will be removed in v1.

    Before:

    {% fill \"footer\" default=\"footer\" %}\n    {{ footer }}\n{% endfill %}\n

    After:

    {% fill \"footer\" fallback=\"footer\" %}\n    {{ footer }}\n{% endfill %}\n
  • The template variable {{ component_vars.is_filled }} is now deprecated. Will be removed in v1. Use {{ component_vars.slots }} instead.

    Before:

    {% if component_vars.is_filled.footer %}\n    <div>\n        {% slot \"footer\" / %}\n    </div>\n{% endif %}\n

    After:

    {% if component_vars.slots.footer %}\n    <div>\n        {% slot \"footer\" / %}\n    </div>\n{% endif %}\n

    NOTE: component_vars.is_filled automatically escaped slot names, so that even slot names that are not valid python identifiers could be set as slot names. component_vars.slots no longer does that.

  • Component attribute Component.is_filled is now deprecated. Will be removed in v1. Use Component.slots instead.

    Before:

    class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        if self.is_filled.footer:\n            color = \"red\"\n        else:\n            color = \"blue\"\n\n        return {\n            \"color\": color,\n        }\n

    After:

    class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        if \"footer\" in slots:\n            color = \"red\"\n        else:\n            color = \"blue\"\n\n        return {\n            \"color\": color,\n        }\n

    NOTE: Component.is_filled automatically escaped slot names, so that even slot names that are not valid python identifiers could be set as slot names. Component.slots no longer does that.

Miscellaneous

  • Template caching with cached_template() helper and template_cache_size setting is deprecated. These will be removed in v1.

    This feature made sense if you were dynamically generating templates for components using Component.get_template_string() and Component.get_template().

    However, in v1, each Component will have at most one static template. This static template is cached internally per component class, and reused across renders.

    This makes the template caching feature obsolete.

    If you relied on cached_template(), you should either:

    1. Wrap the templates as Components.
    2. Manage the cache of Templates yourself.
  • The debug_highlight_components and debug_highlight_slots settings are deprecated. These will be removed in v1.

    The debug highlighting feature was re-implemented as an extension. As such, the recommended way for enabling it has changed:

    Before:

    COMPONENTS = ComponentsSettings(\n    debug_highlight_components=True,\n    debug_highlight_slots=True,\n)\n

    After:

    Set extensions_defaults in your settings.py file.

    COMPONENTS = ComponentsSettings(\n    extensions_defaults={\n        \"debug_highlight\": {\n            \"highlight_components\": True,\n            \"highlight_slots\": True,\n        },\n    },\n)\n

    Alternatively, you can enable highlighting for specific components by setting Component.DebugHighlight.highlight_components to True:

    class MyComponent(Component):\n    class DebugHighlight:\n        highlight_components = True\n        highlight_slots = True\n
"},{"location":"release_notes/#feat_1","title":"Feat","text":"
  • New method to render template variables - get_template_data()

    get_template_data() behaves the same way as get_context_data(), but has a different function signature to accept also slots and context.

    class Button(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"val1\": args[0],\n            \"val2\": kwargs[\"field\"],\n        }\n

    If you define Component.Args, Component.Kwargs, Component.Slots, then the args, kwargs, slots arguments will be instances of these classes:

    class Button(Component):\n    class Args(NamedTuple):\n        field1: str\n\n    class Kwargs(NamedTuple):\n        field2: int\n\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots, context):\n        return {\n            \"val1\": args.field1,\n            \"val2\": kwargs.field2,\n        }\n
  • Input validation is now part of the render process.

    When you specify the input types (such as Component.Args, Component.Kwargs, etc), the actual inputs to data methods (Component.get_template_data(), etc) will be instances of the types you specified.

    This practically brings back input validation, because the instantiation of the types will raise an error if the inputs are not valid.

    Read more on Typing and validation

  • Render emails or other non-browser HTML with new \"dependencies strategies\"

    When rendering a component with Component.render() or Component.render_to_response(), the deps_strategy kwarg (previously type) now accepts additional options:

    • \"simple\"
    • \"prepend\"
    • \"append\"
    • \"ignore\"
    Calendar.render_to_response(\n    request=request,\n    kwargs={\n        \"date\": request.GET.get(\"date\", \"\"),\n    },\n    deps_strategy=\"append\",\n)\n

    Comparison of dependencies render strategies:

    • \"document\"
      • Smartly inserts JS / CSS into placeholders or into <head> and <body> tags.
      • Inserts extra script to allow fragment strategy to work.
      • Assumes the HTML will be rendered in a JS-enabled browser.
    • \"fragment\"
      • A lightweight HTML fragment to be inserted into a document with AJAX.
      • Ignores placeholders and any <head> / <body> tags.
      • No JS / CSS included.
    • \"simple\"
      • Smartly insert JS / CSS into placeholders or into <head> and <body> tags.
      • No extra script loaded.
    • \"prepend\"
      • Insert JS / CSS before the rendered HTML.
      • Ignores placeholders and any <head> / <body> tags.
      • No extra script loaded.
    • \"append\"
      • Insert JS / CSS after the rendered HTML.
      • Ignores placeholders and any <head> / <body> tags.
      • No extra script loaded.
    • \"ignore\"
      • Rendered HTML is left as-is. You can still process it with a different strategy later with render_dependencies().
      • Used for inserting rendered HTML into other components.

    See Dependencies rendering for more info.

  • New Component.args, Component.kwargs, Component.slots attributes available on the component class itself.

    These attributes are the same as the ones available in Component.get_template_data().

    You can use these in other methods like Component.on_render_before() or Component.on_render_after().

    from django_components import Component, SlotInput\n\nclass Table(Component):\n    class Args(NamedTuple):\n        page: int\n\n    class Kwargs(NamedTuple):\n        per_page: int\n\n    class Slots(NamedTuple):\n        content: SlotInput\n\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.args.page == 123\n        assert self.kwargs.per_page == 10\n        content_html = self.slots.content()\n

    Same as with the parameters in Component.get_template_data(), they will be instances of the Args, Kwargs, Slots classes if defined, or plain lists / dictionaries otherwise.

  • 4 attributes that were previously available only under the Component.input attribute are now available directly on the Component instance:

    • Component.raw_args
    • Component.raw_kwargs
    • Component.raw_slots
    • Component.deps_strategy

    The first 3 attributes are the same as the deprecated Component.input.args, Component.input.kwargs, Component.input.slots properties.

    Compared to the Component.args / Component.kwargs / Component.slots attributes, these \"raw\" attributes are not typed and will remain as plain lists / dictionaries even if you define the Args, Kwargs, Slots classes.

    The Component.deps_strategy attribute is the same as the deprecated Component.input.deps_strategy property.

  • New template variables {{ component_vars.args }}, {{ component_vars.kwargs }}, {{ component_vars.slots }}

    These attributes are the same as the ones available in Component.get_template_data().

    {# Typed #}\n{% if component_vars.args.page == 123 %}\n    <div>\n        {% slot \"content\" / %}\n    </div>\n{% endif %}\n\n{# Untyped #}\n{% if component_vars.args.0 == 123 %}\n    <div>\n        {% slot \"content\" / %}\n    </div>\n{% endif %}\n

    Same as with the parameters in Component.get_template_data(), they will be instances of the Args, Kwargs, Slots classes if defined, or plain lists / dictionaries otherwise.

  • New component lifecycle hook Component.on_render().

    This hook is called when the component is being rendered.

    You can override this method to:

    • Change what template gets rendered
    • Modify the context
    • Modify the rendered output after it has been rendered
    • Handle errors

    See on_render for more info.

  • get_component_url() now optionally accepts query and fragment arguments.

    from django_components import get_component_url\n\nurl = get_component_url(\n    MyComponent,\n    query={\"foo\": \"bar\"},\n    fragment=\"baz\",\n)\n# /components/ext/view/components/c1ab2c3?foo=bar#baz\n
  • The BaseNode class has a new contents attribute, which contains the raw contents (string) of the tag body.

    This is relevant when you define custom template tags with @template_tag decorator or BaseNode class.

    When you define a custom template tag like so:

    from django_components import BaseNode, template_tag\n\n@template_tag(\n    library,\n    tag=\"mytag\",\n    end_tag=\"endmytag\",\n    allowed_flags=[\"required\"]\n)\ndef mytag(node: BaseNode, context: Context, name: str, **kwargs) -> str:\n    print(node.contents)\n    return f\"Hello, {name}!\"\n

    And render it like so:

    {% mytag name=\"John\" %}\n    Hello, world!\n{% endmytag %}\n

    Then, the contents attribute of the BaseNode instance will contain the string \"Hello, world!\".

  • The BaseNode class also has two new metadata attributes:

    • template_name - the name of the template that rendered the node.
    • template_component - the component class that the template belongs to.

    This is useful for debugging purposes.

  • Slot class now has 3 new metadata fields:

    1. Slot.contents attribute contains the original contents:

      • If Slot was created from {% fill %} tag, Slot.contents will contain the body of the {% fill %} tag.
      • If Slot was created from string via Slot(\"...\"), Slot.contents will contain that string.
      • If Slot was created from a function, Slot.contents will contain that function.
    2. Slot.extra attribute where you can put arbitrary metadata about the slot.

    3. Slot.fill_node attribute tells where the slot comes from:

      • FillNode instance if the slot was created from {% fill %} tag.
      • ComponentNode instance if the slot was created as a default slot from a {% component %} tag.
      • None if the slot was created from a string, function, or Slot instance.

    See Slot metadata.

  • {% fill %} tag now accepts body kwarg to pass a Slot instance to fill.

    First pass a Slot instance to the template with the get_template_data() method:

    from django_components import component, Slot\n\nclass Table(Component):\n  def get_template_data(self, args, kwargs, slots, context):\n    return {\n        \"my_slot\": Slot(lambda ctx: \"Hello, world!\"),\n    }\n

    Then pass the slot to the {% fill %} tag:

    {% component \"table\" %}\n  {% fill \"pagination\" body=my_slot / %}\n{% endcomponent %}\n
  • You can now access the {% component %} tag (ComponentNode instance) from which a Component was created. Use Component.node to access it.

    This is mostly useful for extensions, which can use this to detect if the given Component comes from a {% component %} tag or from a different source (such as Component.render()).

    Component.node is None if the component is created by Component.render() (but you can pass in the node kwarg yourself).

    class MyComponent(Component):\n    def get_template_data(self, context, template):\n        if self.node is not None:\n            assert self.node.name == \"my_component\"\n
  • Node classes ComponentNode, FillNode, ProvideNode, and SlotNode are part of the public API.

    These classes are what is instantiated when you use {% component %}, {% fill %}, {% provide %}, and {% slot %} tags.

    You can for example use these for type hints:

    from django_components import Component, ComponentNode\n\nclass MyTable(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        if kwargs.get(\"show_owner\"):\n            node: Optional[ComponentNode] = self.node\n            owner: Optional[Component] = self.node.template_component\n        else:\n            node = None\n            owner = None\n\n        return {\n            \"owner\": owner,\n            \"node\": node,\n        }\n
  • Component caching can now take slots into account, by setting Component.Cache.include_slots to True.

    class MyComponent(Component):\n    class Cache:\n        enabled = True\n        include_slots = True\n

    In which case the following two calls will generate separate cache entries:

    {% component \"my_component\" position=\"left\" %}\n    Hello, Alice\n{% endcomponent %}\n\n{% component \"my_component\" position=\"left\" %}\n    Hello, Bob\n{% endcomponent %}\n

    Same applies to Component.render() with string slots:

    MyComponent.render(\n    kwargs={\"position\": \"left\"},\n    slots={\"content\": \"Hello, Alice\"}\n)\nMyComponent.render(\n    kwargs={\"position\": \"left\"},\n    slots={\"content\": \"Hello, Bob\"}\n)\n

    Read more on Component caching.

  • New extension hook on_slot_rendered()

    This hook is called when a slot is rendered, and allows you to access and/or modify the rendered result.

    This is used by the \"debug highlight\" feature.

    To modify the rendered result, return the new value:

    class MyExtension(ComponentExtension):\n    def on_slot_rendered(self, ctx: OnSlotRenderedContext) -> Optional[str]:\n        return ctx.result + \"<!-- Hello, world! -->\"\n

    If you don't want to modify the rendered result, return None.

    See all Extension hooks.

  • When creating extensions, the previous syntax with ComponentExtension.ExtensionClass was causing Mypy errors, because Mypy doesn't allow using class attributes as bases:

    Before:

    from django_components import ComponentExtension\n\nclass MyExtension(ComponentExtension):\n    class ExtensionClass(ComponentExtension.ExtensionClass):  # Error!\n        pass\n

    Instead, you can import ExtensionComponentConfig directly:

    After:

    from django_components import ComponentExtension, ExtensionComponentConfig\n\nclass MyExtension(ComponentExtension):\n    class ComponentConfig(ExtensionComponentConfig):\n        pass\n
"},{"location":"release_notes/#refactor_1","title":"Refactor","text":"
  • When a component is being rendered, a proper Component instance is now created.

    Previously, the Component state was managed as half-instance, half-stack.

  • Component's \"Render API\" (args, kwargs, slots, context, inputs, request, context data, etc) can now be accessed also outside of the render call. So now its possible to take the component instance out of get_template_data() (although this is not recommended).

  • Components can now be defined without a template.

    Previously, the following would raise an error:

    class MyComponent(Component):\n    pass\n

    \"Template-less\" components can be used together with Component.on_render() to dynamically pick what to render:

    class TableNew(Component):\n    template_file = \"table_new.html\"\n\nclass TableOld(Component):\n    template_file = \"table_old.html\"\n\nclass Table(Component):\n    def on_render(self, context, template):\n        if self.kwargs.get(\"feat_table_new_ui\"):\n            return TableNew.render(args=self.args, kwargs=self.kwargs, slots=self.slots)\n        else:\n            return TableOld.render(args=self.args, kwargs=self.kwargs, slots=self.slots)\n

    \"Template-less\" components can be also used as a base class for other components, or as mixins.

  • Passing Slot instance to Slot constructor raises an error.

  • Extension hook on_component_rendered now receives error field.

    on_component_rendered now behaves similar to Component.on_render_after:

    • Raising error in this hook overrides what error will be returned from Component.render().
    • Returning new string overrides what will be returned from Component.render().

    Before:

    class OnComponentRenderedContext(NamedTuple):\n    component: \"Component\"\n    component_cls: Type[\"Component\"]\n    component_id: str\n    result: str\n

    After:

    class OnComponentRenderedContext(NamedTuple):\n    component: \"Component\"\n    component_cls: Type[\"Component\"]\n    component_id: str\n    result: Optional[str]\n    error: Optional[Exception]\n
"},{"location":"release_notes/#fix_4","title":"Fix","text":"
  • Fix bug: Context processors data was being generated anew for each component. Now the data is correctly created once and reused across components with the same request (#1165).

  • Fix KeyError on component_context_cache when slots are rendered outside of the component's render context. (#1189)

  • Component classes now have do_not_call_in_templates=True to prevent them from being called as functions in templates.

"},{"location":"release_notes/#v01391","title":"v0.139.1","text":""},{"location":"release_notes/#fix_5","title":"Fix","text":"
  • Fix compatibility of component caching with {% extend %} block (#1135)
"},{"location":"release_notes/#refactor_2","title":"Refactor","text":"
  • Component ID is now prefixed with c, e.g. c123456.

  • When typing a Component, you can now specify as few or as many parameters as you want.

    Component[Args]\nComponent[Args, Kwargs]\nComponent[Args, Kwargs, Slots]\nComponent[Args, Kwargs, Slots, Data]\nComponent[Args, Kwargs, Slots, Data, JsData]\nComponent[Args, Kwargs, Slots, Data, JsData, CssData]\n

    All omitted parameters will default to Any.

  • Added typing_extensions to the project as a dependency

  • Multiple extensions with the same name (case-insensitive) now raise an error

  • Extension names (case-insensitive) also MUST NOT conflict with existing Component class API.

    So if you name an extension render, it will conflict with the render() method of the Component class, and thus raise an error.

"},{"location":"release_notes/#v01390","title":"v0.139.0","text":""},{"location":"release_notes/#fix_6","title":"Fix","text":"
  • Fix bug: Fix compatibility with Finder.find() in Django 5.2 (#1119)
"},{"location":"release_notes/#v0138","title":"v0.138","text":""},{"location":"release_notes/#fix_7","title":"Fix","text":"
  • Fix bug: Allow components with Url.public = True to be defined before django.setup()
"},{"location":"release_notes/#v0137","title":"v0.137","text":""},{"location":"release_notes/#feat_2","title":"Feat","text":"
  • Each Component class now has a class_id attribute, which is unique to the component subclass.

    NOTE: This is different from Component.id, which is unique to each rendered instance.

    To look up a component class by its class_id, use get_component_by_class_id().

  • It's now easier to create URLs for component views.

    Before, you had to call Component.as_view() and pass that to urlpatterns.

    Now this can be done for you if you set Component.Url.public to True:

    class MyComponent(Component):\n    class Url:\n        public = True\n    ...\n

    Then, to get the URL for the component, use get_component_url():

    from django_components import get_component_url\n\nurl = get_component_url(MyComponent)\n

    This way you don't have to mix your app URLs with component URLs.

    Read more on Component views and URLs.

  • Per-component caching - Set Component.Cache.enabled to True to enable caching for a component.

    Component caching allows you to store the rendered output of a component. Next time the component is rendered with the same input, the cached output is returned instead of re-rendering the component.

    class TestComponent(Component):\n    template = \"Hello\"\n\n    class Cache:\n        enabled = True\n        ttl = 0.1  # .1 seconds TTL\n        cache_name = \"custom_cache\"\n\n        # Custom hash method for args and kwargs\n        # NOTE: The default implementation simply serializes the input into a string.\n        #       As such, it might not be suitable for complex objects like Models.\n        def hash(self, *args, **kwargs):\n            return f\"{json.dumps(args)}:{json.dumps(kwargs)}\"\n

    Read more on Component caching.

  • @djc_test can now be called without first calling django.setup(), in which case it does it for you.

  • Expose ComponentInput class, which is a typing for Component.input.

"},{"location":"release_notes/#deprecation_1","title":"Deprecation","text":"
  • Currently, view request handlers such as get() and post() methods can be defined directly on the Component class:

    class MyComponent(Component):\n    def get(self, request):\n        return self.render_to_response()\n

    Or, nested within the Component.View class:

    class MyComponent(Component):\n    class View:\n        def get(self, request):\n            return self.render_to_response()\n

    In v1, these methods should be defined only on the Component.View class instead.

"},{"location":"release_notes/#refactor_3","title":"Refactor","text":"
  • Component.get_context_data() can now omit a return statement or return None.
"},{"location":"release_notes/#v0136","title":"\ud83d\udea8\ud83d\udce2 v0.136","text":""},{"location":"release_notes/#breaking-changes_1","title":"\ud83d\udea8\ud83d\udce2 BREAKING CHANGES","text":"
  • Component input validation was moved to a separate extension djc-ext-pydantic.

    If you relied on components raising errors when inputs were invalid, you need to install djc-ext-pydantic and add it to extensions:

    # settings.py\nCOMPONENTS = {\n    \"extensions\": [\n        \"djc_pydantic.PydanticExtension\",\n    ],\n}\n
"},{"location":"release_notes/#fix_8","title":"Fix","text":"
  • Make it possible to resolve URLs added by extensions by their names
"},{"location":"release_notes/#v0135","title":"v0.135","text":""},{"location":"release_notes/#feat_3","title":"Feat","text":"
  • Add defaults for the component inputs with the Component.Defaults nested class. Defaults are applied if the argument is not given, or if it set to None.

For lists, dictionaries, or other objects, wrap the value in Default() class to mark it as a factory function:

```python\nfrom django_components import Default\n\nclass Table(Component):\n    class Defaults:\n        position = \"left\"\n        width = \"200px\"\n        options = Default(lambda: [\"left\", \"right\", \"center\"])\n\n    def get_context_data(self, position, width, options):\n        return {\n            \"position\": position,\n            \"width\": width,\n            \"options\": options,\n        }\n\n# `position` is used as given, `\"right\"`\n# `width` uses default because it's `None`\n# `options` uses default because it's missing\nTable.render(\n    kwargs={\n        \"position\": \"right\",\n        \"width\": None,\n    }\n)\n```\n
  • {% html_attrs %} now offers a Vue-like granular control over class and style HTML attributes, where each class name or style property can be managed separately.

    {% html_attrs\n    class=\"foo bar\"\n    class={\"baz\": True, \"foo\": False}\n    class=\"extra\"\n%}\n
    {% html_attrs\n    style=\"text-align: center; background-color: blue;\"\n    style={\"background-color\": \"green\", \"color\": None, \"width\": False}\n    style=\"position: absolute; height: 12px;\"\n%}\n

    Read more on HTML attributes.

"},{"location":"release_notes/#fix_9","title":"Fix","text":"
  • Fix compat with Windows when reading component files (#1074)
  • Fix resolution of component media files edge case (#1073)
"},{"location":"release_notes/#v0134","title":"v0.134","text":""},{"location":"release_notes/#fix_10","title":"Fix","text":"
  • HOTFIX: Fix the use of URLs in Component.Media.js and Component.Media.css
"},{"location":"release_notes/#v0133","title":"v0.133","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.134 to fix bugs introduced in v0.132.

"},{"location":"release_notes/#fix_11","title":"Fix","text":"
  • HOTFIX: Fix the use of URLs in Component.Media.js and Component.Media.css
"},{"location":"release_notes/#v0132","title":"v0.132","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.134 to fix bugs introduced in v0.132.

"},{"location":"release_notes/#feat_4","title":"Feat","text":"
  • Allow to use glob patterns as paths for additional JS / CSS in Component.Media.js and Component.Media.css

    class MyComponent(Component):\n    class Media:\n        js = [\"*.js\"]\n        css = [\"*.css\"]\n
"},{"location":"release_notes/#fix_12","title":"Fix","text":"
  • Fix installation for Python 3.13 on Windows.
"},{"location":"release_notes/#v0131","title":"v0.131","text":""},{"location":"release_notes/#feat_5","title":"Feat","text":"
  • Support for extensions (plugins) for django-components!

    • Hook into lifecycle events of django-components
    • Pre-/post-process component inputs, outputs, and templates
    • Add extra methods or attributes to Components
    • Add custom extension-specific CLI commands
    • Add custom extension-specific URL routes

    Read more on Extensions.

  • New CLI commands:

    • components list - List all components
    • components create <name> - Create a new component (supersedes startcomponent)
    • components upgrade - Upgrade a component (supersedes upgradecomponent)
    • components ext list - List all extensions
    • components ext run <extension> <command> - Run a command added by an extension
  • @djc_test decorator for writing tests that involve Components.

    • The decorator manages global state, ensuring that tests don't leak.
    • If using pytest, the decorator allows you to parametrize Django or Components settings.
    • The decorator also serves as a stand-in for Django's @override_settings.

    See the API reference for @djc_test for more details.

  • ComponentRegistry now has a has() method to check if a component is registered without raising an error.

  • Get all created Component classes with all_components().

  • Get all created ComponentRegistry instances with all_registries().

"},{"location":"release_notes/#refactor_4","title":"Refactor","text":"
  • The startcomponent and upgradecomponent commands are deprecated, and will be removed in v1.

    Instead, use components create <name> and components upgrade.

"},{"location":"release_notes/#internal","title":"Internal","text":"
  • Settings are now loaded only once, and thus are considered immutable once loaded. Previously, django-components would load settings from settings.COMPONENTS on each access. The new behavior aligns with Django's settings.
"},{"location":"release_notes/#v0130","title":"v0.130","text":""},{"location":"release_notes/#feat_6","title":"Feat","text":"
  • Access the HttpRequest object under Component.request.

    To pass the request object to a component, either: - Render a template or component with RequestContext, - Or set the request kwarg to Component.render() or Component.render_to_response().

    Read more on HttpRequest.

  • Access the context processors data under Component.context_processors_data.

    Context processors data is available only when the component has access to the request object, either by: - Passing the request to Component.render() or Component.render_to_response(), - Or by rendering a template or component with RequestContext, - Or being nested in another component that has access to the request object.

    The data from context processors is automatically available within the component's template.

    Read more on HttpRequest.

"},{"location":"release_notes/#v0129","title":"v0.129","text":""},{"location":"release_notes/#fix_13","title":"Fix","text":"
  • Fix thread unsafe media resolve validation by moving it to ComponentMedia __post_init (#977
  • Fix bug: Relative path in extends and include does not work when using template_file (#976
  • Fix error when template cache setting (template_cache_size) is set to 0 (#974
"},{"location":"release_notes/#v0128","title":"v0.128","text":""},{"location":"release_notes/#feat_7","title":"Feat","text":"
  • Configurable cache - Set COMPONENTS.cache to change where and how django-components caches JS and CSS files. (#946)

    Read more on Caching.

  • Highlight coponents and slots in the UI - We've added two boolean settings COMPONENTS.debug_highlight_components and COMPONENTS.debug_highlight_slots, which can be independently set to True. First will wrap components in a blue border, the second will wrap slots in a red border. (#942)

    Read more on Troubleshooting.

"},{"location":"release_notes/#refactor_5","title":"Refactor","text":"
  • Removed use of eval for node validation (#944)
"},{"location":"release_notes/#perf","title":"Perf","text":"
  • Components can now be infinitely nested. (#936)

  • Component input validation is now 6-7x faster on CPython and PyPy. This previously made up 10-30% of the total render time. (#945)

"},{"location":"release_notes/#v0127","title":"v0.127","text":""},{"location":"release_notes/#fix_14","title":"Fix","text":"
  • Fix component rendering when using {% cache %} with remote cache and multiple web servers (#930)
"},{"location":"release_notes/#v0126","title":"v0.126","text":""},{"location":"release_notes/#refactor_6","title":"Refactor","text":"
  • Replaced BeautifulSoup4 with a custom HTML parser.
  • The heuristic for inserting JS and CSS dependenies into the default place has changed.
    • JS is still inserted at the end of the <body>, and CSS at the end of <head>.
    • However, we find end of <body> by searching for last occurrence of </body>
    • And for the end of <head> we search for the first occurrence of </head>
"},{"location":"release_notes/#v0125","title":"v0.125","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - We migrated from EmilStenstrom/django-components to django-components/django-components.

Repo name and documentation URL changed. Package name remains the same.

If you see any broken links or other issues, please report them in #922.

"},{"location":"release_notes/#feat_8","title":"Feat","text":"
  • @template_tag and BaseNode - A decorator and a class that allow you to define custom template tags that will behave similarly to django-components' own template tags.

Read more on Template tags.

Template tags defined with @template_tag and BaseNode will have the following features:

  • Accepting args, kwargs, and flags.

  • Allowing literal lists and dicts as inputs as:

    key=[1, 2, 3] or key={\"a\": 1, \"b\": 2} - Using template tags tag inputs as:

    {% my_tag key=\"{% lorem 3 w %}\" / %} - Supporting the flat dictionary definition:

    attr:key=value - Spreading args and kwargs with ...:

    {% my_tag ...args ...kwargs / %} - Being able to call the template tag as:

    {% my_tag %} ... {% endmy_tag %} or {% my_tag / %}

"},{"location":"release_notes/#refactor_7","title":"Refactor","text":"
  • Refactored template tag input validation. When you now call template tags like {% slot %}, {% fill %}, {% html_attrs %}, and others, their inputs are now validated the same way as Python function inputs are.

    So, for example

    {% slot \"my_slot\" name=\"content\" / %}\n

    will raise an error, because the positional argument name is given twice.

    NOTE: Special kwargs whose keys are not valid Python variable names are not affected by this change. So when you define:

    {% component data-id=123 / %}\n

    The data-id will still be accepted as a valid kwarg, assuming that your get_context_data() accepts **kwargs:

    def get_context_data(self, **kwargs):\n    return {\n        \"data_id\": kwargs[\"data-id\"],\n    }\n
"},{"location":"release_notes/#v0124","title":"v0.124","text":""},{"location":"release_notes/#feat_9","title":"Feat","text":"
  • Instead of inlining the JS and CSS under Component.js and Component.css, you can move them to their own files, and link the JS/CSS files with Component.js_file and Component.css_file.

    Even when you specify the JS/CSS with Component.js_file or Component.css_file, then you can still access the content under Component.js or Component.css - behind the scenes, the content of the JS/CSS files will be set to Component.js / Component.css upon first access.

    The same applies to Component.template_file, which will populate Component.template upon first access.

    With this change, the role of Component.js/css and the JS/CSS in Component.Media has changed:

    • The JS/CSS defined in Component.js/css or Component.js/css_file is the \"main\" JS/CSS
    • The JS/CSS defined in Component.Media.js/css are secondary or additional

    See the updated \"Getting Started\" tutorial

"},{"location":"release_notes/#refactor_8","title":"Refactor","text":"
  • The canonical way to define a template file was changed from template_name to template_file, to align with the rest of the API.

    template_name remains for backwards compatibility. When you get / set template_name, internally this is proxied to template_file.

  • The undocumented Component.component_id was removed. Instead, use Component.id. Changes:

    • While component_id was unique every time you instantiated Component, the new id is unique every time you render the component (e.g. with Component.render())
    • The new id is available only during render, so e.g. from within get_context_data()
  • Component's HTML / CSS / JS are now resolved and loaded lazily. That is, if you specify template_name/template_file, js_file, css_file, or Media.js/css, the file paths will be resolved only once you:

    1. Try to access component's HTML / CSS / JS, or
    2. Render the component.

    Read more on Accessing component's HTML / JS / CSS.

  • Component inheritance:

    • When you subclass a component, the JS and CSS defined on parent's Media class is now inherited by the child component.
    • You can disable or customize Media inheritance by setting extend attribute on the Component.Media nested class. This work similarly to Django's Media.extend.
    • When child component defines either template or template_file, both of parent's template and template_file are ignored. The same applies to js_file and css_file.
  • Autodiscovery now ignores files and directories that start with an underscore (_), except __init__.py

  • The Signals emitted by or during the use of django-components are now documented, together the template_rendered signal.

"},{"location":"release_notes/#v0123","title":"v0.123","text":""},{"location":"release_notes/#fix_15","title":"Fix","text":"
  • Fix edge cases around rendering components whose templates used the {% extends %} template tag (#859)
"},{"location":"release_notes/#v0122","title":"v0.122","text":""},{"location":"release_notes/#feat_10","title":"Feat","text":"
  • Add support for HTML fragments. HTML fragments can be rendered by passing type=\"fragment\" to Component.render() or Component.render_to_response(). Read more on how to use HTML fragments with HTMX, AlpineJS, or vanillaJS.
"},{"location":"release_notes/#v0121","title":"v0.121","text":""},{"location":"release_notes/#fix_16","title":"Fix","text":"
  • Fix the use of Django template filters (|lower:\"etc\") with component inputs #855.
"},{"location":"release_notes/#v0120","title":"v0.120","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.121 to fix bugs introduced in v0.119.

"},{"location":"release_notes/#fix_17","title":"Fix","text":"
  • Fix the use of translation strings _(\"bla\") as inputs to components #849.
"},{"location":"release_notes/#v0119","title":"v0.119","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - This release introduced bugs #849, #855. Please update to v0.121.

"},{"location":"release_notes/#fix_18","title":"Fix","text":"
  • Fix compatibility with custom subclasses of Django's Template that need to access origin or other initialization arguments. (https://github.com/django-components/django-components/pull/828)
"},{"location":"release_notes/#refactor_9","title":"Refactor","text":"
  • Compatibility with django-debug-toolbar-template-profiler:
  • Monkeypatching of Django's Template now happens at AppConfig.ready() (https://github.com/django-components/django-components/pull/825)

  • Internal parsing of template tags tag was updated. No API change. (https://github.com/django-components/django-components/pull/827)

"},{"location":"release_notes/#v0118","title":"v0.118","text":""},{"location":"release_notes/#feat_11","title":"Feat","text":"
  • Add support for context_processors and RenderContext inside component templates

Component.render() and Component.render_to_response() now accept an extra kwarg request.

```py\ndef my_view(request)\n    return MyTable.render_to_response(\n        request=request\n    )\n```\n
  • When you pass in request, the component will use RenderContext instead of Context. Thus the context processors will be applied to the context.

  • NOTE: When you pass in both request and context to Component.render(), and context is already an instance of Context, the request kwarg will be ignored.

"},{"location":"release_notes/#v0117","title":"v0.117","text":""},{"location":"release_notes/#fix_19","title":"Fix","text":"
  • The HTML parser no longer erronously inserts <html><head><body> on some occasions, and no longer tries to close unclosed HTML tags.
"},{"location":"release_notes/#refactor_10","title":"Refactor","text":"
  • Replaced Selectolax with BeautifulSoup4 as project dependencies.
"},{"location":"release_notes/#v0116","title":"v0.116","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.117 to fix known bugs. See #791 and #789 and #818.

"},{"location":"release_notes/#fix_20","title":"Fix","text":"
  • Fix the order of execution of JS scripts:
  • Scripts in Component.Media.js are executed in the order they are defined
  • Scripts in Component.js are executed AFTER Media.js scripts

  • Fix compatibility with AlpineJS

  • Scripts in Component.Media.js are now again inserted as <script> tags
  • By default, Component.Media.js are inserted as synchronous <script> tags, so the AlpineJS components registered in the Media.js scripts will now again run BEFORE the core AlpineJS script.

AlpineJS can be configured like so:

Option 1 - AlpineJS loaded in <head> with defer attribute:

<html>\n  <head>\n    {% component_css_dependencies %}\n    <script defer src=\"https://unpkg.com/alpinejs\"></script>\n  </head>\n  <body>\n    {% component 'my_alpine_component' / %}\n    {% component_js_dependencies %}\n  </body>\n</html>\n

Option 2 - AlpineJS loaded in <body> AFTER {% component_js_depenencies %}:

<html>\n    <head>\n        {% component_css_dependencies %}\n    </head>\n    <body>\n        {% component 'my_alpine_component' / %}\n        {% component_js_dependencies %}\n\n        <script src=\"https://unpkg.com/alpinejs\"></script>\n    </body>\n</html>\n

"},{"location":"release_notes/#v0115","title":"v0.115","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.117 to fix known bugs. See #791 and #789 and #818.

"},{"location":"release_notes/#fix_21","title":"Fix","text":"
  • Fix integration with ManifestStaticFilesStorage on Windows by resolving component filepaths (like Component.template_name) to POSIX paths.
"},{"location":"release_notes/#v0114","title":"v0.114","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.117 to fix known bugs. See #791 and #789 and #818.

"},{"location":"release_notes/#fix_22","title":"Fix","text":"
  • Prevent rendering Slot tags during fill discovery stage to fix a case when a component inside a slot fill tried to access provided data too early.
"},{"location":"release_notes/#v0113","title":"v0.113","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.117 to fix known bugs. See #791 and #789 and #818.

"},{"location":"release_notes/#fix_23","title":"Fix","text":"
  • Ensure consistent order of scripts in Component.Media.js
"},{"location":"release_notes/#v0112","title":"v0.112","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.117 to fix known bugs. See #791 and #789 and #818.

"},{"location":"release_notes/#fix_24","title":"Fix","text":"
  • Allow components to accept default fill even if no default slot was encountered during rendering
"},{"location":"release_notes/#v0111","title":"v0.111","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.117 to fix known bugs. See #791 and #789 and #818.

"},{"location":"release_notes/#fix_25","title":"Fix","text":"
  • Prevent rendering Component tags during fill discovery stage to fix a case when a component inside the default slot tried to access provided data too early.
"},{"location":"release_notes/#v0110","title":"\ud83d\udea8\ud83d\udce2 v0.110","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.117 to fix known bugs. See #791 and #789 and #818.

"},{"location":"release_notes/#general","title":"General","text":""},{"location":"release_notes/#breaking-changes_2","title":"\ud83d\udea8\ud83d\udce2 BREAKING CHANGES","text":"
  • Installation changes:

    • If your components include JS or CSS, you now must use the middleware and add django-components' URLs to your urlpatterns (See \"Adding support for JS and CSS\")
  • Component typing signature changed from

    Component[Args, Kwargs, Data, Slots]\n

    to

    Component[Args, Kwargs, Slots, Data, JsData, CssData]\n
  • If you rendered a component A with Component.render() and then inserted that into another component B, now you must pass render_dependencies=False to component A:

    prerendered_a = CompA.render(\n    args=[...],\n    kwargs={...},\n    render_dependencies=False,\n)\n\nhtml = CompB.render(\n    kwargs={\n        content=prerendered_a,\n    },\n)\n
"},{"location":"release_notes/#feat_12","title":"Feat","text":"
  • Intellisense and mypy validation for settings:

Instead of defining the COMPONENTS settings as a plain dict, you can use ComponentsSettings:

# settings.py\nfrom django_components import ComponentsSettings\n\nCOMPONENTS = ComponentsSettings(\n    autodiscover=True,\n    ...\n)\n
  • Use get_component_dirs() and get_component_files() to get the same list of dirs / files that would be imported by autodiscover(), but without actually importing them.
"},{"location":"release_notes/#refactor_11","title":"Refactor","text":"
  • For advanced use cases, use can omit the middleware and instead manage component JS and CSS dependencies yourself with render_dependencies

  • The ComponentRegistry settings RegistrySettings were lowercased to align with the global settings:

  • RegistrySettings.CONTEXT_BEHAVIOR -> RegistrySettings.context_behavior
  • RegistrySettings.TAG_FORMATTER -> RegistrySettings.tag_formatter

The old uppercase settings CONTEXT_BEHAVIOR and TAG_FORMATTER are deprecated and will be removed in v1.

  • The setting reload_on_template_change was renamed to reload_on_file_change. And now it properly triggers server reload when any file in the component dirs change. The old name reload_on_template_change is deprecated and will be removed in v1.

  • The setting forbidden_static_files was renamed to static_files_forbidden to align with static_files_allowed The old name forbidden_static_files is deprecated and will be removed in v1.

"},{"location":"release_notes/#tags","title":"Tags","text":""},{"location":"release_notes/#breaking-changes_3","title":"\ud83d\udea8\ud83d\udce2 BREAKING CHANGES","text":"
  • {% component_dependencies %} tag was removed. Instead, use {% component_js_dependencies %} and {% component_css_dependencies %}

    • The combined tag was removed to encourage the best practice of putting JS scripts at the end of <body>, and CSS styles inside <head>.

      On the other hand, co-locating JS script and CSS styles can lead to a flash of unstyled content, as either JS scripts will block the rendering, or CSS will load too late.

  • The undocumented keyword arg preload of {% component_js_dependencies %} and {% component_css_dependencies %} tags was removed. This will be replaced with HTML fragment support.

"},{"location":"release_notes/#fix_26","title":"Fix","text":"
  • Allow using forward slash (/) when defining custom TagFormatter, e.g. {% MyComp %}..{% /MyComp %}.
"},{"location":"release_notes/#refactor_12","title":"Refactor","text":"
  • {% component_dependencies %} tags are now OPTIONAL - If your components use JS and CSS, but you don't use {% component_dependencies %} tags, the JS and CSS will now be, by default, inserted at the end of <body> and at the end of <head> respectively.
"},{"location":"release_notes/#slots","title":"Slots","text":""},{"location":"release_notes/#feat_13","title":"Feat","text":"
  • Fills can now be defined within loops ({% for %}) or other tags (like {% with %}), or even other templates using {% include %}.

Following is now possible

{% component \"table\" %}\n  {% for slot_name in slots %}\n    {% fill name=slot_name %}\n    {% endfill %}\n  {% endfor %}\n{% endcomponent %}\n
  • If you need to access the data or the default content of a default fill, you can set the name kwarg to \"default\".

Previously, a default fill would be defined simply by omitting the {% fill %} tags:

{% component \"child\" %}\n  Hello world\n{% endcomponent %}\n

But in that case you could not access the slot data or the default content, like it's possible for named fills:

{% component \"child\" %}\n  {% fill name=\"header\" data=\"data\" %}\n    Hello {{ data.user.name }}\n  {% endfill %}\n{% endcomponent %}\n

Now, you can specify default tag by using name=\"default\":

{% component \"child\" %}\n  {% fill name=\"default\" data=\"data\" %}\n    Hello {{ data.user.name }}\n  {% endfill %}\n{% endcomponent %}\n
  • When inside get_context_data() or other component methods, the default fill can now be accessed as Component.input.slots[\"default\"], e.g.:
class MyTable(Component):\n    def get_context_data(self, *args, **kwargs):\n        default_slot = self.input.slots[\"default\"]\n        ...\n
  • You can now dynamically pass all slots to a child component. This is similar to passing all slots in Vue:
class MyTable(Component):\n    def get_context_data(self, *args, **kwargs):\n        return {\n            \"slots\": self.input.slots,\n        }\n\n    template: \"\"\"\n      <div>\n        {% component \"child\" %}\n          {% for slot_name in slots %}\n            {% fill name=slot_name data=\"data\" %}\n              {% slot name=slot_name ...data / %}\n            {% endfill %}\n          {% endfor %}\n        {% endcomponent %}\n      </div>\n    \"\"\"\n
"},{"location":"release_notes/#fix_27","title":"Fix","text":"
  • Slots defined with {% fill %} tags are now properly accessible via self.input.slots in get_context_data()

  • Do not raise error if multiple slots with same name are flagged as default

  • Slots can now be defined within loops ({% for %}) or other tags (like {% with %}), or even other templates using {% include %}.

Previously, following would cause the kwarg name to be an empty string:

{% for slot_name in slots %}\n  {% slot name=slot_name %}\n{% endfor %}\n
"},{"location":"release_notes/#refactor_13","title":"Refactor","text":"
  • When you define multiple slots with the same name inside a template, you now have to set the default and required flags individually.
<div class=\"calendar-component\">\n    <div class=\"header\">\n        {% slot \"image\" default required %}Image here{% endslot %}\n    </div>\n    <div class=\"body\">\n        {% slot \"image\" default required %}Image here{% endslot %}\n    </div>\n</div>\n

This means you can also have multiple slots with the same name but different conditions.

E.g. in this example, we have a component that renders a user avatar - a small circular image with a profile picture of name initials.

If the component is given image_src or name_initials variables, the image slot is optional. But if neither of those are provided, you MUST fill the image slot.

<div class=\"avatar\">\n    {% if image_src %}\n        {% slot \"image\" default %}\n            <img src=\"{{ image_src }}\" />\n        {% endslot %}\n    {% elif name_initials %}\n        {% slot \"image\" default required %}\n            <div style=\"\n                border-radius: 25px;\n                width: 50px;\n                height: 50px;\n                background: blue;\n            \">\n                {{ name_initials }}\n            </div>\n        {% endslot %}\n    {% else %}\n        {% slot \"image\" default required / %}\n    {% endif %}\n</div>\n
  • The slot fills that were passed to a component and which can be accessed as Component.input.slots can now be passed through the Django template, e.g. as inputs to other tags.

Internally, django-components handles slot fills as functions.

Previously, if you tried to pass a slot fill within a template, Django would try to call it as a function.

Now, something like this is possible:

class MyTable(Component):\n    def get_context_data(self, *args, **kwargs):\n        return {\n            \"child_slot\": self.input.slots[\"child_slot\"],\n        }\n\n    template: \"\"\"\n      <div>\n        {% component \"child\" content=child_slot / %}\n      </div>\n    \"\"\"\n

NOTE: Using {% slot %} and {% fill %} tags is still the preferred method, but the approach above may be necessary in some complex or edge cases.

  • The is_filled variable (and the {{ component_vars.is_filled }} context variable) now returns False when you try to access a slot name which has not been defined:

Before:

{{ component_vars.is_filled.header }} -> True\n{{ component_vars.is_filled.footer }} -> False\n{{ component_vars.is_filled.nonexist }} -> \"\" (empty string)\n

After:

{{ component_vars.is_filled.header }} -> True\n{{ component_vars.is_filled.footer }} -> False\n{{ component_vars.is_filled.nonexist }} -> False\n

  • Components no longer raise an error if there are extra slot fills

  • Components will raise error when a slot is doubly-filled.

E.g. if we have a component with a default slot:

{% slot name=\"content\" default / %}\n

Now there is two ways how we can target this slot: Either using name=\"default\" or name=\"content\".

In case you specify BOTH, the component will raise an error:

{% component \"child\" %}\n  {% fill slot=\"default\" %}\n    Hello from default slot\n  {% endfill %}\n  {% fill slot=\"content\" data=\"data\" %}\n    Hello from content slot\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"release_notes/#v0100","title":"\ud83d\udea8\ud83d\udce2 v0.100","text":""},{"location":"release_notes/#breaking-changes_4","title":"BREAKING CHANGES","text":"
  • 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

"},{"location":"release_notes/#feat_14","title":"Feat","text":"
  • Beside the top-level /components directory, you can now define also app-level components dirs, e.g. [app]/components (See COMPONENTS.app_dirs).
"},{"location":"release_notes/#refactor_14","title":"Refactor","text":"
  • When you call as_view() on a component instance, that instance will be passed to View.as_view()
"},{"location":"release_notes/#v097","title":"v0.97","text":""},{"location":"release_notes/#fix_28","title":"Fix","text":"
  • Fixed template caching. You can now also manually create cached templates with cached_template()
"},{"location":"release_notes/#refactor_15","title":"Refactor","text":"
  • 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.

"},{"location":"release_notes/#v096","title":"v0.96","text":""},{"location":"release_notes/#feat_15","title":"Feat","text":"
  • 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

"},{"location":"release_notes/#095","title":"0.95","text":""},{"location":"release_notes/#feat_16","title":"Feat","text":"
  • Added support for dynamic components, where the component name is passed as a variable. (See Dynamic components)
"},{"location":"release_notes/#refactor_16","title":"Refactor","text":"
  • Changed Component.input to raise RuntimeError if accessed outside of render context. Previously it returned None if unset.
"},{"location":"release_notes/#v094","title":"v0.94","text":""},{"location":"release_notes/#feat_17","title":"Feat","text":"
  • 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)

"},{"location":"release_notes/#v093","title":"v0.93","text":""},{"location":"release_notes/#feat_18","title":"Feat","text":"
  • 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.

"},{"location":"release_notes/#v092","title":"\ud83d\udea8\ud83d\udce2 v0.92","text":""},{"location":"release_notes/#breaking-changes_5","title":"BREAKING CHANGES","text":"
  • 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)
"},{"location":"release_notes/#feat_19","title":"Feat","text":"
  • 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)

"},{"location":"release_notes/#v090","title":"v0.90","text":""},{"location":"release_notes/#feat_20","title":"Feat","text":"
  • All tags (component, slot, fill, ...) now support \"self-closing\" or \"inline\" form, where you can omit the closing tag:

    {# Before #}\n{% component \"button\" %}{% endcomponent %}\n{# After #}\n{% component \"button\" / %}\n
  • All tags now support the \"dictionary key\" or \"aggregate\" syntax (kwarg:key=val):

    {% component \"button\" attrs:class=\"hidden\" %}\n
  • You can change how the components are written in the template with TagFormatter.

    The default is django_components.component_formatter:

    {% component \"button\" href=\"...\" disabled %}\n    Click me!\n{% endcomponent %}\n

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

    {% button href=\"...\" disabled %}\n    Click me!\n{% endbutton %}\n
"},{"location":"release_notes/#v085","title":"\ud83d\udea8\ud83d\udce2 v0.85","text":""},{"location":"release_notes/#breaking-changes_6","title":"BREAKING CHANGES","text":"
  • 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).

"},{"location":"release_notes/#v081","title":"\ud83d\udea8\ud83d\udce2 v0.81","text":""},{"location":"release_notes/#breaking-changes_7","title":"BREAKING CHANGES","text":"
  • The order of arguments to render_to_response has changed, to align with the (now public) render method of Component class.
"},{"location":"release_notes/#feat_21","title":"Feat","text":"
  • Component.render() is public and documented

  • Slots passed render_to_response and render can now be rendered also as functions.

"},{"location":"release_notes/#v080","title":"v0.80","text":""},{"location":"release_notes/#feat_22","title":"Feat","text":"
  • Vue-like provide/inject with the {% provide %} tag and inject() method.
"},{"location":"release_notes/#v079","title":"\ud83d\udea8\ud83d\udce2 v0.79","text":""},{"location":"release_notes/#breaking-changes_8","title":"BREAKING CHANGES","text":"
  • 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.
"},{"location":"release_notes/#v077","title":"\ud83d\udea8\ud83d\udce2 v0.77","text":""},{"location":"release_notes/#breaking","title":"BREAKING","text":"
  • The syntax for accessing default slot content has changed from

    {% fill \"my_slot\" as \"alias\" %}\n    {{ alias.default }}\n{% endfill %}\n

    to

    {% fill \"my_slot\" default=\"alias\" %}\n    {{ alias }}\n{% endfill %}\n
"},{"location":"release_notes/#v074","title":"v0.74","text":""},{"location":"release_notes/#feat_23","title":"Feat","text":"
  • {% html_attrs %} tag for formatting data as HTML attributes

  • prefix:key=val construct for passing dicts to components

"},{"location":"release_notes/#v070","title":"\ud83d\udea8\ud83d\udce2 v0.70","text":""},{"location":"release_notes/#breaking-changes_9","title":"BREAKING CHANGES","text":"
  • {% 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.

"},{"location":"release_notes/#v067","title":"v0.67","text":""},{"location":"release_notes/#refactor_17","title":"Refactor","text":"
  • Changed the default way how context variables are resolved in slots. See the documentation for more details.
"},{"location":"release_notes/#v050","title":"\ud83d\udea8\ud83d\udce2 v0.50","text":""},{"location":"release_notes/#breaking-changes_10","title":"BREAKING CHANGES","text":"
  • {% 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.

"},{"location":"release_notes/#v034","title":"v0.34","text":""},{"location":"release_notes/#feat_24","title":"Feat","text":"
  • Components as views, which allows you to handle requests and render responses from within a component. See the documentation for more details.
"},{"location":"release_notes/#v028","title":"v0.28","text":""},{"location":"release_notes/#feat_25","title":"Feat","text":"
  • 'implicit' slot filling and the default option for slot tags.
"},{"location":"release_notes/#v027","title":"v0.27","text":""},{"location":"release_notes/#feat_26","title":"Feat","text":"
  • 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).
"},{"location":"release_notes/#v026","title":"\ud83d\udea8\ud83d\udce2 v0.26","text":""},{"location":"release_notes/#breaking-changes_11","title":"BREAKING CHANGES","text":"
  • Changed the syntax for {% slot %} tags. From now on, we separate defining a slot ({% slot %}) from filling a slot with content ({% fill %}). This means you will likely need to change a lot of slot tags to fill.

    We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice feature to have access to. Hoping that this will feel worth it!

"},{"location":"release_notes/#v022","title":"v0.22","text":""},{"location":"release_notes/#feat_27","title":"Feat","text":"
  • All files inside components subdirectores are autoimported 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.

"},{"location":"release_notes/#v017","title":"v0.17","text":""},{"location":"release_notes/#breaking-changes_12","title":"BREAKING CHANGES","text":"
  • Renamed 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.

"},{"location":"concepts/advanced/component_caching/","title":"Component caching","text":"

Component caching allows you to store the rendered output of a component. Next time the component is rendered with the same input, the cached output is returned instead of re-rendering the component.

This is particularly useful for components that are expensive to render or do not change frequently.

Info

Component caching uses Django's cache framework, so you can use any cache backend that is supported by Django.

"},{"location":"concepts/advanced/component_caching/#enabling-caching","title":"Enabling caching","text":"

Caching is disabled by default.

To enable caching for a component, set Component.Cache.enabled to True:

from django_components import Component\n\nclass MyComponent(Component):\n    class Cache:\n        enabled = True\n
"},{"location":"concepts/advanced/component_caching/#time-to-live-ttl","title":"Time-to-live (TTL)","text":"

You can specify a time-to-live (TTL) for the cache entry with Component.Cache.ttl, which determines how long the entry remains valid. The TTL is specified in seconds.

class MyComponent(Component):\n    class Cache:\n        enabled = True\n        ttl = 60 * 60 * 24  # 1 day\n
  • If ttl > 0, entries are cached for the specified number of seconds.
  • If ttl = -1, entries are cached indefinitely.
  • If ttl = 0, entries are not cached.
  • If ttl = None, the default TTL is used.
"},{"location":"concepts/advanced/component_caching/#custom-cache-name","title":"Custom cache name","text":"

Since component caching uses Django's cache framework, you can specify a custom cache name with Component.Cache.cache_name to use a different cache backend:

class MyComponent(Component):\n    class Cache:\n        enabled = True\n        cache_name = \"my_cache\"\n
"},{"location":"concepts/advanced/component_caching/#cache-key-generation","title":"Cache key generation","text":"

By default, the cache key is generated based on the component's input (args and kwargs). So the following two calls would generate separate entries in the cache:

MyComponent.render(name=\"Alice\")\nMyComponent.render(name=\"Bob\")\n

However, you have full control over the cache key generation. As such, you can:

  • Cache the component on all inputs (default)
  • Cache the component on particular inputs
  • Cache the component irrespective of the inputs

To achieve that, you can override the Component.Cache.hash() method to customize how arguments are hashed into the cache key.

class MyComponent(Component):\n    class Cache:\n        enabled = True\n\n        def hash(self, *args, **kwargs):\n            return f\"{json.dumps(args)}:{json.dumps(kwargs)}\"\n

For even more control, you can override other methods available on the ComponentCache class.

Warning

The default implementation of Cache.hash() simply serializes the input into a string. As such, it might not be suitable if you need to hash complex objects like Models.

"},{"location":"concepts/advanced/component_caching/#caching-slots","title":"Caching slots","text":"

By default, the cache key is generated based ONLY on the args and kwargs.

To cache the component based on the slots, set Component.Cache.include_slots to True:

class MyComponent(Component):\n    class Cache:\n        enabled = True\n        include_slots = True\n

with include_slots = True, the cache key will be generated also based on the given slots.

As such, the following two calls would generate separate entries in the cache:

{% component \"my_component\" position=\"left\" %}\n    Hello, Alice\n{% endcomponent %}\n\n{% component \"my_component\" position=\"left\" %}\n    Hello, Bob\n{% endcomponent %}\n

Same when using Component.render() with string slots:

MyComponent.render(\n    kwargs={\"position\": \"left\"},\n    slots={\"content\": \"Hello, Alice\"}\n)\nMyComponent.render(\n    kwargs={\"position\": \"left\"},\n    slots={\"content\": \"Hello, Bob\"}\n)\n

Warning

Passing slots as functions to cached components with include_slots=True will raise an error.

MyComponent.render(\n    kwargs={\"position\": \"left\"},\n    slots={\"content\": lambda ctx: \"Hello, Alice\"}\n)\n

Warning

Slot caching DOES NOT account for context variables within the {% fill %} tag.

For example, the following two cases will be treated as the same entry:

{% with my_var=\"foo\" %}\n    {% component \"mycomponent\" name=\"foo\" %}\n        {{ my_var }}\n    {% endcomponent %}\n{% endwith %}\n\n{% with my_var=\"bar\" %}\n    {% component \"mycomponent\" name=\"bar\" %}\n        {{ my_var }}\n    {% endcomponent %}\n{% endwith %}\n

Currently it's impossible to capture used variables. This will be addressed in v2. Read more about it in django-components/#1164.

"},{"location":"concepts/advanced/component_caching/#example","title":"Example","text":"

Here's a complete example of a component with caching enabled:

from django_components import Component\n\nclass MyComponent(Component):\n    template = \"Hello, {{ name }}\"\n\n    class Cache:\n        enabled = True\n        ttl = 300  # Cache for 5 minutes\n        cache_name = \"my_cache\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\"name\": kwargs[\"name\"]}\n

In this example, the component's rendered output is cached for 5 minutes using the my_cache backend.

"},{"location":"concepts/advanced/component_context_scope/","title":"Component context and scope","text":"

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

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_template_data by accessing the property self.outer_context.

"},{"location":"concepts/advanced/component_context_scope/#example-of-accessing-outer-context","title":"Example of Accessing Outer Context","text":"
<div>\n  {% component \"calender\" / %}\n</div>\n

Assuming that the rendering context has variables such as date, you can use self.outer_context to access them from within get_template_data. Here's how you might implement it:

class Calender(Component):\n\n    ...\n\n    def get_template_data(self, args, kwargs, slots, context):\n        outer_field = self.outer_context[\"date\"]\n        return {\n            \"date\": outer_fields,\n        }\n

However, as a best practice, it\u2019s 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.

"},{"location":"concepts/advanced/component_context_scope/#context-behavior","title":"Context behavior","text":"

django_components supports both Django and Vue-like behavior when it comes to passing data to and through components. This can be configured in context_behavior.

This has two modes:

  • \"django\"

    The default Django template behavior.

    Inside the {% fill %} tag, the context variables you can access are a union of:

    • All the variables that were OUTSIDE the fill tag, including any\\ {% with %} tags.
    • Any loops ({% for ... %}) that the {% fill %} tag is part of.
    • Data returned from Component.get_template_data() of the component that owns the fill tag.
  • \"isolated\"

    Similar behavior to Vue or React, this is useful if you want to make sure that components don't accidentally access variables defined outside of the component.

    Inside the {% fill %} tag, you can ONLY access variables from 2 places:

    • Any loops ({% for ... %}) that the {% fill %} tag is part of.
    • Component.get_template_data() of the component which defined the template (AKA the \"root\" component).

Warning

Notice that the component whose get_template_data() we use inside {% fill %} is NOT the same across the two modes!

Consider this example:

class Outer(Component):\n    template = \"\"\"\n      <div>\n        {% component \"inner\" %}\n          {% fill \"content\" %}\n            {{ my_var }}\n          {% endfill %}\n        {% endcomponent %}\n      </div>\n    \"\"\"\n
  • \"django\" - my_var has access to data from get_template_data() of both Inner and Outer. If there are variables defined in both, then Inner overshadows Outer.

  • \"isolated\" - my_var has access to data from get_template_data() of ONLY Outer.

"},{"location":"concepts/advanced/component_context_scope/#example-django","title":"Example \"django\"","text":"

Given this template:

@register(\"root_comp\")\nclass RootComp(Component):\n    template = \"\"\"\n        {% with cheese=\"feta\" %}\n            {% component 'my_comp' %}\n                {{ my_var }}  # my_var\n                {{ cheese }}  # cheese\n            {% endcomponent %}\n        {% endwith %}\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return { \"my_var\": 123 }\n

Then if get_template_data() of the component \"my_comp\" returns following data:

{ \"my_var\": 456 }\n

Then the template will be rendered as:

456   # my_var\nfeta  # cheese\n

Because \"my_comp\" overshadows the outer 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.

"},{"location":"concepts/advanced/component_context_scope/#example-isolated","title":"Example \"isolated\"","text":"

Given this template:

class RootComp(Component):\n    template = \"\"\"\n        {% with cheese=\"feta\" %}\n            {% component 'my_comp' %}\n                {{ my_var }}  # my_var\n                {{ cheese }}  # cheese\n            {% endcomponent %}\n        {% endwith %}\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return { \"my_var\": 123 }\n

Then if get_template_data() of the component \"my_comp\" returns following data:

{ \"my_var\": 456 }\n

Then the template will be rendered as:

123   # my_var\n    # cheese\n

Because variables \"my_var\" and \"cheese\" are searched only inside RootComponent.get_template_data(). But since \"cheese\" is not defined there, it's empty.

Info

Notice that the variables defined with the {% with %} tag are ignored inside the {% fill %} tag with the \"isolated\" mode.

"},{"location":"concepts/advanced/component_libraries/","title":"Component libraries","text":"

You can publish and share your components for others to use. Below you will find the steps to do so.

For live examples, see the Community examples.

"},{"location":"concepts/advanced/component_libraries/#writing-component-libraries","title":"Writing component libraries","text":"
  1. Create a Django project with a similar structure:

    project/\n  |--  myapp/\n    |--  __init__.py\n    |--  apps.py\n    |--  templates/\n      |--  table/\n        |--  table.py\n        |--  table.js\n        |--  table.css\n        |--  table.html\n    |--  menu.py   <--- single-file component\n  |--  templatetags/\n    |--  __init__.py\n    |--  mytags.py\n
  2. Create custom Library and ComponentRegistry instances in mytags.py

    This will be the entrypoint for using the components inside Django templates.

    Remember that Django requires the Library instance to be accessible under the register variable (See Django docs):

    from django.template import Library\nfrom django_components import ComponentRegistry, RegistrySettings\n\nregister = library = django.template.Library()\ncomp_registry = ComponentRegistry(\n    library=library,\n    settings=RegistrySettings(\n        context_behavior=\"isolated\",\n        tag_formatter=\"django_components.component_formatter\",\n    ),\n)\n

    As you can see above, this is also the place where we configure how our components should behave, using the settings argument. If omitted, default settings are used.

    For library authors, we recommend setting context_behavior to \"isolated\", so that the state cannot leak into the components, and so the components' behavior is configured solely through the inputs. This means that the components will be more predictable and easier to debug.

    Next, you can decide how will others use your components by setting the tag_formatter options.

    If omitted or set to \"django_components.component_formatter\", your components will be used like this:

    {% component \"table\" items=items headers=headers %}\n{% endcomponent %}\n

    Or you can use \"django_components.component_shorthand_formatter\" to use components like so:

    {% table items=items headers=headers %}\n{% endtable %}\n

    Or you can define a custom TagFormatter.

    Either way, these settings will be scoped only to your components. So, in the user code, there may be components side-by-side that use different formatters:

    {% load mytags %}\n\n{# Component from your library \"mytags\", using the \"shorthand\" formatter #}\n{% table items=items headers=header %}\n{% endtable %}\n\n{# User-created components using the default settings #}\n{% component \"my_comp\" title=\"Abc...\" %}\n{% endcomponent %}\n
  3. Write your components and register them with your instance of ComponentRegistry

    There's one difference when you are writing components that are to be shared, and that's that the components must be explicitly registered with your instance of ComponentRegistry from the previous step.

    For better user experience, you can also define the types for the args, kwargs, slots and data.

    It's also a good idea to have a common prefix for your components, so they can be easily distinguished from users' components. In the example below, we use the prefix my_ / My.

    from typing import NamedTuple, Optional\nfrom django_components import Component, SlotInput, register, types\n\nfrom myapp.templatetags.mytags import comp_registry\n\n# Define the component\n# NOTE: Don't forget to set the `registry`!\n@register(\"my_menu\", registry=comp_registry)\nclass MyMenu(Component):\n    # Define the types\n    class Args(NamedTuple):\n        size: int\n        text: str\n\n    class Kwargs(NamedTuple):\n        vertical: Optional[bool] = None\n        klass: Optional[str] = None\n        style: Optional[str] = None\n\n    class Slots(NamedTuple):\n        default: Optional[SlotInput] = None\n\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        attrs = ...\n        return {\n            \"attrs\": attrs,\n        }\n\n    template: types.django_html = \"\"\"\n        {# Load django_components template tags #}\n        {% load component_tags %}\n\n        <div {% html_attrs attrs class=\"my-menu\" %}>\n            <div class=\"my-menu__content\">\n                {% slot \"default\" default / %}\n            </div>\n        </div>\n    \"\"\"\n
  4. Import the components in apps.py

    Normally, users rely on autodiscovery and COMPONENTS.dirs to load the component files.

    Since you, as the library author, are not in control of the file system, it is recommended to load the components manually.

    We recommend doing this in the AppConfig.ready() hook of your apps.py:

    from django.apps import AppConfig\n\nclass MyAppConfig(AppConfig):\n    default_auto_field = \"django.db.models.BigAutoField\"\n    name = \"myapp\"\n\n    # This is the code that gets run when user adds myapp\n    # to Django's INSTALLED_APPS\n    def ready(self) -> None:\n        # Import the components that you want to make available\n        # inside the templates.\n        from myapp.templates import (\n            menu,\n            table,\n        )\n

    Note that you can also include any other startup logic within AppConfig.ready().

And that's it! The next step is to publish it.

"},{"location":"concepts/advanced/component_libraries/#publishing-component-libraries","title":"Publishing component libraries","text":"

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/ .\n

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

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

Notes on publishing:

  • 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).
"},{"location":"concepts/advanced/component_libraries/#installing-and-using-component-libraries","title":"Installing and using component libraries","text":"

After the package has been published, all that remains is to install it in other django projects:

  1. Install the package:

    pip install myapp django_components\n
  2. Add the package to INSTALLED_APPS

    INSTALLED_APPS = [\n    ...\n    \"django_components\",\n    \"myapp\",\n]\n
  3. Optionally add the template tags to the builtins, so you don't have to call {% load mytags %} in every template:

    TEMPLATES = [\n    {\n        ...,\n        'OPTIONS': {\n            'builtins': [\n                'myapp.templatetags.mytags',\n            ]\n        },\n    },\n]\n
  4. And, at last, you can use the components in your own project!

    {% my_menu title=\"Abc...\" %}\n    Hello World!\n{% endmy_menu %}\n
"},{"location":"concepts/advanced/component_registry/","title":"Registering components","text":"

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\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"template.html\"\n\n    # This component takes one parameter, a date string to show in the template\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"date\"],\n        }\n

which we then render in the template as:

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

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.

"},{"location":"concepts/advanced/component_registry/#what-is-componentregistry","title":"What is ComponentRegistry","text":"

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()\n\n@register(registry=my_registry)\nclass MyComponent(Component):\n    ...\n

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

"},{"location":"concepts/advanced/component_registry/#working-with-componentregistry","title":"Working with ComponentRegistry","text":"

The default ComponentRegistry instance can be imported as:

from django_components import registry\n

You can use the registry to manually add/remove/get components:

from django_components import registry\n\n# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get all or single\nregistry.all()  # {\"button\": ButtonComponent, \"card\": CardComponent}\nregistry.get(\"card\")  # CardComponent\n\n# Check if component is registered\nregistry.has(\"button\")  # True\n\n# Unregister single component\nregistry.unregister(\"card\")\n\n# Unregister all components\nregistry.clear()\n
"},{"location":"concepts/advanced/component_registry/#registering-components-to-custom-componentregistry","title":"Registering components to custom ComponentRegistry","text":"

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\nfrom django_components import ComponentRegistry\n\nmy_library = Library(...)\nmy_registry = ComponentRegistry(library=my_library)\n

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\n\n@register(\"my_component\", registry=my_registry)\nclass MyComponent(Component):\n    ...\n

NOTE: The Library instance can be accessed under library attribute of ComponentRegistry.

"},{"location":"concepts/advanced/component_registry/#componentregistry-settings","title":"ComponentRegistry settings","text":"

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\nfrom django_components import ComponentRegistry, RegistrySettings\n\nregister = library = django.template.Library()\ncomp_registry = ComponentRegistry(\n    library=library,\n    settings=RegistrySettings(\n        context_behavior=\"isolated\",\n        tag_formatter=\"django_components.component_formatter\",\n    ),\n)\n

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.

"},{"location":"concepts/advanced/extensions/","title":"Extensions","text":"

New in version 0.131

Django-components functionality can be extended with \"extensions\". Extensions allow for powerful customization and integrations. They can:

  • Tap into lifecycle events, such as when a component is created, deleted, registered, or unregistered.
  • Add new attributes and methods to the components under an extension-specific nested class.
  • Define custom commands that can be executed via the Django management command interface.
"},{"location":"concepts/advanced/extensions/#live-examples","title":"Live examples","text":"
  • djc-ext-pydantic
"},{"location":"concepts/advanced/extensions/#install-extensions","title":"Install extensions","text":"

Extensions are configured in the Django settings under COMPONENTS.extensions.

Extensions can be set by either as an import string or by passing in a class:

# settings.py\n\nclass MyExtension(ComponentExtension):\n    name = \"my_extension\"\n\n    class ComponentConfig(ExtensionComponentConfig):\n        ...\n\nCOMPONENTS = ComponentsSettings(\n    extensions=[\n        MyExtension,\n        \"another_app.extensions.AnotherExtension\",\n        \"my_app.extensions.ThirdExtension\",\n    ],\n)\n
"},{"location":"concepts/advanced/extensions/#lifecycle-hooks","title":"Lifecycle hooks","text":"

Extensions can define methods to hook into lifecycle events, such as:

  • Component creation or deletion
  • Un/registering a component
  • Creating or deleting a registry
  • Pre-processing data passed to a component on render
  • Post-processing data returned from get_template_data() and others.

See the full list in Extension Hooks Reference.

"},{"location":"concepts/advanced/extensions/#per-component-configuration","title":"Per-component configuration","text":"

Each extension has a corresponding nested class within the Component class. These allow to configure the extensions on a per-component basis.

E.g.:

  • \"view\" extension -> Component.View
  • \"cache\" extension -> Component.Cache
  • \"defaults\" extension -> Component.Defaults

Note

Accessing the component instance from inside the nested classes:

Each method of the nested classes has access to the component attribute, which points to the component instance.

class MyTable(Component):\n    class MyExtension:\n        def get(self, request):\n            # `self.component` points to the instance of `MyTable` Component.\n            return self.component.render_to_response(request=request)\n
"},{"location":"concepts/advanced/extensions/#example-component-as-view","title":"Example: Component as View","text":"

The Components as Views feature is actually implemented as an extension that is configured by a View nested class.

You can override the get(), post(), etc methods to customize the behavior of the component as a view:

class MyTable(Component):\n    class View:\n        def get(self, request):\n            return self.component_class.render_to_response(request=request)\n\n        def post(self, request):\n            return self.component_class.render_to_response(request=request)\n\n        ...\n
"},{"location":"concepts/advanced/extensions/#example-storybook-integration","title":"Example: Storybook integration","text":"

The Storybook integration (work in progress) is an extension that is configured by a Storybook nested class.

You can override methods such as title, parameters, etc, to customize how to generate a Storybook JSON file from the component.

class MyTable(Component):\n    class Storybook:\n        def title(self):\n            return self.component_cls.__name__\n\n        def parameters(self) -> Parameters:\n            return {\n                \"server\": {\n                    \"id\": self.component_cls.__name__,\n                }\n            }\n\n        def stories(self) -> List[StoryAnnotations]:\n            return []\n\n        ...\n
"},{"location":"concepts/advanced/extensions/#extension-defaults","title":"Extension defaults","text":"

Extensions are incredibly flexible, but configuring the same extension for every component can be a pain.

For this reason, django-components allows for extension defaults. This is like setting the extension config for every component.

To set extension defaults, use the COMPONENTS.extensions_defaults setting.

The extensions_defaults setting is a dictionary where the key is the extension name and the value is a dictionary of config attributes:

COMPONENTS = ComponentsSettings(\n    extensions=[\n        \"my_extension.MyExtension\",\n        \"storybook.StorybookExtension\",\n    ],\n    extensions_defaults={\n        \"my_extension\": {\n            \"key\": \"value\",\n        },\n        \"view\": {\n            \"public\": True,\n        },\n        \"cache\": {\n            \"ttl\": 60,\n        },\n        \"storybook\": {\n            \"title\": lambda self: self.component_cls.__name__,\n        },\n    },\n)\n

Which is equivalent to setting the following for every component:

class MyTable(Component):\n    class MyExtension:\n        key = \"value\"\n\n    class View:\n        public = True\n\n    class Cache:\n        ttl = 60\n\n    class Storybook:\n        def title(self):\n            return self.component_cls.__name__\n

Info

If you define an attribute as a function, it is like defining a method on the extension class.

E.g. in the example above, title is a method on the Storybook extension class.

As the name suggests, these are defaults, and so you can still selectively override them on a per-component basis:

class MyTable(Component):\n    class View:\n        public = False\n
"},{"location":"concepts/advanced/extensions/#extensions-in-component-instances","title":"Extensions in component instances","text":"

Above, we've configured extensions View and Storybook for the MyTable component.

You can access the instances of these extension classes in the component instance.

Extensions are available under their names (e.g. self.view, self.storybook).

For example, the View extension is available as self.view:

class MyTable(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        # `self.view` points to the instance of `View` extension.\n        return {\n            \"view\": self.view,\n        }\n

And the Storybook extension is available as self.storybook:

class MyTable(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        # `self.storybook` points to the instance of `Storybook` extension.\n        return {\n            \"title\": self.storybook.title(),\n        }\n
"},{"location":"concepts/advanced/extensions/#writing-extensions","title":"Writing extensions","text":"

Creating extensions in django-components involves defining a class that inherits from ComponentExtension. This class can implement various lifecycle hooks and define new attributes or methods to be added to components.

"},{"location":"concepts/advanced/extensions/#extension-class","title":"Extension class","text":"

To create an extension, define a class that inherits from ComponentExtension and implement the desired hooks.

  • Each extension MUST have a name attribute. The name MUST be a valid Python identifier.
  • The extension may implement any of the hook methods.

    Each hook method receives a context object with relevant data.

  • Extension may own URLs or CLI commands.

from django_components.extension import ComponentExtension, OnComponentClassCreatedContext\n\nclass MyExtension(ComponentExtension):\n    name = \"my_extension\"\n\n    def on_component_class_created(self, ctx: OnComponentClassCreatedContext) -> None:\n        # Custom logic for when a component class is created\n        ctx.component_cls.my_attr = \"my_value\"\n

Warning

The name attribute MUST be unique across all extensions.

Moreover, the name attribute MUST NOT conflict with existing Component class API.

So if you name an extension render, it will conflict with the render() method of the Component class.

"},{"location":"concepts/advanced/extensions/#component-config","title":"Component config","text":"

In previous sections we've seen the View and Storybook extensions classes that were nested within the Component class:

class MyComponent(Component):\n    class View:\n        ...\n\n    class Storybook:\n        ...\n

These can be understood as component-specific overrides or configuration.

Whether it's Component.View or Component.Storybook, their respective extensions defined how these nested classes will behave.

For example, the View extension defines the API that users may override in ViewExtension.ComponentConfig:

from django_components.extension import ComponentExtension, ExtensionComponentConfig\n\nclass ViewExtension(ComponentExtension):\n    name = \"view\"\n\n    # The default behavior of the `View` extension class.\n    class ComponentConfig(ExtensionComponentConfig):\n        def get(self, request):\n            raise NotImplementedError(\"You must implement the `get` method.\")\n\n        def post(self, request):\n            raise NotImplementedError(\"You must implement the `post` method.\")\n\n        ...\n

In any component that then defines a nested Component.View extension class, the resulting View class will actually subclass from the ViewExtension.ComponentConfig class.

In other words, when you define a component like this:

class MyTable(Component):\n    class View:\n        def get(self, request):\n            # Do something\n            ...\n

Behind the scenes it is as if you defined the following:

class MyTable(Component):\n    class View(ViewExtension.ComponentConfig):\n        def get(self, request):\n            # Do something\n            ...\n

Warning

When writing an extension, the ComponentConfig MUST subclass the base class ExtensionComponentConfig.

This base class ensures that the extension class will have access to the component instance.

"},{"location":"concepts/advanced/extensions/#install-your-extension","title":"Install your extension","text":"

Once the extension is defined, it needs to be installed in the Django settings to be used by the application.

Extensions can be given either as an extension class, or its import string:

# settings.py\nCOMPONENTS = {\n    \"extensions\": [\n        \"my_app.extensions.MyExtension\",\n    ],\n}\n

Or by reference:

# settings.py\nfrom my_app.extensions import MyExtension\n\nCOMPONENTS = {\n    \"extensions\": [\n        MyExtension,\n    ],\n}\n
"},{"location":"concepts/advanced/extensions/#full-example-custom-logging-extension","title":"Full example: Custom logging extension","text":"

To tie it all together, here's an example of a custom logging extension that logs when components are created, deleted, or rendered:

  • Each component can specify which color to use for the logging by setting Component.ColorLogger.color.
  • The extension will log the component name and color when the component is created, deleted, or rendered.
from django_components.extension import (\n    ComponentExtension,\n    ExtensionComponentConfig,\n    OnComponentClassCreatedContext,\n    OnComponentClassDeletedContext,\n    OnComponentInputContext,\n)\n\n\nclass ColorLoggerExtension(ComponentExtension):\n    name = \"color_logger\"\n\n    # All `Component.ColorLogger` classes will inherit from this class.\n    class ComponentConfig(ExtensionComponentConfig):\n        color: str\n\n    # These hooks don't have access to the Component instance,\n    # only to the Component class, so we access the color\n    # as `Component.ColorLogger.color`.\n    def on_component_class_created(self, ctx: OnComponentClassCreatedContext):\n        log.info(\n            f\"Component {ctx.component_cls} created.\",\n            color=ctx.component_cls.ColorLogger.color,\n        )\n\n    def on_component_class_deleted(self, ctx: OnComponentClassDeletedContext):\n        log.info(\n            f\"Component {ctx.component_cls} deleted.\",\n            color=ctx.component_cls.ColorLogger.color,\n        )\n\n    # This hook has access to the Component instance, so we access the color\n    # as `self.component.color_logger.color`.\n    def on_component_input(self, ctx: OnComponentInputContext):\n        log.info(\n            f\"Rendering component {ctx.component_cls}.\",\n            color=ctx.component.color_logger.color,\n        )\n

To use the ColorLoggerExtension, add it to your settings:

# settings.py\nCOMPONENTS = {\n    \"extensions\": [\n        ColorLoggerExtension,\n    ],\n}\n

Once installed, in any component, you can define a ColorLogger attribute:

class MyComponent(Component):\n    class ColorLogger:\n        color = \"red\"\n

This will log the component name and color when the component is created, deleted, or rendered.

"},{"location":"concepts/advanced/extensions/#utility-functions","title":"Utility functions","text":"

django-components provides a few utility functions to help with writing extensions:

  • all_components() - returns a list of all created component classes.
  • all_registries() - returns a list of all created registry instances.
"},{"location":"concepts/advanced/extensions/#access-component-class","title":"Access component class","text":"

You can access the owner Component class (MyTable) from within methods of the extension class (MyExtension) by using the component_cls attribute:

class MyTable(Component):\n    class MyExtension:\n        def some_method(self):\n            print(self.component_cls)\n

Here is how the component_cls attribute may be used with our ColorLogger extension shown above:

class ColorLoggerComponentConfig(ExtensionComponentConfig):\n    color: str\n\n    def log(self, msg: str) -> None:\n        print(f\"{self.component_cls.__name__}: {msg}\")\n\n\nclass ColorLoggerExtension(ComponentExtension):\n    name = \"color_logger\"\n\n    # All `Component.ColorLogger` classes will inherit from this class.\n    ComponentConfig = ColorLoggerComponentConfig\n
"},{"location":"concepts/advanced/extensions/#pass-slot-metadata","title":"Pass slot metadata","text":"

When a slot is passed to a component, it is copied, so that the original slot is not modified with rendering metadata.

Therefore, don't use slot's identity to associate metadata with the slot:

# \u274c Don't do this:\nslots_cache = {}\n\nclass LoggerExtension(ComponentExtension):\n    name = \"logger\"\n\n    def on_component_input(self, ctx: OnComponentInputContext):\n        for slot in ctx.component.slots.values():\n            slots_cache[id(slot)] = {\"some\": \"metadata\"}\n

Instead, use the Slot.extra attribute, which is copied from the original slot:

# \u2705 Do this:\nclass LoggerExtension(ComponentExtension):\n    name = \"logger\"\n\n    # Save component-level logger settings for each slot when a component is rendered.\n    def on_component_input(self, ctx: OnComponentInputContext):\n        for slot in ctx.component.slots.values():\n            slot.extra[\"logger\"] = ctx.component.logger\n\n    # Then, when a fill is rendered with `{% slot %}`, we can access the logger settings\n    # from the slot's metadata.\n    def on_slot_rendered(self, ctx: OnSlotRenderedContext):\n        logger = ctx.slot.extra[\"logger\"]\n        logger.log(...)\n
"},{"location":"concepts/advanced/extensions/#extension-commands","title":"Extension commands","text":"

Extensions in django-components can define custom commands that can be executed via the Django management command interface. This allows for powerful automation and customization capabilities.

For example, if you have an extension that defines a command that prints \"Hello world\", you can run the command with:

python manage.py components ext run my_ext hello\n

Where:

  • python manage.py components - is the Django entrypoint
  • ext run - is the subcommand to run extension commands
  • my_ext - is the extension name
  • hello - is the command name
"},{"location":"concepts/advanced/extensions/#define-commands","title":"Define commands","text":"

To define a command, subclass from ComponentCommand. This subclass should define:

  • name - the command's name
  • help - the command's help text
  • handle - the logic to execute when the command is run
from django_components import ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n    name = \"hello\"\n    help = \"Say hello\"\n\n    def handle(self, *args, **kwargs):\n        print(\"Hello, world!\")\n\nclass MyExt(ComponentExtension):\n    name = \"my_ext\"\n    commands = [HelloCommand]\n
"},{"location":"concepts/advanced/extensions/#define-arguments-and-options","title":"Define arguments and options","text":"

Commands can accept positional arguments and options (e.g. --foo), which are defined using the arguments attribute of the ComponentCommand class.

The arguments are parsed with argparse into a dictionary of arguments and options. These are then available as keyword arguments to the handle method of the command.

from django_components import CommandArg, ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n    name = \"hello\"\n    help = \"Say hello\"\n\n    arguments = [\n        # Positional argument\n        CommandArg(\n            name_or_flags=\"name\",\n            help=\"The name to say hello to\",\n        ),\n        # Optional argument\n        CommandArg(\n            name_or_flags=[\"--shout\", \"-s\"],\n            action=\"store_true\",\n            help=\"Shout the hello\",\n        ),\n    ]\n\n    def handle(self, name: str, *args, **kwargs):\n        shout = kwargs.get(\"shout\", False)\n        msg = f\"Hello, {name}!\"\n        if shout:\n            msg = msg.upper()\n        print(msg)\n

You can run the command with arguments and options:

python manage.py components ext run my_ext hello John --shout\n>>> HELLO, JOHN!\n

Note

Command definitions are parsed with argparse, so you can use all the features of argparse to define your arguments and options.

See the argparse documentation for more information.

django-components defines types as CommandArg, CommandArgGroup, CommandSubcommand, and CommandParserInput to help with type checking.

Note

If a command doesn't have the handle method defined, the command will print a help message and exit.

"},{"location":"concepts/advanced/extensions/#argument-groups","title":"Argument groups","text":"

Arguments can be grouped using CommandArgGroup to provide better organization and help messages.

Read more on argparse argument groups.

from django_components import CommandArg, CommandArgGroup, ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n    name = \"hello\"\n    help = \"Say hello\"\n\n    # Argument parsing is managed by `argparse`.\n    arguments = [\n        # Positional argument\n        CommandArg(\n            name_or_flags=\"name\",\n            help=\"The name to say hello to\",\n        ),\n        # Optional argument\n        CommandArg(\n            name_or_flags=[\"--shout\", \"-s\"],\n            action=\"store_true\",\n            help=\"Shout the hello\",\n        ),\n        # When printing the command help message, `--bar` and `--baz`\n        # will be grouped under \"group bar\".\n        CommandArgGroup(\n            title=\"group bar\",\n            description=\"Group description.\",\n            arguments=[\n                CommandArg(\n                    name_or_flags=\"--bar\",\n                    help=\"Bar description.\",\n                ),\n                CommandArg(\n                    name_or_flags=\"--baz\",\n                    help=\"Baz description.\",\n                ),\n            ],\n        ),\n    ]\n\n    def handle(self, name: str, *args, **kwargs):\n        shout = kwargs.get(\"shout\", False)\n        msg = f\"Hello, {name}!\"\n        if shout:\n            msg = msg.upper()\n        print(msg)\n
"},{"location":"concepts/advanced/extensions/#subcommands","title":"Subcommands","text":"

Extensions can define subcommands, allowing for more complex command structures.

Subcommands are defined similarly to root commands, as subclasses of ComponentCommand class.

However, instead of defining the subcommands in the commands attribute of the extension, you define them in the subcommands attribute of the parent command:

from django_components import CommandArg, CommandArgGroup, ComponentCommand, ComponentExtension\n\nclass ChildCommand(ComponentCommand):\n    name = \"child\"\n    help = \"Child command\"\n\n    def handle(self, *args, **kwargs):\n        print(\"Child command\")\n\nclass ParentCommand(ComponentCommand):\n    name = \"parent\"\n    help = \"Parent command\"\n    subcommands = [\n        ChildCommand,\n    ]\n\n    def handle(self, *args, **kwargs):\n        print(\"Parent command\")\n

In this example, we can run two commands.

Either the parent command:

python manage.py components ext run parent\n>>> Parent command\n

Or the child command:

python manage.py components ext run parent child\n>>> Child command\n

Warning

Subcommands are independent of the parent command. When a subcommand runs, the parent command is NOT executed.

As such, if you want to pass arguments to both the parent and child commands, e.g.:

python manage.py components ext run parent --foo child --bar\n

You should instead pass all the arguments to the subcommand:

python manage.py components ext run parent child --foo --bar\n
"},{"location":"concepts/advanced/extensions/#help-message","title":"Help message","text":"

By default, all commands will print their help message when run with the --help / -h flag.

python manage.py components ext run my_ext --help\n

The help message prints out all the arguments and options available for the command, as well as any subcommands.

"},{"location":"concepts/advanced/extensions/#testing-commands","title":"Testing commands","text":"

Commands can be tested using Django's call_command() function, which allows you to simulate running the command in tests.

from django.core.management import call_command\n\ncall_command('components', 'ext', 'run', 'my_ext', 'hello', '--name', 'John')\n

To capture the output of the command, you can use the StringIO module to redirect the output to a string:

from io import StringIO\n\nout = StringIO()\nwith patch(\"sys.stdout\", new=out):\n    call_command('components', 'ext', 'run', 'my_ext', 'hello', '--name', 'John')\noutput = out.getvalue()\n

And to temporarily set the extensions, you can use the @djc_test decorator.

Thus, a full test example can then look like this:

from io import StringIO\nfrom unittest.mock import patch\n\nfrom django.core.management import call_command\nfrom django_components.testing import djc_test\n\n@djc_test(\n    components_settings={\n        \"extensions\": [\n            \"my_app.extensions.MyExtension\",\n        ],\n    },\n)\ndef test_hello_command(self):\n    out = StringIO()\n    with patch(\"sys.stdout\", new=out):\n        call_command('components', 'ext', 'run', 'my_ext', 'hello', '--name', 'John')\n    output = out.getvalue()\n    assert output == \"Hello, John!\\n\"\n
"},{"location":"concepts/advanced/extensions/#extension-urls","title":"Extension URLs","text":"

Extensions can define custom views and endpoints that can be accessed through the Django application.

To define URLs for an extension, set them in the urls attribute of your ComponentExtension class. Each URL is defined using the URLRoute class, which specifies the path, handler, and optional name for the route.

Here's an example of how to define URLs within an extension:

from django_components.extension import ComponentExtension, URLRoute\nfrom django.http import HttpResponse\n\ndef my_view(request):\n    return HttpResponse(\"Hello from my extension!\")\n\nclass MyExtension(ComponentExtension):\n    name = \"my_extension\"\n\n    urls = [\n        URLRoute(path=\"my-view/\", handler=my_view, name=\"my_view\"),\n        URLRoute(path=\"another-view/<int:id>/\", handler=my_view, name=\"another_view\"),\n    ]\n

Warning

The URLRoute objects are different from objects created with Django's django.urls.path(). Do NOT use URLRoute objects in Django's urlpatterns and vice versa!

django-components uses a custom URLRoute class to define framework-agnostic routing rules.

As of v0.131, URLRoute objects are directly converted to Django's URLPattern and URLResolver objects.

"},{"location":"concepts/advanced/extensions/#url-paths","title":"URL paths","text":"

The URLs defined in an extension are available under the path

/components/ext/<extension_name>/\n

For example, if you have defined a URL with the path my-view/<str:name>/ in an extension named my_extension, it can be accessed at:

/components/ext/my_extension/my-view/john/\n
"},{"location":"concepts/advanced/extensions/#nested-urls","title":"Nested URLs","text":"

Extensions can also define nested URLs to allow for more complex routing structures.

To define nested URLs, set the children attribute of the URLRoute object to a list of child URLRoute objects:

class MyExtension(ComponentExtension):\n    name = \"my_extension\"\n\n    urls = [\n        URLRoute(\n            path=\"parent/\",\n            name=\"parent_view\",\n            children=[\n                URLRoute(path=\"child/<str:name>/\", handler=my_view, name=\"child_view\"),\n            ],\n        ),\n    ]\n

In this example, the URL

/components/ext/my_extension/parent/child/john/\n

would call the my_view handler with the parameter name set to \"John\".

"},{"location":"concepts/advanced/extensions/#extra-url-data","title":"Extra URL data","text":"

The URLRoute class is framework-agnostic, so that extensions could be used with non-Django frameworks in the future.

However, that means that there may be some extra fields that Django's django.urls.path() accepts, but which are not defined on the URLRoute object.

To address this, the URLRoute object has an extra attribute, which is a dictionary that can be used to pass any extra kwargs to django.urls.path():

URLRoute(\n    path=\"my-view/<str:name>/\",\n    handler=my_view,\n    name=\"my_view\",\n    extra={\"kwargs\": {\"foo\": \"bar\"} },\n)\n

Is the same as:

django.urls.path(\n    \"my-view/<str:name>/\",\n    view=my_view,\n    name=\"my_view\",\n    kwargs={\"foo\": \"bar\"},\n)\n

because URLRoute is converted to Django's route like so:

django.urls.path(\n    route.path,\n    view=route.handler,\n    name=route.name,\n    **route.extra,\n)\n
"},{"location":"concepts/advanced/hooks/","title":"Lifecycle hooks","text":"

New in version 0.96

Intercept the rendering lifecycle with Component hooks.

Unlike the extension hooks, these are defined directly on the Component class.

"},{"location":"concepts/advanced/hooks/#available-hooks","title":"Available hooks","text":""},{"location":"concepts/advanced/hooks/#on_render_before","title":"on_render_before","text":"
def on_render_before(\n    self: Component,\n    context: Context,\n    template: Optional[Template],\n) -> None:\n

Component.on_render_before runs just before the component's template is rendered.

It is called for every component, including nested ones, as part of the component render lifecycle.

It receives the Context and the Template as arguments.

The template argument is None if the component has no template.

Example:

You can use this hook to access the context or the template:

from django.template import Context, Template\nfrom django_components import Component\n\nclass MyTable(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        # Insert value into the Context\n        context[\"from_on_before\"] = \":)\"\n\n        assert isinstance(template, Template)\n

Warning

If you want to pass data to the template, prefer using get_template_data() instead of this hook.

Warning

Do NOT modify the template in this hook. The template is reused across renders.

Since this hook is called for every component, this means that the template would be modified every time a component is rendered.

"},{"location":"concepts/advanced/hooks/#on_render","title":"on_render","text":"

New in version 0.140

def on_render(\n    self: Component,\n    context: Context,\n    template: Optional[Template],\n) -> Union[str, SafeString, OnRenderGenerator, None]:\n

Component.on_render does the actual rendering.

You can override this method to:

  • Change what template gets rendered
  • Modify the context
  • Modify the rendered output after it has been rendered
  • Handle errors

The default implementation renders the component's Template with the given Context.

class MyTable(Component):\n    def on_render(self, context, template):\n        if template is None:\n            return None\n        else:\n            return template.render(context)\n

The template argument is None if the component has no template.

"},{"location":"concepts/advanced/hooks/#modifying-rendered-template","title":"Modifying rendered template","text":"

To change what gets rendered, you can:

  • Render a different template
  • Render a component
  • Return a different string or SafeString
class MyTable(Component):\n    def on_render(self, context, template):\n        return \"Hello\"\n

You can also use on_render() as a router, rendering other components based on the parent component's arguments:

class MyTable(Component):\n    def on_render(self, context, template):\n        # Select different component based on `feature_new_table` kwarg\n        if self.kwargs.get(\"feature_new_table\"):\n            comp_cls = NewTable\n        else:\n            comp_cls = OldTable\n\n        # Render the selected component\n        return comp_cls.render(\n            args=self.args,\n            kwargs=self.kwargs,\n            slots=self.slots,\n            context=context,\n        )\n
"},{"location":"concepts/advanced/hooks/#post-processing-rendered-template","title":"Post-processing rendered template","text":"

When you render the original template in on_render() as:

template.render(context)\n

The result is NOT the final output, but an intermediate result. Nested components are not rendered yet.

Instead, django-components needs to take this result and process it to actually render the child components.

To access the final output, you can yield the result instead of returning it.

This will return a tuple of (rendered HTML, error). The error is None if the rendering succeeded.

class MyTable(Component):\n    def on_render(self, context, template):\n        html, error = yield template.render(context)\n\n        if error is None:\n            # The rendering succeeded\n            return html\n        else:\n            # The rendering failed\n            print(f\"Error: {error}\")\n

At this point you can do 3 things:

  1. Return a new HTML

    The new HTML will be used as the final output.

    If the original template raised an error, it will be ignored.

    class MyTable(Component):\n    def on_render(self, context, template):\n        html, error = yield template.render(context)\n\n        return \"NEW HTML\"\n
  2. Raise a new exception

    The new exception is what will bubble up from the component.

    The original HTML and original error will be ignored.

    class MyTable(Component):\n    def on_render(self, context, template):\n        html, error = yield template.render(context)\n\n        raise Exception(\"Error message\")\n
  3. Return nothing (or None) to handle the result as usual

    If you don't raise an exception, and neither return a new HTML, then original HTML / error will be used:

    • If rendering succeeded, the original HTML will be used as the final output.
    • If rendering failed, the original error will be propagated.
    class MyTable(Component):\n    def on_render(self, context, template):\n        html, error = yield template.render(context)\n\n        if error is not None:\n            # The rendering failed\n            print(f\"Error: {error}\")\n
"},{"location":"concepts/advanced/hooks/#example-errorboundary","title":"Example: ErrorBoundary","text":"

on_render() can be used to implement React's ErrorBoundary.

That is, a component that catches errors in nested components and displays a fallback UI instead:

{% component \"error_boundary\" %}\n  {% fill \"content\" %}\n    {% component \"nested_component\" %}\n  {% endfill %}\n  {% fill \"fallback\" %}\n    Sorry, something went wrong.\n  {% endfill %}\n{% endcomponent %}\n

To implement this, we render the fallback slot in on_render() and return it if an error occured:

class ErrorFallback(Component):\n    template = \"\"\"\n      {% slot \"content\" default / %}\n    \"\"\"\n\n    def on_render(self, context, template):\n        fallback = self.slots.fallback\n\n        if fallback is None:\n            raise ValueError(\"fallback slot is required\")\n\n        html, error = yield template.render(context)\n\n        if error is not None:\n            return fallback()\n        else:\n            return html\n
"},{"location":"concepts/advanced/hooks/#on_render_after","title":"on_render_after","text":"
def on_render_after(\n    self: Component,\n    context: Context,\n    template: Optional[Template],\n    result: Optional[str | SafeString],\n    error: Optional[Exception],\n) -> Union[str, SafeString, None]:\n

on_render_after() runs when the component was fully rendered, including all its children.

It receives the same arguments as on_render_before(), plus the outcome of the rendering:

  • result: The rendered output of the component. None if the rendering failed.
  • error: The error that occurred during the rendering, or None if the rendering succeeded.

on_render_after() behaves the same way as the second part of on_render() (after the yield).

class MyTable(Component):\n    def on_render_after(self, context, template, result, error):\n        if error is None:\n            # The rendering succeeded\n            return result\n        else:\n            # The rendering failed\n            print(f\"Error: {error}\")\n

Same as on_render(), you can return a new HTML, raise a new exception, or return nothing:

  1. Return a new HTML

    The new HTML will be used as the final output.

    If the original template raised an error, it will be ignored.

    class MyTable(Component):\n    def on_render_after(self, context, template, result, error):\n        return \"NEW HTML\"\n
  2. Raise a new exception

    The new exception is what will bubble up from the component.

    The original HTML and original error will be ignored.

    class MyTable(Component):\n    def on_render_after(self, context, template, result, error):\n        raise Exception(\"Error message\")\n
  3. Return nothing (or None) to handle the result as usual

    If you don't raise an exception, and neither return a new HTML, then original HTML / error will be used:

    • If rendering succeeded, the original HTML will be used as the final output.
    • If rendering failed, the original error will be propagated.
    class MyTable(Component):\n    def on_render_after(self, context, template, result, error):\n        if error is not None:\n            # The rendering failed\n            print(f\"Error: {error}\")\n
"},{"location":"concepts/advanced/hooks/#example","title":"Example","text":"

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\" %}\n  {% component \"tab_item\" header=\"Tab 1\" %}\n    <p>\n      hello from tab 1\n    </p>\n    {% component \"button\" %}\n      Click me!\n    {% endcomponent %}\n  {% endcomponent %}\n\n  {% component \"tab_item\" header=\"Tab 2\" %}\n    Hello this is tab 2\n  {% endcomponent %}\n{% endcomponent %}\n
"},{"location":"concepts/advanced/html_fragments/","title":"HTML fragments","text":"

Django-components provides a seamless integration with HTML fragments with AJAX (HTML over the wire), whether you're using jQuery, HTMX, AlpineJS, vanilla JavaScript, or other.

If the fragment component has any JS or CSS, django-components will:

  • Automatically load the associated JS and CSS
  • Ensure that JS is loaded and executed only once even if the fragment is inserted multiple times

Info

What are HTML fragments and \"HTML over the wire\"?

It is one of the methods for updating the state in the browser UI upon user interaction.

How it works is that:

  1. User makes an action - clicks a button or submits a form
  2. The action causes a request to be made from the client to the server.
  3. Server processes the request (e.g. form submission), and responds with HTML of some part of the UI (e.g. a new entry in a table).
  4. A library like HTMX, AlpineJS, or custom function inserts the new HTML into the correct place.
"},{"location":"concepts/advanced/html_fragments/#document-and-fragment-strategies","title":"Document and fragment strategies","text":"

Components support different \"strategies\" for rendering JS and CSS.

Two of them are used to enable HTML fragments - \"document\" and \"fragment\".

What's the difference?

"},{"location":"concepts/advanced/html_fragments/#document-strategy","title":"Document strategy","text":"

Document strategy assumes that the rendered components will be embedded into the HTML of the initial page load. This means that:

  • The JS and CSS is embedded into the HTML as <script> and <style> tags (see Default JS / CSS locations)
  • Django-components injects a JS script for managing JS and CSS assets

A component is rendered as a \"document\" when:

  • It is embedded inside a template as {% component %}
  • It is rendered with Component.render() or Component.render_to_response() with the deps_strategy kwarg set to \"document\" (default)

Example:

MyTable.render(\n    kwargs={...},\n)\n\n# or\n\nMyTable.render(\n    kwargs={...},\n    deps_strategy=\"document\",\n)\n
"},{"location":"concepts/advanced/html_fragments/#fragment-strategy","title":"Fragment strategy","text":"

Fragment strategy assumes that the main HTML has already been rendered and loaded on the page. The component renders HTML that will be inserted into the page as a fragment, at a LATER time:

  • JS and CSS is not directly embedded to avoid duplicately executing the same JS scripts. So template tags like {% component_js_dependencies %} inside of fragments are ignored.
  • Instead, django-components appends the fragment's content with a JSON <script> to trigger a call to its asset manager JS script, which will load the JS and CSS smartly.
  • The asset manager JS script is assumed to be already loaded on the page.

A component is rendered as \"fragment\" when:

  • It is rendered with Component.render() or Component.render_to_response() with the deps_strategy kwarg set to \"fragment\"

Example:

MyTable.render(\n    kwargs={...},\n    deps_strategy=\"fragment\",\n)\n
"},{"location":"concepts/advanced/html_fragments/#live-examples","title":"Live examples","text":"

For live interactive examples, start our demo project (sampleproject).

Then navigate to these URLs:

  • /fragment/base/alpine
  • /fragment/base/htmx
  • /fragment/base/js
"},{"location":"concepts/advanced/html_fragments/#example-htmx","title":"Example - HTMX","text":""},{"location":"concepts/advanced/html_fragments/#1-define-document-html","title":"1. Define document HTML","text":"

This is the HTML into which a fragment will be loaded using HTMX.

[root]/components/demo.py
from django_components import Component, types\n\nclass MyPage(Component):\n    template = \"\"\"\n        {% load component_tags %}\n        <!DOCTYPE html>\n        <html>\n            <head>\n                {% component_css_dependencies %}\n                <script src=\"https://unpkg.com/htmx.org@1.9.12\"></script>\n            </head>\n            <body>\n                <div id=\"target\">OLD</div>\n\n                <button\n                    hx-get=\"/mypage/frag\"\n                    hx-swap=\"outerHTML\"\n                    hx-target=\"#target\"\n                >\n                  Click me!\n                </button>\n\n                {% component_js_dependencies %}\n            </body>\n        </html>\n    \"\"\"\n\n    class View:\n        def get(self, request):\n            return self.component_cls.render_to_response(request=request)\n
"},{"location":"concepts/advanced/html_fragments/#2-define-fragment-html","title":"2. Define fragment HTML","text":"

The fragment to be inserted into the document.

IMPORTANT: Don't forget to set deps_strategy=\"fragment\"

[root]/components/demo.py
class Frag(Component):\n    template = \"\"\"\n        <div class=\"frag\">\n            123\n            <span id=\"frag-text\"></span>\n        </div>\n    \"\"\"\n\n    js = \"\"\"\n        document.querySelector('#frag-text').textContent = 'xxx';\n    \"\"\"\n\n    css = \"\"\"\n        .frag {\n            background: blue;\n        }\n    \"\"\"\n\n    class View:\n        def get(self, request):\n            return self.component_cls.render_to_response(\n                request=request,\n                # IMPORTANT: Don't forget `deps_strategy=\"fragment\"`\n                deps_strategy=\"fragment\",\n            )\n
"},{"location":"concepts/advanced/html_fragments/#3-create-view-and-urls","title":"3. Create view and URLs","text":"[app]/urls.py
from django.urls import path\n\nfrom components.demo import MyPage, Frag\n\nurlpatterns = [\n    path(\"mypage/\", MyPage.as_view())\n    path(\"mypage/frag\", Frag.as_view()),\n]\n
"},{"location":"concepts/advanced/html_fragments/#example-alpinejs","title":"Example - AlpineJS","text":""},{"location":"concepts/advanced/html_fragments/#1-define-document-html_1","title":"1. Define document HTML","text":"

This is the HTML into which a fragment will be loaded using AlpineJS.

[root]/components/demo.py
from django_components import Component, types\n\nclass MyPage(Component):\n    template = \"\"\"\n        {% load component_tags %}\n        <!DOCTYPE html>\n        <html>\n            <head>\n                {% component_css_dependencies %}\n                <script defer src=\"https://unpkg.com/alpinejs\"></script>\n            </head>\n            <body x-data=\"{\n                htmlVar: 'OLD',\n                loadFragment: function () {\n                    const url = '/mypage/frag';\n                    fetch(url)\n                        .then(response => response.text())\n                        .then(html => {\n                            this.htmlVar = html;\n                        });\n                }\n            }\">\n                <div id=\"target\" x-html=\"htmlVar\">OLD</div>\n\n                <button @click=\"loadFragment\">\n                  Click me!\n                </button>\n\n                {% component_js_dependencies %}\n            </body>\n        </html>\n    \"\"\"\n\n    class View:\n        def get(self, request):\n            return self.component_cls.render_to_response(request=request)\n
"},{"location":"concepts/advanced/html_fragments/#2-define-fragment-html_1","title":"2. Define fragment HTML","text":"

The fragment to be inserted into the document.

IMPORTANT: Don't forget to set deps_strategy=\"fragment\"

[root]/components/demo.py
class Frag(Component):\n    # NOTE: We wrap the actual fragment in a template tag with x-if=\"false\" to prevent it\n    #       from being rendered until we have registered the component with AlpineJS.\n    template = \"\"\"\n        <template x-if=\"false\" data-name=\"frag\">\n            <div class=\"frag\">\n                123\n                <span x-data=\"frag\" x-text=\"fragVal\">\n                </span>\n            </div>\n        </template>\n    \"\"\"\n\n    js = \"\"\"\n        Alpine.data('frag', () => ({\n            fragVal: 'xxx',\n        }));\n\n        // Now that the component has been defined in AlpineJS, we can \"activate\"\n        // all instances where we use the `x-data=\"frag\"` directive.\n        document.querySelectorAll('[data-name=\"frag\"]').forEach((el) => {\n            el.setAttribute('x-if', 'true');\n        });\n    \"\"\"\n\n    css = \"\"\"\n        .frag {\n            background: blue;\n        }\n    \"\"\"\n\n    class View:\n        def get(self, request):\n            return self.component_cls.render_to_response(\n                request=request,\n                # IMPORTANT: Don't forget `deps_strategy=\"fragment\"`\n                deps_strategy=\"fragment\",\n            )\n
"},{"location":"concepts/advanced/html_fragments/#3-create-view-and-urls_1","title":"3. Create view and URLs","text":"[app]/urls.py
from django.urls import path\n\nfrom components.demo import MyPage, Frag\n\nurlpatterns = [\n    path(\"mypage/\", MyPage.as_view())\n    path(\"mypage/frag\", Frag.as_view()),\n]\n
"},{"location":"concepts/advanced/html_fragments/#example-vanilla-js","title":"Example - Vanilla JS","text":""},{"location":"concepts/advanced/html_fragments/#1-define-document-html_2","title":"1. Define document HTML","text":"

This is the HTML into which a fragment will be loaded using vanilla JS.

[root]/components/demo.py
from django_components import Component, types\n\nclass MyPage(Component):\n    template = \"\"\"\n        {% load component_tags %}\n        <!DOCTYPE html>\n        <html>\n            <head>\n                {% component_css_dependencies %}\n            </head>\n            <body>\n                <div id=\"target\">OLD</div>\n\n                <button>\n                  Click me!\n                </button>\n                <script>\n                    const url = `/mypage/frag`;\n                    document.querySelector('#loader').addEventListener('click', function () {\n                        fetch(url)\n                            .then(response => response.text())\n                            .then(html => {\n                                document.querySelector('#target').outerHTML = html;\n                            });\n                    });\n                </script>\n\n                {% component_js_dependencies %}\n            </body>\n        </html>\n    \"\"\"\n\n    class View:\n        def get(self, request):\n            return self.component_cls.render_to_response(request=request)\n
"},{"location":"concepts/advanced/html_fragments/#2-define-fragment-html_2","title":"2. Define fragment HTML","text":"

The fragment to be inserted into the document.

IMPORTANT: Don't forget to set deps_strategy=\"fragment\"

[root]/components/demo.py
class Frag(Component):\n    template = \"\"\"\n        <div class=\"frag\">\n            123\n            <span id=\"frag-text\"></span>\n        </div>\n    \"\"\"\n\n    js = \"\"\"\n        document.querySelector('#frag-text').textContent = 'xxx';\n    \"\"\"\n\n    css = \"\"\"\n        .frag {\n            background: blue;\n        }\n    \"\"\"\n\n    class View:\n        def get(self, request):\n            return self.component_cls.render_to_response(\n                request=request,\n                # IMPORTANT: Don't forget `deps_strategy=\"fragment\"`\n                deps_strategy=\"fragment\",\n            )\n
"},{"location":"concepts/advanced/html_fragments/#3-create-view-and-urls_2","title":"3. Create view and URLs","text":"[app]/urls.py
from django.urls import path\n\nfrom components.demo import MyPage, Frag\n\nurlpatterns = [\n    path(\"mypage/\", MyPage.as_view())\n    path(\"mypage/frag\", Frag.as_view()),\n]\n
"},{"location":"concepts/advanced/provide_inject/","title":"Prop drilling and provide / inject","text":"

New in version 0.80:

django-components supports the provide / inject pattern, similarly to React's Context Providers or Vue's provide / inject.

This is achieved with the combination of:

  • {% provide %} tag
  • Component.inject() method
"},{"location":"concepts/advanced/provide_inject/#what-is-prop-drilling","title":"What is \"prop drilling\"","text":"

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.

With provide / inject, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.

This feature is inspired by Vue's Provide / Inject and React's Context / useContext.

As the name suggest, using provide / inject consists of 2 steps

  1. Providing data
  2. Injecting provided data

For examples of advanced uses of provide / inject, see this discussion.

"},{"location":"concepts/advanced/provide_inject/#providing-data","title":"Providing data","text":"

First we use the {% provide %} tag to define the data we want to \"provide\" (make available).

{% provide \"my_data\" hello=\"hi\" another=123 %}\n    {% component \"child\" / %}  <--- Can access \"my_data\"\n{% endprovide %}\n\n{% component \"child\" / %}  <--- Cannot access \"my_data\"\n

The first argument to the {% provide %} tag is the key by which we can later access the data passed to this tag. The key in this case is \"my_data\".

The key must resolve to a valid identifier (AKA a valid Python variable name).

Next you define the data you want to \"provide\" by passing them as keyword arguments. This is similar to how you pass data to the {% with %} tag or the {% slot %} tag.

Note

Kwargs passed to {% provide %} are NOT added to the context. In the example below, the {{ hello }} won't render anything:

{% provide \"my_data\" hello=\"hi\" another=123 %}\n    {{ hello }}\n{% endprovide %}\n

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

{% with my_name=\"my_name\" %}\n    {% provide name=my_name ... %}\n        ...\n    {% endprovide %}\n{% endwith %}\n
"},{"location":"concepts/advanced/provide_inject/#injecting-data","title":"Injecting data","text":"

To \"inject\" (access) the data defined on the {% provide %} tag, you can use the Component.inject() method from within any other component methods.

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: hello=\"hi\" another=123. That means that if we now inject \"my_data\", we get an object with 2 attributes - hello and another.

class ChildComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        my_data = self.inject(\"my_data\")\n        print(my_data.hello)    # hi\n        print(my_data.another)  # 123\n

First argument to Component.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(). This will act as a default value similar to dict.get(key, default):

class ChildComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        my_data = self.inject(\"invalid_key\", DEFAULT_DATA)\n        assert my_data == DEFAULT_DATA\n

Note

The instance returned from inject() is immutable (subclass of NamedTuple). This ensures that the data returned from inject() will always have all the keys that were passed to the {% provide %} tag.

Warning

inject() works strictly only during render execution. If you try to call inject() from outside, it will raise an error.

"},{"location":"concepts/advanced/provide_inject/#full-example","title":"Full example","text":"
@register(\"child\")\nclass ChildComponent(Component):\n    template = \"\"\"\n        <div> {{ my_data.hello }} </div>\n        <div> {{ my_data.another }} </div>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        my_data = self.inject(\"my_data\", \"default\")\n        return {\"my_data\": my_data}\n\ntemplate_str = \"\"\"\n    {% load component_tags %}\n    {% provide \"my_data\" hello=\"hi\" another=123 %}\n        {% component \"child\" / %}\n    {% endprovide %}\n\"\"\"\n

renders:

<div>hi</div>\n<div>123</div>\n
"},{"location":"concepts/advanced/rendering_js_css/","title":"Rendering JS / CSS","text":""},{"location":"concepts/advanced/rendering_js_css/#introduction","title":"Introduction","text":"

Components consist of 3 parts - HTML, JS and CSS.

Handling of HTML is straightforward - it is rendered as is, and inserted where the {% component %} tag is.

However, handling of JS and CSS is more complex:

  • JS and CSS is are inserted elsewhere in the HTML. As a best practice, JS is placed in the <body> HTML tag, and CSS in the <head>.
  • Multiple components may use the same JS and CSS files. We don't want to load the same files multiple times.
  • Fetching of JS and CSS may block the page, so the JS / CSS should be embedded in the HTML.
  • Components inserted as HTML fragments need different handling for JS and CSS.
"},{"location":"concepts/advanced/rendering_js_css/#default-js-css-locations","title":"Default JS / CSS locations","text":"

If your components use JS and CSS then, by default, the JS and CSS will be automatically inserted into the HTML:

  • CSS styles will be inserted at the end of the <head>
  • JS scripts will be inserted at the end of the <body>

If you want to place the dependencies elsewhere in the HTML, you can override the locations by inserting following Django template tags:

  • {% component_js_dependencies %} - Set new location(s) for JS scripts
  • {% component_css_dependencies %} - Set new location(s) for CSS styles

So if you have a component with JS and CSS:

from django_components import Component, types\n\nclass MyButton(Component):\n    template: types.django_html = \"\"\"\n        <button class=\"my-button\">\n            Click me!\n        </button>\n    \"\"\"\n\n    js: types.js = \"\"\"\n        for (const btnEl of document.querySelectorAll(\".my-button\")) {\n            btnEl.addEventListener(\"click\", () => {\n                console.log(\"BUTTON CLICKED!\");\n            });\n        }\n    \"\"\"\n\n    css: types.css \"\"\"\n        .my-button {\n            background: green;\n        }\n    \"\"\"\n\n    class Media:\n        js = [\"/extra/script.js\"]\n        css = [\"/extra/style.css\"]\n

Then:

  • JS from MyButton.js and MyButton.Media.js will be rendered at the default place (<body>), or in {% component_js_dependencies %}.

  • CSS from MyButton.css and MyButton.Media.css will be rendered at the default place (<head>), or in {% component_css_dependencies %}.

And if you don't specify {% component_dependencies %} tags, it is the equivalent of:

<!doctype html>\n<html>\n  <head>\n    <title>MyPage</title>\n    ...\n    {% component_css_dependencies %}\n  </head>\n  <body>\n    <main>\n      ...\n    </main>\n    {% component_js_dependencies %}\n  </body>\n</html>\n

Warning

If the rendered HTML does NOT contain neither {% component_dependencies %} template tags, nor <head> and <body> HTML tags, then the JS and CSS will NOT be inserted!

To force the JS and CSS to be inserted, use the \"append\" or \"prepend\" strategies.

"},{"location":"concepts/advanced/rendering_js_css/#dependencies-strategies","title":"Dependencies strategies","text":"

The rendered HTML may be used in different contexts (browser, email, etc). If your components use JS and CSS scripts, you may need to handle them differently.

The different ways for handling JS / CSS are called \"dependencies strategies\".

render() and render_to_response() accept a deps_strategy parameter, which controls where and how the JS / CSS are inserted into the HTML.

main_page = MainPage.render(deps_strategy=\"document\")\nfragment = MyComponent.render_to_response(deps_strategy=\"fragment\")\n

The deps_strategy parameter is set at the root of a component render tree, which is why it is not available for the {% component %} tag.

When you use Django's django.shortcuts.render() or Template.render() to render templates, you can't directly set the deps_strategy parameter.

In this case, you can set the deps_strategy with the DJC_DEPS_STRATEGY context variable.

from django.template.context import Context\nfrom django.shortcuts import render\n\nctx = Context({\"DJC_DEPS_STRATEGY\": \"fragment\"})\nfragment = render(request, \"my_component.html\", ctx=ctx)\n

Info

The deps_strategy parameter is ultimately passed to render_dependencies().

Why is deps_strategy required?

This is a technical limitation of the current implementation.

When a component is rendered, django-components embeds metadata about the component's JS and CSS into the HTML.

This way we can compose components together, and know which JS / CSS dependencies are needed.

As the last step of rendering, django-components extracts this metadata and uses a selected strategy to insert the JS / CSS into the HTML.

There are six dependencies strategies:

  • document (default)
    • Smartly inserts JS / CSS into placeholders or into <head> and <body> tags.
    • Inserts extra script to allow fragment strategy to work.
    • Assumes the HTML will be rendered in a JS-enabled browser.
  • fragment
    • A lightweight HTML fragment to be inserted into a document with AJAX.
    • No JS / CSS included.
  • simple
    • Smartly insert JS / CSS into placeholders or into <head> and <body> tags.
    • No extra script loaded.
  • prepend
    • Insert JS / CSS before the rendered HTML.
    • No extra script loaded.
  • append
    • Insert JS / CSS after the rendered HTML.
    • No extra script loaded.
  • ignore
    • HTML is left as-is. You can still process it with a different strategy later with render_dependencies().
    • Used for inserting rendered HTML into other components.
"},{"location":"concepts/advanced/rendering_js_css/#document","title":"document","text":"

deps_strategy=\"document\" is the default. Use this if you are rendering a whole page, or if no other option suits better.

html = Button.render(deps_strategy=\"document\")\n

When you render a component tree with the \"document\" strategy, it is expected that:

  • The HTML will be rendered at page load.
  • The HTML will be inserted into a page / browser where JS can be executed.

Location:

JS and CSS is inserted:

  • Preferentially into JS / CSS placeholders like {% component_js_dependencies %}
  • Otherwise, JS into <body> element, and CSS into <head> element
  • If neither found, JS / CSS are NOT inserted

Included scripts:

For the \"document\" strategy, the JS and CSS is set up to avoid any delays when the end user loads the page in the browser:

  • Components' primary JS and CSS scripts (Component.js and Component.css) - fully inlined:

    <script>\n    console.log(\"Hello from Button!\");\n</script>\n<style>\n    .button {\n        background-color: blue;\n    }\n</style>\n
  • Components' secondary JS and CSS scripts (Component.Media) - inserted as links:

    <link rel=\"stylesheet\" href=\"https://example.com/styles.css\" />\n<script src=\"https://example.com/script.js\"></script>\n
  • A JS script is injected to manage component dependencies, enabling lazy loading of JS and CSS for HTML fragments.

Info

This strategy is required for fragments to work properly, as it sets up the dependency manager that fragments rely on.

How the dependency manager works

The dependency manager is a JS script that keeps track of all the JS and CSS dependencies that have already been loaded.

When a fragment is inserted into the page, it will also insert a JSON <script> tag with fragment metadata.

The dependency manager will pick up on that, and check which scripts the fragment needs.

It will then fetch only the scripts that haven't been loaded yet.

"},{"location":"concepts/advanced/rendering_js_css/#fragment","title":"fragment","text":"

deps_strategy=\"fragment\" is used when rendering a piece of HTML that will be inserted into a page that has already been rendered with the \"document\" strategy:

fragment = MyComponent.render(deps_strategy=\"fragment\")\n

The HTML of fragments is very lightweight because it doesn't include the JS and CSS scripts of the rendered components.

With fragments, even if a component has JS and CSS, you can insert the same component into a page hundreds of times, and the JS and CSS will only ever be loaded once.

This is intended for dynamic content that's loaded with AJAX after the initial page load, such as with jQuery, HTMX, AlpineJS or similar libraries.

Location:

None. The fragment's JS and CSS files will be loaded dynamically into the page.

Included scripts:

  • A special JSON <script> tag that tells the dependency manager what JS and CSS to load.
"},{"location":"concepts/advanced/rendering_js_css/#simple","title":"simple","text":"

deps_strategy=\"simple\" is used either for non-browser use cases, or when you don't want to use the dependency manager.

Practically, this is the same as the \"document\" strategy, except that the dependency manager is not used.

html = MyComponent.render(deps_strategy=\"simple\")\n

Location:

JS and CSS is inserted:

  • Preferentially into JS / CSS placeholders like {% component_js_dependencies %}
  • Otherwise, JS into <body> element, and CSS into <head> element
  • If neither found, JS / CSS are NOT inserted

Included scripts:

  • Components' primary JS and CSS scripts (Component.js and Component.css) - fully inlined:

    <script>\n    console.log(\"Hello from Button!\");\n</script>\n<style>\n    .button {\n        background-color: blue;\n    }\n</style>\n
  • Components' secondary JS and CSS scripts (Component.Media) - inserted as links:

    <link rel=\"stylesheet\" href=\"https://example.com/styles.css\" />\n<script src=\"https://example.com/script.js\"></script>\n
  • No extra scripts are inserted.

"},{"location":"concepts/advanced/rendering_js_css/#prepend","title":"prepend","text":"

This is the same as \"simple\", but placeholders like {% component_js_dependencies %} and HTML tags <head> and <body> are all ignored. The JS and CSS are always inserted before the rendered content.

html = MyComponent.render(deps_strategy=\"prepend\")\n

Location:

JS and CSS is always inserted before the rendered content.

Included scripts:

Same as for the \"simple\" strategy.

"},{"location":"concepts/advanced/rendering_js_css/#append","title":"append","text":"

This is the same as \"simple\", but placeholders like {% component_js_dependencies %} and HTML tags <head> and <body> are all ignored. The JS and CSS are always inserted after the rendered content.

html = MyComponent.render(deps_strategy=\"append\")\n

Location:

JS and CSS is always inserted after the rendered content.

Included scripts:

Same as for the \"simple\" strategy.

"},{"location":"concepts/advanced/rendering_js_css/#ignore","title":"ignore","text":"

deps_strategy=\"ignore\" is used when you do NOT want to process JS and CSS of the rendered HTML.

html = MyComponent.render(deps_strategy=\"ignore\")\n

The rendered HTML is left as-is. You can still process it with a different strategy later with render_dependencies().

This is useful when you want to insert rendered HTML into another component.

html = MyComponent.render(deps_strategy=\"ignore\")\nhtml = AnotherComponent.render(slots={\"content\": html})\n
"},{"location":"concepts/advanced/rendering_js_css/#manually-rendering-js-css","title":"Manually rendering JS / CSS","text":"

When rendering templates or components, django-components covers all the traditional ways how components or templates can be rendered:

  • Component.render()
  • Component.render_to_response()
  • Template.render()
  • django.shortcuts.render()

This way you don't need to manually handle rendering of JS / CSS.

However, for advanced or low-level use cases, you may need to control when to render JS / CSS.

In such case you can directly pass rendered HTML to render_dependencies().

This function will extract all used components in the HTML string, and insert the components' JS and CSS based on given strategy.

Info

The truth is that all the methods listed above call render_dependencies() internally.

Example:

To see how render_dependencies() works, let's render a template with a component.

We will render it twice:

  • First time, we let template.render() handle the rendering.
  • Second time, we prevent template.render() from inserting the component's JS and CSS with deps_strategy=\"ignore\".

    Instead, we pass the \"unprocessed\" HTML to render_dependencies() ourselves to insert the component's JS and CSS.

from django.template.base import Template\nfrom django.template.context import Context\nfrom django_components import render_dependencies\n\ntemplate = Template(\"\"\"\n    {% load component_tags %}\n    <!doctype html>\n    <html>\n    <head>\n        <title>MyPage</title>\n    </head>\n    <body>\n        <main>\n            {% component \"my_button\" %}\n                Click me!\n            {% endcomponent %}\n        </main>\n    </body>\n    </html>\n\"\"\")\n\nrendered = template.render(Context({}))\n\nrendered2_raw = template.render(Context({\"DJC_DEPS_STRATEGY\": \"ignore\"}))\nrendered2 = render_dependencies(rendered2_raw)\n\nassert rendered == rendered2\n

Same applies to other strategies and other methods of rendering:

raw_html = MyComponent.render(deps_strategy=\"ignore\")\nhtml = render_dependencies(raw_html, deps_strategy=\"document\")\n\nhtml2 = MyComponent.render(deps_strategy=\"document\")\n\nassert html == html2\n
"},{"location":"concepts/advanced/rendering_js_css/#html-fragments","title":"HTML fragments","text":"

Django-components provides a seamless integration with HTML fragments with AJAX (HTML over the wire), whether you're using jQuery, HTMX, AlpineJS, vanilla JavaScript, or other.

This is achieved by the combination of the \"document\" and \"fragment\" strategies.

Read more about HTML fragments.

"},{"location":"concepts/advanced/tag_formatters/","title":"Tag formatters","text":""},{"location":"concepts/advanced/tag_formatters/#customizing-component-tags-with-tagformatter","title":"Customizing component tags with TagFormatter","text":"

New in version 0.89

By default, components are rendered using the pair of {% component %} / {% endcomponent %} template tags:

{% component \"button\" href=\"...\" disabled %}\nClick me!\n{% endcomponent %}\n\n{# or #}\n\n{% component \"button\" href=\"...\" disabled / %}\n

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

then the components' names will be used as the template tags:

{% button href=\"...\" disabled %}\n  Click me!\n{% endbutton %}\n\n{# or #}\n\n{% button href=\"...\" disabled / %}\n
"},{"location":"concepts/advanced/tag_formatters/#available-tagformatters","title":"Available TagFormatters","text":"

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=\"...\" %}\n    {% fill \"content\" %}\n        ...\n    {% endfill %}\n{% endcomponent %}\n

Example as inlined tag:

{% component \"button\" href=\"...\" / %}\n
  • ShorthandComponentFormatter (django_components.component_shorthand_formatter)

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

Example as block:

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

Example as inlined tag:

{% button href=\"...\" / %}\n
"},{"location":"concepts/advanced/tag_formatters/#writing-your-own-tagformatter","title":"Writing your own TagFormatter","text":""},{"location":"concepts/advanced/tag_formatters/#background","title":"Background","text":"

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:

{% component \"button\" href=\"...\" disabled %}\n{% endcomponent %}\n

Then TagFormatter.parse() will receive a following input:

[\"component\", '\"button\"', 'href=\"...\"', 'disabled']\n
  1. TagFormatter extracts the component name and the remaining input.

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

TagResult(\n    component_name=\"button\",\n    tokens=['href=\"...\"', 'disabled']\n)\n
  1. 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 %}\n
  1. Tag handler looks up the component button, and passes the args, kwargs, and slots to it.
"},{"location":"concepts/advanced/tag_formatters/#tagformatter","title":"TagFormatter","text":"

TagFormatter handles following parts of the process above:

  • Generates start/end tags, given a component. This is what you then call from within your template as {% component %}.

  • When you {% component %}, tag formatter pre-processes the tag contents, so it can link back the custom template tag to the right component.

To do so, subclass from TagFormatterABC and implement following method:

  • start_tag
  • end_tag
  • parse

For example, this is the implementation of ShorthandComponentFormatter

class ShorthandComponentFormatter(TagFormatterABC):\n    # Given a component name, generate the start template tag\n    def start_tag(self, name: str) -> str:\n        return name  # e.g. 'button'\n\n    # Given a component name, generate the start template tag\n    def end_tag(self, name: str) -> str:\n        return f\"end{name}\"  # e.g. 'endbutton'\n\n    # Given a tag, e.g.\n    # `{% button href=\"...\" disabled %}`\n    #\n    # The parser receives:\n    # `['button', 'href=\"...\"', 'disabled']`\n    def parse(self, tokens: List[str]) -> TagResult:\n        tokens = [*tokens]\n        name = tokens.pop(0)\n        return TagResult(\n            name,  # e.g. 'button'\n            tokens  # e.g. ['href=\"...\"', 'disabled']\n        )\n

That's it! And once your TagFormatter is ready, don't forget to update the settings!

"},{"location":"concepts/advanced/template_tags/","title":"Custom template tags","text":"

Template tags introduced by django-components, such as {% component %} and {% slot %}, offer additional features over the default Django template tags:

  • Self-closing tags {% mytag / %}
  • Allowing the use of :, - (and more) in keys
  • Spread operator ...
  • Using template tags as inputs to other template tags
  • Flat definition of dictionaries attr:key=val
  • Function-like input validation

You too can easily create custom template tags that use the above features.

"},{"location":"concepts/advanced/template_tags/#defining-template-tags-with-template_tag","title":"Defining template tags with @template_tag","text":"

The simplest way to create a custom template tag is using the template_tag decorator. This decorator allows you to define a template tag by just writing a function that returns the rendered content.

from django.template import Context, Library\nfrom django_components import BaseNode, template_tag\n\nlibrary = Library()\n\n@template_tag(\n    library,\n    tag=\"mytag\",\n    end_tag=\"endmytag\",\n    allowed_flags=[\"required\"]\n)\ndef mytag(node: BaseNode, context: Context, name: str, **kwargs) -> str:\n    return f\"Hello, {name}!\"\n

This will allow you to use the tag in your templates like this:

{% mytag name=\"John\" %}\n{% endmytag %}\n\n{# or with self-closing syntax #}\n{% mytag name=\"John\" / %}\n\n{# or with flags #}\n{% mytag name=\"John\" required %}\n{% endmytag %}\n
"},{"location":"concepts/advanced/template_tags/#parameters","title":"Parameters","text":"

The @template_tag decorator accepts the following parameters:

  • library: The Django template library to register the tag with
  • tag: The name of the template tag (e.g. \"mytag\" for {% mytag %})
  • end_tag: Optional. The name of the end tag (e.g. \"endmytag\" for {% endmytag %})
  • allowed_flags: Optional. List of flags that can be used with the tag (e.g. [\"required\"] for {% mytag required %})
"},{"location":"concepts/advanced/template_tags/#function-signature","title":"Function signature","text":"

The function decorated with @template_tag must accept at least two arguments:

  1. node: The node instance (we'll explain this in detail in the next section)
  2. context: The Django template context

Any additional parameters in your function's signature define what inputs your template tag accepts. For example:

@template_tag(library, tag=\"greet\")\ndef greet(\n    node: BaseNode,\n    context: Context,\n    name: str,                    # required positional argument\n    count: int = 1,              # optional positional argument\n    *,                           # keyword-only arguments marker\n    msg: str,                    # required keyword argument\n    mode: str = \"default\",       # optional keyword argument\n) -> str:\n    return f\"{msg}, {name}!\" * count\n

This allows the tag to be used like:

{# All parameters #}\n{% greet \"John\" count=2 msg=\"Hello\" mode=\"custom\" %}\n\n{# Only required parameters #}\n{% greet \"John\" msg=\"Hello\" %}\n\n{# Missing required parameter - will raise error #}\n{% greet \"John\" %}  {# Error: missing 'msg' #}\n

When you pass input to a template tag, it behaves the same way as if you passed the input to a function:

  • If required parameters are missing, an error is raised
  • If unexpected parameters are passed, an error is raised

To accept keys that are not valid Python identifiers (e.g. data-id), or would conflict with Python keywords (e.g. is), you can use the **kwargs syntax:

@template_tag(library, tag=\"greet\")\ndef greet(\n    node: BaseNode,\n    context: Context,\n    **kwargs,\n) -> str:\n    attrs = kwargs.copy()\n    is_var = attrs.pop(\"is\", None)\n    attrs_str = \" \".join(f'{k}=\"{v}\"' for k, v in attrs.items())\n\n    return mark_safe(f\"\"\"\n        <div {attrs_str}>\n            Hello, {is_var}!\n        </div>\n    \"\"\")\n

This allows you to use the tag like this:

{% greet is=\"John\" data-id=\"123\" %}\n
"},{"location":"concepts/advanced/template_tags/#defining-template-tags-with-basenode","title":"Defining template tags with BaseNode","text":"

For more control over your template tag, you can subclass BaseNode directly instead of using the decorator. This gives you access to additional features like the node's internal state and parsing details.

from django_components import BaseNode\n\nclass GreetNode(BaseNode):\n    tag = \"greet\"\n    end_tag = \"endgreet\"\n    allowed_flags = [\"required\"]\n\n    def render(self, context: Context, name: str, **kwargs) -> str:\n        # Access node properties\n        if self.flags[\"required\"]:\n            return f\"Required greeting: Hello, {name}!\"\n        return f\"Hello, {name}!\"\n\n# Register the node\nGreetNode.register(library)\n
"},{"location":"concepts/advanced/template_tags/#node-properties","title":"Node properties","text":"

When using BaseNode, you have access to several useful properties:

  • node_id: A unique identifier for this node instance
  • flags: Dictionary of flag values (e.g. {\"required\": True})
  • params: List of raw parameters passed to the tag
  • nodelist: The template nodes between the start and end tags
  • contents: The raw contents between the start and end tags
  • active_flags: List of flags that are currently set to True
  • template_name: The name of the Template instance inside which the node was defined
  • template_component: The component class that the Template belongs to

This is what the node parameter in the @template_tag decorator gives you access to - it's the instance of the node class that was automatically created for your template tag.

"},{"location":"concepts/advanced/template_tags/#rendering-content-between-tags","title":"Rendering content between tags","text":"

When your tag has an end tag, you can access and render the content between the tags using nodelist:

class WrapNode(BaseNode):\n    tag = \"wrap\"\n    end_tag = \"endwrap\"\n\n    def render(self, context: Context, tag: str = \"div\", **attrs) -> str:\n        # Render the content between tags\n        inner = self.nodelist.render(context)\n        attrs_str = \" \".join(f'{k}=\"{v}\"' for k, v in attrs.items())\n        return f\"<{tag} {attrs_str}>{inner}</{tag}>\"\n\n# Usage:\n{% wrap tag=\"section\" class=\"content\" %}\n    Hello, world!\n{% endwrap %}\n
"},{"location":"concepts/advanced/template_tags/#unregistering-nodes","title":"Unregistering nodes","text":"

You can unregister a node from a library using the unregister method:

GreetNode.unregister(library)\n

This is particularly useful in testing when you want to clean up after registering temporary tags.

"},{"location":"concepts/advanced/testing/","title":"Testing","text":"

New in version 0.131

The @djc_test decorator is a powerful tool for testing components created with django-components. It ensures that each test is properly isolated, preventing components registered in one test from affecting others.

"},{"location":"concepts/advanced/testing/#usage","title":"Usage","text":"

The @djc_test decorator can be applied to functions, methods, or classes.

When applied to a class, it decorates all methods starting with test_, and all nested classes starting with Test, recursively.

"},{"location":"concepts/advanced/testing/#applying-to-a-function","title":"Applying to a Function","text":"

To apply djc_test to a function, simply decorate the function as shown below:

import django\nfrom django_components.testing import djc_test\n\n@djc_test\ndef test_my_component():\n    @register(\"my_component\")\n    class MyComponent(Component):\n        template = \"...\"\n    ...\n
"},{"location":"concepts/advanced/testing/#applying-to-a-class","title":"Applying to a Class","text":"

When applied to a class, djc_test decorates each test_ method, as well as all nested classes starting with Test.

import django\nfrom django_components.testing import djc_test\n\n@djc_test\nclass TestMyComponent:\n    def test_something(self):\n        ...\n\n    class TestNested:\n        def test_something_else(self):\n            ...\n

This is equivalent to applying the decorator to both of the methods individually:

import django\nfrom django_components.testing import djc_test\n\nclass TestMyComponent:\n    @djc_test\n    def test_something(self):\n        ...\n\n    class TestNested:\n        @djc_test\n        def test_something_else(self):\n            ...\n
"},{"location":"concepts/advanced/testing/#arguments","title":"Arguments","text":"

See the API reference for @djc_test for more details.

"},{"location":"concepts/advanced/testing/#setting-up-django","title":"Setting Up Django","text":"

If you want to define a common Django settings that would be the baseline for all tests, you can call django.setup() before the @djc_test decorator:

import django\nfrom django_components.testing import djc_test\n\ndjango.setup(...)\n\n@djc_test\ndef test_my_component():\n    ...\n

Info

If you omit django.setup() in the example above, @djc_test will call it for you, so you don't need to do it manually.

"},{"location":"concepts/advanced/testing/#example-parametrizing-context-behavior","title":"Example: Parametrizing Context Behavior","text":"

You can parametrize the context behavior using djc_test:

from django_components.testing import djc_test\n\n@djc_test(\n    # Settings applied to all cases\n    components_settings={\n        \"app_dirs\": [\"custom_dir\"],\n    },\n    # Parametrized settings\n    parametrize=(\n        [\"components_settings\"],\n        [\n            [{\"context_behavior\": \"django\"}],\n            [{\"context_behavior\": \"isolated\"}],\n        ],\n        [\"django\", \"isolated\"],\n    )\n)\ndef test_context_behavior(components_settings):\n    rendered = MyComponent.render()\n    ...\n
"},{"location":"concepts/fundamentals/autodiscovery/","title":"Autodiscovery","text":"

django-components automatically searches for files containing components in the COMPONENTS.dirs and COMPONENTS.app_dirs directories.

"},{"location":"concepts/fundamentals/autodiscovery/#manually-register-components","title":"Manually register components","text":"

Every component that you want to use in the template with the {% component %} tag needs to be registered with the ComponentRegistry.

We use the @register decorator for that:

from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    ...\n

But for the component to be registered, the code needs to be executed - and for that, the file needs to be imported as a module.

This is the \"discovery\" part of the process.

One way to do that is by importing all your components in apps.py:

from django.apps import AppConfig\n\nclass MyAppConfig(AppConfig):\n    name = \"my_app\"\n\n    def ready(self) -> None:\n        from components.card.card import Card\n        from components.list.list import List\n        from components.menu.menu import Menu\n        from components.button.button import Button\n        ...\n

However, there's a simpler way!

"},{"location":"concepts/fundamentals/autodiscovery/#autodiscovery","title":"Autodiscovery","text":"

By default, the Python files found in the COMPONENTS.dirs and COMPONENTS.app_dirs are auto-imported in order to execute the code that registers the components.

Autodiscovery occurs when Django is loaded, during the AppConfig.ready() hook of the apps.py file.

If you are using autodiscovery, keep a few points in mind:

  • Avoid defining any logic on the module-level inside the components directories, that you would not want to run anyway.
  • Components inside the auto-imported files still need to be registered with @register
  • Auto-imported component files must be valid Python modules, they must use suffix .py, and module name should follow PEP-8.
  • Subdirectories and files starting with an underscore _ (except __init__.py) are ignored.

Autodiscovery can be disabled in the settings with autodiscover=False.

"},{"location":"concepts/fundamentals/autodiscovery/#manually-trigger-autodiscovery","title":"Manually trigger autodiscovery","text":"

Autodiscovery can be also triggered manually, using the autodiscover() function. This is useful if you want to run autodiscovery at a custom point of the lifecycle:

from django_components import autodiscover\n\nautodiscover()\n

To get the same list of modules that autodiscover() would return, but without importing them, use get_component_files():

from django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
"},{"location":"concepts/fundamentals/component_defaults/","title":"Component defaults","text":"

When a component is being rendered, the component inputs are passed to various methods like get_template_data(), get_js_data(), or get_css_data().

It can be cumbersome to specify default values for each input in each method.

To make things easier, Components can specify their defaults. Defaults are used when no value is provided, or when the value is set to None for a particular input.

"},{"location":"concepts/fundamentals/component_defaults/#defining-defaults","title":"Defining defaults","text":"

To define defaults for a component, you create a nested Defaults class within your Component class. Each attribute in the Defaults class represents a default value for a corresponding input.

from django_components import Component, Default, register\n\n@register(\"my_table\")\nclass MyTable(Component):\n\n    class Defaults:\n        position = \"left\"\n        selected_items = Default(lambda: [1, 2, 3])\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"position\": kwargs[\"position\"],\n            \"selected_items\": kwargs[\"selected_items\"],\n        }\n\n    ...\n

In this example, position is a simple default value, while selected_items uses a factory function wrapped in Default to ensure a new list is created each time the default is used.

Now, when we render the component, the defaults will be applied:

{% component \"my_table\" position=\"right\" / %}\n

In this case:

  • position input is set to right, so no defaults applied
  • selected_items is not set, so it will be set to [1, 2, 3].

Same applies to rendering the Component in Python with the render() method:

MyTable.render(\n    kwargs={\n        \"position\": \"right\",\n        \"selected_items\": None,\n    },\n)\n

Notice that we've set selected_items to None. None values are treated as missing values, and so selected_items will be set to [1, 2, 3].

Warning

The defaults are aplied only to keyword arguments. They are NOT applied to positional arguments!

Warning

When typing your components with Args, Kwargs, or Slots classes, you may be inclined to define the defaults in the classes.

class ProfileCard(Component):\n    class Kwargs(NamedTuple):\n        show_details: bool = True\n

This is NOT recommended, because:

  • The defaults will NOT be applied to inputs when using self.raw_kwargs property.
  • The defaults will NOT be applied when a field is given but set to None.

Instead, define the defaults in the Defaults class.

"},{"location":"concepts/fundamentals/component_defaults/#default-factories","title":"Default factories","text":"

For objects such as lists, dictionaries or other instances, you have to be careful - if you simply set a default value, this instance will be shared across all instances of the component!

from django_components import Component\n\nclass MyTable(Component):\n    class Defaults:\n        # All instances will share the same list!\n        selected_items = [1, 2, 3]\n

To avoid this, you can use a factory function wrapped in Default.

from django_components import Component, Default\n\nclass MyTable(Component):\n    class Defaults:\n        # A new list is created for each instance\n        selected_items = Default(lambda: [1, 2, 3])\n

This is similar to how the dataclass fields work.

In fact, you can also use the dataclass's field function to define the factories:

from dataclasses import field\nfrom django_components import Component\n\nclass MyTable(Component):\n    class Defaults:\n        selected_items = field(default_factory=lambda: [1, 2, 3])\n
"},{"location":"concepts/fundamentals/component_defaults/#accessing-defaults","title":"Accessing defaults","text":"

Since the defaults are defined on the component class, you can access the defaults for a component with the Component.Defaults property.

So if we have a component like this:

from django_components import Component, Default, register\n\n@register(\"my_table\")\nclass MyTable(Component):\n\n    class Defaults:\n        position = \"left\"\n        selected_items = Default(lambda: [1, 2, 3])\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"position\": kwargs[\"position\"],\n            \"selected_items\": kwargs[\"selected_items\"],\n        }\n

We can access individual defaults like this:

print(MyTable.Defaults.position)\nprint(MyTable.Defaults.selected_items)\n
"},{"location":"concepts/fundamentals/component_views_urls/","title":"Component views and URLs","text":"

New in version 0.34

Note: Since 0.92, Component is no longer a subclass of Django's View. Instead, the nested Component.View class is a subclass of Django's View.

For web applications, it's common to define endpoints that serve HTML content (AKA views).

django-components has a suite of features that help you write and manage views and their URLs:

  • For each component, you can define methods for handling HTTP requests (GET, POST, etc.) - get(), post(), etc.

  • Use Component.as_view() to be able to use your Components with Django's urlpatterns. This works the same way as View.as_view().

  • To avoid having to manually define the endpoints for each component, you can set the component to be \"public\" with Component.View.public = True. This will automatically create a URL for the component. To retrieve the component URL, use get_component_url().

  • In addition, Component has a render_to_response() method that renders the component template based on the provided input and returns an HttpResponse object.

"},{"location":"concepts/fundamentals/component_views_urls/#define-handlers","title":"Define handlers","text":"

Here's an example of a calendar component defined as a view. Simply define a View class with your custom get() method to handle GET requests:

[project root]/components/calendar.py
from django_components import Component, ComponentView, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template = \"\"\"\n        <div class=\"calendar-component\">\n            <div class=\"header\">\n                {% slot \"header\" / %}\n            </div>\n            <div class=\"body\">\n                Today's date is <span>{{ date }}</span>\n            </div>\n        </div>\n    \"\"\"\n\n    class View:\n        # Handle GET requests\n        def get(self, request, *args, **kwargs):\n            # Return HttpResponse with the rendered content\n            return Calendar.render_to_response(\n                request=request,\n                kwargs={\n                    \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n                },\n                slots={\n                    \"header\": \"Calendar header\",\n                },\n            )\n

Info

The View class supports all the same HTTP methods as Django's View class. These are:

get(), post(), put(), patch(), delete(), head(), options(), trace()

Each of these receive the HttpRequest object as the first argument.

Warning

Deprecation warning:

Previously, the handler methods such as get() and post() could be defined directly on the Component class:

class Calendar(Component):\n    def get(self, request, *args, **kwargs):\n        return self.render_to_response(\n            kwargs={\n                \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n            }\n        )\n

This is deprecated from v0.137 onwards, and will be removed in v1.0.

"},{"location":"concepts/fundamentals/component_views_urls/#acccessing-component-class","title":"Acccessing component class","text":"

You can access the component class from within the View methods by using the View.component_cls attribute:

class Calendar(Component):\n    ...\n\n    class View:\n        def get(self, request):\n            return self.component_cls.render_to_response(request=request)\n
"},{"location":"concepts/fundamentals/component_views_urls/#register-urls-manually","title":"Register URLs manually","text":"

To register the component as a route / endpoint in Django, add an entry to your urlpatterns. In place of the view function, create a view object with Component.as_view():

[project root]/urls.py
from django.urls import path\nfrom components.calendar.calendar import Calendar\n\nurlpatterns = [\n    path(\"calendar/\", Calendar.as_view()),\n]\n

Component.as_view() internally calls View.as_view(), passing the component instance as one of the arguments.

"},{"location":"concepts/fundamentals/component_views_urls/#register-urls-automatically","title":"Register URLs automatically","text":"

If you don't care about the exact URL of the component, you can let django-components manage the URLs for you by setting the Component.View.public attribute to True:

class MyComponent(Component):\n    class View:\n        public = True\n\n        def get(self, request):\n            return self.component_cls.render_to_response(request=request)\n    ...\n

Then, to get the URL for the component, use get_component_url():

from django_components import get_component_url\n\nurl = get_component_url(MyComponent)\n

This way you don't have to mix your app URLs with component URLs.

Info

If you need to pass query parameters or a fragment to the component URL, you can do so by passing the query and fragment arguments to get_component_url():

url = get_component_url(\n    MyComponent,\n    query={\"foo\": \"bar\"},\n    fragment=\"baz\",\n)\n# /components/ext/view/components/c1ab2c3?foo=bar#baz\n
"},{"location":"concepts/fundamentals/html_attributes/","title":"HTML attributes","text":"

New in version 0.74:

You can use the {% html_attrs %} tag to render various data as key=\"value\" HTML attributes.

{% html_attrs %} tag is versatile, allowing you to define HTML attributes however you need:

  • Define attributes within the HTML template
  • Define attributes in Python code
  • Merge attributes from multiple sources
  • Boolean attributes
  • Append attributes
  • Remove attributes
  • Define default attributes

From v0.135 onwards, {% html_attrs %} tag also supports merging style and class attributes the same way how Vue does.

To get started, let's consider a simple example. If you have a template:

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

You can rewrite it with the {% html_attrs %} tag:

<div {% html_attrs class=classes data-id=my_id %}>\n</div>\n

The {% html_attrs %} tag accepts any number of keyword arguments, which will be merged and rendered as HTML attributes:

<div class=\"text-red\" data-id=\"123\">\n</div>\n

Moreover, the {% html_attrs %} tag accepts two positional arguments:

  • attrs - a dictionary of attributes to be rendered
  • defaults - a dictionary of default attributes

You can use this for example to allow users of your component to add extra attributes. We achieve this by capturing the extra attributes and passing them to the {% html_attrs %} tag as a dictionary:

@register(\"my_comp\")\nclass MyComp(Component):\n    # Pass all kwargs as `attrs`\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"attrs\": kwargs,\n            \"classes\": \"text-red\",\n            \"my_id\": 123,\n        }\n\n    template: t.django_html = \"\"\"\n        {# Pass the extra attributes to `html_attrs` #}\n        <div {% html_attrs attrs class=classes data-id=my_id %}>\n        </div>\n    \"\"\"\n

This way you can render MyComp with extra attributes:

Either via Django template:

{% component \"my_comp\"\n  id=\"example\"\n  class=\"pa-4\"\n  style=\"color: red;\"\n%}\n

Or via Python:

MyComp.render(\n    kwargs={\n        \"id\": \"example\",\n        \"class\": \"pa-4\",\n        \"style\": \"color: red;\",\n    }\n)\n

In both cases, the attributes will be merged and rendered as:

<div id=\"example\" class=\"text-red pa-4\" style=\"color: red;\" data-id=\"123\"></div>\n
"},{"location":"concepts/fundamentals/html_attributes/#summary","title":"Summary","text":"
  1. The two arguments, attrs and defaults, can be passed as positional args:

    {% html_attrs attrs defaults key=val %}\n

    or as kwargs:

    {% html_attrs key=val defaults=defaults attrs=attrs %}\n
  2. Both attrs and defaults are optional and can be omitted.

  3. Both attrs and defaults are dictionaries. As such, there's multiple ways to define them:

    • By referencing a variable:

      {% html_attrs attrs=attrs %}\n
    • By defining a literal dictionary:

      {% html_attrs attrs={\"key\": value} %}\n
    • Or by defining the dictionary keys:

      {% html_attrs attrs:key=value %}\n
  4. All other kwargs are merged and can be repeated.

    {% html_attrs class=\"text-red\" class=\"pa-4\" %}\n

    Will render:

    <div class=\"text-red pa-4\"></div>\n
"},{"location":"concepts/fundamentals/html_attributes/#usage","title":"Usage","text":""},{"location":"concepts/fundamentals/html_attributes/#boolean-attributes","title":"Boolean attributes","text":"

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>\n<button>Click me!</button>\n

HTML rendering with html_attrs tag or format_attributes works the same way - an attribute set to True is rendered without the value, and an attribute set to False is not rendered at all.

So given this input:

attrs = {\n    \"disabled\": True,\n    \"autofocus\": False,\n}\n

And template:

<div {% html_attrs attrs %}>\n</div>\n

Then this renders:

<div disabled></div>\n
"},{"location":"concepts/fundamentals/html_attributes/#removing-attributes","title":"Removing attributes","text":"

Given how the boolean attributes work, you can \"remove\" or prevent an attribute from being rendered by setting it to False or None.

So given this input:

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

And template:

<div {% html_attrs attrs %}>\n</div>\n

Then this renders:

<div class=\"text-green\"></div>\n
"},{"location":"concepts/fundamentals/html_attributes/#default-attributes","title":"Default attributes","text":"

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

<div {% html_attrs attrs defaults %}>\n    ...\n</div>\n

In the example above, if attrs contains a certain key, e.g. the class key, {% html_attrs %} will render:

<div class=\"{{ attrs.class }}\">\n    ...\n</div>\n

Otherwise, {% html_attrs %} will render:

<div class=\"{{ defaults.class }}\">\n    ...\n</div>\n
"},{"location":"concepts/fundamentals/html_attributes/#appending-attributes","title":"Appending attributes","text":"

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

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 = {\n    \"class\": \"my-class pa-4\",\n}\n

And on {% html_attrs %} tag, we set the key class:

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

Then these will be merged and rendered as:

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

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\" #}\n<div {% html_attrs attrs class=\"some-class another-class\" class=my_var %}>\n</div>\n

Renders:

<div\n  data-value=\"my-class pa-4 some-class another-class class-from-var text-red\"\n></div>\n
"},{"location":"concepts/fundamentals/html_attributes/#merging-class-attributes","title":"Merging class attributes","text":"

The class attribute can be specified as a string of class names as usual.

If you want granular control over individual class names, you can use a dictionary.

  • String: Used as is.

    {% html_attrs class=\"my-class other-class\" %}\n

    Renders:

    <div class=\"my-class other-class\"></div>\n
  • Dictionary: Keys are the class names, and values are booleans. Only keys with truthy values are rendered.

    {% html_attrs class={\n    \"extra-class\": True,\n    \"other-class\": False,\n} %}\n

    Renders:

    <div class=\"extra-class\"></div>\n

If a certain class is specified multiple times, it's the last instance that decides whether the class is rendered or not.

Example:

In this example, the other-class is specified twice. The last instance is {\"other-class\": False}, so the class is not rendered.

{% html_attrs\n    class=\"my-class other-class\"\n    class={\"extra-class\": True, \"other-class\": False}\n%}\n

Renders:

<div class=\"my-class extra-class\"></div>\n
"},{"location":"concepts/fundamentals/html_attributes/#merging-style-attributes","title":"Merging style attributes","text":"

The style attribute can be specified as a string of style properties as usual.

If you want granular control over individual style properties, you can use a dictionary.

  • String: Used as is.

    {% html_attrs style=\"color: red; background-color: blue;\" %}\n

    Renders:

    <div style=\"color: red; background-color: blue;\"></div>\n
  • Dictionary: Keys are the style properties, and values are their values.

    {% html_attrs style={\n    \"color\": \"red\",\n    \"background-color\": \"blue\",\n} %}\n

    Renders:

    <div style=\"color: red; background-color: blue;\"></div>\n

If a style property is specified multiple times, the last value is used.

  • Properties set to None are ignored.
  • If the last non-None instance of the property is set to False, the property is removed.

Example:

In this example, the width property is specified twice. The last instance is {\"width\": False}, so the property is removed.

Secondly, the background-color property is also set twice. But the second time it's set to None, so that instance is ignored, leaving us only with background-color: blue.

The color property is set to a valid value in both cases, so the latter (green) is used.

{% html_attrs\n    style=\"color: red; background-color: blue; width: 100px;\"\n    style={\"color\": \"green\", \"background-color\": None, \"width\": False}\n%}\n

Renders:

<div style=\"color: green; background-color: blue;\"></div>\n
"},{"location":"concepts/fundamentals/html_attributes/#usage-outside-of-templates","title":"Usage outside of templates","text":"

In some cases, you want to prepare HTML attributes outside of templates.

To achieve the same behavior as {% html_attrs %} tag, you can use the merge_attributes() and format_attributes() helper functions.

"},{"location":"concepts/fundamentals/html_attributes/#merging-attributes","title":"Merging attributes","text":"

merge_attributes() accepts any number of dictionaries and merges them together, using the same merge strategy as {% html_attrs %}.

from django_components import merge_attributes\n\nmerge_attributes(\n    {\"class\": \"my-class\", \"data-id\": 123},\n    {\"class\": \"extra-class\"},\n    {\"class\": {\"cool-class\": True, \"uncool-class\": False} },\n)\n

Which will output:

{\n    \"class\": \"my-class extra-class cool-class\",\n    \"data-id\": 123,\n}\n

Warning

Unlike {% html_attrs %}, where you can pass extra kwargs, merge_attributes() requires each argument to be a dictionary.

"},{"location":"concepts/fundamentals/html_attributes/#formatting-attributes","title":"Formatting attributes","text":"

format_attributes() serializes attributes the same way as {% html_attrs %} tag does.

from django_components import format_attributes\n\nformat_attributes({\n    \"class\": \"my-class text-red pa-4\",\n    \"data-id\": 123,\n    \"required\": True,\n    \"disabled\": False,\n    \"ignored-attr\": None,\n})\n

Which will output:

'class=\"my-class text-red pa-4\" data-id=\"123\" required'\n

Note

Prior to v0.135, the format_attributes() function was named attributes_to_string().

This function is now deprecated and will be removed in v1.0.

"},{"location":"concepts/fundamentals/html_attributes/#cheat-sheet","title":"Cheat sheet","text":"

Assuming that:

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

Then:

  • Empty tag

    <div {% html_attr %}></div>\n

    renders nothing:

    <div></div>\n
  • Only kwargs

    <div {% html_attr class=\"some-class\" class=class_from_var data-id=\"123\" %}></div>\n

    renders:

    <div class=\"some-class from-var\" data-id=\"123\"></div>\n
  • Only attrs

    <div {% html_attr attrs %}></div>\n

    renders:

    <div class=\"from-attrs\" type=\"submit\"></div>\n
  • Attrs as kwarg

    <div {% html_attr attrs=attrs %}></div>\n

    renders:

    <div class=\"from-attrs\" type=\"submit\"></div>\n
  • Only defaults (as kwarg)

    <div {% html_attr defaults=defaults %}></div>\n

    renders:

    <div class=\"from-defaults\" role=\"button\"></div>\n
  • Attrs using the prefix:key=value construct

    <div {% html_attr attrs:class=\"from-attrs\" attrs:type=\"submit\" %}></div>\n

    renders:

    <div class=\"from-attrs\" type=\"submit\"></div>\n
  • Defaults using the prefix:key=value construct

    <div {% html_attr defaults:class=\"from-defaults\" %}></div>\n

    renders:

    <div class=\"from-defaults\" role=\"button\"></div>\n
  • All together (1) - attrs and defaults as positional args:

    <div {% html_attrs attrs defaults class=\"added_class\" class=class_from_var data-id=123 %}></div>\n

    renders:

    <div class=\"from-attrs added_class from-var\" type=\"submit\" role=\"button\" data-id=123></div>\n
  • All together (2) - attrs and defaults as kwargs args:

    <div {% html_attrs class=\"added_class\" class=class_from_var data-id=123 attrs=attrs defaults=defaults %}></div>\n

    renders:

    <div class=\"from-attrs added_class from-var\" type=\"submit\" role=\"button\" data-id=123></div>\n
  • All together (3) - mixed:

    <div {% html_attrs attrs defaults:class=\"default-class\" class=\"added_class\" class=class_from_var data-id=123 %}></div>\n

    renders:

    <div class=\"from-attrs added_class from-var\" type=\"submit\" data-id=123></div>\n
"},{"location":"concepts/fundamentals/html_attributes/#full-example","title":"Full example","text":"
@register(\"my_comp\")\nclass MyComp(Component):\n    template: t.django_html = \"\"\"\n        <div\n            {% html_attrs attrs\n                defaults:class=\"pa-4 text-red\"\n                class=\"my-comp-date\"\n                class=class_from_var\n                data-id=\"123\"\n            %}\n        >\n            Today's date is <span>{{ date }}</span>\n        </div>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        date = kwargs.pop(\"date\")\n        return {\n            \"date\": date,\n            \"attrs\": kwargs,\n            \"class_from_var\": \"extra-class\"\n        }\n\n@register(\"parent\")\nclass Parent(Component):\n    template: t.django_html = \"\"\"\n        {% component \"my_comp\"\n            date=date\n            attrs:class=\"pa-0 border-solid border-red\"\n            attrs:data-json=json_data\n            attrs:@click=\"(e) => onClick(e, 'from_parent')\"\n        / %}\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": datetime.now(),\n            \"json_data\": json.dumps({\"value\": 456})\n        }\n

Note: For readability, we've split the tags across multiple lines.

Inside MyComp, we defined a default attribute

defaults:class=\"pa-4 text-red\"\n

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

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\"\n    attrs:data-json=json_data\n    attrs:@click=\"(e) => onClick(e, 'from_parent')\"\n

And get_template_data of MyComp will receive a kwarg named attrs with following keys:

attrs = {\n    \"class\": \"pa-0 border-solid\",\n    \"data-json\": '{\"value\": 456}',\n    \"@click\": \"(e) => onClick(e, 'from_parent')\",\n}\n

attrs[\"class\"] overrides the default value for class, whereas other keys will be merged.

So in the end MyComp will render:

<div\n  class=\"pa-0 border-solid my-comp-date extra-class\"\n  data-id=\"123\"\n  data-json='{\"value\": 456}'\n  @click=\"(e) => onClick(e, 'from_parent')\"\n>\n  ...\n</div>\n
"},{"location":"concepts/fundamentals/html_js_css_files/","title":"HTML / JS / CSS files","text":""},{"location":"concepts/fundamentals/html_js_css_files/#overview","title":"Overview","text":"

Each component can have single \"primary\" HTML, CSS and JS file associated with them.

Each of these can be either defined inline, or in a separate file:

  • HTML files are defined using Component.template or Component.template_file
  • CSS files are defined using Component.css or Component.css_file
  • JS files are defined using Component.js or Component.js_file
@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    css_file = \"calendar.css\"\n    js_file = \"calendar.js\"\n

or

@register(\"calendar\")\nclass Calendar(Component):\n    template = \"\"\"\n        <div class=\"welcome\">\n            Hi there!\n        </div>\n    \"\"\"\n    css = \"\"\"\n        .welcome {\n            color: red;\n        }\n    \"\"\"\n    js = \"\"\"\n        console.log(\"Hello, world!\");\n    \"\"\"\n

These \"primary\" files will have special behavior. For example, each will receive variables from the component's data methods. Read more about each file type below:

  • HTML
  • CSS
  • JS

In addition, you can define extra \"secondary\" CSS / JS files using the nested Component.Media class, by setting Component.Media.js and Component.Media.css.

Single component can have many secondary files. There is no special behavior for them.

You can use these for third-party libraries, or for shared CSS / JS files.

Read more about Secondary JS / CSS files.

Warning

You cannot use both inlined code and separate file for a single language type (HTML, CSS, JS).

However, you can freely mix these for different languages:

class MyTable(Component):\n    template: types.django_html = \"\"\"\n      <div class=\"welcome\">\n        Hi there!\n      </div>\n    \"\"\"\n    js_file = \"my_table.js\"\n    css_file = \"my_table.css\"\n
"},{"location":"concepts/fundamentals/html_js_css_files/#html","title":"HTML","text":"

Components use Django's template system to define their HTML. This means that you can use Django's template syntax to define your HTML.

Inside the template, you can access the data returned from the get_template_data() method.

You can define the HTML directly in your Python code using the template attribute:

class Button(Component):\n    template = \"\"\"\n        <button class=\"btn\">\n            {% if icon %}\n                <i class=\"{{ icon }}\"></i>\n            {% endif %}\n            {{ text }}\n        </button>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"text\": kwargs.get(\"text\", \"Click me\"),\n            \"icon\": kwargs.get(\"icon\", None),\n        }\n

Or you can define the HTML in a separate file and reference it using template_file:

class Button(Component):\n    template_file = \"button.html\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"text\": kwargs.get(\"text\", \"Click me\"),\n            \"icon\": kwargs.get(\"icon\", None),\n        }\n
button.html
<button class=\"btn\">\n    {% if icon %}\n        <i class=\"{{ icon }}\"></i>\n    {% endif %}\n    {{ text }}\n</button>\n
"},{"location":"concepts/fundamentals/html_js_css_files/#dynamic-templates","title":"Dynamic templates","text":"

Each component has only a single template associated with it.

However, whether it's for A/B testing or for preserving public API when sharing your components, sometimes you may need to render different templates based on the input to your component.

You can use Component.on_render() to dynamically override what template gets rendered.

By default, the component's template is rendered as-is.

class Table(Component):\n    def on_render(self, context: Context, template: Optional[Template]):\n        if template is not None:\n            return template.render(context)\n

If you want to render a different template in its place, we recommended you to:

  1. Wrap the substitute templates as new Components
  2. Then render those Components inside Component.on_render():
class TableNew(Component):\n    template_file = \"table_new.html\"\n\nclass TableOld(Component):\n    template_file = \"table_old.html\"\n\nclass Table(Component):\n    def on_render(self, context, template):\n        if self.kwargs.get(\"feat_table_new_ui\"):\n            return TableNew.render(\n                args=self.args,\n                kwargs=self.kwargs,\n                slots=self.slots,\n            )\n        else:\n            return TableOld.render(\n                args=self.args,\n                kwargs=self.kwargs,\n                slots=self.slots,\n            )\n

Warning

If you do not wrap the templates as Components, there is a risk that some extensions will not work as expected.

new_template = Template(\"\"\"\n    {% load django_components %}\n    <div>\n        {% slot \"content\" %}\n            Other template\n        {% endslot %}\n    </div>\n\"\"\")\n\nclass Table(Component):\n    def on_render(self, context, template):\n        if self.kwargs.get(\"feat_table_new_ui\"):\n            return new_template.render(context)\n        else:\n            return template.render(context)\n
"},{"location":"concepts/fundamentals/html_js_css_files/#template-less-components","title":"Template-less components","text":"

Since you can use Component.on_render() to render other components, there is no need to define a template for the component.

So even an empty component like this is valid:

class MyComponent(Component):\n    pass\n

These \"template-less\" components can be useful as base classes for other components, or as mixins.

"},{"location":"concepts/fundamentals/html_js_css_files/#html-processing","title":"HTML processing","text":"

Django Components expects the rendered template to be a valid HTML. This is needed to enable features like CSS / JS variables.

Here is how the HTML is post-processed:

  1. Insert component ID: Each root element in the rendered HTML automatically receives a data-djc-id-cxxxxxx attribute containing a unique component instance ID.

    <!-- Output HTML -->\n<div class=\"card\" data-djc-id-c1a2b3c>\n    ...\n</div>\n<div class=\"backdrop\" data-djc-id-c1a2b3c>\n    ...\n</div>\n
  2. Insert CSS ID: If the component defines CSS variables through get_css_data(), the root elements also receive a data-djc-css-xxxxxx attribute. This attribute links the element to its specific CSS variables.

    <!-- Output HTML -->\n<div class=\"card\" data-djc-id-c1a2b3c data-djc-css-d4e5f6>\n    <!-- Component content -->\n</div>\n
  3. Insert JS and CSS: After the HTML is rendered, Django Components handles inserting JS and CSS dependencies into the page based on the dependencies rendering strategy (document, fragment, or inline).

    For example, if your component contains the {% component_js_dependencies %} or {% component_css_dependencies %} tags, or the <head> and <body> elements, the JS and CSS scripts will be inserted into the HTML.

    For more information on how JS and CSS dependencies are rendered, see Rendering JS / CSS.

"},{"location":"concepts/fundamentals/html_js_css_files/#js","title":"JS","text":"

The component's JS script is executed in the browser:

  • It is executed AFTER the \"secondary\" JS files from Component.Media.js are loaded.
  • The script is only executed once, even if there are multiple instances of the component on the page.
  • Component JS scripts are executed in the order how they appeared in the template / HTML (top to bottom).

You can define the JS directly in your Python code using the js attribute:

class Button(Component):\n    js = \"\"\"\n        console.log(\"Hello, world!\");\n    \"\"\"\n\n    def get_js_data(self, args, kwargs, slots, context):\n        return {\n            \"text\": kwargs.get(\"text\", \"Click me\"),\n        }\n

Or you can define the JS in a separate file and reference it using js_file:

class Button(Component):\n    js_file = \"button.js\"\n\n    def get_js_data(self, args, kwargs, slots, context):\n        return {\n            \"text\": kwargs.get(\"text\", \"Click me\"),\n        }\n
button.js
console.log(\"Hello, world!\");\n
"},{"location":"concepts/fundamentals/html_js_css_files/#css","title":"CSS","text":"

You can define the CSS directly in your Python code using the css attribute:

class Button(Component):\n    css = \"\"\"\n        .btn {\n            width: 100px;\n            color: var(--color);\n        }\n    \"\"\"\n\n    def get_css_data(self, args, kwargs, slots, context):\n        return {\n            \"color\": kwargs.get(\"color\", \"red\"),\n        }\n

Or you can define the CSS in a separate file and reference it using css_file:

class Button(Component):\n    css_file = \"button.css\"\n\n    def get_css_data(self, args, kwargs, slots, context):\n        return {\n            \"text\": kwargs.get(\"text\", \"Click me\"),\n        }\n
button.css
.btn {\n    color: red;\n}\n
"},{"location":"concepts/fundamentals/html_js_css_files/#file-paths","title":"File paths","text":"

Compared to the secondary JS / CSS files, the definition of file paths for the main HTML / JS / CSS files is quite simple - just strings, without any lists, objects, or globs.

However, similar to the secondary JS / CSS files, you can specify the file paths relative to the component's directory.

So if you have a directory with following files:

[project root]/components/calendar/\n\u251c\u2500\u2500 calendar.html\n\u251c\u2500\u2500 calendar.css\n\u251c\u2500\u2500 calendar.js\n\u2514\u2500\u2500 calendar.py\n

You can define the component like this:

[project root]/components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    css_file = \"calendar.css\"\n    js_file = \"calendar.js\"\n

Assuming that COMPONENTS.dirs contains path [project root]/components, the example above is the same as writing out:

[project root]/components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar/template.html\"\n    css_file = \"calendar/style.css\"\n    js_file = \"calendar/script.js\"\n

If the path cannot be resolved relative to the component, django-components will attempt to resolve the path relative to the component directories, as set in COMPONENTS.dirs or COMPONENTS.app_dirs.

Read more about file path resolution.

"},{"location":"concepts/fundamentals/html_js_css_files/#access-component-definition","title":"Access component definition","text":"

Component's HTML / CSS / JS is resolved and loaded lazily.

This means that, when you specify any of template_file, js_file, css_file, or Media.js/css, these file paths will be resolved only once you either:

  1. Access any of the following attributes on the component:

    • media, template, template_file, js, js_file, css, css_file
  2. Render the component.

Once the component's media files have been loaded once, they will remain in-memory on the Component class:

  • HTML from Component.template_file will be available under Component.template
  • CSS from Component.css_file will be available under Component.css
  • JS from Component.js_file will be available under Component.js

Thus, whether you define HTML via Component.template_file or Component.template, you can always access the HTML content under Component.template. And the same applies for JS and CSS.

Example:

# When we create Calendar component, the files like `calendar/template.html`\n# are not yet loaded!\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar/template.html\"\n    css_file = \"calendar/style.css\"\n    js_file = \"calendar/script.js\"\n\n    class Media:\n        css = \"calendar/style1.css\"\n        js = \"calendar/script2.js\"\n\n# It's only at this moment that django-components reads the files like `calendar/template.html`\nprint(Calendar.css)\n# Output:\n# .calendar {\n#   width: 200px;\n#   background: pink;\n# }\n

Warning

Do NOT modify HTML / CSS / JS after it has been loaded

django-components assumes that the component's media files like js_file or Media.js/css are static.

If you need to dynamically change these media files, consider instead defining multiple Components.

Modifying these files AFTER the component has been loaded at best does nothing. However, this is an untested behavior, which may lead to unexpected errors.

"},{"location":"concepts/fundamentals/html_js_css_variables/","title":"HTML / JS / CSS variables","text":"

When a component recieves input through {% component %} tag, or the Component.render() or Component.render_to_response() methods, you can define how the input is handled, and what variables will be available to the template, JavaScript and CSS.

"},{"location":"concepts/fundamentals/html_js_css_variables/#overview","title":"Overview","text":"

Django Components offers three key methods for passing variables to different parts of your component:

  • get_template_data() - Provides variables to your HTML template
  • get_js_data() - Provides variables to your JavaScript code
  • get_css_data() - Provides variables to your CSS styles

These methods let you pre-process inputs before they're used in rendering.

Each method handles the data independently - you can define different data for the template, JS, and CSS.

class ProfileCard(Component):\n    class Kwargs(NamedTuple):\n        user_id: int\n        show_details: bool\n\n    class Defaults:\n        show_details = True\n\n    def get_template_data(self, args, kwargs: Kwargs, slots, context):\n        user = User.objects.get(id=kwargs.user_id)\n        return {\n            \"user\": user,\n            \"show_details\": kwargs.show_details,\n        }\n\n    def get_js_data(self, args, kwargs: Kwargs, slots, context):\n        return {\n            \"user_id\": kwargs.user_id,\n        }\n\n    def get_css_data(self, args, kwargs: Kwargs, slots, context):\n        text_color = \"red\" if kwargs.show_details else \"blue\"\n        return {\n            \"text_color\": text_color,\n        }\n
"},{"location":"concepts/fundamentals/html_js_css_variables/#template-variables","title":"Template variables","text":"

The get_template_data() method is the primary way to provide variables to your HTML template. It receives the component inputs and returns a dictionary of data that will be available in the template.

If get_template_data() returns None, an empty dictionary will be used.

class ProfileCard(Component):\n    template_file = \"profile_card.html\"\n\n    class Kwargs(NamedTuple):\n        user_id: int\n        show_details: bool\n\n    def get_template_data(self, args, kwargs: Kwargs, slots, context):\n        user = User.objects.get(id=kwargs.user_id)\n\n        # Process and transform inputs\n        return {\n            \"user\": user,\n            \"show_details\": kwargs.show_details,\n            \"user_joined_days\": (timezone.now() - user.date_joined).days,\n        }\n

In your template, you can then use these variables:

<div class=\"profile-card\">\n    <h2>{{ user.username }}</h2>\n\n    {% if show_details %}\n        <p>Member for {{ user_joined_days }} days</p>\n        <p>Email: {{ user.email }}</p>\n    {% endif %}\n</div>\n
"},{"location":"concepts/fundamentals/html_js_css_variables/#legacy-get_context_data","title":"Legacy get_context_data()","text":"

The get_context_data() method is the legacy way to provide variables to your HTML template. It serves the same purpose as get_template_data() - it receives the component inputs and returns a dictionary of data that will be available in the template.

However, get_context_data() has a few drawbacks:

  • It does NOT receive the slots and context parameters.
  • The args and kwargs parameters are given as variadic *args and **kwargs parameters. As such, they cannot be typed.
class ProfileCard(Component):\n    template_file = \"profile_card.html\"\n\n    def get_context_data(self, user_id, show_details=False, *args, **kwargs):\n        user = User.objects.get(id=user_id)\n        return {\n            \"user\": user,\n            \"show_details\": show_details,\n        }\n

There is a slight difference between get_context_data() and get_template_data() when rendering a component with the {% component %} tag.

For example if you have component that accepts kwarg date:

class MyComponent(Component):\n    def get_context_data(self, date, *args, **kwargs):\n        return {\n            \"date\": date,\n        }\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"date\"],\n        }\n

The difference is that:

  • With get_context_data(), you can pass date either as arg or kwarg:

    \u2705\n{% component \"my_component\" date=some_date %}\n{% component \"my_component\" some_date %}\n
  • But with get_template_data(), date MUST be passed as kwarg:

    \u2705\n{% component \"my_component\" date=some_date %}\n\n\u274c\n{% component \"my_component\" some_date %}\n

Warning

get_template_data() and get_context_data() are mutually exclusive.

If both methods return non-empty dictionaries, an error will be raised.

Note

The get_context_data() method will be removed in v2.

"},{"location":"concepts/fundamentals/html_js_css_variables/#accessing-component-inputs","title":"Accessing component inputs","text":"

The component inputs are available in 3 ways:

"},{"location":"concepts/fundamentals/html_js_css_variables/#function-arguments","title":"Function arguments","text":"

The data methods receive the inputs as parameters directly.

class ProfileCard(Component):\n    # Access inputs directly as parameters\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"user_id\": args[0],\n            \"show_details\": kwargs[\"show_details\"],\n        }\n

Info

By default, the args parameter is a list, while kwargs and slots are dictionaries.

If you add typing to your component with Args, Kwargs, or Slots classes, the respective inputs will be given as instances of these classes.

Learn more about Component typing.

class ProfileCard(Component):\n    class Args(NamedTuple):\n        user_id: int\n\n    class Kwargs(NamedTuple):\n        show_details: bool\n\n    # Access inputs directly as parameters\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots, context):\n        return {\n            \"user_id\": args.user_id,\n            \"show_details\": kwargs.show_details,\n        }\n
"},{"location":"concepts/fundamentals/html_js_css_variables/#args-kwargs-slots-properties","title":"args, kwargs, slots properties","text":"

In other methods, you can access the inputs via self.args, self.kwargs, and self.slots properties:

class ProfileCard(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]):\n        # Access inputs via self.args, self.kwargs, self.slots\n        self.args[0]\n        self.kwargs.get(\"show_details\", False)\n        self.slots[\"footer\"]\n

Info

These properties work the same way as args, kwargs, and slots parameters in the data methods:

By default, the args property is a list, while kwargs and slots are dictionaries.

If you add typing to your component with Args, Kwargs, or Slots classes, the respective inputs will be given as instances of these classes.

Learn more about Component typing.

class ProfileCard(Component):\n    class Args(NamedTuple):\n        user_id: int\n\n    class Kwargs(NamedTuple):\n        show_details: bool\n\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots, context):\n        return {\n            \"user_id\": self.args.user_id,\n            \"show_details\": self.kwargs.show_details,\n        }\n
"},{"location":"concepts/fundamentals/html_js_css_variables/#input-property-low-level","title":"input property (low-level)","text":"

Warning

The input property is deprecated and will be removed in v1.

Instead, use properties defined on the Component class directly like self.context.

To access the unmodified inputs, use self.raw_args, self.raw_kwargs, and self.raw_slots properties.

The previous two approaches allow you to access only the most important inputs.

There are additional settings that may be passed to components. If you need to access these, you can use self.input property for a low-level access to all the inputs.

The input property contains all the inputs passed to the component (instance of ComponentInput).

This includes:

  • input.args - List of positional arguments
  • input.kwargs - Dictionary of keyword arguments
  • input.slots - Dictionary of slots. Values are normalized to Slot instances
  • input.context - Context object that should be used to render the component
  • input.type - The type of the component (document, fragment)
  • input.render_dependencies - Whether to render dependencies (CSS, JS)
class ProfileCard(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        # Access positional arguments\n        user_id = self.input.args[0] if self.input.args else None\n\n        # Access keyword arguments\n        show_details = self.input.kwargs.get(\"show_details\", False)\n\n        # Render component differently depending on the type\n        if self.input.type == \"fragment\":\n            ...\n\n        return {\n            \"user_id\": user_id,\n            \"show_details\": show_details,\n        }\n

Info

Unlike the parameters passed to the data methods, the args, kwargs, and slots in self.input property are always lists and dictionaries, regardless of whether you added typing classes to your component (like Args, Kwargs, or Slots).

"},{"location":"concepts/fundamentals/html_js_css_variables/#default-values","title":"Default values","text":"

You can use Defaults class to provide default values for your inputs.

These defaults will be applied either when:

  • The input is not provided at rendering time
  • The input is provided as None

When you then access the inputs in your data methods, the default values will be already applied.

Read more about Component Defaults.

from django_components import Component, Default, register\n\n@register(\"profile_card\")\nclass ProfileCard(Component):\n    class Kwargs(NamedTuple):\n        show_details: bool\n\n    class Defaults:\n        show_details = True\n\n    # show_details will be set to True if `None` or missing\n    def get_template_data(self, args, kwargs: Kwargs, slots, context):\n        return {\n            \"show_details\": kwargs.show_details,\n        }\n\n    ...\n

Warning

When typing your components with Args, Kwargs, or Slots classes, you may be inclined to define the defaults in the classes.

class ProfileCard(Component):\n    class Kwargs(NamedTuple):\n        show_details: bool = True\n

This is NOT recommended, because:

  • The defaults will NOT be applied to inputs when using self.raw_kwargs property.
  • The defaults will NOT be applied when a field is given but set to None.

Instead, define the defaults in the Defaults class.

"},{"location":"concepts/fundamentals/html_js_css_variables/#accessing-render-api","title":"Accessing Render API","text":"

All three data methods have access to the Component's Render API, which includes:

  • self.args - The positional arguments for the current render call
  • self.kwargs - The keyword arguments for the current render call
  • self.slots - The slots for the current render call
  • self.raw_args - Unmodified positional arguments for the current render call
  • self.raw_kwargs - Unmodified keyword arguments for the current render call
  • self.raw_slots - Unmodified slots for the current render call
  • self.context - The context for the current render call
  • self.id - The unique ID for the current render call
  • self.request - The request object
  • self.context_processors_data - Data from Django's context processors
  • self.inject() - Inject data into the component
  • self.registry - The ComponentRegistry instance
  • self.registered_name - The name under which the component was registered
  • self.outer_context - The context outside of the {% component %} tag
  • self.deps_strategy - The strategy for rendering dependencies
"},{"location":"concepts/fundamentals/html_js_css_variables/#type-hints","title":"Type hints","text":""},{"location":"concepts/fundamentals/html_js_css_variables/#typing-inputs","title":"Typing inputs","text":"

You can add type hints for the component inputs to ensure that the component logic is correct.

For this, define the Args, Kwargs, and Slots classes, and then add type hints to the data methods.

This will also validate the inputs at runtime, as the type classes will be instantiated with the inputs.

Read more about Component typing.

from typing import NamedTuple, Optional\nfrom django_components import Component, SlotInput\n\nclass Button(Component):\n    class Args(NamedTuple):\n        name: str\n\n    class Kwargs(NamedTuple):\n        surname: str\n        maybe_var: Optional[int] = None  # May be omitted\n\n    class Slots(NamedTuple):\n        my_slot: Optional[SlotInput] = None\n        footer: SlotInput\n\n    # Use the above classes to add type hints to the data method\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        # The parameters are instances of the classes we defined\n        assert isinstance(args, Button.Args)\n        assert isinstance(kwargs, Button.Kwargs)\n        assert isinstance(slots, Button.Slots)\n

Note

To access \"untyped\" inputs, use self.raw_args, self.raw_kwargs, and self.raw_slots properties.

These are plain lists and dictionaries, even when you added typing to your component.

"},{"location":"concepts/fundamentals/html_js_css_variables/#typing-data","title":"Typing data","text":"

In the same fashion, you can add types and validation for the data that should be RETURNED from each data method.

For this, set the TemplateData, JsData, and CssData classes on the component class.

For each data method, you can either return a plain dictionary with the data, or an instance of the respective data class.

from typing import NamedTuple\nfrom django_components import Component\n\nclass Button(Component):\n    class TemplateData(NamedTuple):\n        data1: str\n        data2: int\n\n    class JsData(NamedTuple):\n        js_data1: str\n        js_data2: int\n\n    class CssData(NamedTuple):\n        css_data1: str\n        css_data2: int\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return Button.TemplateData(\n            data1=\"...\",\n            data2=123,\n        )\n\n    def get_js_data(self, args, kwargs, slots, context):\n        return Button.JsData(\n            js_data1=\"...\",\n            js_data2=123,\n        )\n\n    def get_css_data(self, args, kwargs, slots, context):\n        return Button.CssData(\n            css_data1=\"...\",\n            css_data2=123,\n        )\n
"},{"location":"concepts/fundamentals/html_js_css_variables/#pass-through-kwargs","title":"Pass-through kwargs","text":"

It's best practice to explicitly define what args and kwargs a component accepts.

However, if you want a looser setup, you can easily write components that accept any number of kwargs, and pass them all to the template (similar to django-cotton).

To do that, simply return the kwargs dictionary itself from get_template_data():

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return kwargs\n

You can do the same for get_js_data() and get_css_data(), if needed:

class MyComponent(Component):\n    def get_js_data(self, args, kwargs, slots, context):\n        return kwargs\n\n    def get_css_data(self, args, kwargs, slots, context):\n        return kwargs\n
"},{"location":"concepts/fundamentals/http_request/","title":"HTTP Request","text":"

The most common use of django-components is to render HTML when the server receives a request. As such, there are a few features that are dependent on the request object.

"},{"location":"concepts/fundamentals/http_request/#passing-the-httprequest-object","title":"Passing the HttpRequest object","text":"

In regular Django templates, the request object is available only within the RequestContext.

In Components, you can either use RequestContext, or pass the request object explicitly to Component.render() and Component.render_to_response().

So the request object is available to components either when:

  • The component is rendered with RequestContext (Regular Django behavior)
  • The component is rendered with a regular Context (or none), but you set the request kwarg of Component.render().
  • The component is nested and the parent has access to the request object.
# \u2705 With request\nMyComponent.render(request=request)\nMyComponent.render(context=RequestContext(request, {}))\n\n# \u274c Without request\nMyComponent.render()\nMyComponent.render(context=Context({}))\n

When a component is rendered within a template with {% component %} tag, the request object is available depending on whether the template is rendered with RequestContext or not.

template = Template(\"\"\"\n<div>\n  {% component \"MyComponent\" / %}\n</div>\n\"\"\")\n\n# \u274c No request\nrendered = template.render(Context({}))\n\n# \u2705 With request\nrendered = template.render(RequestContext(request, {}))\n
"},{"location":"concepts/fundamentals/http_request/#accessing-the-httprequest-object","title":"Accessing the HttpRequest object","text":"

When the component has access to the request object, the request object will be available in Component.request.

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            'user_id': self.request.GET['user_id'],\n        }\n
"},{"location":"concepts/fundamentals/http_request/#context-processors","title":"Context Processors","text":"

Components support Django's context processors.

In regular Django templates, the context processors are applied only when the template is rendered with RequestContext.

In Components, the context processors are applied when the component has access to the request object.

"},{"location":"concepts/fundamentals/http_request/#accessing-context-processors-data","title":"Accessing context processors data","text":"

The data from context processors is automatically available within the component's template.

class MyComponent(Component):\n    template = \"\"\"\n        <div>\n            {{ csrf_token }}\n        </div>\n    \"\"\"\n\nMyComponent.render(request=request)\n

You can also access the context processors data from within get_template_data() and other methods under Component.context_processors_data.

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        csrf_token = self.context_processors_data['csrf_token']\n        return {\n            'csrf_token': csrf_token,\n        }\n

This is a dictionary with the context processors data.

If the request object is not available, then self.context_processors_data will be an empty dictionary.

Warning

The self.context_processors_data object is generated dynamically, so changes to it are not persisted.

"},{"location":"concepts/fundamentals/render_api/","title":"Render API","text":"

When a component is being rendered, whether with Component.render() or {% component %}, a component instance is populated with the current inputs and context. This allows you to access things like component inputs.

We refer to these render-time-only methods and attributes as the \"Render API\".

Render API is available inside these Component methods:

  • get_template_data()
  • get_js_data()
  • get_css_data()
  • get_context_data()
  • on_render_before()
  • on_render()
  • on_render_after()

Example:

class Table(Component):\n    def on_render_before(self, context, template):\n        # Access component's ID\n        assert self.id == \"c1A2b3c\"\n\n        # Access component's inputs, slots and context\n        assert self.args == [123, \"str\"]\n        assert self.kwargs == {\"variable\": \"test\", \"another\": 1}\n        footer_slot = self.slots[\"footer\"]\n        some_var = self.context[\"some_var\"]\n\n    def get_template_data(self, args, kwargs, slots, context):\n        # Access the request object and Django's context processors, if available\n        assert self.request.GET == {\"query\": \"something\"}\n        assert self.context_processors_data['user'].username == \"admin\"\n\nrendered = Table.render(\n    kwargs={\"variable\": \"test\", \"another\": 1},\n    args=(123, \"str\"),\n    slots={\"footer\": \"MY_SLOT\"},\n)\n
"},{"location":"concepts/fundamentals/render_api/#overview","title":"Overview","text":"

The Render API includes:

  • Component inputs:

    • self.args - The positional arguments for the current render call
    • self.kwargs - The keyword arguments for the current render call
    • self.slots - The slots for the current render call
    • self.raw_args - Unmodified positional arguments for the current render call
    • self.raw_kwargs - Unmodified keyword arguments for the current render call
    • self.raw_slots - Unmodified slots for the current render call
    • self.context - The context for the current render call
    • self.deps_strategy - The strategy for rendering dependencies
  • Request-related:

    • self.request - The request object (if available)
    • self.context_processors_data - Data from Django's context processors
  • Provide / inject:

    • self.inject() - Inject data into the component
  • Template tag metadata:

    • self.node - The ComponentNode instance
    • self.registry - The ComponentRegistry instance
    • self.registered_name - The name under which the component was registered
    • self.outer_context - The context outside of the {% component %} tag
  • Other metadata:

    • self.id - The unique ID for the current render call
"},{"location":"concepts/fundamentals/render_api/#component-inputs","title":"Component inputs","text":""},{"location":"concepts/fundamentals/render_api/#args","title":"Args","text":"

The args argument as passed to Component.get_template_data().

If you defined the Component.Args class, then the Component.args property will return an instance of that class.

Otherwise, args will be a plain list.

Use self.raw_args to access the positional arguments as a plain list irrespective of Component.Args.

Example:

With Args class:

from django_components import Component\n\nclass Table(Component):\n    class Args(NamedTuple):\n        page: int\n        per_page: int\n\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.args.page == 123\n        assert self.args.per_page == 10\n\nrendered = Table.render(\n    args=[123, 10],\n)\n

Without Args class:

from django_components import Component\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.args[0] == 123\n        assert self.args[1] == 10\n
"},{"location":"concepts/fundamentals/render_api/#kwargs","title":"Kwargs","text":"

The kwargs argument as passed to Component.get_template_data().

If you defined the Component.Kwargs class, then the Component.kwargs property will return an instance of that class.

Otherwise, kwargs will be a plain dictionary.

Use self.raw_kwargs to access the keyword arguments as a plain dictionary irrespective of Component.Kwargs.

Example:

With Kwargs class:

from django_components import Component\n\nclass Table(Component):\n    class Kwargs(NamedTuple):\n        page: int\n        per_page: int\n\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.kwargs.page == 123\n        assert self.kwargs.per_page == 10\n\nrendered = Table.render(\n    kwargs={\"page\": 123, \"per_page\": 10},\n)\n

Without Kwargs class:

from django_components import Component\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.kwargs[\"page\"] == 123\n        assert self.kwargs[\"per_page\"] == 10\n
"},{"location":"concepts/fundamentals/render_api/#slots","title":"Slots","text":"

The slots argument as passed to Component.get_template_data().

If you defined the Component.Slots class, then the Component.slots property will return an instance of that class.

Otherwise, slots will be a plain dictionary.

Use self.raw_slots to access the slots as a plain dictionary irrespective of Component.Slots.

Example:

With Slots class:

from django_components import Component, Slot, SlotInput\n\nclass Table(Component):\n    class Slots(NamedTuple):\n        header: SlotInput\n        footer: SlotInput\n\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert isinstance(self.slots.header, Slot)\n        assert isinstance(self.slots.footer, Slot)\n\nrendered = Table.render(\n    slots={\n        \"header\": \"MY_HEADER\",\n        \"footer\": lambda ctx: \"FOOTER: \" + ctx.data[\"user_id\"],\n    },\n)\n

Without Slots class:

from django_components import Component, Slot, SlotInput\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert isinstance(self.slots[\"header\"], Slot)\n        assert isinstance(self.slots[\"footer\"], Slot)\n
"},{"location":"concepts/fundamentals/render_api/#context","title":"Context","text":"

The context argument as passed to Component.get_template_data().

This is Django's Context with which the component template is rendered.

If the root component or template was rendered with RequestContext then this will be an instance of RequestContext.

Whether the context variables defined in context are available to the template depends on the context behavior mode:

  • In \"django\" context behavior mode, the template will have access to the keys of this context.

  • In \"isolated\" context behavior mode, the template will NOT have access to this context, and data MUST be passed via component's args and kwargs.

"},{"location":"concepts/fundamentals/render_api/#component-id","title":"Component ID","text":"

Component ID (or render ID) is a unique identifier for the current render call.

That means that if you call Component.render() multiple times, the ID will be different for each call.

It is available as self.id.

The ID is a 7-letter alphanumeric string in the format cXXXXXX, where XXXXXX is a random string of 6 alphanumeric characters (case-sensitive).

E.g. c1a2b3c.

A single render ID has a chance of collision 1 in 57 billion. However, due to birthday paradox, the chance of collision increases to 1% when approaching ~33K render IDs.

Thus, there is currently a soft-cap of ~30K components rendered on a single page.

If you need to expand this limit, please open an issue on GitHub.

class Table(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        # Access component's ID\n        assert self.id == \"c1A2b3c\"\n
"},{"location":"concepts/fundamentals/render_api/#request-and-context-processors","title":"Request and context processors","text":"

Components have access to the request object and context processors data if the component was:

  • Given a request kwarg directly
  • Rendered with RenderContext
  • Nested in another component for which any of these conditions is true

Then the request object will be available in self.request.

If the request object is available, you will also be able to access the context processors data in self.context_processors_data.

This is a dictionary with the context processors data.

If the request object is not available, then self.context_processors_data will be an empty dictionary.

Read more about the request object and context processors in the HTTP Request section.

from django.http import HttpRequest\n\nclass Table(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        # Access the request object and Django's context processors\n        assert self.request.GET == {\"query\": \"something\"}\n        assert self.context_processors_data['user'].username == \"admin\"\n\nrendered = Table.render(\n    request=HttpRequest(),\n)\n
"},{"location":"concepts/fundamentals/render_api/#provide-inject","title":"Provide / Inject","text":"

Components support a provide / inject system as known from Vue or React.

When rendering the component, you can call self.inject() with the key of the data you want to inject.

The object returned by self.inject()

To provide data to components, use the {% provide %} template tag.

Read more about Provide / Inject.

class Table(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        # Access provided data\n        data = self.inject(\"some_data\")\n        assert data.some_data == \"some_data\"\n
"},{"location":"concepts/fundamentals/render_api/#template-tag-metadata","title":"Template tag metadata","text":"

If the component is rendered with {% component %} template tag, the following metadata is available:

  • self.node - The ComponentNode instance
  • self.registry - The ComponentRegistry instance that was used to render the component
  • self.registered_name - The name under which the component was registered
  • self.outer_context - The context outside of the {% component %} tag

    {% with abc=123 %}\n    {{ abc }} {# <--- This is in outer context #}\n    {% component \"my_component\" / %}\n{% endwith %}\n

You can use these to check whether the component was rendered inside a template with {% component %} tag or in Python with Component.render().

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        if self.registered_name is None:\n            # Do something for the render() function\n        else:\n            # Do something for the {% component %} template tag\n

You can access the ComponentNode under Component.node:

class MyComponent(Component):\n    def get_template_data(self, context, template):\n        if self.node is not None:\n            assert self.node.name == \"my_component\"\n

Accessing the ComponentNode is mostly useful for extensions, which can modify their behaviour based on the source of the Component.

For example, if MyComponent was used in another component - that is, with a {% component \"my_component\" %} tag in a template that belongs to another component - then you can use self.node.template_component to access the owner Component class.

class Parent(Component):\n    template: types.django_html = \"\"\"\n        <div>\n            {% component \"my_component\" / %}\n        </div>\n    \"\"\"\n\n@register(\"my_component\")\nclass MyComponent(Component):\n    def get_template_data(self, context, template):\n        if self.node is not None:\n            assert self.node.template_component == Parent\n

Info

Component.node is None if the component is created by Component.render() (but you can pass in the node kwarg yourself).

"},{"location":"concepts/fundamentals/rendering_components/","title":"Rendering components","text":"

Your components can be rendered either within your Django templates, or directly in Python code.

"},{"location":"concepts/fundamentals/rendering_components/#overview","title":"Overview","text":"

Django Components provides three main methods to render components:

  • {% component %} tag - Renders the component within your Django templates
  • Component.render() method - Renders the component to a string
  • Component.render_to_response() method - Renders the component and wraps it in an HTTP response
"},{"location":"concepts/fundamentals/rendering_components/#component-tag","title":"{% component %} tag","text":"

Use the {% component %} tag to render a component within your Django templates.

The {% component %} tag takes:

  • Component's registered name as the first positional argument,
  • Followed by any number of positional and keyword arguments.
{% load component_tags %}\n<div>\n  {% component \"button\" name=\"John\" job=\"Developer\" / %}\n</div>\n

To pass in slots content, you can insert {% fill %} tags, directly within the {% component %} tag to \"fill\" the slots:

{% component \"my_table\" rows=rows headers=headers %}\n    {% fill \"pagination\" %}\n      < 1 | 2 | 3 >\n    {% endfill %}\n{% endcomponent %}\n

You can even nest {% fill %} tags within {% if %}, {% for %} and other tags:

{% component \"my_table\" rows=rows headers=headers %}\n    {% if rows %}\n        {% fill \"pagination\" %}\n            < 1 | 2 | 3 >\n        {% endfill %}\n    {% endif %}\n{% endcomponent %}\n

Omitting the component keyword

If you would like to omit the component keyword, and simply refer to your components by their registered names:

{% button name=\"John\" job=\"Developer\" / %}\n

You can do so by setting the \"shorthand\" Tag formatter in the settings:

# settings.py\nCOMPONENTS = {\n    \"tag_formatter\": \"django_components.component_shorthand_formatter\",\n}\n

Extended template tag syntax

Unlike regular Django template tags, django-components' tags offer extra features like defining literal lists and dicts, and more. Read more about Template tag syntax.

"},{"location":"concepts/fundamentals/rendering_components/#registering-components","title":"Registering components","text":"

For a component to be renderable with the {% component %} tag, it must be first registered with the @register() decorator.

For example, if you register a component under the name \"button\":

from typing import NamedTuple\nfrom django_components import Component, register\n\n@register(\"button\")\nclass Button(Component):\n    template_file = \"button.html\"\n\n    class Kwargs(NamedTuple):\n        name: str\n        job: str\n\n    def get_template_data(self, args, kwargs, slots, context):\n        ...\n

Then you can render this component by using its registered name \"button\" in the template:

{% component \"button\" name=\"John\" job=\"Developer\" / %}\n

As you can see above, the args and kwargs passed to the {% component %} tag correspond to the component's input.

For more details, read Registering components.

Why do I need to register components?

TL;DR: To be able to share components as libraries, and because components can be registed with multiple registries / libraries.

Django-components allows to share components across projects.

However, different projects may use different settings. For example, one project may prefer the \"long\" format:

{% component \"button\" name=\"John\" job=\"Developer\" / %}\n

While the other may use the \"short\" format:

{% button name=\"John\" job=\"Developer\" / %}\n

Both approaches are supported simultaneously for backwards compatibility, because django-components started out with only the \"long\" format.

To avoid ambiguity, when you use a 3rd party library, it uses the syntax that the author had configured for it.

So when you are creating a component, django-components need to know which registry the component belongs to, so it knows which syntax to use.

"},{"location":"concepts/fundamentals/rendering_components/#rendering-templates","title":"Rendering templates","text":"

If you have embedded the component in a Django template using the {% component %} tag:

[project root]/templates/my_template.html
{% load component_tags %}\n<div>\n  {% component \"calendar\" date=\"2024-12-13\" / %}\n</div>\n

You can simply render the template with the Django's API:

  • django.shortcuts.render()

    from django.shortcuts import render\n\ncontext = {\"date\": \"2024-12-13\"}\nrendered_template = render(request, \"my_template.html\", context)\n
  • Template.render()

    from django.template import Template\nfrom django.template.loader import get_template\n\n# Either from a file\ntemplate = get_template(\"my_template.html\")\n\n# or inlined\ntemplate = Template(\"\"\"\n    {% load component_tags %}\n    <div>\n        {% component \"calendar\" date=\"2024-12-13\" / %}\n    </div>\n\"\"\")\n\nrendered_template = template.render()\n
"},{"location":"concepts/fundamentals/rendering_components/#isolating-components","title":"Isolating components","text":"

By default, components behave similarly to Django's {% include %}, and the template inside the component has access to the variables defined in the outer template.

You can selectively isolate a component, using the only flag, so that the inner template can access only the data that was explicitly passed to it:

{% component \"name\" positional_arg keyword_arg=value ... only / %}\n

Alternatively, you can set all components to be isolated by default, by setting context_behavior to \"isolated\" in your settings:

# settings.py\nCOMPONENTS = {\n    \"context_behavior\": \"isolated\",\n}\n
"},{"location":"concepts/fundamentals/rendering_components/#render-method","title":"render() method","text":"

The Component.render() method renders a component to a string.

This is the equivalent of calling the {% component %} tag.

from typing import NamedTuple, Optional\nfrom django_components import Component, SlotInput\n\nclass Button(Component):\n    template_file = \"button.html\"\n\n    class Args(NamedTuple):\n        name: str\n\n    class Kwargs(NamedTuple):\n        surname: str\n        age: int\n\n    class Slots(NamedTuple):\n        footer: Optional[SlotInput] = None\n\n    def get_template_data(self, args, kwargs, slots, context):\n        ...\n\nButton.render(\n    args=[\"John\"],\n    kwargs={\n        \"surname\": \"Doe\",\n        \"age\": 30,\n    },\n    slots={\n        \"footer\": \"i AM A SLOT\",\n    },\n)\n

Component.render() accepts the following arguments:

  • args - Positional arguments to pass to the component (as a list or tuple)
  • kwargs - Keyword arguments to pass to the component (as a dictionary)
  • slots - Slot content to pass to the component (as a dictionary)
  • context - Django context for rendering (can be a dictionary or a Context object)
  • deps_strategy - Dependencies rendering strategy (default: \"document\")
  • request - HTTP request object, used for context processors (optional)

All arguments are optional. If not provided, they default to empty values or sensible defaults.

See the API reference for Component.render() for more details on the arguments.

"},{"location":"concepts/fundamentals/rendering_components/#render_to_response-method","title":"render_to_response() method","text":"

The Component.render_to_response() method works just like Component.render(), but wraps the result in an HTTP response.

It accepts all the same arguments as Component.render().

Any extra arguments are passed to the HttpResponse constructor.

from typing import NamedTuple, Optional\nfrom django_components import Component, SlotInput\n\nclass Button(Component):\n    template_file = \"button.html\"\n\n    class Args(NamedTuple):\n        name: str\n\n    class Kwargs(NamedTuple):\n        surname: str\n        age: int\n\n    class Slots(NamedTuple):\n        footer: Optional[SlotInput] = None\n\n    def get_template_data(self, args, kwargs, slots, context):\n        ...\n\n# Render the component to an HttpResponse\nresponse = Button.render_to_response(\n    args=[\"John\"],\n    kwargs={\n        \"surname\": \"Doe\",\n        \"age\": 30,\n    },\n    slots={\n        \"footer\": \"i AM A SLOT\",\n    },\n    # Additional response arguments\n    status=200,\n    headers={\"X-Custom-Header\": \"Value\"},\n)\n

This method is particularly useful in view functions, as you can return the result of the component directly:

def profile_view(request, user_id):\n    return Button.render_to_response(\n        kwargs={\n            \"surname\": \"Doe\",\n            \"age\": 30,\n        },\n        request=request,\n    )\n
"},{"location":"concepts/fundamentals/rendering_components/#custom-response-classes","title":"Custom response classes","text":"

By default, Component.render_to_response() returns a standard Django HttpResponse.

You can customize this by setting the response_class attribute on your component:

from django.http import HttpResponse\nfrom django_components import Component\n\nclass MyHttpResponse(HttpResponse):\n    ...\n\nclass MyComponent(Component):\n    response_class = MyHttpResponse\n\nresponse = MyComponent.render_to_response()\nassert isinstance(response, MyHttpResponse)\n
"},{"location":"concepts/fundamentals/rendering_components/#dependencies-rendering","title":"Dependencies rendering","text":"

The rendered HTML may be used in different contexts (browser, email, etc), and each may need different handling of JS and CSS scripts.

render() and render_to_response() accept a deps_strategy parameter, which controls where and how the JS / CSS are inserted into the HTML.

The deps_strategy parameter is ultimately passed to render_dependencies().

Learn more about Rendering JS / CSS.

There are six dependencies rendering strategies:

  • document (default)
    • Smartly inserts JS / CSS into placeholders ({% component_js_dependencies %}) or into <head> and <body> tags.
    • Inserts extra script to allow fragment components to work.
    • Assumes the HTML will be rendered in a JS-enabled browser.
  • fragment
    • A lightweight HTML fragment to be inserted into a document with AJAX.
    • Assumes the page was already rendered with \"document\" strategy.
    • No JS / CSS included.
  • simple
    • Smartly insert JS / CSS into placeholders ({% component_js_dependencies %}) or into <head> and <body> tags.
    • No extra script loaded.
  • prepend
    • Insert JS / CSS before the rendered HTML.
    • Ignores the placeholders ({% component_js_dependencies %}) and any <head>/<body> HTML tags.
    • No extra script loaded.
  • append
    • Insert JS / CSS after the rendered HTML.
    • Ignores the placeholders ({% component_js_dependencies %}) and any <head>/<body> HTML tags.
    • No extra script loaded.
  • ignore
    • HTML is left as-is. You can still process it with a different strategy later with render_dependencies().
    • Used for inserting rendered HTML into other components.

Info

You can use the \"prepend\" and \"append\" strategies to force to output JS / CSS for components that don't have neither the placeholders like {% component_js_dependencies %}, nor any <head>/<body> HTML tags:

rendered = Calendar.render_to_response(\n    request=request,\n    kwargs={\n        \"date\": request.GET.get(\"date\", \"\"),\n    },\n    deps_strategy=\"append\",\n)\n

Renders something like this:

<!-- Calendar component -->\n<div class=\"calendar\">\n    ...\n</div>\n<!-- Appended JS / CSS -->\n<script src=\"...\"></script>\n<link href=\"...\"></link>\n
"},{"location":"concepts/fundamentals/rendering_components/#passing-context","title":"Passing context","text":"

The render() and render_to_response() methods accept an optional context argument. This sets the context within which the component is rendered.

When a component is rendered within a template with the {% component %} tag, this will be automatically set to the Context instance that is used for rendering the template.

When you call Component.render() directly from Python, there is no context object, so you can ignore this input most of the time. Instead, use args, kwargs, and slots to pass data to the component.

However, you can pass RequestContext to the context argument, so that the component will gain access to the request object and will use context processors. Read more on Working with HTTP requests.

Button.render(\n    context=RequestContext(request),\n)\n

For advanced use cases, you can use context argument to \"pre-render\" the component in Python, and then pass the rendered output as plain string to the template. With this, the inner component is rendered as if it was within the template with {% component %}.

class Button(Component):\n    def render(self, context, template):\n        # Pass `context` to Icon component so it is rendered\n        # as if nested within Button.\n        icon = Icon.render(\n            context=context,\n            args=[\"icon-name\"],\n            deps_strategy=\"ignore\",\n        )\n        # Update context with icon\n        with context.update({\"icon\": icon}):\n            return template.render(context)\n

Warning

Whether the variables defined in context are actually available in the template depends on the context behavior mode:

  • In \"django\" context behavior mode, the template will have access to the keys of this context.

  • In \"isolated\" context behavior mode, the template will NOT have access to this context, and data MUST be passed via component's args and kwargs.

Therefore, it's strongly recommended to not rely on defining variables on the context object, but instead passing them through as args and kwargs

\u274c Don't do this:

html = ProfileCard.render(\n    context={\"name\": \"John\"},\n)\n

\u2705 Do this:

html = ProfileCard.render(\n    kwargs={\"name\": \"John\"},\n)\n
"},{"location":"concepts/fundamentals/rendering_components/#typing-render-methods","title":"Typing render methods","text":"

Neither Component.render() nor Component.render_to_response() are typed, due to limitations of Python's type system.

To add type hints, you can wrap the inputs in component's Args, Kwargs, and Slots classes.

Read more on Typing and validation.

from typing import NamedTuple, Optional\nfrom django_components import Component, Slot, SlotInput\n\n# Define the component with the types\nclass Button(Component):\n    class Args(NamedTuple):\n        name: str\n\n    class Kwargs(NamedTuple):\n        surname: str\n        age: int\n\n    class Slots(NamedTuple):\n        my_slot: Optional[SlotInput] = None\n        footer: SlotInput\n\n# Add type hints to the render call\nButton.render(\n    args=Button.Args(\n        name=\"John\",\n    ),\n    kwargs=Button.Kwargs(\n        surname=\"Doe\",\n        age=30,\n    ),\n    slots=Button.Slots(\n        footer=Slot(lambda ctx: \"Click me!\"),\n    ),\n)\n
"},{"location":"concepts/fundamentals/rendering_components/#components-as-input","title":"Components as input","text":"

django_components makes it possible to compose components in a \"React-like\" way, where you can render one component and use its output as input to another component:

from django.utils.safestring import mark_safe\n\n# Render the inner component\ninner_html = InnerComponent.render(\n    kwargs={\"some_data\": \"value\"},\n    deps_strategy=\"ignore\",  # Important for nesting!\n)\n\n# Use inner component's output in the outer component\nouter_html = OuterComponent.render(\n    kwargs={\n        \"content\": mark_safe(inner_html),  # Mark as safe to prevent escaping\n    },\n)\n

The key here is setting deps_strategy=\"ignore\" for the inner component. This prevents duplicate rendering of JS / CSS dependencies when the outer component is rendered.

When deps_strategy=\"ignore\":

  • No JS or CSS dependencies will be added to the output HTML
  • The component's content is rendered as-is
  • The outer component will take care of including all needed dependencies

Read more about Rendering JS / CSS.

"},{"location":"concepts/fundamentals/rendering_components/#dynamic-components","title":"Dynamic components","text":"

Django components defines a special \"dynamic\" component (DynamicComponent).

Normally, you have to hard-code the component name in the template:

{% component \"button\" / %}\n

The dynamic component allows you to dynamically render any component based on the is kwarg. This is similar to Vue's dynamic components (<component :is>).

{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% endcomponent %}\n

The args, kwargs, and slot fills are all passed down to the underlying component.

As with other components, the dynamic component can be rendered from Python:

from django_components import DynamicComponent\n\nDynamicComponent.render(\n    kwargs={\n        \"is\": table_comp,\n        \"data\": table_data,\n        \"headers\": table_headers,\n    },\n    slots={\n        \"pagination\": PaginationComponent.render(\n            deps_strategy=\"ignore\",\n        ),\n    },\n)\n
"},{"location":"concepts/fundamentals/rendering_components/#dynamic-component-name","title":"Dynamic component name","text":"

By default, the dynamic component is registered under the name \"dynamic\". In case of a conflict, you can set the COMPONENTS.dynamic_component_name setting to change the name used for the dynamic components.

# settings.py\nCOMPONENTS = ComponentsSettings(\n    dynamic_component_name=\"my_dynamic\",\n)\n

After which you will be able to use the dynamic component with the new name:

{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"concepts/fundamentals/rendering_components/#html-fragments","title":"HTML fragments","text":"

Django-components provides a seamless integration with HTML fragments with AJAX (HTML over the wire), whether you're using jQuery, HTMX, AlpineJS, vanilla JavaScript, or other.

This is achieved by the combination of the \"document\" and \"fragment\" dependencies rendering strategies.

Read more about HTML fragments and Rendering JS / CSS.

"},{"location":"concepts/fundamentals/secondary_js_css_files/","title":"Secondary JS / CSS files","text":""},{"location":"concepts/fundamentals/secondary_js_css_files/#overview","title":"Overview","text":"

Each component can define extra or \"secondary\" CSS / JS files using the nested Component.Media class, by setting Component.Media.js and Component.Media.css.

The main HTML / JS / CSS files are limited to 1 per component. This is not the case for the secondary files, where components can have many of them.

There is also no special behavior or post-processing for these secondary files, they are loaded as is.

You can use these for third-party libraries, or for shared CSS / JS files.

These must be set as paths, URLs, or custom objects.

@register(\"calendar\")\nclass Calendar(Component):\n    class Media:\n        js = [\n            \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\",\n            \"calendar/script.js\",\n        ]\n        css = [\n            \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\",\n            \"calendar/style.css\",\n        ]\n

Note

django-component's management of files is inspired by Django's Media class.

To be familiar with how Django handles static files, we recommend reading also:

  • How to manage static files (e.g. images, JavaScript, CSS)
"},{"location":"concepts/fundamentals/secondary_js_css_files/#media-class","title":"Media class","text":"

Use the Media class to define secondary JS / CSS files for a component.

This Media class behaves similarly to Django's Media class:

  • Static paths - Paths are handled as static file paths, and are resolved to URLs with Django's {% static %} template tag.
  • URLs - A path that starts with http, https, or / is considered a URL. URLs are NOT resolved with {% static %}.
  • HTML tags - Both static paths and URLs are rendered to <script> and <link> HTML tags with media_class.render_js() and media_class.render_css().
  • Bypass formatting - A SafeString, or a function (with __html__ method) is considered an already-formatted HTML tag, skipping both static file resolution and rendering with media_class.render_js() or media_class.render_css().
  • Inheritance - You can set extend to configure whether to inherit JS / CSS from parent components. See Media inheritance.

However, there's a few differences from Django's Media class:

  1. Our Media class accepts various formats for the JS and CSS files: either a single file, a list, or (CSS-only) a dictonary (See ComponentMediaInput).
  2. Individual JS / CSS files can be any of str, bytes, Path, SafeString, or a function (See ComponentMediaInputPath).
  3. Individual JS / CSS files can be glob patterns, e.g. *.js or styles/**/*.css.
  4. If you set Media.extend to a list, it should be a list of Component classes.
from components.layout import LayoutComp\n\nclass MyTable(Component):\n    class Media:\n        js = [\n            \"path/to/script.js\",\n            \"path/to/*.js\",  # Or as a glob\n            \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\",  # AlpineJS\n        ]\n        css = {\n            \"all\": [\n                \"path/to/style.css\",\n                \"path/to/*.css\",  # Or as a glob\n                \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\",  # TailwindCSS\n            ],\n            \"print\": [\"path/to/style2.css\"],\n        }\n\n        # Reuse JS / CSS from LayoutComp\n        extend = [\n            LayoutComp,\n        ]\n
"},{"location":"concepts/fundamentals/secondary_js_css_files/#css-media-types","title":"CSS media types","text":"

You can define which stylesheets will be associated with which CSS media types. You do so by defining CSS files as a dictionary.

See the corresponding Django Documentation.

Again, you can set either a single file or a list of files per media type:

class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": \"path/to/style1.css\",\n            \"print\": [\"path/to/style2.css\", \"path/to/style3.css\"],\n        }\n

Which will render the following HTML:

<link href=\"/static/path/to/style1.css\" media=\"all\" rel=\"stylesheet\">\n<link href=\"/static/path/to/style2.css\" media=\"print\" rel=\"stylesheet\">\n<link href=\"/static/path/to/style3.css\" media=\"print\" rel=\"stylesheet\">\n

Note

When you define CSS as a string or a list, the all media type is implied.

So these two examples are the same:

class MyComponent(Component):\n    class Media:\n        css = \"path/to/style1.css\"\n
class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": [\"path/to/style1.css\"],\n        }\n
"},{"location":"concepts/fundamentals/secondary_js_css_files/#media-inheritance","title":"Media inheritance","text":"

By default, the media files are inherited from the parent component.

class ParentComponent(Component):\n    class Media:\n        js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n    class Media:\n        js = [\"script.js\"]\n\nprint(MyComponent.media._js)  # [\"parent.js\", \"script.js\"]\n

You can set the component NOT to inherit from the parent component by setting the extend attribute to False:

class ParentComponent(Component):\n    class Media:\n        js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n    class Media:\n        extend = False  # Don't inherit parent media\n        js = [\"script.js\"]\n\nprint(MyComponent.media._js)  # [\"script.js\"]\n

Alternatively, you can specify which components to inherit from. In such case, the media files are inherited ONLY from the specified components, and NOT from the original parent components:

class ParentComponent(Component):\n    class Media:\n        js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n    class Media:\n        # Only inherit from these, ignoring the files from the parent\n        extend = [OtherComponent1, OtherComponent2]\n\n        js = [\"script.js\"]\n\nprint(MyComponent.media._js)  # [\"script.js\", \"other1.js\", \"other2.js\"]\n

Info

The extend behaves consistently with Django's Media class, with one exception:

  • When you set extend to a list, the list is expected to contain Component classes (or other classes that have a nested Media class).
"},{"location":"concepts/fundamentals/secondary_js_css_files/#accessing-media-files","title":"Accessing Media files","text":"

To access the files that you defined under Component.Media, use Component.media (lowercase).

This is consistent behavior with Django's Media class.

class MyComponent(Component):\n    class Media:\n        js = \"path/to/script.js\"\n        css = \"path/to/style.css\"\n\nprint(MyComponent.media)\n# Output:\n# <script src=\"/static/path/to/script.js\"></script>\n# <link href=\"/static/path/to/style.css\" media=\"all\" rel=\"stylesheet\">\n

When working with component media files, it is important to understand the difference:

  • Component.Media

    • Is the \"raw\" media definition, or the input, which holds only the component's own media definition
    • This class is NOT instantiated, it merely holds the JS / CSS files.
  • Component.media

    • Returns all resolved media files, including those inherited from parent components
    • Is an instance of Component.media_class
class ParentComponent(Component):\n    class Media:\n        js = [\"parent.js\"]\n\nclass ChildComponent(ParentComponent):\n    class Media:\n        js = [\"child.js\"]\n\n# Access only this component's media\nprint(ChildComponent.Media.js)  # [\"child.js\"]\n\n# Access all inherited media\nprint(ChildComponent.media._js)  # [\"parent.js\", \"child.js\"]\n

Note

You should not manually modify Component.media or Component.Media after the component has been resolved, as this may lead to unexpected behavior.

If you want to modify the class that is instantiated for Component.media, you can configure Component.media_class (See example).

"},{"location":"concepts/fundamentals/secondary_js_css_files/#file-paths","title":"File paths","text":"

Unlike the main HTML / JS / CSS files, the path definition for the secondary files are quite ergonomic.

"},{"location":"concepts/fundamentals/secondary_js_css_files/#relative-to-component","title":"Relative to component","text":"

As seen in the getting started example, to associate HTML / JS / CSS files with a component, you can set them as Component.template_file, Component.js_file and Component.css_file respectively:

[project root]/components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"template.html\"\n    css_file = \"style.css\"\n    js_file = \"script.js\"\n

In the example above, we defined the files relative to the directory where the component file is defined.

Alternatively, you can specify the file paths relative to the directories set in COMPONENTS.dirs or COMPONENTS.app_dirs.

If you specify the paths relative to component's directory, django-componenents does the conversion automatically for you.

Thus, assuming that COMPONENTS.dirs contains path [project root]/components, the example above is the same as writing:

[project root]/components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar/template.html\"\n    css_file = \"calendar/style.css\"\n    js_file = \"calendar/script.js\"\n

Important

File path resolution in-depth

At component class creation, django-components checks all file paths defined on the component (e.g. Component.template_file).

For each file path, it checks if the file path is relative to the component's directory. And such file exists, the component's file path is re-written to be defined relative to a first matching directory in COMPONENTS.dirs or COMPONENTS.app_dirs.

Example:

[root]/components/mytable/mytable.py
class MyTable(Component):\n    template_file = \"mytable.html\"\n
  1. Component MyTable is defined in file [root]/components/mytable/mytable.py.
  2. The component's directory is thus [root]/components/mytable/.
  3. Because MyTable.template_file is mytable.html, django-components tries to resolve it as [root]/components/mytable/mytable.html.
  4. django-components checks the filesystem. If there's no such file, nothing happens.
  5. If there IS such file, django-components tries to rewrite the path.
  6. django-components searches COMPONENTS.dirs and COMPONENTS.app_dirs for a first directory that contains [root]/components/mytable/mytable.html.
  7. It comes across [root]/components/, which DOES contain the path to mytable.html.
  8. Thus, it rewrites template_file from mytable.html to mytable/mytable.html.

NOTE: In case of ambiguity, the preference goes to resolving the files relative to the component's directory.

"},{"location":"concepts/fundamentals/secondary_js_css_files/#globs","title":"Globs","text":"

Components can have many secondary files. To simplify their declaration, you can use globs.

Globs MUST be relative to the component's directory.

[project root]/components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    class Media:\n        js = [\n            \"path/to/*.js\",\n            \"another/path/*.js\",\n        ]\n        css = \"*.css\"\n

How this works is that django-components will detect that the path is a glob, and will try to resolve all files matching the glob pattern relative to the component's directory.

After that, the file paths are handled the same way as if you defined them explicitly.

"},{"location":"concepts/fundamentals/secondary_js_css_files/#supported-types","title":"Supported types","text":"

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

To help with typing the union, use ComponentMediaInputPath.

from pathlib import Path\n\nfrom django.utils.safestring import mark_safe\n\nclass SimpleComponent(Component):\n    class Media:\n        css = [\n            mark_safe('<link href=\"/static/calendar/style1.css\" rel=\"stylesheet\" />'),\n            Path(\"calendar/style1.css\"),\n            \"calendar/style2.css\",\n            b\"calendar/style3.css\",\n            lambda: \"calendar/style4.css\",\n        ]\n        js = [\n            mark_safe('<script src=\"/static/calendar/script1.js\"></script>'),\n            Path(\"calendar/script1.js\"),\n            \"calendar/script2.js\",\n            b\"calendar/script3.js\",\n            lambda: \"calendar/script4.js\",\n        ]\n
"},{"location":"concepts/fundamentals/secondary_js_css_files/#paths-as-objects","title":"Paths as objects","text":"

In the example above, you can see that when we used Django's mark_safe() to mark a string as a SafeString, we had to define the URL / path as an HTML <script>/<link> elements.

This is an extension of Django's Paths as objects feature, where \"safe\" strings are taken as is, and are accessed only at render time.

Because of that, the paths defined as \"safe\" strings are NEVER resolved, neither relative to component's directory, nor relative to COMPONENTS.dirs. It is assumed that you will define the full <script>/<link> tag with the correct URL / path.

\"Safe\" strings can be used to lazily resolve a path, or to customize the <script> or <link> tag for individual paths:

In the example below, we make use of \"safe\" strings to add type=\"module\" to the script tag that will fetch calendar/script2.js. In this case, we implemented a \"safe\" string by defining a __html__ method.

# Path object\nclass ModuleJsPath:\n    def __init__(self, static_path: str) -> None:\n        self.static_path = static_path\n\n    # Lazily resolve the path\n    def __html__(self):\n        full_path = static(self.static_path)\n        return format_html(\n            f'<script type=\"module\" src=\"{full_path}\"></script>'\n        )\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar/template.html\"\n\n    class Media:\n        css = \"calendar/style1.css\"\n        js = [\n            # <script> tag constructed by Media class\n            \"calendar/script1.js\",\n            # Custom <script> tag\n            ModuleJsPath(\"calendar/script2.js\"),\n        ]\n
"},{"location":"concepts/fundamentals/secondary_js_css_files/#rendering-paths","title":"Rendering paths","text":"

As part of the rendering process, the secondary JS / CSS files are resolved and rendered into <link> and <script> HTML tags, so they can be inserted into the render.

In the Paths as objects section, we saw that we can use that to selectively change how the HTML tags are constructed.

However, if you need to change how ALL CSS and JS files are rendered for a given component, you can provide your own subclass of Django's Media class to the Component.media_class attribute.

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\nfrom django_components import Component, register\n\nclass MyMedia(Media):\n    # Same as original Media.render_js, except\n    # the `<script>` tag has also `type=\"module\"`\n    def render_js(self):\n        tags = []\n        for path in self._js:\n            if hasattr(path, \"__html__\"):\n                tag = path.__html__()\n            else:\n                tag = format_html(\n                    '<script type=\"module\" src=\"{}\"></script>',\n                    self.absolute_path(path)\n                )\n        return tags\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar/template.html\"\n    css_file = \"calendar/style.css\"\n    js_file = \"calendar/script.js\"\n\n    class Media:\n        css = \"calendar/style1.css\"\n        js = \"calendar/script2.js\"\n\n    # Override the behavior of Media class\n    media_class = MyMedia\n
"},{"location":"concepts/fundamentals/single_file_components/","title":"Single-file components","text":"

Components can be defined in a single file, inlining the HTML, JS and CSS within the Python code.

"},{"location":"concepts/fundamentals/single_file_components/#writing-single-file-components","title":"Writing single file components","text":"

To do this, you can use the template, js, and css class attributes instead of the template_file, js_file, and css_file.

For example, here's the calendar component from the Getting started tutorial:

calendar.py
from django_components import Component\n\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    js_file = \"calendar.js\"\n    css_file = \"calendar.css\"\n

And here is the same component, rewritten in a single file:

[project root]/components/calendar.py
from django_components import Component, register, types\n\n@register(\"calendar\")\nclass Calendar(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"date\"],\n        }\n\n    template: types.django_html = \"\"\"\n        <div class=\"calendar\">\n            Today's date is <span>{{ date }}</span>\n        </div>\n    \"\"\"\n\n    css: types.css = \"\"\"\n        .calendar {\n            width: 200px;\n            background: pink;\n        }\n        .calendar span {\n            font-weight: bold;\n        }\n    \"\"\"\n\n    js: types.js = \"\"\"\n        (function(){\n            if (document.querySelector(\".calendar\")) {\n                document.querySelector(\".calendar\").onclick = () => {\n                    alert(\"Clicked calendar!\");\n                };\n            }\n        })()\n    \"\"\"\n

You can mix and match, so you can have a component with inlined HTML, while the JS and CSS are in separate files:

[project root]/components/calendar.py
from django_components import Component, register, types\n\n@register(\"calendar\")\nclass Calendar(Component):\n    js_file = \"calendar.js\"\n    css_file = \"calendar.css\"\n\n    template: types.django_html = \"\"\"\n        <div class=\"calendar\">\n            Today's date is <span>{{ date }}</span>\n        </div>\n    \"\"\"\n
"},{"location":"concepts/fundamentals/single_file_components/#syntax-highlighting","title":"Syntax highlighting","text":"

If you \"inline\" the HTML, JS and CSS code into the Python class, you should set up syntax highlighting to let your code editor know that the inlined code is HTML, JS and CSS.

In the examples above, we've annotated the template, js, and css attributes with the types.django_html, types.js and types.css types. These are used for syntax highlighting in VSCode.

Warning

Autocompletion / intellisense does not work in the inlined code.

Help us add support for intellisense in the inlined code! Start a conversation in the GitHub Discussions.

"},{"location":"concepts/fundamentals/single_file_components/#vscode","title":"VSCode","text":"
  1. First install Python Inline Source Syntax Highlighting extension, it will give you syntax highlighting for the template, CSS, and JS.

  2. Next, in your component, set typings of Component.template, Component.js, Component.css to types.django_html, types.css, and types.js respectively. The extension will recognize these and will activate syntax highlighting.

[project root]/components/calendar.py
from django_components import Component, register, types\n\n@register(\"calendar\")\nclass Calendar(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"date\"],\n        }\n\n    template: types.django_html = \"\"\"\n        <div class=\"calendar-component\">\n            Today's date is <span>{{ date }}</span>\n        </div>\n    \"\"\"\n\n    css: types.css = \"\"\"\n        .calendar-component {\n            width: 200px;\n            background: pink;\n        }\n        .calendar-component span {\n            font-weight: bold;\n        }\n    \"\"\"\n\n    js: types.js = \"\"\"\n        (function(){\n            if (document.querySelector(\".calendar-component\")) {\n                document.querySelector(\".calendar-component\").onclick = function(){ alert(\"Clicked calendar!\"); };\n            }\n        })()\n    \"\"\"\n
"},{"location":"concepts/fundamentals/single_file_components/#pycharm-or-other-jetbrains-ides","title":"Pycharm (or other Jetbrains IDEs)","text":"

With PyCharm (or any other editor from Jetbrains), you don't need to use types.django_html, types.css, types.js since Pycharm uses language injections.

You only need to write the comments # language=<lang> above the variables.

from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"date\"],\n        }\n\n    # language=HTML\n    template= \"\"\"\n        <div class=\"calendar-component\">\n            Today's date is <span>{{ date }}</span>\n        </div>\n    \"\"\"\n\n    # language=CSS\n    css = \"\"\"\n        .calendar-component {\n            width: 200px;\n            background: pink;\n        }\n        .calendar-component span {\n            font-weight: bold;\n        }\n    \"\"\"\n\n    # language=JS\n    js = \"\"\"\n        (function(){\n            if (document.querySelector(\".calendar-component\")) {\n                document.querySelector(\".calendar-component\").onclick = function(){ alert(\"Clicked calendar!\"); };\n            }\n        })()\n    \"\"\"\n
"},{"location":"concepts/fundamentals/single_file_components/#markdown-code-blocks-with-pygments","title":"Markdown code blocks with Pygments","text":"

Pygments is a syntax highlighting library written in Python. It's also what's used by this documentation site (mkdocs-material) to highlight code blocks.

To write code blocks with syntax highlighting, you need to install the pygments-djc package.

pip install pygments-djc\n

And then initialize it by importing pygments_djc somewhere in your project:

import pygments_djc\n

Now you can use the djc_py code block to write code blocks with syntax highlighting for components.

\\```djc_py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template = \"\"\"\n        <div class=\"calendar-component\">\n            Today's date is <span>{{ date }}</span>\n        </div>\n    \"\"\"\n\n    css = \"\"\"\n        .calendar-component {\n            width: 200px;\n            background: pink;\n        }\n        .calendar-component span {\n            font-weight: bold;\n        }\n    \"\"\"\n\\```\n

Will be rendered as below. Notice that the CSS and HTML are highlighted correctly:

from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template= \"\"\"\n        <div class=\"calendar-component\">\n            Today's date is <span>{{ date }}</span>\n        </div>\n    \"\"\"\n\n    css = \"\"\"\n        .calendar-component {\n            width: 200px;\n            background: pink;\n        }\n        .calendar-component span {\n            font-weight: bold;\n        }\n    \"\"\"\n
"},{"location":"concepts/fundamentals/slots/","title":"Slots","text":"

django-components has the most extensive slot system of all the popular Python templating engines.

The slot system is based on Vue, and works across both Django templates and Python code.

"},{"location":"concepts/fundamentals/slots/#what-are-slots","title":"What are slots?","text":"

Components support something called 'slots'.

When you write a component, you define its template. The template will always be the same each time you render the component.

However, sometimes you may want to customize the component slightly to change the content of the component. This is where slots come in.

Slots allow you to insert parts of HTML into the component. This makes components more reusable and composable.

<div class=\"calendar-component\">\n    <div class=\"header\">\n        {# This is where the component will insert the content #}\n        {% slot \"header\" / %}\n    </div>\n</div>\n
"},{"location":"concepts/fundamentals/slots/#slot-anatomy","title":"Slot anatomy","text":"

Slots consists of two parts:

  1. {% slot %} tag - Inside your component you decide where you want to insert the content.
  2. {% fill %} tag - In the parent template (outside the component) you decide what content to insert into the slot. It \"fills\" the slot with the specified content.

Let's look at an example:

First, we define the component template. This component contains two slots, header and body.

<!-- calendar.html -->\n<div class=\"calendar-component\">\n    <div class=\"header\">\n        {% slot \"header\" %}\n            Calendar header\n        {% endslot %}\n    </div>\n    <div class=\"body\">\n        {% slot \"body\" %}\n            Today's date is <span>{{ date }}</span>\n        {% endslot %}\n    </div>\n</div>\n

Next, when using the component, we can insert our own content into the slots. It looks like this:

{% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"body\" %}\n        Can you believe it's already\n        <span>{{ date }}</span>??\n    {% endfill %}\n{% endcomponent %}\n

Since the 'header' fill is unspecified, it's default value is used.

When rendered, notice that:

  • The body is filled with the content we specified,
  • The header is still the default value we defined in the component template.
<div class=\"calendar-component\">\n    <div class=\"header\">\n        Calendar header\n    </div>\n    <div class=\"body\">\n        Can you believe it's already <span>2020-06-06</span>??\n    </div>\n</div>\n
"},{"location":"concepts/fundamentals/slots/#slots-overview","title":"Slots overview","text":""},{"location":"concepts/fundamentals/slots/#slot-definition","title":"Slot definition","text":"

Slots are defined with the {% slot %} tag:

{% slot \"name\" %}\n    Default content\n{% endslot %}\n

Single component can have multiple slots:

{% slot \"name\" %}\n    Default content\n{% endslot %}\n\n{% slot \"other_name\" / %}\n

And you can even define the same slot in multiple places:

<div>\n    {% slot \"name\" %}\n        First content\n    {% endslot %}\n</div>\n<div>\n    {% slot \"name\" %}\n        Second content\n    {% endslot %}\n</div>\n

Info

If you define the same slot in multiple places, you must mark each slot individually when setting default or required flags, e.g.:

<div class=\"calendar-component\">\n    <div class=\"header\">\n        {% slot \"image\" default required %}Image here{% endslot %}\n    </div>\n    <div class=\"body\">\n        {% slot \"image\" default required %}Image here{% endslot %}\n    </div>\n</div>\n
"},{"location":"concepts/fundamentals/slots/#slot-filling","title":"Slot filling","text":"

Fill can be defined with the {% fill %} tag:

{% component \"calendar\" %}\n    {% fill \"name\" %}\n        Filled content\n    {% endfill %}\n    {% fill \"other_name\" %}\n        Filled content\n    {% endfill %}\n{% endcomponent %}\n

Or in Python with the slots argument:

Calendar.render(\n    slots={\n        \"name\": \"Filled content\",\n        \"other_name\": \"Filled content\",\n    },\n)\n
"},{"location":"concepts/fundamentals/slots/#default-slot","title":"Default slot","text":"

You can make the syntax shorter by marking the slot as default:

{% slot \"name\" default %}\n    Default content\n{% endslot %}\n

This allows you to fill the slot directly in the {% component %} tag, omitting the {% fill %} tag:

{% component \"calendar\" %}\n    Filled content\n{% endcomponent %}\n

To target the default slot in Python, you can use the \"default\" slot name:

Calendar.render(\n    slots={\"default\": \"Filled content\"},\n)\n

Accessing default slot in Python

Since the default slot is stored under the slot name default, you can access the default slot in Python under the \"default\" key:

class MyTable(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        default_slot = slots[\"default\"]\n        return {\n            \"default_slot\": default_slot,\n        }\n

Warning

Only one {% slot %} can be marked as default. But you can have multiple slots with the same name all marked as default.

If you define multiple different slots as default, this will raise an error.

\u274c Don't do this

{% slot \"name\" default %}\n    Default content\n{% endslot %}\n{% slot \"other_name\" default %}\n    Default content\n{% endslot %}\n

\u2705 Do this instead

{% slot \"name\" default %}\n    Default content\n{% endslot %}\n{% slot \"name\" default %}\n    Default content\n{% endslot %}\n

Warning

Do NOT combine default fills with explicit named {% fill %} tags.

The following component template will raise an error when rendered:

\u274c Don't do this

{% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"header\" %}Totally new header!{% endfill %}\n    Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n

\u2705 Do this instead

{% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"header\" %}Totally new header!{% endfill %}\n    {% fill \"default\" %}\n        Can you believe it's already <span>{{ date }}</span>??\n    {% endfill %}\n{% endcomponent %}\n

Warning

You cannot double-fill a slot.

That is, if both {% fill \"default\" %} and {% fill \"header\" %} point to the same slot, this will raise an error when rendered.

"},{"location":"concepts/fundamentals/slots/#required-slot","title":"Required slot","text":"

You can make the slot required by adding the required keyword:

{% slot \"name\" required %}\n    Default content\n{% endslot %}\n

This will raise an error if the slot is not filled.

"},{"location":"concepts/fundamentals/slots/#access-fills","title":"Access fills","text":"

You can access the fills with the {{ component_vars.slots.<name> }} template variable:

{% if component_vars.slots.my_slot %}\n    <div>\n        {% fill \"my_slot\" %}\n            Filled content\n        {% endfill %}\n    </div>\n{% endif %}\n

And in Python with the Component.slots property:

class Calendar(Component):\n    # `get_template_data` receives the `slots` argument directly\n    def get_template_data(self, args, kwargs, slots, context):\n        if \"my_slot\" in slots:\n            content = \"Filled content\"\n        else:\n            content = \"Default content\"\n\n        return {\n            \"my_slot\": content,\n        }\n\n    # In other methods you can still access the slots with `Component.slots`\n    def on_render_before(self, context, template):\n        if \"my_slot\" in self.slots:\n            # Do something\n
"},{"location":"concepts/fundamentals/slots/#dynamic-fills","title":"Dynamic fills","text":"

The slot and fill names can be set as variables. This way you can fill slots dynamically:

{% with \"body\" as slot_name %}\n    {% component \"calendar\" %}\n        {% fill slot_name %}\n            Filled content\n        {% endfill %}\n    {% endcomponent %}\n{% endwith %}\n

You can even use {% if %} and {% for %} tags inside the {% component %} tag to fill slots with more control:

{% component \"calendar\" %}\n    {% if condition %}\n        {% fill \"name\" %}\n            Filled content\n        {% endfill %}\n    {% endif %}\n\n    {% for item in items %}\n        {% fill item.name %}\n            Item: {{ item.value }}\n        {% endfill %}\n    {% endfor %}\n{% endcomponent %}\n

You can also use {% with %} or even custom tags to generate the fills dynamically:

{% component \"calendar\" %}\n    {% with item.name as name %}\n        {% fill name %}\n            Item: {{ item.value }}\n        {% endfill %}\n    {% endwith %}\n{% endcomponent %}\n

Warning

If you dynamically generate {% fill %} tags, be careful to render text only inside the {% fill %} tags.

Any text rendered outside {% fill %} tags will be considered a default fill and will raise an error if combined with explicit fills. (See Default slot)

"},{"location":"concepts/fundamentals/slots/#slot-data","title":"Slot data","text":"

Sometimes the slots need to access data from the component. Imagine an HTML table component which has a slot to configure how to render the rows. Each row has a different data, so you need to pass the data to the slot.

Similarly to Vue's scoped slots, you can pass data to the slot, and then access it in the fill.

This consists of two steps:

  1. Passing data to {% slot %} tag
  2. Accessing data in {% fill %} tag

The data is passed to the slot as extra keyword arguments. Below we set two extra arguments: first_name and job.

{# Pass data to the slot #}\n{% slot \"name\" first_name=\"John\" job=\"Developer\" %}\n    {# Fallback implementation #}\n    Name: {{ first_name }}\n    Job: {{ job }}\n{% endslot %}\n

Note

name kwarg is already used for slot name, so you cannot pass it as slot data.

To access the slot's data in the fill, use the data keyword. This sets the name of the variable that holds the data in the fill:

{# Access data in the fill #}\n{% component \"profile\" %}\n    {% fill \"name\" data=\"d\" %}\n        Hello, my name is <h1>{{ d.first_name }}</h1>\n        and I'm a <h2>{{ d.job }}</h2>\n    {% endfill %}\n{% endcomponent %}\n

To access the slot data in Python, use the data attribute in slot functions.

def my_slot(ctx):\n    return f\"\"\"\n        Hello, my name is <h1>{ctx.data[\"first_name\"]}</h1>\n        and I'm a <h2>{ctx.data[\"job\"]}</h2>\n    \"\"\"\n\nProfile.render(\n    slots={\n        \"name\": my_slot,\n    },\n)\n

Slot data can be set also when rendering a slot in Python:

slot = Slot(lambda ctx: f\"Hello, {ctx.data['name']}!\")\n\n# Render the slot\nhtml = slot({\"name\": \"John\"})\n

Info

To access slot data on a default slot, you have to explictly define the {% fill %} tags with name \"default\".

{% component \"my_comp\" %}\n    {% fill \"default\" data=\"slot_data\" %}\n        {{ slot_data.input }}\n    {% endfill %}\n{% endcomponent %}\n

Warning

You cannot set the data attribute and fallback attribute to the same name. This raises an error:

{% component \"my_comp\" %}\n    {% fill \"content\" data=\"slot_var\" fallback=\"slot_var\" %}\n        {{ slot_var.input }}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"concepts/fundamentals/slots/#slot-fallback","title":"Slot fallback","text":"

The content between the {% slot %}..{% endslot %} tags is the fallback content that will be rendered if no fill is given for the slot.

{% slot \"name\" %}\n    Hello, my name is {{ name }}  <!-- Fallback content -->\n{% endslot %}\n

Sometimes you may want to keep the fallback content, but only wrap it in some other content.

To do so, you can access the fallback content via the fallback kwarg. This sets the name of the variable that holds the fallback content in the fill:

{% component \"profile\" %}\n    {% fill \"name\" fallback=\"fb\" %}\n        Original content:\n        <div>\n            {{ fb }}  <!-- fb = 'Hello, my name...' -->\n        </div>\n    {% endfill %}\n{% endcomponent %}\n

To access the fallback content in Python, use the fallback attribute in slot functions.

The fallback value is rendered lazily. Coerce the fallback to a string to render it.

def my_slot(ctx):\n    # Coerce the fallback to a string\n    fallback = str(ctx.fallback)\n    return f\"Original content: \" + fallback\n\nProfile.render(\n    slots={\n        \"name\": my_slot,\n    },\n)\n

Fallback can be set also when rendering a slot in Python:

slot = Slot(lambda ctx: f\"Hello, {ctx.data['name']}!\")\n\n# Render the slot\nhtml = slot({\"name\": \"John\"}, fallback=\"Hello, world!\")\n

Info

To access slot fallback on a default slot, you have to explictly define the {% fill %} tags with name \"default\".

{% component \"my_comp\" %}\n    {% fill \"default\" fallback=\"fallback\" %}\n        {{ fallback }}\n    {% endfill %}\n{% endcomponent %}\n

Warning

You cannot set the data attribute and fallback attribute to the same name. This raises an error:

{% component \"my_comp\" %}\n    {% fill \"content\" data=\"slot_var\" fallback=\"slot_var\" %}\n        {{ slot_var.input }}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"concepts/fundamentals/slots/#slot-functions","title":"Slot functions","text":"

In Python code, slot fills can be defined as strings, functions, or Slot instances that wrap the two. Slot functions have access to slot data, fallback, and context.

def row_slot(ctx):\n    if ctx.data[\"disabled\"]:\n        return ctx.fallback\n\n    item = ctx.data[\"item\"]\n    if ctx.data[\"type\"] == \"table\":\n        return f\"<tr><td>{item}</td></tr>\"\n    else:\n        return f\"<li>{item}</li>\"\n\nTable.render(\n    slots={\n        \"prepend\": \"Ice cream selection:\",\n        \"append\": Slot(\"\u00a9 2025\"),\n        \"row\": row_slot,\n        \"column_title\": Slot(lambda ctx: f\"<th>{ctx.data['name']}</th>\"),\n    },\n)\n

Inside the component, these will all be normalized to Slot instances:

class Table(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        assert isinstance(slots[\"prepend\"], Slot)\n        assert isinstance(slots[\"row\"], Slot)\n        assert isinstance(slots[\"header\"], Slot)\n        assert isinstance(slots[\"footer\"], Slot)\n

You can render Slot instances by simply calling them with data:

class Table(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        prepend_slot = slots[\"prepend\"]\n        return {\n            \"prepend\": prepend_slot({\"item\": \"ice cream\"}),\n        }\n
"},{"location":"concepts/fundamentals/slots/#filling-slots-with-functions","title":"Filling slots with functions","text":"

You can \"fill\" slots by passing a string or Slot instance directly to the {% fill %} tag:

class Table(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        def my_fill(ctx):\n            return f\"Hello, {ctx.data['name']}!\"\n\n        return {\n            \"my_fill\": Slot(my_fill),\n        }\n
{% component \"table\" %}\n    {% fill \"name\" body=my_fill / %}\n{% endcomponent %}\n

Note

Django automatically executes functions when it comes across them in templates.

Because of this you MUST wrap the function in Slot instance to prevent it from being called.

Read more about Django's do_not_call_in_templates.

"},{"location":"concepts/fundamentals/slots/#slot-class","title":"Slot class","text":"

The Slot class is a wrapper around a function that can be used to fill a slot.

from django_components import Component, Slot\n\ndef footer(ctx):\n    return f\"Hello, {ctx.data['name']}!\"\n\nTable.render(\n    slots={\n        \"footer\": Slot(footer),\n    },\n)\n

Slot class can be instantiated with a function or a string:

slot1 = Slot(lambda ctx: f\"Hello, {ctx.data['name']}!\")\nslot2 = Slot(\"Hello, world!\")\n

Warning

Passing a Slot instance to the Slot constructor results in an error:

slot = Slot(\"Hello\")\n\n# Raises an error\nslot2 = Slot(slot)\n
"},{"location":"concepts/fundamentals/slots/#rendering-slots","title":"Rendering slots","text":"

Python

You can render a Slot instance by simply calling it with data:

slot = Slot(lambda ctx: f\"Hello, {ctx.data['name']}!\")\n\n# Render the slot with data\nhtml = slot({\"name\": \"John\"})\n

Optionally you can pass the fallback value to the slot. Fallback should be a string.

html = slot({\"name\": \"John\"}, fallback=\"Hello, world!\")\n

Template

Alternatively, you can pass the Slot instance to the {% fill %} tag:

{% fill \"name\" body=slot / %}\n
"},{"location":"concepts/fundamentals/slots/#slot-context","title":"Slot context","text":"

If a slot function is rendered by the {% slot %} tag, you can access the current Context using the context attribute.

class Table(Component):\n    template = \"\"\"\n        {% with \"abc\" as my_var %}\n            {% slot \"name\" %}\n                Hello!\n            {% endslot %}\n        {% endwith %}\n    \"\"\"\n\ndef slot_func(ctx):\n    return f\"Hello, {ctx.context['my_var']}!\"\n\nslot = Slot(slot_func)\nhtml = slot()\n

Warning

While available, try to avoid using the context attribute in slot functions.

Instead, prefer using the data and fallback attributes.

Access to context may be removed in future versions (v2, v3).

"},{"location":"concepts/fundamentals/slots/#slot-metadata","title":"Slot metadata","text":"

When accessing slots from within Component methods, the Slot instances are populated with extra metadata:

  • component_name
  • slot_name
  • nodelist
  • fill_node
  • extra

These are populated the first time a slot is passed to a component.

So if you pass the same slot through multiple nested components, the metadata will still point to the first component that received the slot.

You can use these for debugging, such as printing out the slot's component name and slot name.

Fill node

Components or extensions can use Slot.fill_node to handle slots differently based on whether the slot was defined in the template with {% fill %} and {% component %} tags, or in the component's Python code.

If the slot was created from a {% fill %} tag, this will be the FillNode instance.

If the slot was a default slot created from a {% component %} tag, this will be the ComponentNode instance.

You can use this to find the Component in whose template the {% fill %} tag was defined:

class MyTable(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        footer_slot = slots.get(\"footer\")\n        if footer_slot is not None and footer_slot.fill_node is not None:\n            owner_component = footer_slot.fill_node.template_component\n            # ...\n

Extra

You can also pass any additional data along with the slot by setting it in Slot.extra:

slot = Slot(\n    lambda ctx: f\"Hello, {ctx.data['name']}!\",\n    extra={\"foo\": \"bar\"},\n)\n

When you create a slot, you can set any of these fields too:

# Either at slot creation\nslot = Slot(\n    lambda ctx: f\"Hello, {ctx.data['name']}!\",\n    # Optional\n    component_name=\"table\",\n    slot_name=\"name\",\n    extra={},\n)\n\n# Or later\nslot.component_name = \"table\"\nslot.slot_name = \"name\"\nslot.extra[\"foo\"] = \"bar\"\n

Read more in Pass slot metadata.

"},{"location":"concepts/fundamentals/slots/#slot-contents","title":"Slot contents","text":"

Whether you create a slot from a function, a string, or from the {% fill %} tags, the Slot class normalizes its contents to a function.

Use Slot.contents to access the original value that was passed to the Slot constructor.

slot = Slot(\"Hello!\")\nprint(slot.contents)  # \"Hello!\"\n

If the slot was created from a string or from the {% fill %} tags, the contents will be accessible also as a Nodelist under Slot.nodelist.

slot = Slot(\"Hello!\")\nprint(slot.nodelist)  # <django.template.Nodelist: ['Hello!']>\n
"},{"location":"concepts/fundamentals/slots/#escaping-slots-content","title":"Escaping slots content","text":"

Slots content are automatically escaped by default to prevent XSS attacks.

In other words, it's as if you would be using Django's escape() on the slot contents / result:

from django.utils.html import escape\n\nclass Calendar(Component):\n    template = \"\"\"\n        <div>\n            {% slot \"date\" default date=date / %}\n        </div>\n    \"\"\"\n\nCalendar.render(\n    slots={\n        \"date\": escape(\"<b>Hello</b>\"),\n    }\n)\n

To disable escaping, you can wrap the slot string or slot result in Django's mark_safe():

Calendar.render(\n    slots={\n        # string\n        \"date\": mark_safe(\"<b>Hello</b>\"),\n\n        # function\n        \"date\": lambda ctx: mark_safe(\"<b>Hello</b>\"),\n    }\n)\n

Info

Read more about Django's format_html and mark_safe.

"},{"location":"concepts/fundamentals/slots/#examples","title":"Examples","text":""},{"location":"concepts/fundamentals/slots/#pass-through-all-the-slots","title":"Pass through all the slots","text":"

You can dynamically pass all slots to a child component. This is similar to passing all slots in Vue:

class MyTable(Component):\n    template = \"\"\"\n        <div>\n          {% component \"child\" %}\n            {% for slot_name, slot in component_vars.slots.items %}\n              {% fill name=slot_name body=slot / %}\n            {% endfor %}\n          {% endcomponent %}\n        </div>\n    \"\"\"\n
"},{"location":"concepts/fundamentals/slots/#required-and-default-slots","title":"Required and default slots","text":"

Since each {% slot %} is tagged with required and default individually, you can have multiple slots with the same name but different conditions.

In this example, we have a component that renders a user avatar - a small circular image with a profile picture or name initials.

If the component is given image_src or name_initials variables, the image slot is optional.

But if neither of those are provided, you MUST fill the image slot.

<div class=\"avatar\">\n    {# Image given, so slot is optional #}\n    {% if image_src %}\n        {% slot \"image\" default %}\n            <img src=\"{{ image_src }}\" />\n        {% endslot %}\n\n    {# Image not given, but we can make image from initials, so slot is optional #}    \n    {% elif name_initials %}\n        {% slot \"image\" default %}\n            <div style=\"\n                border-radius: 25px;\n                width: 50px;\n                height: 50px;\n                background: blue;\n            \">\n                {{ name_initials }}\n            </div>\n        {% endslot %}\n\n    {# Neither image nor initials given, so slot is required #}\n    {% else %}\n        {% slot \"image\" default required / %}\n    {% endif %}\n</div>\n
"},{"location":"concepts/fundamentals/slots/#dynamic-slots-in-table-component","title":"Dynamic slots in table component","text":"

Sometimes you may want to generate slots based on the given input. One example of this is Vuetify's table component, which creates a header and an item slots for each user-defined column.

So if you pass columns named name and age to the table component:

[\n    {\"key\": \"name\", \"title\": \"Name\"},\n    {\"key\": \"age\", \"title\": \"Age\"},\n]\n

Then the component will accept fills named header-name and header-age (among others):

{% fill \"header-name\" data=\"data\" %}\n    <b>{{ data.value }}</b>\n{% endfill %}\n\n{% fill \"header-age\" data=\"data\" %}\n    <b>{{ data.value }}</b>\n{% endfill %}\n

In django-components you can achieve the same, simply by using a variable or a template expression instead of a string literal:

<table>\n  <tr>\n    {% for header in headers %}\n      <th>\n        {% slot \"header-{{ header.key }}\" value=header.title %}\n          {{ header.title }}\n        {% endslot %}\n      </th>\n    {% endfor %}\n  </tr>\n</table>\n

When using the component, you can either set the fill explicitly:

{% component \"table\" headers=headers items=items %}\n    {% fill \"header-name\" data=\"data\" %}\n        <b>{{ data.value }}</b>\n    {% endfill %}\n{% endcomponent %}\n

Or also use a variable:

{% component \"table\" headers=headers items=items %}\n    {% fill \"header-{{ active_header_name }}\" data=\"data\" %}\n        <b>{{ data.value }}</b>\n    {% endfill %}\n{% endcomponent %}\n

Note

It's better to use literal slot names whenever possible for clarity. The dynamic slot names should be reserved for advanced use only.

"},{"location":"concepts/fundamentals/slots/#spread-operator","title":"Spread operator","text":"

Lastly, you can also pass the slot name through the spread operator.

When you define a slot name, it's actually a shortcut for a name keyword argument.

So this:

{% slot \"content\" / %}\n

is the same as:

{% slot name=\"content\" / %}\n

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

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

Full example:

class MyTable(Component):\n    template = \"\"\"\n        {% slot ...slot_props / %}\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"slot_props\": {\"name\": \"content\", \"extra_field\": 123},\n        }\n

Info

This applies for both {% slot %} and {% fill %} tags.

"},{"location":"concepts/fundamentals/slots/#legacy-conditional-slots","title":"Legacy conditional slots","text":"

Since version 0.70, you could check if a slot was filled with

{{ component_vars.is_filled.<name> }}

Since version 0.140, this has been deprecated and superseded with

{% component_vars.slots.<name> %}

The component_vars.is_filled variable is still available, but will be removed in v1.0.

NOTE: component_vars.slots no longer escapes special characters in slot names.

You can use {{ component_vars.is_filled.<name> }} 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\">\n    <div class=\"title\">\n        {% slot \"title\" %}\n            Title\n        {% endslot %}\n    </div>\n    {% if component_vars.is_filled.subtitle %}\n        <div class=\"subtitle\">\n            {% slot \"subtitle\" %}\n                {# Optional subtitle #}\n            {% endslot %}\n        </div>\n    {% elif component_vars.is_filled.title %}\n        ...\n    {% elif component_vars.is_filled.<name> %}\n        ...\n    {% endif %}\n</div>\n
"},{"location":"concepts/fundamentals/slots/#accessing-is_filled-of-slot-names-with-special-characters","title":"Accessing is_filled of slot names with special characters","text":"

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

Same applies when you are accessing is_filled from within the Python, e.g.:

class MyTable(Component):\n    def on_render_before(self, context, template) -> None:\n        # \u2705 Works\n        if self.is_filled[\"my_super_slot___\"]:\n            # Do something\n\n        # \u274c Does not work\n        if self.is_filled[\"my super-slot :)\"]:\n            # Do something\n
"},{"location":"concepts/fundamentals/subclassing_components/","title":"Subclassing components","text":"

In larger projects, you might need to write multiple components with similar behavior. In such cases, you can extract shared behavior into a standalone component class to keep things DRY.

When subclassing a component, there's a couple of things to keep in mind:

"},{"location":"concepts/fundamentals/subclassing_components/#template-js-and-css-inheritance","title":"Template, JS, and CSS inheritance","text":"

When it comes to the pairs:

  • Component.template/Component.template_file
  • Component.js/Component.js_file
  • Component.css/Component.css_file

inheritance follows these rules:

  • If a child component class defines either member of a pair (e.g., either template or template_file), it takes precedence and the parent's definition is ignored completely.
  • For example, if a child component defines template_file, the parent's template or template_file will be ignored.
  • This applies independently to each pair - you can inherit the JS while overriding the template, for instance.

For example:

class BaseCard(Component):\n    template = \"\"\"\n        <div class=\"card\">\n            <div class=\"card-content\">{{ content }}</div>\n        </div>\n    \"\"\"\n    css = \"\"\"\n        .card {\n            border: 1px solid gray;\n        }\n    \"\"\"\n    js = \"\"\"console.log('Base card loaded');\"\"\"\n\n# This class overrides parent's template, but inherits CSS and JS\nclass SpecialCard(BaseCard):\n    template = \"\"\"\n        <div class=\"card special\">\n            <div class=\"card-content\">\u2728 {{ content }} \u2728</div>\n        </div>\n    \"\"\"\n\n# This class overrides parent's template and CSS, but inherits JS\nclass CustomCard(BaseCard):\n    template_file = \"custom_card.html\"\n    css = \"\"\"\n        .card {\n            border: 2px solid gold;\n        }\n    \"\"\"\n
"},{"location":"concepts/fundamentals/subclassing_components/#media-inheritance","title":"Media inheritance","text":"

The Component.Media nested class follows Django's media inheritance rules:

  • If both parent and child define a Media class, the child's media will automatically include both its own and the parent's JS and CSS files.
  • This behavior can be configured using the extend attribute in the Media class, similar to Django's forms. Read more on this in Media inheritance.

For example:

class BaseModal(Component):\n    template = \"<div>Modal content</div>\"\n\n    class Media:\n        css = [\"base_modal.css\"]\n        js = [\"base_modal.js\"]  # Contains core modal functionality\n\nclass FancyModal(BaseModal):\n    class Media:\n        # Will include both base_modal.css/js AND fancy_modal.css/js\n        css = [\"fancy_modal.css\"]  # Additional styling\n        js = [\"fancy_modal.js\"]    # Additional animations\n\nclass SimpleModal(BaseModal):\n    class Media:\n        extend = False  # Don't inherit parent's media\n        css = [\"simple_modal.css\"]  # Only this CSS will be included\n        js = [\"simple_modal.js\"]    # Only this JS will be included\n
"},{"location":"concepts/fundamentals/subclassing_components/#opt-out-of-inheritance","title":"Opt out of inheritance","text":"

For the following media attributes, when you don't want to inherit from the parent, but you also don't need to set the template / JS / CSS to any specific value, you can set these attributes to None.

  • template / template_file
  • js / js_file
  • css / css_file
  • Media class

For example:

class BaseForm(Component):\n    template = \"...\"\n    css = \"...\"\n    js = \"...\"\n\n    class Media:\n        js = [\"form.js\"]\n\n# Use parent's template and CSS, but no JS\nclass ContactForm(BaseForm):\n    js = None\n    Media = None\n
"},{"location":"concepts/fundamentals/subclassing_components/#regular-python-inheritance","title":"Regular Python inheritance","text":"

All other attributes and methods (including the Component.View class and its methods) follow standard Python inheritance rules.

For example:

class BaseForm(Component):\n    template = \"\"\"\n        <form>\n            {{ form_content }}\n            <button type=\"submit\">\n                {{ submit_text }}\n            </button>\n        </form>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"form_content\": self.get_form_content(),\n            \"submit_text\": \"Submit\"\n        }\n\n    def get_form_content(self):\n        return \"<input type='text' name='data'>\"\n\nclass ContactForm(BaseForm):\n    # Extend parent's \"context\"\n    # but override \"submit_text\"\n    def get_template_data(self, args, kwargs, slots, context):\n        context = super().get_template_data(args, kwargs, slots, context)\n        context[\"submit_text\"] = \"Send Message\"  \n        return context\n\n    # Completely override parent's get_form_content\n    def get_form_content(self):\n        return \"\"\"\n            <input type='text' name='name' placeholder='Your Name'>\n            <input type='email' name='email' placeholder='Your Email'>\n            <textarea name='message' placeholder='Your Message'></textarea>\n        \"\"\"\n
"},{"location":"concepts/fundamentals/template_tag_syntax/","title":"Template tag syntax","text":"

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

"},{"location":"concepts/fundamentals/template_tag_syntax/#self-closing-tags","title":"Self-closing tags","text":"

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

becomes

{% component \"button\" / %}\n
"},{"location":"concepts/fundamentals/template_tag_syntax/#special-characters","title":"Special characters","text":"

New in version 0.71:

Keyword arguments can contain special characters # @ . - _, so keywords like so are still valid:

<body>\n    {% component \"calendar\" my-date=\"2015-06-19\" @click.native=do_something #some_id=True / %}\n</body>\n

These can then be accessed inside get_template_data so:

@register(\"calendar\")\nclass Calendar(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"my-date\"],\n            \"id\": kwargs[\"#some_id\"],\n            \"on_click\": kwargs[\"@click.native\"]\n        }\n
"},{"location":"concepts/fundamentals/template_tag_syntax/#spread-operator","title":"Spread operator","text":"

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\" / %}\n

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

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

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

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

"},{"location":"concepts/fundamentals/template_tag_syntax/#template-tags-inside-literal-strings","title":"Template tags inside literal strings","text":"

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_template_data(). But this can get messy if your components contain a lot of logic.

@register(\"calendar\")\nclass Calendar(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"editable\": kwargs[\"editable\"],\n            \"readonly\": not kwargs[\"editable\"],\n            \"input_id\": f\"input-{kwargs['id']}\",\n            \"icon_id\": f\"icon-{kwargs['id']}\",\n            ...\n        }\n

Instead, template tags in django_components ({% component %}, {% slot %}, {% provide %}, etc) allow you to treat literal string values as templates:

{% component 'blog_post'\n  \"As positional arg {# yay #}\"\n  title=\"{{ person.first_name }} {{ person.last_name }}\"\n  id=\"{% random_int 10 20 %}\"\n  readonly=\"{{ editable|not }}\"\n  author=\"John Wick {# TODO: parametrize #}\"\n/ %}\n

In the example above, the component receives:

  • Positional argument \"As positional arg \" (Comment omitted)
  • title - passed as str, e.g. John Doe
  • id - passed as int, e.g. 15
  • readonly - passed as bool, e.g. False
  • author - passed as str, e.g. John Wick (Comment omitted)

This is inspired by django-cotton.

"},{"location":"concepts/fundamentals/template_tag_syntax/#passing-data-as-string-vs-original-values","title":"Passing data as string vs original values","text":"

In the example above, the kwarg id was passed as an integer, NOT a string.

When the string literal contains only a single template tag, with no extra text (and no extra whitespace), 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 %}\" / %}\n

Here, page is a string:

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

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

Here, items is a list:

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

Here, items is a string:

{% component 'cat_list' items=\"{{ cats|slice:':2' }} See more\" / %}\n
"},{"location":"concepts/fundamentals/template_tag_syntax/#evaluating-python-expressions-in-template","title":"Evaluating Python expressions in template","text":"

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} />\n

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\"\n  value=\"{% expr 'input_value if is_enabled else None' %}\"\n/ %}\n

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

"},{"location":"concepts/fundamentals/template_tag_syntax/#pass-dictonary-by-its-key-value-pairs","title":"Pass dictonary by its key-value pairs","text":"

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\")\nclass MyComp(Component):\n    template = \"\"\"\n        {% component \"other\" attrs=attrs / %}\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        attrs = {\n            \"class\": \"pa-4 flex\",\n            \"data-some-id\": kwargs[\"some_id\"],\n            \"@click.stop\": \"onClickHandler\",\n        }\n        return {\"attrs\": attrs}\n

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\")\nclass MyComp(Component):\n    template = \"\"\"\n        {% component \"other\"\n            attrs:class=\"pa-4 flex\"\n            attrs:data-some-id=some_id\n            attrs:@click.stop=\"onClickHandler\"\n        / %}\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\"some_id\": kwargs[\"some_id\"]}\n

Sweet! Now all the relevant HTML is inside the template, and we can move it to a separate file with confidence:

{% component \"other\"\n    attrs:class=\"pa-4 flex\"\n    attrs:data-some-id=some_id\n    attrs:@click.stop=\"onClickHandler\"\n/ %}\n

Note: It is NOT possible to define nested dictionaries, so attrs:my_key:two=2 would be interpreted as:

{\"attrs\": {\"my_key:two\": 2}}\n
"},{"location":"concepts/fundamentals/template_tag_syntax/#multiline-tags","title":"Multiline tags","text":"

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

Instead, when you install django_components, it automatically configures Django to suport multi-line tags.

So we can rewrite the above as:

{% component \"card\"\n    title=\"Joanne Arc\"\n    subtitle=\"Head of Kitty Relations\"\n    date_last_active=\"2024-09-03\"\n    ...\n%}\n

Much better!

To disable this behavior, set COMPONENTS.multiline_tag to False

"},{"location":"concepts/fundamentals/typing_and_validation/","title":"Typing and validation","text":""},{"location":"concepts/fundamentals/typing_and_validation/#typing-overview","title":"Typing overview","text":"

Warning

In versions 0.92 to 0.139 (inclusive), the component typing was specified through generics.

Since v0.140, the types must be specified as class attributes of the Component class - Args, Kwargs, Slots, TemplateData, JsData, and CssData.

See Migrating from generics to class attributes for more info.

Warning

Input validation was NOT part of Django Components between versions 0.136 and 0.139 (inclusive).

The Component class optionally accepts class attributes that allow you to define the types of args, kwargs, slots, as well as the data returned from the data methods.

Use this to add type hints to your components, to validate the inputs at runtime, and to document them.

from typing import NamedTuple, Optional\nfrom django.template import Context\nfrom django_components import Component, SlotInput\n\nclass Button(Component):\n    class Args(NamedTuple):\n        size: int\n        text: str\n\n    class Kwargs(NamedTuple):\n        variable: str\n        maybe_var: Optional[int] = None  # May be omitted\n\n    class Slots(NamedTuple):\n        my_slot: Optional[SlotInput] = None\n\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        ...\n\n    template_file = \"button.html\"\n

The class attributes are:

  • Args - Type for positional arguments.
  • Kwargs - Type for keyword arguments.
  • Slots - Type for slots.
  • TemplateData - Type for data returned from get_template_data().
  • JsData - Type for data returned from get_js_data().
  • CssData - Type for data returned from get_css_data().

You can specify as many or as few of these as you want, the rest will default to None.

"},{"location":"concepts/fundamentals/typing_and_validation/#typing-inputs","title":"Typing inputs","text":"

You can use Component.Args, Component.Kwargs, and Component.Slots to type the component inputs.

When you set these classes, at render time the args, kwargs, and slots parameters of the data methods (get_template_data(), get_js_data(), get_css_data()) will be instances of these classes.

This way, each component can have runtime validation of the inputs:

  • When you use NamedTuple or @dataclass, instantiating these classes will check ONLY for the presence of the attributes.
  • When you use Pydantic models, instantiating these classes will check for the presence AND type of the attributes.

If you omit the Args, Kwargs, or Slots classes, or set them to None, the inputs will be passed as plain lists or dictionaries, and will not be validated.

from typing_extensions import NamedTuple, TypedDict\nfrom django.template import Context\nfrom django_components import Component, Slot, SlotInput\n\n# The data available to the `footer` scoped slot\nclass ButtonFooterSlotData(TypedDict):\n    value: int\n\n# Define the component with the types\nclass Button(Component):\n    class Args(NamedTuple):\n        name: str\n\n    class Kwargs(NamedTuple):\n        surname: str\n        age: int\n        maybe_var: Optional[int] = None  # May be omitted\n\n    class Slots(NamedTuple):\n        # Use `SlotInput` to allow slots to be given as `Slot` instance,\n        # plain string, or a function that returns a string.\n        my_slot: Optional[SlotInput] = None\n        # Use `Slot` to allow ONLY `Slot` instances.\n        # The generic is optional, and it specifies the data available\n        # to the slot function.\n        footer: Slot[ButtonFooterSlotData]\n\n    # Add type hints to the data method\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        # The parameters are instances of the classes we defined\n        assert isinstance(args, Button.Args)\n        assert isinstance(kwargs, Button.Kwargs)\n        assert isinstance(slots, Button.Slots)\n\n        args.name  # str\n        kwargs.age  # int\n        slots.footer  # Slot[ButtonFooterSlotData]\n\n# Add type hints to the render call\nButton.render(\n    args=Button.Args(\n        name=\"John\",\n    ),\n    kwargs=Button.Kwargs(\n        surname=\"Doe\",\n        age=30,\n    ),\n    slots=Button.Slots(\n        footer=Slot(lambda ctx: \"Click me!\"),\n    ),\n)\n

If you don't want to validate some parts, set them to None or omit them.

The following will validate only the keyword inputs:

class Button(Component):\n    # We could also omit these\n    Args = None\n    Slots = None\n\n    class Kwargs(NamedTuple):\n        name: str\n        age: int\n\n    # Only `kwargs` is instantiated. `args` and `slots` are not.\n    def get_template_data(self, args, kwargs: Kwargs, slots, context: Context):\n        assert isinstance(args, list)\n        assert isinstance(slots, dict)\n        assert isinstance(kwargs, Button.Kwargs)\n\n        args[0]  # str\n        slots[\"footer\"]  # Slot[ButtonFooterSlotData]\n        kwargs.age  # int\n

Info

Components can receive slots as strings, functions, or instances of Slot.

Internally these are all normalized to instances of Slot.

Therefore, the slots dictionary available in data methods (like get_template_data()) will always be a dictionary of Slot instances.

To correctly type this dictionary, you should set the fields of Slots to Slot or SlotInput:

SlotInput is a union of Slot, string, and function types.

"},{"location":"concepts/fundamentals/typing_and_validation/#typing-data","title":"Typing data","text":"

You can use Component.TemplateData, Component.JsData, and Component.CssData to type the data returned from get_template_data(), get_js_data(), and get_css_data().

When you set these classes, at render time they will be instantiated with the data returned from these methods.

This way, each component can have runtime validation of the returned data:

  • When you use NamedTuple or @dataclass, instantiating these classes will check ONLY for the presence of the attributes.
  • When you use Pydantic models, instantiating these classes will check for the presence AND type of the attributes.

If you omit the TemplateData, JsData, or CssData classes, or set them to None, the validation and instantiation will be skipped.

from typing import NamedTuple\nfrom django_components import Component\n\nclass Button(Component):\n    class TemplateData(NamedTuple):\n        data1: str\n        data2: int\n\n    class JsData(NamedTuple):\n        js_data1: str\n        js_data2: int\n\n    class CssData(NamedTuple):\n        css_data1: str\n        css_data2: int\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"data1\": \"...\",\n            \"data2\": 123,\n        }\n\n    def get_js_data(self, args, kwargs, slots, context):\n        return {\n            \"js_data1\": \"...\",\n            \"js_data2\": 123,\n        }\n\n    def get_css_data(self, args, kwargs, slots, context):\n        return {\n            \"css_data1\": \"...\",\n            \"css_data2\": 123,\n        }\n

For each data method, you can either return a plain dictionary with the data, or an instance of the respective data class directly.

from typing import NamedTuple\nfrom django_components import Component\n\nclass Button(Component):\n    class TemplateData(NamedTuple):\n        data1: str\n        data2: int\n\n    class JsData(NamedTuple):\n        js_data1: str\n        js_data2: int\n\n    class CssData(NamedTuple):\n        css_data1: str\n        css_data2: int\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return Button.TemplateData(\n            data1=\"...\",\n            data2=123,\n        )\n\n    def get_js_data(self, args, kwargs, slots, context):\n        return Button.JsData(\n            js_data1=\"...\",\n            js_data2=123,\n        )\n\n    def get_css_data(self, args, kwargs, slots, context):\n        return Button.CssData(\n            css_data1=\"...\",\n            css_data2=123,\n        )\n
"},{"location":"concepts/fundamentals/typing_and_validation/#custom-types","title":"Custom types","text":"

We recommend to use NamedTuple for the Args class, and NamedTuple, dataclasses, or Pydantic models for Kwargs, Slots, TemplateData, JsData, and CssData classes.

However, you can use any class, as long as they meet the conditions below.

For example, here is how you can use Pydantic models to validate the inputs at runtime.

from django_components import Component\nfrom pydantic import BaseModel\n\nclass Table(Component):\n    class Kwargs(BaseModel):\n        name: str\n        age: int\n\n    def get_template_data(self, args, kwargs, slots, context):\n        assert isinstance(kwargs, Table.Kwargs)\n\nTable.render(\n    kwargs=Table.Kwargs(name=\"John\", age=30),\n)\n
"},{"location":"concepts/fundamentals/typing_and_validation/#args-class","title":"Args class","text":"

The Args class represents a list of positional arguments. It must meet two conditions:

  1. The constructor for the Args class must accept positional arguments.

    Args(*args)\n
  2. The Args instance must be convertable to a list.

    list(Args(1, 2, 3))\n

To implement the conversion to a list, you can implement the __iter__() method:

class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def __iter__(self):\n        return iter([('x', self.x), ('y', self.y)])\n
"},{"location":"concepts/fundamentals/typing_and_validation/#dictionary-classes","title":"Dictionary classes","text":"

On the other hand, other types (Kwargs, Slots, TemplateData, JsData, and CssData) represent dictionaries. They must meet these two conditions:

  1. The constructor must accept keyword arguments.

    Kwargs(**kwargs)\nSlots(**slots)\n
  2. The instance must be convertable to a dictionary.

    dict(Kwargs(a=1, b=2))\ndict(Slots(a=1, b=2))\n

To implement the conversion to a dictionary, you can implement either:

  1. _asdict() method

    class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def _asdict(self):\n        return {'x': self.x, 'y': self.y}\n

  2. Or make the class dict-like with __iter__() and __getitem__()

    class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def __iter__(self):\n        return iter([('x', self.x), ('y', self.y)])\n\n    def __getitem__(self, key):\n        return getattr(self, key)\n

"},{"location":"concepts/fundamentals/typing_and_validation/#passing-variadic-args-and-kwargs","title":"Passing variadic args and kwargs","text":"

You may have a component that accepts any number of args or kwargs.

However, this cannot be described with the current Python's typing system (as of v0.140).

As a workaround:

  • For a variable number of positional arguments (*args), set a positional argument that accepts a list of values:

    class Table(Component):\n    class Args(NamedTuple):\n        args: List[str]\n\nTable.render(\n    args=Table.Args(args=[\"a\", \"b\", \"c\"]),\n)\n
  • For a variable number of keyword arguments (**kwargs), set a keyword argument that accepts a dictionary of values:

    class Table(Component):\n    class Kwargs(NamedTuple):\n        variable: str\n        another: int\n        # Pass any extra keys under `extra`\n        extra: Dict[str, any]\n\nTable.render(\n    kwargs=Table.Kwargs(\n        variable=\"a\",\n        another=1,\n        extra={\"foo\": \"bar\"},\n    ),\n)\n
"},{"location":"concepts/fundamentals/typing_and_validation/#handling-no-args-or-no-kwargs","title":"Handling no args or no kwargs","text":"

To declare that a component accepts no args, kwargs, etc, define the types with no attributes using the pass keyword:

from typing import NamedTuple\nfrom django_components import Component\n\nclass Button(Component):\n    class Args(NamedTuple):\n        pass\n\n    class Kwargs(NamedTuple):\n        pass\n\n    class Slots(NamedTuple):\n        pass\n

This can get repetitive, so we added a Empty type to make it easier:

from django_components import Component, Empty\n\nclass Button(Component):\n    Args = Empty\n    Kwargs = Empty\n    Slots = Empty\n
"},{"location":"concepts/fundamentals/typing_and_validation/#subclassing","title":"Subclassing","text":"

Subclassing components with types is simple.

Since each type class is a separate class attribute, you can just override them in the Component subclass.

In the example below, ButtonExtra inherits Kwargs from Button, but overrides the Args class.

from django_components import Component, Empty\n\nclass Button(Component):\n    class Args(NamedTuple):\n        size: int\n\n    class Kwargs(NamedTuple):\n        color: str\n\nclass ButtonExtra(Button):\n    class Args(NamedTuple):\n        name: str\n        size: int\n\n# Stil works the same way!\nButtonExtra.render(\n    args=ButtonExtra.Args(name=\"John\", size=30),\n    kwargs=ButtonExtra.Kwargs(color=\"red\"),\n)\n

The only difference is when it comes to type hints to the data methods like get_template_data().

When you define the nested classes like Args and Kwargs directly on the class, you can reference them just by their class name (Args and Kwargs).

But when you have a Component subclass, and it uses Args or Kwargs from the parent, you will have to reference the type as a forward reference, including the full name of the component (Button.Args and Button.Kwargs).

Compare the following:

class Button(Component):\n    class Args(NamedTuple):\n        size: int\n\n    class Kwargs(NamedTuple):\n        color: str\n\n    # Both `Args` and `Kwargs` are defined on the class\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots, context):\n        pass\n\nclass ButtonExtra(Button):\n    class Args(NamedTuple):\n        name: str\n        size: int\n\n    # `Args` is defined on the subclass, `Kwargs` is defined on the parent\n    def get_template_data(self, args: Args, kwargs: \"ButtonExtra.Kwargs\", slots, context):\n        pass\n\nclass ButtonSame(Button):\n    # Both `Args` and `Kwargs` are defined on the parent\n    def get_template_data(self, args: \"ButtonSame.Args\", kwargs: \"ButtonSame.Kwargs\", slots, context):\n        pass\n
"},{"location":"concepts/fundamentals/typing_and_validation/#runtime-type-validation","title":"Runtime type validation","text":"

When you add types to your component, and implement them as NamedTuple or dataclass, the validation will check only for the presence of the attributes.

So this will not catch if you pass a string to an int attribute.

To enable runtime type validation, you need to use Pydantic models, and install the djc-ext-pydantic extension.

The djc-ext-pydantic extension ensures compatibility between django-components' classes such as Component, or Slot and Pydantic models.

First install the extension:

pip install djc-ext-pydantic\n

And then add the extension to your project:

COMPONENTS = {\n    \"extensions\": [\n        \"djc_pydantic.PydanticExtension\",\n    ],\n}\n
"},{"location":"concepts/fundamentals/typing_and_validation/#migrating-from-generics-to-class-attributes","title":"Migrating from generics to class attributes","text":"

In versions 0.92 to 0.139 (inclusive), the component typing was specified through generics.

Since v0.140, the types must be specified as class attributes of the Component class - Args, Kwargs, Slots, TemplateData, JsData, and CssData.

This change was necessary to make it possible to subclass components. Subclassing with generics was otherwise too complicated. Read the discussion here.

Because of this change, the Component.render() method is no longer typed. To type-check the inputs, you should wrap the inputs in Component.Args, Component.Kwargs, Component.Slots, etc.

For example, if you had a component like this:

from typing import NotRequired, Tuple, TypedDict\nfrom django_components import Component, Slot, SlotInput\n\nButtonArgs = Tuple[int, str]\n\nclass ButtonKwargs(TypedDict):\n    variable: str\n    another: int\n    maybe_var: NotRequired[int] # May be omitted\n\nclass ButtonSlots(TypedDict):\n    # Use `SlotInput` to allow slots to be given as `Slot` instance,\n    # plain string, or a function that returns a string.\n    my_slot: NotRequired[SlotInput]\n    # Use `Slot` to allow ONLY `Slot` instances.\n    another_slot: Slot\n\nButtonType = Component[ButtonArgs, ButtonKwargs, ButtonSlots]\n\nclass Button(ButtonType):\n    def get_context_data(self, *args, **kwargs):\n        self.input.args[0]  # int\n        self.input.kwargs[\"variable\"]  # str\n        self.input.slots[\"my_slot\"]  # Slot[MySlotData]\n\nButton.render(\n    args=(1, \"hello\"),\n    kwargs={\n        \"variable\": \"world\",\n        \"another\": 123,\n    },\n    slots={\n        \"my_slot\": \"...\",\n        \"another_slot\": Slot(lambda ctx: ...),\n    },\n)\n

The steps to migrate are:

  1. Convert all the types (ButtonArgs, ButtonKwargs, ButtonSlots) to subclasses of NamedTuple.
  2. Move these types inside the Component class (Button), and rename them to Args, Kwargs, and Slots.
  3. If you defined typing for the data methods (like get_context_data()), move them inside the Component class, and rename them to TemplateData, JsData, and CssData.
  4. Remove the Component generic.
  5. If you accessed the args, kwargs, or slots attributes via self.input, you will need to add the type hints yourself, because self.input is no longer typed.

    Otherwise, you may use Component.get_template_data() instead of get_context_data(), as get_template_data() receives args, kwargs, slots and context as arguments. You will still need to add the type hints yourself.

  6. Lastly, you will need to update the Component.render() calls to wrap the inputs in Component.Args, Component.Kwargs, and Component.Slots, to manually add type hints.

Thus, the code above will become:

from typing import NamedTuple, Optional\nfrom django.template import Context\nfrom django_components import Component, Slot, SlotInput\n\n# The Component class does not take any generics\nclass Button(Component):\n    # Types are now defined inside the component class\n    class Args(NamedTuple):\n        size: int\n        text: str\n\n    class Kwargs(NamedTuple):\n        variable: str\n        another: int\n        maybe_var: Optional[int] = None  # May be omitted\n\n    class Slots(NamedTuple):\n        # Use `SlotInput` to allow slots to be given as `Slot` instance,\n        # plain string, or a function that returns a string.\n        my_slot: Optional[SlotInput] = None\n        # Use `Slot` to allow ONLY `Slot` instances.\n        another_slot: Slot\n\n    # The args, kwargs, slots are instances of the component's Args, Kwargs, and Slots classes\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        args.size  # int\n        kwargs.variable  # str\n        slots.my_slot  # Slot[MySlotData]\n\nButton.render(\n    # Wrap the inputs in the component's Args, Kwargs, and Slots classes\n    args=Button.Args(1, \"hello\"),\n    kwargs=Button.Kwargs(\n        variable=\"world\",\n        another=123,\n    ),\n    slots=Button.Slots(\n        my_slot=\"...\",\n        another_slot=Slot(lambda ctx: ...),\n    ),\n)\n
"},{"location":"getting_started/adding_js_and_css/","title":"Adding JS and CSS","text":"

Next we will add CSS and JavaScript to our template.

Info

In django-components, using JS and CSS is as simple as defining them on the Component class. You don't have to insert the <script> and <link> tags into the HTML manually.

Behind the scenes, django-components keeps track of which components use which JS and CSS files. Thus, when a component is rendered on the page, the page will contain only the JS and CSS used by the components, and nothing more!

"},{"location":"getting_started/adding_js_and_css/#1-update-project-structure","title":"1. Update project structure","text":"

Start by creating empty calendar.js and calendar.css files:

sampleproject/\n\u251c\u2500\u2500 calendarapp/\n\u251c\u2500\u2500 components/\n\u2502   \u2514\u2500\u2500 calendar/\n\u2502       \u251c\u2500\u2500 calendar.py\n\u2502       \u251c\u2500\u2500 calendar.js       \ud83c\udd95\n\u2502       \u251c\u2500\u2500 calendar.css      \ud83c\udd95\n\u2502       \u2514\u2500\u2500 calendar.html\n\u251c\u2500\u2500 sampleproject/\n\u251c\u2500\u2500 manage.py\n\u2514\u2500\u2500 requirements.txt\n
"},{"location":"getting_started/adding_js_and_css/#2-write-css","title":"2. Write CSS","text":"

Inside calendar.css, write:

[project root]/components/calendar/calendar.css
.calendar {\n  width: 200px;\n  background: pink;\n}\n.calendar span {\n  font-weight: bold;\n}\n

Be sure to prefix your rules with unique CSS class like calendar, so the CSS doesn't clash with other rules.

Note

Soon, django-components will automatically scope your CSS by default, so you won't have to worry about CSS class clashes.

This CSS will be inserted into the page as an inlined <style> tag, at the position defined by {% component_css_dependencies %}, or at the end of the inside the <head> tag (See Default JS / CSS locations).

So in your HTML, you may see something like this:

<html>\n  <head>\n    ...\n    <style>\n      .calendar {\n        width: 200px;\n        background: pink;\n      }\n      .calendar span {\n        font-weight: bold;\n      }\n    </style>\n  </head>\n  <body>\n    ...\n  </body>\n</html>\n
"},{"location":"getting_started/adding_js_and_css/#3-write-js","title":"3. Write JS","text":"

Next we write a JavaScript file that specifies how to interact with this component.

You are free to use any javascript framework you want.

[project root]/components/calendar/calendar.js
(function () {\n  document.querySelector(\".calendar\").onclick = () => {\n    alert(\"Clicked calendar!\");\n  };\n})();\n

A good way to make sure the JS of this component doesn't clash with other components is to define all JS code inside an anonymous self-invoking function ((() => { ... })()). This makes all variables defined only be defined inside this component and not affect other components.

Note

Soon, django-components will automatically wrap your JS in a self-invoking function by default (except for JS defined with <script type=\"module\">).

Similarly to CSS, JS will be inserted into the page as an inlined <script> tag, at the position defined by {% component_js_dependencies %}, or at the end of the inside the <body> tag (See Default JS / CSS locations).

So in your HTML, you may see something like this:

<html>\n  <head>\n    ...\n  </head>\n  <body>\n    ...\n    <script>\n      (function () {\n        document.querySelector(\".calendar\").onclick = () => {\n          alert(\"Clicked calendar!\");\n        };\n      })();\n    </script>\n  </body>\n</html>\n
"},{"location":"getting_started/adding_js_and_css/#rules-of-js-execution","title":"Rules of JS execution","text":"
  1. JS is executed in the order in which the components are found in the HTML

    By default, the JS is inserted as a synchronous script (<script> ... </script>)

    So if you define multiple components on the same page, their JS will be executed in the order in which the components are found in the HTML.

    So if we have a template like so:

    <html>\n  <head>\n    ...\n  </head>\n  <body>\n    {% component \"calendar\" / %}\n    {% component \"table\" / %}\n  </body>\n</html>\n

    Then the JS file of the component calendar will be executed first, and the JS file of component table will be executed second.

  2. JS will be executed only once, even if there is multiple instances of the same component

    In this case, the JS of calendar will STILL execute first (because it was found first), and will STILL execute only once, even though it's present twice:

    <html>\n  <head>\n    ...\n  </head>\n  <body>\n    {% component \"calendar\" / %}\n    {% component \"table\" / %}\n    {% component \"calendar\" / %}\n  </body>\n</html>\n
"},{"location":"getting_started/adding_js_and_css/#4-link-js-and-css-to-a-component","title":"4. Link JS and CSS to a component","text":"

Finally, we return to our Python component in calendar.py to tie this together.

To link JS and CSS defined in other files, use js_file and css_file attributes:

[project root]/components/calendar/calendar.py
from django_components import Component\n\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    js_file = \"calendar.js\"   # <--- new\n    css_file = \"calendar.css\"   # <--- new\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": \"1970-01-01\",\n        }\n

And that's it! If you were to embed this component in an HTML, django-components will automatically embed the associated JS and CSS.

Note

Similarly to the template file, the JS and CSS file paths can be either:

  1. Relative to the Python component file (as seen above),
  2. Relative to any of the component directories as defined by COMPONENTS.dirs and/or COMPONENTS.app_dirs (e.g. [your apps]/components dir and [project root]/components)
  3. Relative to any of the directories defined by STATICFILES_DIRS.
"},{"location":"getting_started/adding_js_and_css/#5-link-additional-js-and-css-to-a-component","title":"5. Link additional JS and CSS to a component","text":"

Your components may depend on third-party packages or styling, or other shared logic. To load these additional dependencies, you can use a nested Media class.

This Media class behaves similarly to Django's Media class, with a few differences:

  1. Our Media class accepts various formats for the JS and CSS files: either a single file, a list, or (CSS-only) a dictonary (see below).
  2. Individual JS / CSS files can be any of str, bytes, Path, SafeString, or a function.
  3. Individual JS / CSS files can be glob patterns, e.g. *.js or styles/**/*.css.
  4. If you set Media.extend to a list, it should be a list of Component classes.

Learn more about using Media.

[project root]/components/calendar/calendar.py
from django_components import Component\n\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    js_file = \"calendar.js\"\n    css_file = \"calendar.css\"\n\n    class Media:   # <--- new\n        js = [\n            \"path/to/shared.js\",\n            \"path/to/*.js\",  # Or as a glob\n            \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\",  # AlpineJS\n        ]\n        css = [\n            \"path/to/shared.css\",\n            \"path/to/*.css\",  # Or as a glob\n            \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\",  # Tailwind\n        ]\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": \"1970-01-01\",\n        }\n

Note

Same as with the \"primary\" JS and CSS, the file paths files can be either:

  1. Relative to the Python component file (as seen above),
  2. Relative to any of the component directories as defined by COMPONENTS.dirs and/or COMPONENTS.app_dirs (e.g. [your apps]/components dir and [project root]/components)

Info

The Media nested class is shaped based on Django's Media class.

As such, django-components allows multiple formats to define the nested Media class:

# Single files\nclass Media:\n    js = \"calendar.js\"\n    css = \"calendar.css\"\n\n# Lists of files\nclass Media:\n    js = [\"calendar.js\", \"calendar2.js\"]\n    css = [\"calendar.css\", \"calendar2.css\"]\n\n# Dictionary of media types for CSS\nclass Media:\n    js = [\"calendar.js\", \"calendar2.js\"]\n    css = {\n      \"all\": [\"calendar.css\", \"calendar2.css\"],\n    }\n

If you define a list of JS files, they will be executed one-by-one, left-to-right.

"},{"location":"getting_started/adding_js_and_css/#rules-of-execution-of-scripts-in-mediajs","title":"Rules of execution of scripts in Media.js","text":"

The scripts defined in Media.js still follow the rules outlined above:

  1. JS is executed in the order in which the components are found in the HTML.
  2. JS will be executed only once, even if there is multiple instances of the same component.

Additionally to Media.js applies that:

  1. JS in Media.js is executed before the component's primary JS.
  2. JS in Media.js is executed in the same order as it was defined.
  3. If there is multiple components that specify the same JS path or URL in Media.js, this JS will be still loaded and executed only once.

Putting all of this together, our Calendar component above would render HTML like so:

<html>\n  <head>\n    ...\n    <!-- CSS from Media.css -->\n    <link href=\"/static/path/to/shared.css\" media=\"all\" rel=\"stylesheet\" />\n    <link\n      href=\"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\"\n      media=\"all\"\n      rel=\"stylesheet\"\n    />\n    <!-- CSS from Component.css_file -->\n    <style>\n      .calendar {\n        width: 200px;\n        background: pink;\n      }\n      .calendar span {\n        font-weight: bold;\n      }\n    </style>\n  </head>\n  <body>\n    ...\n    <!-- JS from Media.js -->\n    <script src=\"/static/path/to/shared.js\"></script>\n    <script src=\"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\"></script>\n    <!-- JS from Component.js_file -->\n    <script>\n      (function () {\n        document.querySelector(\".calendar\").onclick = () => {\n          alert(\"Clicked calendar!\");\n        };\n      })();\n    </script>\n  </body>\n</html>\n

Now that we have a fully-defined component, next let's use it in a Django template \u27a1\ufe0f.

"},{"location":"getting_started/adding_slots/","title":"Adding slots","text":"

Our calendar component's looking great! But we just got a new assignment from our colleague - The calendar date needs to be shown on 3 different pages:

  1. On one page, it needs to be shown as is
  2. On the second, the date needs to be bold
  3. On the third, the date needs to be in italics

As a reminder, this is what the component's template looks like:

<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n

There's many ways we could approach this:

  • Expose the date in a slot
  • Style .calendar > span differently on different pages
  • Pass a variable to the component that decides how the date is rendered
  • Create a new component

First two options are more flexible, because the custom styling is not baked into a component's implementation. And for the sake of demonstration, we'll solve this challenge with slots.

"},{"location":"getting_started/adding_slots/#1-what-are-slots","title":"1. What are slots","text":"

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 tags that work hand in hand to make this work. These are...

  • {% slot <name> %}/{% endslot %}: Declares a new slot in the component template.
  • {% fill <name> %}/{% endfill %}: (Used inside a {% component %} tag pair.) Fills a declared slot with the specified content.
"},{"location":"getting_started/adding_slots/#2-add-a-slot-tag","title":"2. Add a slot tag","text":"

Let's update our calendar component to support more customization. We'll add {% slot %} tag to the template:

<div class=\"calendar\">\n  Today's date is\n  {% slot \"date\" default %}  {# <--- new #}\n    <span>{{ date }}</span>\n  {% endslot %}\n</div>\n

Notice that:

  1. We named the slot date - so we can fill this slot by using {% fill \"date\" %}

  2. We also made it the default slot.

  3. We placed our original implementation inside the {% slot %} tag - this is what will be rendered when the slot is NOT overriden.

"},{"location":"getting_started/adding_slots/#3-add-fill-tag","title":"3. Add fill tag","text":"

Now we can use {% fill %} tags inside the {% component %} tags to override the date slot to generate the bold and italics variants:

{# Default #}\n{% component \"calendar\" date=\"2024-12-13\" / %}\n\n{# Bold #}\n{% component \"calendar\" date=\"2024-12-13\" %}\n  <b> 2024-12-13 </b>\n{% endcomponent %}\n\n{# Italics #}\n{% component \"calendar\" date=\"2024-12-13\" %}\n  <i> 2024-12-13 </i>\n{% endcomponent %}\n

Which will render as:

<!-- Default -->\n<div class=\"calendar\">\n  Today's date is <span>2024-12-13</span>\n</div>\n\n<!-- Bold -->\n<div class=\"calendar\">\n  Today's date is <b>2024-12-13</b>\n</div>\n\n<!-- Italics -->\n<div class=\"calendar\">\n  Today's date is <i>2024-12-13</i>\n</div>\n

Info

Since we used the default flag on {% slot \"date\" %} inside our calendar component, we can target the date component in multiple ways:

  1. Explicitly by it's name

    {% component \"calendar\" date=\"2024-12-13\" %}\n  {% fill \"date\" %}\n    <i> 2024-12-13 </i>\n  {% endfill %}\n{% endcomponent %}\n

  2. Implicitly as the default slot (Omitting the {% fill %} tag)

    {% component \"calendar\" date=\"2024-12-13\" %}\n  <i> 2024-12-13 </i>\n{% endcomponent %}\n

  3. Explicitly as the default slot (Setting fill name to default)

    {% component \"calendar\" date=\"2024-12-13\" %}\n  {% fill \"default\" %}\n    <i> 2024-12-13 </i>\n  {% endfill %}\n{% endcomponent %}\n

"},{"location":"getting_started/adding_slots/#4-wait-theres-a-bug","title":"4. Wait, there's a bug","text":"

There is a mistake in our code! 2024-12-13 is Friday, so that's fine. But if we updated the to 2024-12-14, which is Saturday, our template from previous step would render this:

<!-- Default -->\n<div class=\"calendar\">\n  Today's date is <span>2024-12-16</span>\n</div>\n\n<!-- Bold -->\n<div class=\"calendar\">\n  Today's date is <b>2024-12-14</b>\n</div>\n\n<!-- Italics -->\n<div class=\"calendar\">\n  Today's date is <i>2024-12-14</i>\n</div>\n

The first instance rendered 2024-12-16, while the rest rendered 2024-12-14!

Why? Remember that in the get_template_data() method of our Calendar component, we pre-process the date. If the date falls on Saturday or Sunday, we shift it to next Monday:

[project root]/components/calendar/calendar.py
from datetime import date\n\nfrom django_components import Component, register\n\n# If date is Sat or Sun, shift it to next Mon, so the date is always workweek.\ndef to_workweek_date(d: date):\n    ...\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    ...\n    def get_template_data(self, args, kwargs, slots, context):\n        workweek_date = to_workweek_date(kwargs[\"date\"])\n        return {\n            \"date\": workweek_date,\n            \"extra_class\": kwargs.get(\"extra_class\", \"text-blue\"),\n        }\n

And the issue is that in our template, we used the date value that we used as input, which is NOT the same as the date variable used inside Calendar's template.

"},{"location":"getting_started/adding_slots/#5-adding-data-to-slots","title":"5. Adding data to slots","text":"

We want to use the same date variable that's used inside Calendar's template.

Luckily, django-components allows passing data to slots, also known as Scoped slots.

This consists of two steps:

  1. Pass the date variable to the {% slot %} tag
  2. Access the date variable in the {% fill %} tag by using the special data kwarg

Let's update the Calendar's template:

<div class=\"calendar\">\n  Today's date is\n  {% slot \"date\" default date=date %}  {# <--- changed #}\n    <span>{{ date }}</span>\n  {% endslot %}\n</div>\n

Info

The {% slot %} tag has one special kwarg, name. When you write

{% slot \"date\" / %}\n

It's the same as:

{% slot name=\"date\" / %}\n

Other than the name kwarg, you can pass any extra kwargs to the {% slot %} tag, and these will be exposed as the slot's data.

{% slot name=\"date\" kwarg1=123 kwarg2=\"text\" kwarg3=my_var / %}\n
"},{"location":"getting_started/adding_slots/#6-accessing-slot-data-in-fills","title":"6. Accessing slot data in fills","text":"

Now, on the {% fill %} tags, we can use the data kwarg to specify the variable under which the slot data will be available.

The variable from the data kwarg contains all the extra kwargs passed to the {% slot %} tag.

So if we set data=\"slot_data\", then we can access the date variable under slot_data.date:

{# Default #}\n{% component \"calendar\" date=\"2024-12-13\" / %}\n\n{# Bold #}\n{% component \"calendar\" date=\"2024-12-13\" %}\n  {% fill \"date\" data=\"slot_data\" %}\n    <b> {{ slot_data.date }} </b>\n  {% endfill %}\n{% endcomponent %}\n\n{# Italics #}\n{% component \"calendar\" date=\"2024-12-13\" %}\n  {% fill \"date\" data=\"slot_data\" %}\n    <i> {{ slot_data.date }} </i>\n  {% endfill %}\n{% endcomponent %}\n

By using the date variable from the slot, we'll render the correct date each time:

<!-- Default -->\n<div class=\"calendar\">\n  Today's date is <span>2024-12-16</span>\n</div>\n\n<!-- Bold -->\n<div class=\"calendar\">\n  Today's date is <b>2024-12-16</b>\n</div>\n\n<!-- Italics -->\n<div class=\"calendar\">\n  Today's date is <i>2024-12-16</i>\n</div>\n

Info

When to use slots vs variables?

Generally, slots are more flexible - you can access the slot data, even the original slot content. Thus, slots behave more like functions that render content based on their context.

On the other hand, variables are simpler - the variable you pass to a component is what will be used.

Moreover, slots are treated as part of the template - for example the CSS scoping (work in progress) is applied to the slot content too.

So far we've rendered components using template tag. [Next, let\u2019s explore other ways to render components \u27a1\ufe0f] (./rendering_components.md)

"},{"location":"getting_started/components_in_templates/","title":"Components in templates","text":"

By the end of this section, we want to be able to use our components in Django templates like so:

{% load component_tags %}\n<!DOCTYPE html>\n<html>\n  <head>\n    <title>My example calendar</title>\n  </head>\n  <body>\n    {% component \"calendar\" / %}\n  </body>\n<html>\n
"},{"location":"getting_started/components_in_templates/#1-register-component","title":"1. Register component","text":"

First, however, we need to register our component class with ComponentRegistry.

To register a component with a ComponentRegistry, we will use the @register decorator, and give it a name under which the component will be accessible from within the template:

[project root]/components/calendar/calendar.py
from django_components import Component, register  # <--- new\n\n@register(\"calendar\")  # <--- new\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    js_file = \"calendar.js\"\n    css_file = \"calendar.css\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": \"1970-01-01\",\n        }\n

This will register the component to the default registry. Default registry is loaded into the template by calling {% load component_tags %} inside the template.

Info

Why do we have to register components?

We want to use our component as a template tag ({% ... %}) in Django template.

In Django, template tags are managed by the Library instances. Whenever you include {% load xxx %} in your template, you are loading a Library instance into your template.

ComponentRegistry acts like a router and connects the registered components with the associated Library.

That way, when you include {% load component_tags %} in your template, you are able to \"call\" components like {% component \"calendar\" / %}.

ComponentRegistries also make it possible to group and share components as standalone packages. Learn more here.

Note

You can create custom ComponentRegistry instances, which will use different Library instances. In that case you will have to load different libraries depending on which components you want to use:

Example 1 - Using component defined in the default registry

{% load component_tags %}\n<div>\n  {% component \"calendar\" / %}\n</div>\n

Example 2 - Using component defined in a custom registry

{% load my_custom_tags %}\n<div>\n  {% my_component \"table\" / %}\n</div>\n

Note that, because the tag name component is use by the default ComponentRegistry, the custom registry was configured to use the tag my_component instead. Read more here

"},{"location":"getting_started/components_in_templates/#2-load-and-use-the-component-in-template","title":"2. Load and use the component in template","text":"

The component is now registered under the name calendar. All that remains to do is to load and render the component inside a template:

{% load component_tags %}  {# Load the default registry #}\n<!DOCTYPE html>\n<html>\n  <head>\n    <title>My example calendar</title>\n  </head>\n  <body>\n    {% component \"calendar\" / %}  {# Render the component #}\n  </body>\n<html>\n

Info

Component tags should end with / if they do not contain any Slot fills. But you can also use {% endcomponent %} instead:

{% component \"calendar\" %}{% endcomponent %}\n

We defined the Calendar's template as

<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n

and the variable date as \"1970-01-01\".

Thus, the final output will look something like this:

<!DOCTYPE html>\n<html>\n  <head>\n    <title>My example calendar</title>\n    <style>\n      .calendar {\n        width: 200px;\n        background: pink;\n      }\n      .calendar span {\n        font-weight: bold;\n      }\n    </style>\n  </head>\n  <body>\n    <div class=\"calendar\">\n      Today's date is <span>1970-01-01</span>\n    </div>\n    <script>\n      (function () {\n        document.querySelector(\".calendar\").onclick = () => {\n          alert(\"Clicked calendar!\");\n        };\n      })();\n    </script>\n  </body>\n<html>\n

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.

Info

Remember that you can use {% component_js_dependencies %} and {% component_css_dependencies %} to change where the <script> and <style> tags will be rendered (See Default JS / CSS locations).

Info

How does django-components pick up registered components?

Notice that it was enough to add @register to the component. We didn't need to import the component file anywhere to execute it.

This is because django-components automatically imports all Python files found in the component directories during an event called Autodiscovery.

So with Autodiscovery, it's the same as if you manually imported the component files on the ready() hook:

class MyApp(AppConfig):\n    default_auto_field = \"django.db.models.BigAutoField\"\n    name = \"myapp\"\n\n    def ready(self):\n        import myapp.components.calendar\n        import myapp.components.table\n        ...\n

You can now render the components in templates!

Currently our component always renders the same content. Let's parametrise it, so that our Calendar component is configurable from within the template \u27a1\ufe0f

"},{"location":"getting_started/parametrising_components/","title":"Parametrising components","text":"

So far, our Calendar component will always render the date 1970-01-01. Let's make it more useful and flexible by being able to pass in custom date.

What we want is to be able to use the Calendar component within the template like so:

{% component \"calendar\" date=\"2024-12-13\" extra_class=\"text-red\" / %}\n
"},{"location":"getting_started/parametrising_components/#1-understading-component-inputs","title":"1. Understading component inputs","text":"

In section Create your first component, we defined the get_template_data() method that defines what variables will be available within the template:

[project root]/components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    ...\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": \"1970-01-01\",\n        }\n

What we didn't say is that get_template_data() actually receives the args and kwargs that were passed to a component.

So if we call a component with a date and extra_class keywords:

{% component \"calendar\" date=\"2024-12-13\" extra_class=\"text-red\" / %}\n

This is the same as calling:

Calendar.get_template_data(\n    args=[],\n    kwargs={\"date\": \"2024-12-13\", \"extra_class\": \"text-red\"},\n)\n

And same applies to positional arguments, or mixing args and kwargs, where:

{% component \"calendar\" \"2024-12-13\" extra_class=\"text-red\" / %}\n

is same as

Calendar.get_template_data(\n    args=[\"2024-12-13\"],\n    kwargs={\"extra_class\": \"text-red\"},\n)\n
"},{"location":"getting_started/parametrising_components/#2-define-inputs","title":"2. Define inputs","text":"

Let's put this to test. We want to pass date and extra_class kwargs to the component. And so, we can write the get_template_data() method such that it expects those parameters:

[project root]/components/calendar/calendar.py
from datetime import date\n\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    ...\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"date\"],\n            \"extra_class\": kwargs.get(\"extra_class\", \"text-blue\"),\n        }\n

Since extra_class is optional in the function signature, it's optional also in the template. So both following calls are valid:

{% component \"calendar\" date=\"2024-12-13\" / %}\n{% component \"calendar\" date=\"2024-12-13\" extra_class=\"text-red\" / %}\n

Warning

get_template_data() differentiates between positional and keyword arguments, so you have to make sure to pass the arguments correctly.

Since date is expected to be a keyword argument, it MUST be provided as such:

\u2705 `date` is kwarg\n{% component \"calendar\" date=\"2024-12-13\" / %}\n\n\u274c `date` is arg\n{% component \"calendar\" \"2024-12-13\" / %}\n
"},{"location":"getting_started/parametrising_components/#3-process-inputs","title":"3. Process inputs","text":"

The get_template_data() method is powerful, because it allows us to decouple component inputs from the template variables. In other words, we can pre-process the component inputs, and massage them into a shape that's most appropriate for what the template needs. And it also allows us to pass in static data into the template.

Imagine our component receives data from the database that looks like below (taken from Django).

cities = [\n    {\"name\": \"Mumbai\", \"population\": \"19,000,000\", \"country\": \"India\"},\n    {\"name\": \"Calcutta\", \"population\": \"15,000,000\", \"country\": \"India\"},\n    {\"name\": \"New York\", \"population\": \"20,000,000\", \"country\": \"USA\"},\n    {\"name\": \"Chicago\", \"population\": \"7,000,000\", \"country\": \"USA\"},\n    {\"name\": \"Tokyo\", \"population\": \"33,000,000\", \"country\": \"Japan\"},\n]\n

We need to group the list items by size into following buckets by population:

  • 0-10,000,000
  • 10,000,001-20,000,000
  • 20,000,001-30,000,000
  • +30,000,001

So we want to end up with following data:

cities_by_pop = [\n    {\n      \"name\": \"0-10,000,000\",\n      \"items\": [\n          {\"name\": \"Chicago\", \"population\": \"7,000,000\", \"country\": \"USA\"},\n      ]\n    },\n    {\n      \"name\": \"10,000,001-20,000,000\",\n      \"items\": [\n          {\"name\": \"Calcutta\", \"population\": \"15,000,000\", \"country\": \"India\"},\n          {\"name\": \"Mumbai\", \"population\": \"19,000,000\", \"country\": \"India\"},\n          {\"name\": \"New York\", \"population\": \"20,000,000\", \"country\": \"USA\"},\n      ]\n    },\n    {\n      \"name\": \"30,000,001-40,000,000\",\n      \"items\": [\n          {\"name\": \"Tokyo\", \"population\": \"33,000,000\", \"country\": \"Japan\"},\n      ]\n    },\n]\n

Without the get_template_data() method, we'd have to either:

  1. Pre-process the data in Python before passing it to the components.
  2. Define a Django filter or template tag to take the data and process it on the spot.

Instead, with get_template_data(), we can keep this transformation private to this component, and keep the rest of the codebase clean.

def group_by_pop(data):\n    ...\n\n@register(\"population_table\")\nclass PopulationTable(Component):\n    template_file = \"population_table.html\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"data\": group_by_pop(kwargs[\"data\"]),\n        }\n

Similarly we can make use of get_template_data() to pre-process the date that was given to the component:

[project root]/components/calendar/calendar.py
from datetime import date\n\nfrom django_components import Component, register\n\n# If date is Sat or Sun, shift it to next Mon, so the date is always workweek.\ndef to_workweek_date(d: date):\n    ...\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    ...\n    def get_template_data(self, args, kwargs, slots, context):\n        workweek_date = to_workweek_date(kwargs[\"date\"])  # <--- new\n        return {\n            \"date\": workweek_date,  # <--- changed\n            \"extra_class\": kwargs.get(\"extra_class\", \"text-blue\"),\n        }\n
"},{"location":"getting_started/parametrising_components/#4-pass-inputs-to-components","title":"4. Pass inputs to components","text":"

Once we're happy with Calendar.get_template_data(), we can update our templates to use the parametrized version of the component:

<div>\n  {% component \"calendar\" date=\"2024-12-13\" / %}\n  {% component \"calendar\" date=\"1970-01-01\" / %}\n</div>\n
"},{"location":"getting_started/parametrising_components/#5-add-defaults","title":"5. Add defaults","text":"

In our example, we've set the extra_class to default to \"text-blue\" by setting it in the get_template_data() method.

However, you may want to use the same default value in multiple methods, like get_js_data() or get_css_data().

To make things easier, Components can specify their defaults. Defaults are used when no value is provided, or when the value is set to None for a particular input.

To define defaults for a component, you create a nested Defaults class within your Component class. Each attribute in the Defaults class represents a default value for a corresponding input.

from django_components import Component, Default, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n\n    class Defaults:  # <--- new\n        extra_class = \"text-blue\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        workweek_date = to_workweek_date(kwargs[\"date\"])\n        return {\n            \"date\": workweek_date,\n            \"extra_class\": kwargs[\"extra_class\"],  # <--- changed\n        }\n

Next, you will learn how to use slots give your components even more flexibility \u27a1\ufe0f

"},{"location":"getting_started/rendering_components/","title":"Rendering components","text":"

Our calendar component can accept and pre-process data, defines its own CSS and JS, and can be used in templates.

...But how do we actually render the components into HTML?

There's 3 ways to render a component:

  • Render the template that contains the {% component %} tag
  • Render the component directly with Component.render()
  • Render the component directly with Component.render_to_response()

As a reminder, this is what the calendar component looks like:

[project root]/components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    js_file = \"calendar.js\"\n    css_file = \"calendar.css\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": \"1970-01-01\",\n        }\n
"},{"location":"getting_started/rendering_components/#1-render-the-template","title":"1. Render the template","text":"

If you have embedded the component in a Django template using the {% component %} tag:

[project root]/templates/my_template.html
{% load component_tags %}\n<div>\n  {% component \"calendar\" date=\"2024-12-13\" / %}\n</div>\n

You can simply render the template with the Django tooling:

"},{"location":"getting_started/rendering_components/#with-djangoshortcutsrender","title":"With django.shortcuts.render()","text":"
from django.shortcuts import render\n\ncontext = {\"date\": \"2024-12-13\"}\nrendered_template = render(request, \"my_template.html\", context)\n
"},{"location":"getting_started/rendering_components/#with-templaterender","title":"With Template.render()","text":"

Either loading the template with get_template():

from django.template.loader import get_template\n\ntemplate = get_template(\"my_template.html\")\ncontext = {\"date\": \"2024-12-13\"}\nrendered_template = template.render(context)\n

Or creating a new Template instance:

from django.template import Template\n\ntemplate = Template(\"\"\"\n{% load component_tags %}\n<div>\n  {% component \"calendar\" date=\"2024-12-13\" / %}\n</div>\n\"\"\")\nrendered_template = template.render()\n
"},{"location":"getting_started/rendering_components/#2-render-the-component","title":"2. Render the component","text":"

You can also render the component directly with Component.render(), without wrapping the component in a template.

from components.calendar import Calendar\n\ncalendar = Calendar\nrendered_component = calendar.render()\n

You can pass args, kwargs, slots, and more, to the component:

from components.calendar import Calendar\n\ncalendar = Calendar\nrendered_component = calendar.render(\n    args=[\"2024-12-13\"],\n    kwargs={\n        \"extra_class\": \"my-class\"\n    },\n    slots={\n        \"date\": \"<b>2024-12-13</b>\"\n    },\n)\n

Info

Among other, you can pass also the request object to the render method:

from components.calendar import Calendar\n\ncalendar = Calendar\nrendered_component = calendar.render(request=request)\n

The request object is required for some of the component's features, like using Django's context processors.

"},{"location":"getting_started/rendering_components/#3-render-the-component-to-httpresponse","title":"3. Render the component to HttpResponse","text":"

A common pattern in Django is to render the component and then return the resulting HTML as a response to an HTTP request.

For this, you can use the Component.render_to_response() convenience method.

render_to_response() accepts the same args, kwargs, slots, and more, as Component.render(), but wraps the result in an HttpResponse.

from components.calendar import Calendar\n\ndef my_view(request):\n    response = Calendar.render_to_response(\n        args=[\"2024-12-13\"],\n        kwargs={\n            \"extra_class\": \"my-class\"\n        },\n        slots={\n            \"date\": \"<b>2024-12-13</b>\"\n        },\n        request=request,\n    )\n    return response\n

Info

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 MyCustomResponse(HttpResponse):\n    def __init__(self, *args, **kwargs) -> None:\n        super().__init__(*args, **kwargs)\n        # Configure response\n        self.headers = ...\n        self.status = ...\n\nclass SimpleComponent(Component):\n    response_class = MyCustomResponse\n
"},{"location":"getting_started/rendering_components/#4-rendering-slots","title":"4. Rendering slots","text":"

Slots content are automatically escaped by default to prevent XSS attacks.

In other words, it's as if you would be using Django's escape() on the slot contents / result:

from django.utils.html import escape\n\nclass Calendar(Component):\n    template = \"\"\"\n        <div>\n            {% slot \"date\" default date=date / %}\n        </div>\n    \"\"\"\n\nCalendar.render(\n    slots={\n        \"date\": escape(\"<b>Hello</b>\"),\n    }\n)\n

To disable escaping, you can wrap the slot string or slot result in Django's mark_safe():

Calendar.render(\n    slots={\n        # string\n        \"date\": mark_safe(\"<b>Hello</b>\"),\n\n        # function\n        \"date\": lambda ctx: mark_safe(\"<b>Hello</b>\"),\n    }\n)\n

Info

Read more about Django's format_html and mark_safe.

"},{"location":"getting_started/rendering_components/#5-component-views-and-urls","title":"5. Component views and URLs","text":"

For web applications, it's common to define endpoints that serve HTML content (AKA views).

If this is your case, you can define the view request handlers directly on your component by using the nestedComponent.View class.

This is a great place for:

  • Endpoints that render whole pages, if your component is a page component.

  • Endpoints that render the component as HTML fragments, to be used with HTMX or similar libraries.

Read more on Component views and URLs.

[project root]/components/calendar.py
from django_components import Component, ComponentView, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template = \"\"\"\n        <div class=\"calendar-component\">\n            <div class=\"header\">\n                {% slot \"header\" / %}\n            </div>\n            <div class=\"body\">\n                Today's date is <span>{{ date }}</span>\n            </div>\n        </div>\n    \"\"\"\n\n    class View:\n        # Handle GET requests\n        def get(self, request, *args, **kwargs):\n            # Return HttpResponse with the rendered content\n            return Calendar.render_to_response(\n                request=request,\n                kwargs={\n                    \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n                },\n                slots={\n                    \"header\": \"Calendar header\",\n                },\n            )\n

Info

The View class supports all the same HTTP methods as Django's View class. These are:

get(), post(), put(), patch(), delete(), head(), options(), trace()

Each of these receive the HttpRequest object as the first argument.

Next, you need to set the URL for the component.

You can either:

  1. Automatically assign the URL by setting the Component.View.public attribute to True.

    In this case, use get_component_url() to get the URL for the component view.

    from django_components import Component, get_component_url\n\nclass Calendar(Component):\n    class View:\n        public = True\n\nurl = get_component_url(Calendar)\n
  2. Manually assign the URL by setting Component.as_view() to your urlpatterns:

    from django.urls import path\nfrom components.calendar import Calendar\n\nurlpatterns = [\n    path(\"calendar/\", Calendar.as_view()),\n]\n

And with that, you're all set! When you visit the URL, the component will be rendered and the content will be returned.

The get(), post(), etc methods will receive the HttpRequest object as the first argument. So you can parametrize how the component is rendered for example by passing extra query parameters to the URL:

http://localhost:8000/calendar/?date=2024-12-13\n
"},{"location":"getting_started/your_first_component/","title":"Create your first component","text":"

A component in django-components can be as simple as a Django template and Python code to declare the component:

calendar.html
<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n
calendar.py
from django_components import Component\n\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n

Or a combination of Django template, Python, CSS, and Javascript:

calendar.html
<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n
calendar.css
.calendar {\n  width: 200px;\n  background: pink;\n}\n
calendar.js
document.querySelector(\".calendar\").onclick = function () {\n  alert(\"Clicked calendar!\");\n};\n
calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    js_file = \"calendar.js\"\n    css_file = \"calendar.css\"\n

Alternatively, you can \"inline\" HTML, JS, and CSS right into the component class:

from django_components import Component\n\nclass Calendar(Component):\n    template = \"\"\"\n      <div class=\"calendar\">\n        Today's date is <span>{{ date }}</span>\n      </div>\n    \"\"\"\n\n    css = \"\"\"\n      .calendar {\n        width: 200px;\n        background: pink;\n      }\n    \"\"\"\n\n    js = \"\"\"\n      document.querySelector(\".calendar\").onclick = function () {\n        alert(\"Clicked calendar!\");\n      };\n    \"\"\"\n

Note

If you \"inline\" the HTML, JS and CSS code into the Python class, you can set up syntax highlighting for better experience. However, autocompletion / intellisense does not work with syntax highlighting.

We'll start by creating a component that defines only a Django template:

"},{"location":"getting_started/your_first_component/#1-create-project-structure","title":"1. Create project structure","text":"

Start by creating empty calendar.py and calendar.html files:

sampleproject/\n\u251c\u2500\u2500 calendarapp/\n\u251c\u2500\u2500 components/             \ud83c\udd95\n\u2502   \u2514\u2500\u2500 calendar/           \ud83c\udd95\n\u2502       \u251c\u2500\u2500 calendar.py     \ud83c\udd95\n\u2502       \u2514\u2500\u2500 calendar.html   \ud83c\udd95\n\u251c\u2500\u2500 sampleproject/\n\u251c\u2500\u2500 manage.py\n\u2514\u2500\u2500 requirements.txt\n
"},{"location":"getting_started/your_first_component/#2-write-django-template","title":"2. Write Django template","text":"

Inside calendar.html, write:

[project root]/components/calendar/calendar.html
<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n

In this example we've defined one template variable date. You can use any and as many variables as you like. These variables will be defined in the Python file in get_template_data() when creating an instance of this component.

Note

The template will be rendered with whatever template backend you've specified in your Django settings file.

Currently django-components supports only the default \"django.template.backends.django.DjangoTemplates\" template backend!

"},{"location":"getting_started/your_first_component/#3-create-new-component-in-python","title":"3. Create new Component in Python","text":"

In calendar.py, create a subclass of Component to create a new component.

To link the HTML template with our component, set template_file to the name of the HTML file.

[project root]/components/calendar/calendar.py
from django_components import Component\n\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n

Note

The path to the template file can be either:

  1. Relative to the component's python file (as seen above),
  2. Relative to any of the component directories as defined by COMPONENTS.dirs and/or COMPONENTS.app_dirs (e.g. [your apps]/components dir and [project root]/components)
"},{"location":"getting_started/your_first_component/#4-define-the-template-variables","title":"4. Define the template variables","text":"

In calendar.html, we've used the variable date. So we need to define it for the template to work.

This is done using Component.get_template_data(). It's a function that returns a dictionary. The entries in this dictionary will become available within the template as variables, e.g. as {{ date }}.

[project root]/components/calendar/calendar.py
from django_components import Component\n\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": \"1970-01-01\",\n        }\n

Now, when we render the component with Component.render() method:

Calendar.render()\n

It will output

<div class=\"calendar\">\n  Today's date is <span>1970-01-01</span>\n</div>\n

And voil\u00e1!! We've created our first component.

Next, let's add JS and CSS to this component \u27a1\ufe0f.

"},{"location":"guides/devguides/dependency_mgmt/","title":"JS and CSS rendering","text":"

Aim of this doc is to share the intuition on how we manage the JS and CSS (\"dependencies\") associated with components, and how we render them.

"},{"location":"guides/devguides/dependency_mgmt/#starting-conditions","title":"Starting conditions","text":"
  1. First of all, when we consider a component, it has two kind of dependencies - the \"inlined\" JS and CSS, and additional linked JS and CSS via Media.js/css:

    from django_components import Component, types\n\nclass MyTable(Component):\n    # Inlined JS\n    js: types.js = \"\"\"\n      console.log(123);\n    \"\"\"\n\n    # Inlined CSS\n    css: types.css = \"\"\"\n      .my-table {\n        color: red;\n      }\n    \"\"\"\n\n    # Linked JS / CSS\n    class Media:\n        js = [\n            \"script-one.js\",  # STATIC file relative to component file\n            \"/script-two.js\", # URL path\n            \"https://example.com/script-three.js\", # URL\n        ]\n\n        css = [\n            \"style-one.css\",  # STATIC file relative to component file\n            \"/style-two.css\", # URL path\n            \"https://example.com/style-three.css\", # URL\n        ]\n
  2. Second thing to keep in mind is that all component's are eventually rendered into a string. And so, if we want to associate extra info with a rendered component, it has to be serialized to a string.

    This is because a component may be embedded in a Django Template with the {% component %} tag, which, when rendered, is turned into a string:

    template = Template(\"\"\"\n  {% load component_tags %}\n  <div>\n    {% component \"my_table\" / %}\n  </div>\n\"\"\")\n\nhtml_str = template.render(Context({}))\n

    And for this reason, we take the same approach also when we render a component with Component.render() - It returns a string.

  3. Thirdly, we also want to add support for JS / CSS variables. That is, that a variable defined on the component would be somehow accessible from within the JS script / CSS style.

    A simple approach to this would be to modify the inlined JS / CSS directly, and insert them for each component. But if you had extremely large JS / CSS, and e.g. only a single JS / CSS variable that you want to insert, it would be wasteful to create a copy of the JS / CSS scripts for each component instance.

    So instead, a preferred approach here is to defined and insert the inlined JS / CSS only once, and have some kind of mechanism on how we make correct the JS / CSS variables available only to the correct components.

  4. Last important thing is that we want the JS / CSS dependencies to work also with HTML fragments.

    So normally, e.g. when a user hits URL of a web page, the server renders full HTML document, with <!doctype>, <html>, <head>, and <body>. In such case, we know about ALL JS and CSS dependencies at render time, so we can e.g. insert them into <head> and <body> ourselves.

    However this renders only the initial state. HTML fragments is a common pattern where interactivity is added to the web page by fetching and replacing bits of HTML on the main HTML document after some user action.

    In the case of HTML fragments, the HTML is NOT a proper document, but only the HTML that will be inserted somewhere into the DOM.

    The challenge here is that Django template for the HTML fragment MAY contain components, and these components MAY have inlined or linked JS and CSS.

    def fragment_view(request):\n    template = Template(\"\"\"\n      {% load component_tags %}\n      <div>\n        {% component \"my_table\" / %}\n      </div>\n    \"\"\")\n\n    fragment_str = template.render(Context({}))\n    return HttpResponse(fragment_str, status=200)\n

    User may use different libraries to fetch and insert the HTML fragments (e.g. HTMX, AlpineJS, ...). From our perspective, the only thing that we can reliably say is that we expect that the HTML fragment WILL be eventually inserted into the DOM.

    So to include the corresponding JS and CSS, a simple approach could be to append them to the HTML as <style> and <script>, e.g.:

    <!-- Original content -->\n<div>...</div>\n<!-- Associated CSS files -->\n<link href=\"http://...\" />\n<style>\n  .my-class {\n    color: red;\n  }\n</style>\n<!-- Associated JS files -->\n<script src=\"http://...\"></script>\n<script>\n  console.log(123);\n</script>\n

    But this has a number of issues:

    • The JS scripts would run for each instance of the component.
    • Bloating of the HTML file, as each inlined JS or CSS would be included fully for each component.
    • While this sound OK, this could really bloat the HTML files if we used a UI component library for the basic building blocks like buttons, lists, cards, etc.
"},{"location":"guides/devguides/dependency_mgmt/#flow","title":"Flow","text":"

So the solution should address all the points above. To achieve that, we manage the JS / CSS dependencies ourselves in the browser. So when a full HTML document is loaded, we keep track of which JS and CSS have been loaded. And when an HTML fragment is inserted, we check which JS / CSS dependencies it has, and load only those that have NOT been loaded yet.

This is how we achieve that:

  1. When a component is rendered, it inserts an HTML comment containing metadata about the rendered component.

    So a template like this

    {% load component_tags %}\n<div>\n  {% component \"my_table\" / %}\n</div>\n{% component \"button\" %}\n  Click me!\n{% endcomponent %}\n

    May actually render:

    <div>\n  <!-- _RENDERED \"my_table_10bc2c,c020ad\" -->\n  <table>\n    ...\n  </table>\n</div>\n<!-- _RENDERED \"button_309dcf,31c0da\" -->\n<button>Click me!</button>\n

    Each <!-- _RENDERED --> comment includes comma-separated data - a unique hash for the component class, e.g. my_table_10bc2c, and the component ID, e.g. c020ad.

    This way, we or the user can freely pass the rendered around or transform it, treating it as a string to add / remove / replace bits. As long as the <!-- _RENDERED --> comments remain in the rendered string, we will be able to deduce which JS and CSS dependencies the component needs.

  2. Post-process the rendered HTML, extracting the <!-- _RENDERED --> comments, and instead inserting the corresponding JS and CSS dependencies.

    If we dealt only with JS, then we could get away with processing the <!-- _RENDERED --> comments on the client (browser). However, the CSS needs to be processed still on the server, so the browser receives CSS styles already inserted as <style> or <link> HTML tags. Because if we do not do that, we get a flash of unstyled content, as there will be a delay between when the HTML page loaded and when the CSS was fetched and loaded.

    So, assuming that a user has already rendered their template, which still contains <!-- _RENDERED --> comments, we need to extract and process these comments.

    There's multiple ways to achieve this:

    • If users are using Component.render() or Component.render_to_response(), these post-process the <!-- _RENDERED --> comments by default.

    • NOTE: Users are able to opt out of the post-processing by setting deps_strategy=\"ignore\".

    • If one renders a Template directly, the <!-- _RENDERED --> will be processed too. We achieve this by modifying Django's Template.render() method.

    • For advanced use cases, users may use render_dependencies() directly. This is the function that Component.render() calls internally.

    render_dependencies(), whether called directly, or other way, does the following:

    1. Find all <!-- _RENDERED --> comments, and for each comment:

    2. Look up the corresponding component class.

    3. Get the component's inlined JS / CSS from Component.js/css, and linked JS / CSS from Component.Media.js/css.

    4. Generate JS script that loads the JS / CSS dependencies.

    5. Insert the JS scripts either at the end of <body>, or in place of {% component_dependencies %} / {% component_js_dependencies %} tags.

    6. To avoid the flash of unstyled content, we need place the styles into the HTML instead of dynamically loading them from within a JS script. The CSS is placed either at the end of <head>, or in place of {% component_dependencies %} / {% component_css_dependencies %}

    7. We cache the component's inlined JS and CSS, so they can be fetched via an URL, so the inlined JS / CSS an be treated the same way as the JS / CSS dependencies set in Component.Media.js/css.

      • NOTE: While this is currently not entirely necessary, it opens up the doors for allowing plugins to post-process the inlined JS and CSS. Because after it has been post-processed, we need to store it somewhere.
  3. Server returns the post-processed HTML.

  4. In the browser, the generated JS script from step 2.4 is executed. It goes through all JS and CSS dependencies it was given. If some JS / CSS was already loaded, it is NOT fetched again. Otherwise it generates the corresponding <script> or <link> HTML tags to load the JS / CSS dependencies.

    In the browser, the \"dependency manager JS\" may look like this:

    // Load JS or CSS script if not loaded already\nComponents.loadJs('<script src=\"/abc/xyz/script.js\">');\nComponents.loadCss('<link href=\"/abc/xyz/style.css\">');\n\n// Or mark one as already-loaded, so it is ignored when\n// we call `loadJs`\nComponents.markScriptLoaded(\"js\", \"/abc/def\");\n

    Note that loadJs() / loadCss() receive whole <script> / <link> tags, not just the URL. This is because when Django's Media class renders JS and CSS, it formats it as <script> and <link> tags. And we allow users to modify how the JS and CSS should be rendered into the <script> and <link> tags.

    So, if users decided to add an extra attribute to their <script> tags, e.g. <script defer src=\"http://...\"></script>, then this way we make sure that the defer attribute will be present on the <script> tag when it is inserted into the DOM at the time of loading the JS script.

  5. To be able to fetch component's inlined JS and CSS, django-components adds a URL path under:

    /components/cache/<str:comp_cls_id>.<str:script_type>/

    E.g. /components/cache/MyTable_10bc2c.js/

    This endpoint takes the component's unique ID, e.g. MyTable_10bc2c, and looks up the component's inlined JS or CSS.

Thus, with this approach, we ensure that:

  1. All JS / CSS dependencies are loaded / executed only once.
  2. The approach is compatible with HTML fragments
  3. The approach is compatible with JS / CSS variables.
  4. Inlined JS / CSS may be post-processed by plugins
"},{"location":"guides/devguides/slot_rendering/","title":"Slot rendering","text":"

This doc serves as a primer on how component slots and fills are resolved.

"},{"location":"guides/devguides/slot_rendering/#flow","title":"Flow","text":"
  1. Imagine you have a template. Some kind of text, maybe HTML:

    | ------\n| ---------\n| ----\n| -------\n

  2. The template may contain some vars, tags, etc

    | -- {{ my_var }} --\n| ---------\n| ----\n| -------\n

  3. The template also contains some slots, etc

    | -- {{ my_var }} --\n| ---------\n| -- {% slot \"myslot\" %} ---\n| -- {% endslot %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| -- {% endslot %} ---\n| -------\n

  4. Slots may be nested

    | -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %} ---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- JKL {{ my_var }}\n| -- {% endslot %} ---\n| -------\n

  5. Some slots may be inside fills for other components

    | -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %}---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ------\n| -- {% component \"mycomp\" %} ---\n| ---- {% slot \"myslot\" %} ---\n| ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n| ---- {% endslot %} ---\n| -- {% endcomponent %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- PQR {{ my_var }}\n| -- {% endslot %} ---\n| -------\n

  6. The names of the slots and fills may be defined using variables

    | -- {% slot slot_name %} ---\n| ---- STU {{ my_var }}\n| -- {% endslot %} ---\n| -------\n

  7. The slot and fill names may be defined using for loops or other variables defined within the template (e.g. {% with %} tag or {% ... as var %} syntax)

    | -- {% for slot_name in slots %} ---\n| ---- {% slot slot_name %} ---\n| ------ STU {{ slot_name }}\n| ---- {% endslot %} ---\n| -- {% endfor %} ---\n| -------\n

  8. Variables for names and for loops allow us implement \"passthrough slots\" - that is, taking all slots that our component received, and passing them to a child component, dynamically.

    | -- {% component \"mycomp\" %} ---\n| ---- {% for slot_name in slots %} ---\n| ------ {% fill slot_name %} ---\n| -------- {% slot slot_name %} ---\n| ---------- XYZ {{ slot_name }}\n| --------- {% endslot %}\n| ------- {% endfill %}\n| ---- {% endfor %} ---\n| -- {% endcomponent %} ---\n| ----\n

  9. Putting that all together, a document may look like this:

    | -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %}---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ------\n| -- {% component \"mycomp\" %} ---\n| ---- {% slot \"myslot\" %} ---\n| ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n| ---- {% endslot %} ---\n| -- {% endcomponent %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- PQR {{ my_var }}\n| -- {% endslot %} ---\n| -------\n| -- {% for slot_name in slots %} ---\n| ---- {% component \"mycomp\" %} ---\n| ------- {% slot slot_name %}\n| ---------- STU {{ slot_name }}\n| ------- {% endslot %}\n| ---- {% endcomponent %} ---\n| -- {% endfor %} ---\n| ----\n| -- {% component \"mycomp\" %} ---\n| ---- {% for slot_name in slots %} ---\n| ------ {% fill slot_name %} ---\n| -------- {% slot slot_name %} ---\n| ---------- XYZ {{ slot_name }}\n| --------- {% endslot %}\n| ------- {% endfill %}\n| ---- {% endfor %} ---\n| -- {% endcomponent %} ---\n| -------\n

  10. Given the above, we want to render the slots with {% fill %} tag that were defined OUTSIDE of this template. How do I do that?

    NOTE: Before v0.110, slots were resolved statically, by walking down the Django Template and Nodes. However, this did not allow for using for loops or other variables defined in the template.

    Currently, this consists of 2 steps:

    1. If a component is rendered within a template using {% component %} tag, determine the given {% fill %} tags in the component's body (the content in between {% component %} and {% endcomponent %}).

      After this step, we know about all the fills that were passed to the component.

    2. Then we simply render the template as usual. And then we reach the {% slot %} tag, we search the context for the available fills.

      • If there IS a fill with the same name as the slot, we render the fill.
      • If the slot is marked default, and there is a fill named default, then we render that.
      • Otherwise, we render the slot's default content.
  11. Obtaining the fills from {% fill %}.

    When a component is rendered with {% component %} tag, and it has some content in between {% component %} and {% endcomponent %}, we want to figure out if that content is a default slot (no {% fill %} used), or if there is a collection of named {% fill %} tags:

    Default slot:

    | -- {% component \"mycomp\" %} ---\n| ---- STU {{ slot_name }}\n| -- {% endcomponent %} ---\n

    Named slots:

    | -- {% component \"mycomp\" %} ---\n| ---- {% fill \"slot_a\" %}\n| ------ STU\n| ---- {% endslot %}\n| ---- {% fill \"slot_b\" %}\n| ------ XYZ\n| ---- {% endslot %}\n| -- {% endcomponent %} ---\n

    To respect any forloops or other variables defined within the template to which the fills may have access, we:

    1. Render the content between {% component %} and {% endcomponent %} using the context outside of the component.
    2. When we reach a {% fill %} tag, we capture any variables that were created between the {% component %} and {% fill %} tags.
    3. When we reach {% fill %} tag, we do not continue rendering deeper. Instead we make a record that we found the fill tag with given name, kwargs, etc.
    4. After the rendering is done, we check if we've encountered any fills. If yes, we expect only named fills. If no, we assume that the the component's body is a default slot.
    5. Lastly we process the found fills, and make them available to the context, so any slots inside the component may access these fills.
  12. Rendering slots

    Slot rendering works similarly to collecting fills, in a sense that we do not search for the slots ahead of the time, but instead let Django handle the rendering of the template, and we step in only when Django come across as {% slot %} tag.

    When we reach a slot tag, we search the context for the available fills.

    • If there IS a fill with the same name as the slot, we render the fill.
    • If the slot is marked default, and there is a fill named default, then we render that.
    • Otherwise, we render the slot's default content.
"},{"location":"guides/devguides/slot_rendering/#using-the-correct-context-in-slotfill-tags","title":"Using the correct context in {% slot/fill %} tags","text":"

In previous section, we said that the {% fill %} tags should be already rendered by the time they are inserted into the {% slot %} tags.

This is not quite true. To help you understand, consider this complex case:

| -- {% for var in [1, 2, 3] %} ---\n| ---- {% component \"mycomp2\" %} ---\n| ------ {% fill \"first\" %}\n| ------- STU {{ my_var }}\n| -------     {{ var }}\n| ------ {% endfill %}\n| ------ {% fill \"second\" %}\n| -------- {% component var=var my_var=my_var %}\n| ---------- VWX {{ my_var }}\n| -------- {% endcomponent %}\n| ------ {% endfill %}\n| ---- {% endcomponent %} ---\n| -- {% endfor %} ---\n| -------\n

We want the forloop variables to be available inside the {% fill %} tags. Because of that, however, we CANNOT render the fills/slots in advance.

Instead, our solution is closer to how Vue handles slots. In Vue, slots are effectively functions that accept a context variables and render some content.

While we do not wrap the logic in a function, we do PREPARE IN ADVANCE: 1. The content that should be rendered for each slot 2. The context variables from get_template_data()

Thus, once we reach the {% slot %} node, in it's render() method, we access the data above, and, depending on the context_behavior setting, include the current context or not. For more info, see SlotNode.render().

"},{"location":"guides/devguides/slots_and_blocks/","title":"Using slot and block tags","text":"
  1. First let's clarify how include and extends tags work inside components.

    When component template includes include or extends tags, it's as if the \"included\" template was inlined. So if the \"included\" template contains slot tags, then the component uses those slots.

    If you have a template abc.html:

    <div>\n  hello\n  {% slot \"body\" %}{% endslot %}\n</div>\n

    And components that make use of abc.html via include or extends:

    from django_components import Component, register\n\n@register(\"my_comp_extends\")\nclass MyCompWithExtends(Component):\n    template = \"\"\"{% extends \"abc.html\" %}\"\"\"\n\n@register(\"my_comp_include\")\nclass MyCompWithInclude(Component):\n    template = \"\"\"{% include \"abc.html\" %}\"\"\"\n

    Then you can set slot fill for the slot imported via include/extends:

    {% component \"my_comp_extends\" %}\n    {% fill \"body\" %}\n        123\n    {% endfill %}\n{% endcomponent %}\n

    And it will render:

    <div>\n  hello\n  123\n</div>\n

  2. Slot and block

    If you have a template abc.html like so:

    <div>\n  hello\n  {% block inner %}\n    1\n    {% slot \"body\" %}\n      2\n    {% endslot %}\n  {% endblock %}\n</div>\n

    and component my_comp:

    @register(\"my_comp\")\nclass MyComp(Component):\n    template_file = \"abc.html\"\n

    Then:

    1. Since the block wasn't overriden, you can use the body slot:

      {% component \"my_comp\" %}\n    {% fill \"body\" %}\n        XYZ\n    {% endfill %}\n{% endcomponent %}\n

      And we get:

      <div>hello 1 XYZ</div>\n
    2. blocks CANNOT be overriden through the component tag, so something like this:

      {% component \"my_comp\" %}\n    {% fill \"body\" %}\n        XYZ\n    {% endfill %}\n{% endcomponent %}\n{% block \"inner\" %}\n    456\n{% endblock %}\n

      Will still render the component content just the same:

      <div>hello 1 XYZ</div>\n
    3. You CAN override the block tags of abc.html if the component template uses extends. In that case, just as you would expect, the block inner inside abc.html will render OVERRIDEN:

      @register(\"my_comp\")\nclass MyComp(Component):\n    template = \"\"\"\n        {% extends \"abc.html\" %}\n        {% block inner %}\n          OVERRIDEN\n        {% endblock %}\n    \"\"\"\n
    4. This is where it gets interesting (but still intuitive). You can insert even new slots inside these \"overriding\" blocks:

      @register(\"my_comp\")\nclass MyComp(Component):\n    template = \"\"\"\n      {% extends \"abc.html\" %}\n\n      {% load component_tags %}\n      {% block \"inner\" %}\n        OVERRIDEN\n        {% slot \"new_slot\" %}\n          hello\n        {% endslot %}\n      {% endblock %}\n    \"\"\"\n

      And you can then pass fill for this new_slot when rendering the component:

      {% component \"my_comp\" %}\n    {% fill \"new_slot\" %}\n        XYZ\n    {% endfill %}\n{% endcomponent %}\n

      NOTE: Currently you can supply fills for both new_slot and body slots, and you will not get an error for an invalid/unknown slot name. But since body slot is not rendered, it just won't do anything. So this renders the same as above:

      {% component \"my_comp\" %}\n    {% fill \"new_slot\" %}\n        XYZ\n    {% endfill %}\n    {% fill \"body\" %}\n        www\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"guides/other/troubleshooting/","title":"Troubleshooting","text":"

As larger projects get more complex, it can be hard to debug issues. Django Components provides a number of tools and approaches that can help you with that.

"},{"location":"guides/other/troubleshooting/#component-and-slot-highlighting","title":"Component and slot highlighting","text":"

Django Components provides a visual debugging feature that helps you understand the structure and boundaries of your components and slots. When enabled, it adds a colored border and a label around each component and slot on your rendered page.

To enable component and slot highlighting for all components and slots, set highlight_components and highlight_slots to True in extensions defaults in your settings.py file:

from django_components import ComponentsSettings\n\nCOMPONENTS = ComponentsSettings(\n    extensions_defaults={\n        \"debug_highlight\": {\n            \"highlight_slots\": True,\n            \"highlight_components\": True,\n        },\n    },\n)\n

Alternatively, you can enable highlighting for specific components by setting Component.DebugHighlight.highlight_components to True:

class MyComponent(Component):\n    class DebugHighlight:\n        highlight_components = True\n        highlight_slots = True\n

Components will be highlighted with a blue border and label:

While the slots will be highlighted with a red border and label:

Warning

Use this feature ONLY in during development. Do NOT use it in production.

"},{"location":"guides/other/troubleshooting/#component-path-in-errors","title":"Component path in errors","text":"

When an error occurs, the error message will show the path to the component that caused the error. E.g.

KeyError: \"An error occured while rendering components MyPage > MyLayout > MyComponent > Childomponent(slot:content)\n

The error message contains also the slot paths, so if you have a template like this:

{% component \"my_page\" %}\n    {% slot \"content\" %}\n        {% component \"table\" %}\n            {% slot \"header\" %}\n                {% component \"table_header\" %}\n                    ...  {# ERROR HERE #}\n                {% endcomponent %}\n            {% endslot %}\n        {% endcomponent %}\n    {% endslot %}\n{% endcomponent %}\n

Then the error message will show the path to the component that caused the error:

KeyError: \"An error occured while rendering components my_page > layout > layout(slot:content) > my_page(slot:content) > table > table(slot:header) > table_header > table_header(slot:content)\n
"},{"location":"guides/other/troubleshooting/#debug-and-trace-logging","title":"Debug and trace logging","text":"

Django components supports logging with Django.

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\nimport sys\n\nLOGGING = {\n    'version': 1,\n    'disable_existing_loggers': False,\n    \"handlers\": {\n        \"console\": {\n            'class': 'logging.StreamHandler',\n            'stream': sys.stdout,\n        },\n    },\n    \"loggers\": {\n        \"django_components\": {\n            \"level\": logging.DEBUG,\n            \"handlers\": [\"console\"],\n        },\n    },\n}\n

Info

To set TRACE level, set \"level\" to 5:

LOGGING = {\n    \"loggers\": {\n        \"django_components\": {\n            \"level\": 5,\n            \"handlers\": [\"console\"],\n        },\n    },\n}\n
"},{"location":"guides/other/troubleshooting/#logger-levels","title":"Logger levels","text":"

As of v0.126, django-components primarily uses these logger levels:

  • DEBUG: Report on loading associated HTML / JS / CSS files, autodiscovery, etc.
  • TRACE: Detailed interaction of components and slots. Logs when template tags, components, and slots are started / ended rendering, and when a slot is filled.
"},{"location":"guides/other/troubleshooting/#slot-origin","title":"Slot origin","text":"

When you pass a slot fill to a Component, the component and slot names is remebered on the slot object.

Thus, you can check where a slot was filled from by printing it out:

class MyComponent(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]):\n        print(self.slots)\n

might print:

{\n    'content': <Slot component_name='layout' slot_name='content'>,\n    'header': <Slot component_name='my_page' slot_name='header'>,\n    'left_panel': <Slot component_name='layout' slot_name='left_panel'>,\n}\n
"},{"location":"guides/other/troubleshooting/#agentic-debugging","title":"Agentic debugging","text":"

All the features above make django-components to work really well with coding AI agents like Github Copilot or CursorAI.

To debug component rendering with LLMs, you want to provide the LLM with:

  1. The components source code
  2. The rendered output
  3. As much additional context as possible

Your codebase already contains the components source code, but not the latter two.

"},{"location":"guides/other/troubleshooting/#providing-rendered-output","title":"Providing rendered output","text":"

To provide the LLM with the rendered output, you can simply export the rendered output to a file.

rendered = ProjectPage.render(...)\nwith open(\"result.html\", \"w\") as f:\n    f.write(rendered)\n

If you're using render_to_response, access the output from the HttpResponse object:

response = ProjectPage.render_to_response(...)\nwith open(\"result.html\", \"wb\") as f:\n    f.write(response.content)\n
"},{"location":"guides/other/troubleshooting/#providing-contextual-logs","title":"Providing contextual logs","text":"

Next, we provide the agent with info on HOW we got the result that we have. We do so by providing the agent with the trace-level logs.

In your settings.py, configure the trace-level logs to be written to the django_components.log file:

LOGGING = {\n    \"version\": 1,\n    \"disable_existing_loggers\": False,\n    \"handlers\": {\n        \"file\": {\n            \"class\": \"logging.FileHandler\",\n            \"filename\": \"django_components.log\",\n            \"mode\": \"w\",  # Overwrite the file each time\n        },\n    },\n    \"loggers\": {\n        \"django_components\": {\n            \"level\": 5,\n            \"handlers\": [\"file\"],\n        },\n    },\n}\n
"},{"location":"guides/other/troubleshooting/#prompting-the-agent","title":"Prompting the agent","text":"

Now, you can prompt the agent and include the trace log and the rendered output to guide the agent with debugging.

I have a django-components (DJC) project. DJC is like if Vue or React component-based web development but made for Django ecosystem.

In the view project_view, I am rendering the ProjectPage component. However, the output is not as expected. The output is missing the tabs.

You have access to the full log trace in django_components.log.

You can also see the rendered output in result.html.

With this information, help me debug the issue.

First, tell me what kind of info you would be looking for in the logs, and why (how it relates to understanding the cause of the bug).

Then tell me if that info was there, and what the implications are.

Finally, tell me what you would do to fix the issue.

"},{"location":"guides/setup/caching/","title":"Caching","text":"

This page describes the kinds of assets that django-components caches and how to configure the cache backends.

"},{"location":"guides/setup/caching/#component-caching","title":"Component caching","text":"

You can cache the output of your components by setting the Component.Cache options.

Read more about Component caching.

"},{"location":"guides/setup/caching/#components-js-and-css-files","title":"Component's JS and CSS files","text":"

django-components simultaneously supports:

  • Rendering and fetching components as HTML fragments
  • Allowing components (even fragments) to have JS and CSS files associated with them
  • Features like JS/CSS variables or CSS scoping

To achieve all this, django-components defines additional temporary JS and CSS files. These temporary files need to be stored somewhere, so that they can be fetched by the browser when the component is rendered as a fragment. And for that, django-components uses Django's cache framework.

This includes:

  • Inlined JS/CSS defined via Component.js and Component.css
  • JS/CSS variables generated from get_js_data() and get_css_data()

By default, django-components uses Django's local memory cache backend to store these assets. You can configure it to use any of your Django cache backends by setting the COMPONENTS.cache option in your settings:

COMPONENTS = {\n    # Name of the cache backend to use\n    \"cache\": \"my-cache-backend\",\n}\n

The value should be the name of one of your configured cache backends from Django's CACHES setting.

For example, to use Redis for caching component assets:

CACHES = {\n    \"default\": {\n        \"BACKEND\": \"django.core.cache.backends.locmem.LocMemCache\",\n    },\n    \"component-media\": {\n        \"BACKEND\": \"django.core.cache.backends.redis.RedisCache\",\n        \"LOCATION\": \"redis://127.0.0.1:6379/1\",\n    }\n}\n\nCOMPONENTS = {\n    # Use the Redis cache backend\n    \"cache\": \"component-media\",\n}\n

See COMPONENTS.cache for more details about this setting.

"},{"location":"guides/setup/development_server/","title":"Development server","text":""},{"location":"guides/setup/development_server/#reload-dev-server-on-component-file-changes","title":"Reload dev server on component file changes","text":"

This is relevant if you are using the project structure as shown in our examples, where HTML, JS, CSS and Python are in separate files and nested in a directory.

sampleproject/\n\u251c\u2500\u2500 components/\n\u2502   \u2514\u2500\u2500 calendar/\n\u2502       \u251c\u2500\u2500 calendar.py\n\u2502       \u2514\u2500\u2500 calendar.html\n\u2502       \u2514\u2500\u2500 calendar.css\n\u2502       \u2514\u2500\u2500 calendar.js\n\u251c\u2500\u2500 sampleproject/\n\u251c\u2500\u2500 manage.py\n\u2514\u2500\u2500 requirements.txt\n

In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.

From relevant StackOverflow thread:

TL;DR is that the server won't reload if it thinks the changed file is in a templates directory, or in a nested sub directory of a templates directory. This is by design.

To make the dev server reload on all component files, set reload_on_file_change to True. This configures Django to watch for component files too.

Warning

This setting should be enabled only for the dev environment!

"},{"location":"overview/code_of_conduct/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"overview/code_of_conduct/#our-pledge","title":"Our Pledge","text":"

In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.

"},{"location":"overview/code_of_conduct/#our-standards","title":"Our Standards","text":"

Examples of behavior that contributes to creating a positive environment include:

  • Using welcoming and inclusive language
  • Being respectful of differing viewpoints and experiences
  • Gracefully accepting constructive criticism
  • Focusing on what is best for the community
  • Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

  • The use of sexualized language or imagery and unwelcome sexual attention or advances
  • Trolling, insulting/derogatory comments, and personal or political attacks
  • Public or private harassment
  • Publishing others' private information, such as a physical or electronic address, without explicit permission
  • Other conduct which could reasonably be considered inappropriate in a professional setting
"},{"location":"overview/code_of_conduct/#our-responsibilities","title":"Our Responsibilities","text":"

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.

"},{"location":"overview/code_of_conduct/#scope","title":"Scope","text":"

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

"},{"location":"overview/code_of_conduct/#enforcement","title":"Enforcement","text":"

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at emil@emilstenstrom.se. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

"},{"location":"overview/code_of_conduct/#attribution","title":"Attribution","text":"

This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq

"},{"location":"overview/community/","title":"Community","text":""},{"location":"overview/community/#community-questions","title":"Community questions","text":"

The best place to ask questions is in our Github Discussion board.

Please, before opening a new discussion, check if similar discussion wasn't opened already.

"},{"location":"overview/community/#community-examples","title":"Community examples","text":"

One of our goals with django-components is to make it easy to share components between projects (see how to package components). 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.

  • django-htmx-components: A set of components for use with htmx.

  • djc-heroicons: A component that renders icons from Heroicons.com.

"},{"location":"overview/compatibility/","title":"Compatibility","text":"

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.1, 5.2 3.11 4.2, 5.1, 5.2 3.12 4.2, 5.1, 5.2 3.13 5.1, 5.2"},{"location":"overview/compatibility/#operating-systems","title":"Operating systems","text":"

django-components is tested against Ubuntu and Windows, and should work on any operating system that supports Python.

Note

django-components uses Rust-based parsers for better performance.

These sub-packages are built with maturin which supports a wide range of operating systems, architectures, and Python versions (see the full list).

This should cover most of the cases.

However, if your environment is not supported, you will need to install Rust and Cargo to build the sub-packages from source.

"},{"location":"overview/contributing/","title":"Contributing","text":""},{"location":"overview/contributing/#bug-reports","title":"Bug reports","text":"

If you find a bug, please open an issue with detailed description of what happened.

"},{"location":"overview/contributing/#bug-fixes","title":"Bug fixes","text":"

If you found a fix for a bug or typo, go ahead and open a PR with a fix. We'll help you out with the rest!

"},{"location":"overview/contributing/#feature-requests","title":"Feature requests","text":"

For feature requests or suggestions, please open either a discussion or an issue.

"},{"location":"overview/contributing/#getting-involved","title":"Getting involved","text":"

django_components is still under active development, and there's much to build, so come aboard!

"},{"location":"overview/contributing/#sponsoring","title":"Sponsoring","text":"

Another way you can get involved is by donating to the development of django_components.

"},{"location":"overview/development/","title":"Development","text":""},{"location":"overview/development/#install-locally-and-run-the-tests","title":"Install locally and run the tests","text":"

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\ncd django-components\n

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

pip install -r requirements-dev.txt\n

You also have to install this local django-components version. Use -e for editable mode so you don't have to re-install after every change:

pip install -e .\n

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

pytest\n

The library is also tested across many versions of Python and Django. To run tests that way:

pyenv install -s 3.8\npyenv install -s 3.9\npyenv install -s 3.10\npyenv install -s 3.11\npyenv install -s 3.12\npyenv install -s 3.13\npyenv local 3.8 3.9 3.10 3.11 3.12 3.13\ntox -p\n

To run tests for a specific Python version, use:

tox -e py38\n

NOTE: See the available environments in tox.ini.

And to run only linters, use:

tox -e mypy,flake8,isort,black\n
"},{"location":"overview/development/#running-playwright-tests","title":"Running Playwright tests","text":"

We use Playwright for end-to-end tests. You will therefore need to install Playwright to be able to run these tests.

Luckily, Playwright makes it very easy:

pip install -r requirements-dev.txt\nplaywright install chromium --with-deps\n

After Playwright is ready, simply run the tests with tox:

tox\n
"},{"location":"overview/development/#developing-against-live-django-app","title":"Developing against live Django app","text":"

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\n
  2. Install dependencies from the requirements.txt file:

    pip install -r requirements.txt\n
  3. Link to your local version of django-components:

    pip install -e ..\n

    Note

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

  4. Start Django server

    python manage.py runserver\n

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

"},{"location":"overview/development/#building-js-code","title":"Building JS code","text":"

django_components uses a bit of JS code to:

  • Manage the loading of JS and CSS files used by the components
  • Allow to pass data from Python to JS

When you make changes to this JS code, you also need to compile it:

  1. Make sure you are inside src/django_components_js:

    cd src/django_components_js\n
  2. Install the JS dependencies

    npm install\n
  3. Compile the JS/TS code:

    python build.py\n

    The script will combine all JS/TS code into a single .js file, minify it, and copy it to django_components/static/django_components/django_components.min.js.

"},{"location":"overview/development/#packaging-and-publishing","title":"Packaging and publishing","text":"

To package the library into a distribution that can be published to PyPI, run:

# Install pypa/build\npython -m pip install build --user\n# Build a binary wheel and a source tarball\npython -m build --sdist --wheel --outdir dist/ .\n

To publish the package to PyPI, use twine (See Python user guide):

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

See the full workflow here.

"},{"location":"overview/development/#maintenance","title":"Maintenance","text":""},{"location":"overview/development/#updating-supported-versions","title":"Updating supported versions","text":"

The scripts/supported_versions.py script can be used to update the supported versions.

python scripts/supported_versions.py\n

This will check the current versions of Django and Python, and will print to the terminal all the places that need updating and what to set them to.

"},{"location":"overview/development/#updating-link-references","title":"Updating link references","text":"

The scripts/validate_links.py script can be used to update the link references.

python scripts/validate_links.py\n

When new version of Django is released, you can use the script to update the URLs pointing to the Django documentation.

First, you need to update the URL_REWRITE_MAP in the script to point to the new version of Django.

Then, you can run the script to update the URLs in the codebase.

python scripts/validate_links.py --rewrite\n
"},{"location":"overview/development/#development-guides","title":"Development guides","text":"

Head over to Dev guides for a deep dive into how django_components' features are implemented.

"},{"location":"overview/installation/","title":"Installation","text":""},{"location":"overview/installation/#basic-installation","title":"Basic installation","text":"
  1. Install django_components into your environment:

    pip install django_components\n
  2. Load django_components into Django by adding it into INSTALLED_APPS in your settings file:

    # app/settings.py\nINSTALLED_APPS = [\n    ...,\n    'django_components',\n]\n
  3. BASE_DIR setting is required. Ensure that it is defined:

    # app/settings.py\nfrom pathlib import Path\n\nBASE_DIR = Path(__file__).resolve().parent.parent\n
  4. Next, modify TEMPLATES section of settings.py as follows:

    • Remove 'APP_DIRS': True,
      • NOTE: Instead of APP_DIRS: True, we will use django.template.loaders.app_directories.Loader, which has the same effect.
    • Add loaders to OPTIONS list and set it to following value:

    This allows Django to load component HTML files as Django templates.

    TEMPLATES = [\n    {\n        ...,\n        'OPTIONS': {\n            ...,\n            'loaders':[(\n                'django.template.loaders.cached.Loader', [\n                    # Default Django loader\n                    'django.template.loaders.filesystem.Loader',\n                    # Including this is the same as APP_DIRS=True\n                    'django.template.loaders.app_directories.Loader',\n                    # Components loader\n                    'django_components.template_loader.Loader',\n                ]\n            )],\n        },\n    },\n]\n
  5. Add django-component's URL paths to your urlpatterns:

    Django components already prefixes all URLs with components/. So when you are adding the URLs to urlpatterns, you can use an empty string as the first argument:

    from django.urls import include, path\n\nurlpatterns = [\n    ...\n    path(\"\", include(\"django_components.urls\")),\n]\n
"},{"location":"overview/installation/#adding-support-for-js-and-css","title":"Adding support for JS and CSS","text":"

If you want to use JS or CSS with components, you will need to:

  1. Add \"django_components.finders.ComponentsFileSystemFinder\" to STATICFILES_FINDERS in your settings file.

    This allows Django to serve component JS and CSS as static files.

    STATICFILES_FINDERS = [\n    # Default finders\n    \"django.contrib.staticfiles.finders.FileSystemFinder\",\n    \"django.contrib.staticfiles.finders.AppDirectoriesFinder\",\n    # Django components\n    \"django_components.finders.ComponentsFileSystemFinder\",\n]\n
  2. Optional. If you want to change where the JS and CSS is rendered, use {% component_js_dependencies %} and {% component_css_dependencies %}.

    By default, the JS <script> and CSS <link> tags are automatically inserted into the HTML (See Default JS / CSS locations).

    <!doctype html>\n<html>\n  <head>\n    ...\n    {% component_css_dependencies %}\n  </head>\n  <body>\n    ...\n    {% component_js_dependencies %}\n  </body>\n</html>\n
  3. Optional. By default, components' JS and CSS files are cached in memory.

    If you want to change the cache backend, set the COMPONENTS.cache setting.

    Read more in Caching.

"},{"location":"overview/installation/#optional","title":"Optional","text":""},{"location":"overview/installation/#builtin-template-tags","title":"Builtin template tags","text":"

To avoid loading the app in each template using {% load component_tags %}, you can add the tag as a 'builtin' in settings.py:

TEMPLATES = [\n    {\n        ...,\n        'OPTIONS': {\n            ...,\n            'builtins': [\n                'django_components.templatetags.component_tags',\n            ]\n        },\n    },\n]\n
"},{"location":"overview/installation/#component-directories","title":"Component directories","text":"

django-components needs to know where to search for component HTML, JS and CSS files.

There are two ways to configure the component directories:

  • COMPONENTS.dirs sets global component directories.
  • COMPONENTS.app_dirs sets app-level component directories.

By default, django-components will look for a top-level /components directory, {BASE_DIR}/components, equivalent to:

from django_components import ComponentsSettings\n\nCOMPONENTS = ComponentsSettings(\n    dirs=[\n        ...,\n        Path(BASE_DIR) / \"components\",\n    ],\n)\n

For app-level directories, the default is [app]/components, equivalent to:

from django_components import ComponentsSettings\n\nCOMPONENTS = ComponentsSettings(\n    app_dirs=[\n        ...,\n        \"components\",\n    ],\n)\n

Note

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

Now you're all set! Read on to find out how to build your first component.

"},{"location":"overview/license/","title":"License","text":"

MIT License

Copyright (c) 2019 Emil Stenstr\u00f6m

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"},{"location":"overview/migrating/","title":"Migrating","text":"

Django-components is still in active development.

Since django-components is in pre-1.0 development, the public API is not yet frozen. This means that there may be breaking changes between minor versions. We try to minimize the number of breaking changes, but sometimes it's unavoidable.

When upgrading, please read the Release notes.

"},{"location":"overview/migrating/#migrating-in-pre-v10","title":"Migrating in pre-v1.0","text":"

If you're on older pre-v1.0 versions of django-components, we recommend doing step-wise upgrades in the following order:

  • v0.26
  • v0.50
  • v0.70
  • v0.77
  • v0.81
  • v0.85
  • v0.92
  • v0.100
  • v0.110
  • v0.140

These versions introduced breaking changes that are not backwards compatible.

"},{"location":"overview/performance/","title":"Performance","text":"

We track the performance of django-components using ASV.

See the benchmarks dashboard.

"},{"location":"overview/security_notes/","title":"Security notes \ud83d\udea8","text":"

It is strongly recommended to read this section before using django-components in production.

"},{"location":"overview/security_notes/#static-files","title":"Static files","text":"

TL;DR: No action needed from v0.100 onwards. Before v0.100, use safer_staticfiles to avoid exposing backend logic.

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.

"},{"location":"overview/security_notes/#static-files-prior-to-v0100","title":"Static files prior to v0.100","text":"

Prior to v0.100, if your were using django.contrib.staticfiles to collect static files, no distinction was made between the different kinds of files.

As a result, your Python code and templates may inadvertently become available on your static file server. You probably don't want this, as parts of your backend logic will be exposed, posing a potential security vulnerability.

From v0.27 until v0.100, django-components shipped with an additional installable app django_components.safer_staticfiles. It was a drop-in replacement for django.contrib.staticfiles. Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server.

To use it, add it to INSTALLED_APPS and remove django.contrib.staticfiles.

INSTALLED_APPS = [\n    # 'django.contrib.staticfiles',   # <-- REMOVE\n    'django_components',\n    'django_components.safer_staticfiles'  # <-- ADD\n]\n

If you are on an pre-v0.27 version of django-components, your alternatives are:

  • a) passing --ignore <pattern> options to the collecstatic CLI command,
  • b) defining a subclass of StaticFilesConfig.

Both routes are described in the official docs of the staticfiles app.

Note that safer_staticfiles excludes the .py and .html files for collectstatic command:

python manage.py collectstatic\n

but it is ignored on the development server:

python manage.py runserver\n

For a step-by-step guide on deploying production server with static files, see the demo project.

See the older versions of the sampleproject for a setup with pre-v0.100 version.

"},{"location":"overview/welcome/","title":"Welcome to Django Components","text":"

django-components combines Django's templating system with the modularity seen in modern frontend frameworks like Vue or React.

With django-components you can support Django projects small and large without leaving the Django ecosystem.

"},{"location":"overview/welcome/#quickstart","title":"Quickstart","text":"

A component in django-components can be as simple as a Django template and Python code to declare the component:

components/calendar/calendar.html
<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n
components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n

Or a combination of Django template, Python, CSS, and Javascript:

components/calendar/calendar.html
<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n
components/calendar/calendar.css
.calendar {\n  width: 200px;\n  background: pink;\n}\n
components/calendar/calendar.js
document.querySelector(\".calendar\").onclick = () => {\n  alert(\"Clicked calendar!\");\n};\n
components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    js_file = \"calendar.js\"\n    css_file = \"calendar.css\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\"date\": kwargs[\"date\"]}\n

Use the component like this:

{% component \"calendar\" date=\"2024-11-06\" %}{% endcomponent %}\n

And this is what gets rendered:

<div class=\"calendar-component\">\n  Today's date is <span>2024-11-06</span>\n</div>\n

Read on to learn about all the exciting details and configuration possibilities!

(If you instead prefer to jump right into the code, check out the example project)

"},{"location":"overview/welcome/#features","title":"Features","text":""},{"location":"overview/welcome/#modern-and-modular-ui","title":"Modern and modular UI","text":"
  • Create self-contained, reusable UI elements.
  • Each component can include its own HTML, CSS, and JS, or additional third-party JS and CSS.
  • HTML, CSS, and JS can be defined on the component class, or loaded from files.
from django_components import Component\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template = \"\"\"\n        <div class=\"calendar\">\n            Today's date is\n            <span>{{ date }}</span>\n        </div>\n    \"\"\"\n\n    css = \"\"\"\n        .calendar {\n            width: 200px;\n            background: pink;\n        }\n    \"\"\"\n\n    js = \"\"\"\n        document.querySelector(\".calendar\")\n            .addEventListener(\"click\", () => {\n                alert(\"Clicked calendar!\");\n            });\n    \"\"\"\n\n    # Additional JS and CSS\n    class Media:\n        js = [\"https://cdn.jsdelivr.net/npm/htmx.org@2/dist/htmx.min.js\"]\n        css = [\"bootstrap/dist/css/bootstrap.min.css\"]\n\n    # Variables available in the template\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"date\"]\n        }\n
"},{"location":"overview/welcome/#composition-with-slots","title":"Composition with slots","text":"
  • Render components inside templates with {% component %} tag.
  • Compose them with {% slot %} and {% fill %} tags.
  • Vue-like slot system, including scoped slots.
{% component \"Layout\"\n    bookmarks=bookmarks\n    breadcrumbs=breadcrumbs\n%}\n    {% fill \"header\" %}\n        <div class=\"flex justify-between gap-x-12\">\n            <div class=\"prose\">\n                <h3>{{ project.name }}</h3>\n            </div>\n            <div class=\"font-semibold text-gray-500\">\n                {{ project.start_date }} - {{ project.end_date }}\n            </div>\n        </div>\n    {% endfill %}\n\n    {# Access data passed to `{% slot %}` with `data` #}\n    {% fill \"tabs\" data=\"tabs_data\" %}\n        {% component \"TabItem\" header=\"Project Info\" %}\n            {% component \"ProjectInfo\"\n                project=project\n                project_tags=project_tags\n                attrs:class=\"py-5\"\n                attrs:width=tabs_data.width\n            / %}\n        {% endcomponent %}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"overview/welcome/#extended-template-tags","title":"Extended template tags","text":"

django-components is designed for flexibility, making working with templates a breeze.

It extends Django's template tags syntax with:

  • Literal lists and dictionaries in the template
  • Self-closing tags {% mytag / %}
  • Multi-line template tags
  • Spread operator ... to dynamically pass args or kwargs into the template tag
  • Template tags inside literal strings like \"{{ first_name }} {{ last_name }}\"
  • Pass dictonaries by their key-value pairs attr:key=val
{% component \"table\"\n    ...default_attrs\n    title=\"Friend list for {{ user.name }}\"\n    headers=[\"Name\", \"Age\", \"Email\"]\n    data=[\n        {\n            \"name\": \"John\"|upper,\n            \"age\": 30|add:1,\n            \"email\": \"john@example.com\",\n            \"hobbies\": [\"reading\"],\n        },\n        {\n            \"name\": \"Jane\"|upper,\n            \"age\": 25|add:1,\n            \"email\": \"jane@example.com\",\n            \"hobbies\": [\"reading\", \"coding\"],\n        },\n    ],\n    attrs:class=\"py-4 ma-2 border-2 border-gray-300 rounded-md\"\n/ %}\n

You too can define template tags with these features by using @template_tag() or BaseNode.

Read more on Custom template tags.

"},{"location":"overview/welcome/#full-programmatic-access","title":"Full programmatic access","text":"

When you render a component, you can access everything about the component:

  • Component input: args, kwargs, slots and context
  • Component's template, CSS and JS
  • Django's context processors
  • Unique render ID
class Table(Component):\n    js_file = \"table.js\"\n    css_file = \"table.css\"\n\n    template = \"\"\"\n        <div class=\"table\">\n            <span>{{ variable }}</span>\n        </div>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        # Access component's ID\n        assert self.id == \"djc1A2b3c\"\n\n        # Access component's inputs and slots\n        assert self.args == [123, \"str\"]\n        assert self.kwargs == {\"variable\": \"test\", \"another\": 1}\n        footer_slot = self.slots[\"footer\"]\n        some_var = self.context[\"some_var\"]\n\n        # Access the request object and Django's context processors, if available\n        assert self.request.GET == {\"query\": \"something\"}\n        assert self.context_processors_data['user'].username == \"admin\"\n\n        return {\n            \"variable\": kwargs[\"variable\"],\n        }\n\n# Access component's HTML / JS / CSS\nTable.template\nTable.js\nTable.css\n\n# Render the component\nrendered = Table.render(\n    kwargs={\"variable\": \"test\", \"another\": 1},\n    args=(123, \"str\"),\n    slots={\"footer\": \"MY_FOOTER\"},\n)\n
"},{"location":"overview/welcome/#granular-html-attributes","title":"Granular HTML attributes","text":"

Use the {% html_attrs %} template tag to render HTML attributes.

It supports:

  • Defining attributes as whole dictionaries or keyword arguments
  • Merging attributes from multiple sources
  • Boolean attributes
  • Appending attributes
  • Removing attributes
  • Defining default attributes
<div\n    {% html_attrs\n        attrs\n        defaults:class=\"default-class\"\n        class=\"extra-class\"\n    %}\n>\n

{% html_attrs %} offers a Vue-like granular control for class and style HTML attributes, where you can use a dictionary to manage each class name or style property separately.

{% html_attrs\n    class=\"foo bar\"\n    class={\n        \"baz\": True,\n        \"foo\": False,\n    }\n    class=\"extra\"\n%}\n
{% html_attrs\n    style=\"text-align: center; background-color: blue;\"\n    style={\n        \"background-color\": \"green\",\n        \"color\": None,\n        \"width\": False,\n    }\n    style=\"position: absolute; height: 12px;\"\n%}\n

Read more about HTML attributes.

"},{"location":"overview/welcome/#html-fragment-support","title":"HTML fragment support","text":"

django-components makes integration with HTMX, AlpineJS or jQuery easy by allowing components to be rendered as HTML fragments:

  • Components's JS and CSS files are loaded automatically when the fragment is inserted into the DOM.

  • Components can be exposed as Django Views with get(), post(), put(), patch(), delete() methods

  • Automatically create an endpoint for a component with Component.View.public

# components/calendar/calendar.py\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n\n    class View:\n        # Register Component with `urlpatterns`\n        public = True\n\n        # Define handlers\n        def get(self, request, *args, **kwargs):\n            page = request.GET.get(\"page\", 1)\n            return self.component.render_to_response(\n                request=request,\n                kwargs={\n                    \"page\": page,\n                },\n            )\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"page\": kwargs[\"page\"],\n        }\n\n# Get auto-generated URL for the component\nurl = get_component_url(Calendar)\n\n# Or define explicit URL in urls.py\npath(\"calendar/\", Calendar.as_view())\n
"},{"location":"overview/welcome/#provide-inject","title":"Provide / Inject","text":"

django-components supports the provide / inject pattern, similarly to React's Context Providers or Vue's provide / inject:

  • Use the {% provide %} tag to provide data to the component tree
  • Use the Component.inject() method to inject data into the component

Read more about Provide / Inject.

<body>\n    {% provide \"theme\" variant=\"light\" %}\n        {% component \"header\" / %}\n    {% endprovide %}\n</body>\n
@register(\"header\")\nclass Header(Component):\n    template = \"...\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        theme = self.inject(\"theme\").variant\n        return {\n            \"theme\": theme,\n        }\n
"},{"location":"overview/welcome/#input-validation-and-static-type-hints","title":"Input validation and static type hints","text":"

Avoid needless errors with type hints and runtime input validation.

To opt-in to input validation, define types for component's args, kwargs, slots:

from typing import NamedTuple, Optional\nfrom django.template import Context\nfrom django_components import Component, Slot, SlotInput\n\nclass Button(Component):\n    class Args(NamedTuple):\n        size: int\n        text: str\n\n    class Kwargs(NamedTuple):\n        variable: str\n        another: int\n        maybe_var: Optional[int] = None  # May be omitted\n\n    class Slots(NamedTuple):\n        my_slot: Optional[SlotInput] = None\n        another_slot: SlotInput\n\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        args.size  # int\n        kwargs.variable  # str\n        slots.my_slot  # Slot[MySlotData]\n

To have type hints when calling Button.render() or Button.render_to_response(), wrap the inputs in their respective Args, Kwargs, and Slots classes:

Button.render(\n    # Error: First arg must be `int`, got `float`\n    args=Button.Args(\n        size=1.25,\n        text=\"abc\",\n    ),\n    # Error: Key \"another\" is missing\n    kwargs=Button.Kwargs(\n        variable=\"text\",\n    ),\n)\n
"},{"location":"overview/welcome/#extensions","title":"Extensions","text":"

Django-components functionality can be extended with Extensions. Extensions allow for powerful customization and integrations. They can:

  • Tap into lifecycle events, such as when a component is created, deleted, or registered
  • Add new attributes and methods to the components
  • Add custom CLI commands
  • Add custom URLs

Some of the extensions include:

  • Component caching
  • Django View integration
  • Component defaults
  • Pydantic integration (input validation)

Some of the planned extensions include:

  • AlpineJS integration
  • Storybook integration
  • Component-level benchmarking with asv
"},{"location":"overview/welcome/#caching","title":"Caching","text":"
  • Components can be cached using Django's cache framework.
  • Caching rules can be configured on a per-component basis.
  • Components are cached based on their input. Or you can write custom caching logic.
from django_components import Component\n\nclass MyComponent(Component):\n    class Cache:\n        enabled = True\n        ttl = 60 * 60 * 24  # 1 day\n\n        def hash(self, *args, **kwargs):\n            return hash(f\"{json.dumps(args)}:{json.dumps(kwargs)}\")\n
"},{"location":"overview/welcome/#simple-testing","title":"Simple testing","text":"
  • Write tests for components with @djc_test decorator.
  • The decorator manages global state, ensuring that tests don't leak.
  • If using pytest, the decorator allows you to parametrize Django or Components settings.
  • The decorator also serves as a stand-in for Django's @override_settings.
from django_components.testing import djc_test\n\nfrom components.my_table import MyTable\n\n@djc_test\ndef test_my_table():\n    rendered = MyTable.render(\n        kwargs={\n            \"title\": \"My table\",\n        },\n    )\n    assert rendered == \"<table>My table</table>\"\n
"},{"location":"overview/welcome/#debugging-features","title":"Debugging features","text":"
  • Visual component inspection: Highlight components and slots directly in your browser.
  • Detailed tracing logs to supply AI-agents with context: The logs include component and slot names and IDs, and their position in the tree.
"},{"location":"overview/welcome/#sharing-components","title":"Sharing components","text":"
  • Install and use third-party components from PyPI
  • Or publish your own \"component registry\"
  • Highly customizable - Choose how the components are called in the template (and more):

    {% component \"calendar\" date=\"2024-11-06\" %}\n{% endcomponent %}\n\n{% calendar date=\"2024-11-06\" %}\n{% endcalendar %}\n
"},{"location":"overview/welcome/#performance","title":"Performance","text":"

Our aim is to be at least as fast as Django templates.

As of 0.130, django-components is ~4x slower than Django templates.

Render time django 68.9\u00b10.6ms django-components 259\u00b14ms

See the full performance breakdown for more information.

"},{"location":"overview/welcome/#release-notes","title":"Release notes","text":"

Read the Release Notes to see the latest features and fixes.

"},{"location":"overview/welcome/#community-examples","title":"Community examples","text":"

One of our goals with django-components is to make it easy to share components between projects. Head over to the Community examples to see some examples.

"},{"location":"overview/welcome/#contributing-and-development","title":"Contributing and development","text":"

Get involved or sponsor this project - See here

Running django-components locally for development - See here

"},{"location":"reference/api/","title":"API","text":""},{"location":"reference/api/#api","title":"API","text":""},{"location":"reference/api/#django_components.BaseNode","title":"BaseNode","text":"
BaseNode(\n    params: List[TagAttr],\n    flags: Optional[Dict[str, bool]] = None,\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    contents: Optional[str] = None,\n    template_name: Optional[str] = None,\n    template_component: Optional[Type[Component]] = None,\n)\n

Bases: django.template.base.Node

See source code

Node class for all django-components custom template tags.

This class has a dual role:

  1. It declares how a particular template tag should be parsed - By setting the tag, end_tag, and allowed_flags attributes:

    class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n    allowed_flags = [\"required\"]\n

    This will allow the template tag {% slot %} to be used like this:

    {% slot required %} ... {% endslot %}\n
  2. The render method is the actual implementation of the template tag.

    This is where the tag's logic is implemented:

    class MyNode(BaseNode):\n    tag = \"mynode\"\n\n    def render(self, context: Context, name: str, **kwargs: Any) -> str:\n        return f\"Hello, {name}!\"\n

    This will allow the template tag {% mynode %} to be used like this:

    {% mynode name=\"John\" %}\n

The template tag accepts parameters as defined on the render method's signature.

For more info, see BaseNode.render().

Methods:

  • parse \u2013
  • register \u2013
  • render \u2013
  • unregister \u2013

Attributes:

  • active_flags (List[str]) \u2013
  • allowed_flags (Optional[List[str]]) \u2013
  • contents (Optional[str]) \u2013
  • end_tag (Optional[str]) \u2013
  • flags (Dict[str, bool]) \u2013
  • node_id (str) \u2013
  • nodelist (NodeList) \u2013
  • params (List[TagAttr]) \u2013
  • tag (str) \u2013
  • template_component (Optional[Type[Component]]) \u2013
  • template_name (Optional[str]) \u2013
"},{"location":"reference/api/#django_components.BaseNode.active_flags","title":"active_flags property","text":"
active_flags: List[str]\n

See source code

Flags that were set for this specific instance as a list of strings.

E.g. the following tag:

{% slot \"content\" default required / %}\n

Will have the following flags:

[\"default\", \"required\"]\n
"},{"location":"reference/api/#django_components.BaseNode.allowed_flags","title":"allowed_flags class-attribute","text":"
allowed_flags: Optional[List[str]] = None\n

See source code

The list of all possible flags for this tag.

E.g. [\"required\"] will allow this tag to be used like {% slot required %}.

class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n    allowed_flags = [\"required\", \"default\"]\n

This will allow the template tag {% slot %} to be used like this:

{% slot required %} ... {% endslot %}\n{% slot default %} ... {% endslot %}\n{% slot required default %} ... {% endslot %}\n
"},{"location":"reference/api/#django_components.BaseNode.contents","title":"contents instance-attribute","text":"
contents: Optional[str] = contents\n

See source code

See source code

The contents of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The contents will be \"<div> ... </div>\".

"},{"location":"reference/api/#django_components.BaseNode.end_tag","title":"end_tag class-attribute","text":"
end_tag: Optional[str] = None\n

See source code

The end tag name.

E.g. \"endcomponent\" or \"endslot\" will make this class match template tags {% endcomponent %} or {% endslot %}.

class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n

This will allow the template tag {% slot %} to be used like this:

{% slot %} ... {% endslot %}\n

If not set, then this template tag has no end tag.

So instead of {% component %} ... {% endcomponent %}, you'd use only {% component %}.

class MyNode(BaseNode):\n    tag = \"mytag\"\n    end_tag = None\n
"},{"location":"reference/api/#django_components.BaseNode.flags","title":"flags instance-attribute","text":"
flags: Dict[str, bool] = flags or {flag: Falsefor flag in (allowed_flags or [])}\n

See source code

See source code

Dictionary of all allowed_flags that were set on the tag.

Flags that were set are True, and the rest are False.

E.g. the following tag:

class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n    allowed_flags = [\"default\", \"required\"]\n
{% slot \"content\" default %}\n

Has 2 flags, default and required, but only default was set.

The flags dictionary will be:

{\n    \"default\": True,\n    \"required\": False,\n}\n

You can check if a flag is set by doing:

if node.flags[\"default\"]:\n    ...\n
"},{"location":"reference/api/#django_components.BaseNode.node_id","title":"node_id instance-attribute","text":"
node_id: str = node_id or gen_id()\n

See source code

See source code

The unique ID of the node.

Extensions can use this ID to store additional information.

"},{"location":"reference/api/#django_components.BaseNode.nodelist","title":"nodelist instance-attribute","text":"
nodelist: NodeList = nodelist or NodeList()\n

See source code

See source code

The nodelist of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The nodelist will contain the <div> ... </div> part.

Unlike contents, the nodelist contains the actual Nodes, not just the text.

"},{"location":"reference/api/#django_components.BaseNode.params","title":"params instance-attribute","text":"
params: List[TagAttr] = params\n

See source code

See source code

The parameters to the tag in the template.

A single param represents an arg or kwarg of the template tag.

E.g. the following tag:

{% component \"my_comp\" key=val key2='val2 two' %}\n

Has 3 params:

  • Posiitonal arg \"my_comp\"
  • Keyword arg key=val
  • Keyword arg key2='val2 two'
"},{"location":"reference/api/#django_components.BaseNode.tag","title":"tag class-attribute","text":"
tag: str\n

See source code

The tag name.

E.g. \"component\" or \"slot\" will make this class match template tags {% component %} or {% slot %}.

class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n

This will allow the template tag {% slot %} to be used like this:

{% slot %} ... {% endslot %}\n
"},{"location":"reference/api/#django_components.BaseNode.template_component","title":"template_component instance-attribute","text":"
template_component: Optional[Type[Component]] = template_component\n

See source code

See source code

If the template that contains this node belongs to a Component, then this will be the Component class.

"},{"location":"reference/api/#django_components.BaseNode.template_name","title":"template_name instance-attribute","text":"
template_name: Optional[str] = template_name\n

See source code

See source code

The name of the Template that contains this node.

The template name is set by Django's template loaders.

For example, the filesystem template loader will set this to the absolute path of the template file.

\"/home/user/project/templates/my_template.html\"\n
"},{"location":"reference/api/#django_components.BaseNode.parse","title":"parse classmethod","text":"
parse(parser: Parser, token: Token, **kwargs: Any) -> BaseNode\n

See source code

This function is what is passed to Django's Library.tag() when registering the tag.

In other words, this method is called by Django's template parser when we encounter a tag that matches this node's tag, e.g. {% component %} or {% slot %}.

To register the tag, you can use BaseNode.register().

"},{"location":"reference/api/#django_components.BaseNode.register","title":"register classmethod","text":"
register(library: Library) -> None\n

See source code

A convenience method for registering the tag with the given library.

class MyNode(BaseNode):\n    tag = \"mynode\"\n\nMyNode.register(library)\n

Allows you to then use the node in templates like so:

{% load mylibrary %}\n{% mynode %}\n
"},{"location":"reference/api/#django_components.BaseNode.render","title":"render","text":"
render(context: Context, *args: Any, **kwargs: Any) -> str\n

See source code

Render the node. This method is meant to be overridden by subclasses.

The signature of this function decides what input the template tag accepts.

The render() method MUST accept a context argument. Any arguments after that will be part of the tag's input parameters.

So if you define a render method like this:

def render(self, context: Context, name: str, **kwargs: Any) -> str:\n

Then the tag will require the name parameter, and accept any extra keyword arguments:

{% component name=\"John\" age=20 %}\n
"},{"location":"reference/api/#django_components.BaseNode.unregister","title":"unregister classmethod","text":"
unregister(library: Library) -> None\n

See source code

Unregisters the node from the given library.

"},{"location":"reference/api/#django_components.CommandLiteralAction","title":"CommandLiteralAction module-attribute","text":"
CommandLiteralAction = Literal['append', 'append_const', 'count', 'extend', 'store', 'store_const', 'store_true', 'store_false', 'version']\n

See source code

The basic type of action to be taken when this argument is encountered at the command line.

This is a subset of the values for action in ArgumentParser.add_argument().

"},{"location":"reference/api/#django_components.Component","title":"Component","text":"
Component(\n    registered_name: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    registry: Optional[ComponentRegistry] = None,\n    context: Optional[Context] = None,\n    args: Optional[Any] = None,\n    kwargs: Optional[Any] = None,\n    slots: Optional[Any] = None,\n    deps_strategy: Optional[DependenciesStrategy] = None,\n    request: Optional[HttpRequest] = None,\n    node: Optional[ComponentNode] = None,\n    id: Optional[str] = None,\n)\n

Methods:

  • as_view \u2013
  • get_context_data \u2013
  • get_css_data \u2013
  • get_js_data \u2013
  • get_template \u2013
  • get_template_data \u2013
  • get_template_name \u2013
  • inject \u2013
  • on_render \u2013
  • on_render_after \u2013
  • on_render_before \u2013
  • render \u2013
  • render_to_response \u2013

Attributes:

  • Args (Optional[Type]) \u2013
  • Cache (Type[ComponentCache]) \u2013
  • CssData (Optional[Type]) \u2013
  • DebugHighlight (Type[ComponentDebugHighlight]) \u2013
  • Defaults (Type[ComponentDefaults]) \u2013
  • JsData (Optional[Type]) \u2013
  • Kwargs (Optional[Type]) \u2013
  • Media (Optional[Type[ComponentMediaInput]]) \u2013
  • Slots (Optional[Type]) \u2013
  • TemplateData (Optional[Type]) \u2013
  • View (Type[ComponentView]) \u2013
  • args (Any) \u2013
  • cache (ComponentCache) \u2013
  • class_id (str) \u2013
  • context (Context) \u2013
  • context_processors_data (Dict) \u2013
  • css (Optional[str]) \u2013
  • css_file (Optional[str]) \u2013
  • debug_highlight (ComponentDebugHighlight) \u2013
  • defaults (ComponentDefaults) \u2013
  • deps_strategy (DependenciesStrategy) \u2013
  • do_not_call_in_templates (bool) \u2013
  • id (str) \u2013
  • input (ComponentInput) \u2013
  • is_filled (SlotIsFilled) \u2013
  • js (Optional[str]) \u2013
  • js_file (Optional[str]) \u2013
  • kwargs (Any) \u2013
  • media (Optional[Media]) \u2013
  • media_class (Type[Media]) \u2013
  • name (str) \u2013
  • node (Optional[ComponentNode]) \u2013
  • outer_context (Optional[Context]) \u2013
  • raw_args (List[Any]) \u2013
  • raw_kwargs (Dict[str, Any]) \u2013
  • raw_slots (Dict[str, Slot]) \u2013
  • registered_name (Optional[str]) \u2013
  • registry (ComponentRegistry) \u2013
  • request (Optional[HttpRequest]) \u2013
  • response_class (Type[HttpResponse]) \u2013
  • slots (Any) \u2013
  • template (Optional[str]) \u2013
  • template_file (Optional[str]) \u2013
  • template_name (Optional[str]) \u2013
  • view (ComponentView) \u2013
"},{"location":"reference/api/#django_components.Component.Args","title":"Args class-attribute","text":"
Args: Optional[Type] = None\n

See source code

Optional typing for positional arguments passed to the component.

If set and not None, then the args parameter of the data methods (get_template_data(), get_js_data(), get_css_data()) will be the instance of this class:

from typing import NamedTuple\nfrom django_components import Component\n\nclass Table(Component):\n    class Args(NamedTuple):\n        color: str\n        size: int\n\n    def get_template_data(self, args: Args, kwargs, slots, context):\n        assert isinstance(args, Table.Args)\n\n        return {\n            \"color\": args.color,\n            \"size\": args.size,\n        }\n

The constructor of this class MUST accept positional arguments:

Args(*args)\n

As such, a good starting point is to set this field to a subclass of NamedTuple.

Use Args to:

  • Validate the input at runtime.
  • Set type hints for the positional arguments for data methods like get_template_data().
  • Document the component inputs.

You can also use Args to validate the positional arguments for Component.render():

Table.render(\n    args=Table.Args(color=\"red\", size=10),\n)\n

Read more on Typing and validation.

"},{"location":"reference/api/#django_components.Component.Cache","title":"Cache class-attribute","text":"
Cache: Type[ComponentCache]\n

See source code

The fields of this class are used to configure the component caching.

Read more about Component caching.

Example:

from django_components import Component\n\nclass MyComponent(Component):\n    class Cache:\n        enabled = True\n        ttl = 60 * 60 * 24  # 1 day\n        cache_name = \"my_cache\"\n
"},{"location":"reference/api/#django_components.Component.CssData","title":"CssData class-attribute","text":"
CssData: Optional[Type] = None\n

See source code

Optional typing for the data to be returned from get_css_data().

If set and not None, then this class will be instantiated with the dictionary returned from get_css_data() to validate the data.

The constructor of this class MUST accept keyword arguments:

CssData(**css_data)\n

You can also return an instance of CssData directly from get_css_data() to get type hints:

from typing import NamedTuple\nfrom django_components import Component\n\nclass Table(Component):\n    class CssData(NamedTuple):\n        color: str\n        size: int\n\n    def get_css_data(self, args, kwargs, slots, context):\n        return Table.CssData(\n            color=kwargs[\"color\"],\n            size=kwargs[\"size\"],\n        )\n

A good starting point is to set this field to a subclass of NamedTuple or a dataclass.

Use CssData to:

  • Validate the data returned from get_css_data() at runtime.
  • Set type hints for this data.
  • Document the component data.

Read more on Typing and validation.

Info

If you use a custom class for CssData, this class needs to be convertable to a dictionary.

You can implement either:

  1. _asdict() method

    class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def _asdict(self):\n        return {'x': self.x, 'y': self.y}\n

  2. Or make the class dict-like with __iter__() and __getitem__()

    class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def __iter__(self):\n        return iter([('x', self.x), ('y', self.y)])\n\n    def __getitem__(self, key):\n        return getattr(self, key)\n

"},{"location":"reference/api/#django_components.Component.DebugHighlight","title":"DebugHighlight class-attribute","text":"
DebugHighlight: Type[ComponentDebugHighlight]\n

See source code

The fields of this class are used to configure the component debug highlighting.

Read more about Component debug highlighting.

"},{"location":"reference/api/#django_components.Component.Defaults","title":"Defaults class-attribute","text":"
Defaults: Type[ComponentDefaults]\n

See source code

The fields of this class are used to set default values for the component's kwargs.

Read more about Component defaults.

Example:

from django_components import Component, Default\n\nclass MyComponent(Component):\n    class Defaults:\n        position = \"left\"\n        selected_items = Default(lambda: [1, 2, 3])\n
"},{"location":"reference/api/#django_components.Component.JsData","title":"JsData class-attribute","text":"
JsData: Optional[Type] = None\n

See source code

Optional typing for the data to be returned from get_js_data().

If set and not None, then this class will be instantiated with the dictionary returned from get_js_data() to validate the data.

The constructor of this class MUST accept keyword arguments:

JsData(**js_data)\n

You can also return an instance of JsData directly from get_js_data() to get type hints:

from typing import NamedTuple\nfrom django_components import Component\n\nclass Table(Component):\n    class JsData(NamedTuple):\n        color: str\n        size: int\n\n    def get_js_data(self, args, kwargs, slots, context):\n        return Table.JsData(\n            color=kwargs[\"color\"],\n            size=kwargs[\"size\"],\n        )\n

A good starting point is to set this field to a subclass of NamedTuple or a dataclass.

Use JsData to:

  • Validate the data returned from get_js_data() at runtime.
  • Set type hints for this data.
  • Document the component data.

Read more on Typing and validation.

Info

If you use a custom class for JsData, this class needs to be convertable to a dictionary.

You can implement either:

  1. _asdict() method

    class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def _asdict(self):\n        return {'x': self.x, 'y': self.y}\n

  2. Or make the class dict-like with __iter__() and __getitem__()

    class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def __iter__(self):\n        return iter([('x', self.x), ('y', self.y)])\n\n    def __getitem__(self, key):\n        return getattr(self, key)\n

"},{"location":"reference/api/#django_components.Component.Kwargs","title":"Kwargs class-attribute","text":"
Kwargs: Optional[Type] = None\n

See source code

Optional typing for keyword arguments passed to the component.

If set and not None, then the kwargs parameter of the data methods (get_template_data(), get_js_data(), get_css_data()) will be the instance of this class:

from typing import NamedTuple\nfrom django_components import Component\n\nclass Table(Component):\n    class Kwargs(NamedTuple):\n        color: str\n        size: int\n\n    def get_template_data(self, args, kwargs: Kwargs, slots, context):\n        assert isinstance(kwargs, Table.Kwargs)\n\n        return {\n            \"color\": kwargs.color,\n            \"size\": kwargs.size,\n        }\n

The constructor of this class MUST accept keyword arguments:

Kwargs(**kwargs)\n

As such, a good starting point is to set this field to a subclass of NamedTuple or a dataclass.

Use Kwargs to:

  • Validate the input at runtime.
  • Set type hints for the keyword arguments for data methods like get_template_data().
  • Document the component inputs.

You can also use Kwargs to validate the keyword arguments for Component.render():

Table.render(\n    kwargs=Table.Kwargs(color=\"red\", size=10),\n)\n

Read more on Typing and validation.

"},{"location":"reference/api/#django_components.Component.Media","title":"Media class-attribute","text":"
Media: Optional[Type[ComponentMediaInput]] = None\n

See source code

Defines JS and CSS media files associated with this component.

This Media class behaves similarly to Django's Media class:

  • Paths are generally handled as static file paths, and resolved URLs are rendered to HTML with media_class.render_js() or media_class.render_css().
  • A path that starts with http, https, or / is considered a URL, skipping the static file resolution. This path is still rendered to HTML with media_class.render_js() or media_class.render_css().
  • A SafeString (with __html__ method) is considered an already-formatted HTML tag, skipping both static file resolution and rendering with media_class.render_js() or media_class.render_css().
  • You can set extend to configure whether to inherit JS / CSS from parent components. See Media inheritance.

However, there's a few differences from Django's Media class:

  1. Our Media class accepts various formats for the JS and CSS files: either a single file, a list, or (CSS-only) a dictionary (See ComponentMediaInput).
  2. Individual JS / CSS files can be any of str, bytes, Path, SafeString, or a function (See ComponentMediaInputPath).

Example:

class MyTable(Component):\n    class Media:\n        js = [\n            \"path/to/script.js\",\n            \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\",  # AlpineJS\n        ]\n        css = {\n            \"all\": [\n                \"path/to/style.css\",\n                \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\",  # TailwindCSS\n            ],\n            \"print\": [\"path/to/style2.css\"],\n        }\n
"},{"location":"reference/api/#django_components.Component.Slots","title":"Slots class-attribute","text":"
Slots: Optional[Type] = None\n

See source code

Optional typing for slots passed to the component.

If set and not None, then the slots parameter of the data methods (get_template_data(), get_js_data(), get_css_data()) will be the instance of this class:

from typing import NamedTuple\nfrom django_components import Component, Slot, SlotInput\n\nclass Table(Component):\n    class Slots(NamedTuple):\n        header: SlotInput\n        footer: Slot\n\n    def get_template_data(self, args, kwargs, slots: Slots, context):\n        assert isinstance(slots, Table.Slots)\n\n        return {\n            \"header\": slots.header,\n            \"footer\": slots.footer,\n        }\n

The constructor of this class MUST accept keyword arguments:

Slots(**slots)\n

As such, a good starting point is to set this field to a subclass of NamedTuple or a dataclass.

Use Slots to:

  • Validate the input at runtime.
  • Set type hints for the slots for data methods like get_template_data().
  • Document the component inputs.

You can also use Slots to validate the slots for Component.render():

Table.render(\n    slots=Table.Slots(\n        header=\"HELLO IM HEADER\",\n        footer=Slot(lambda ctx: ...),\n    ),\n)\n

Read more on Typing and validation.

Info

Components can receive slots as strings, functions, or instances of Slot.

Internally these are all normalized to instances of Slot.

Therefore, the slots dictionary available in data methods (like get_template_data()) will always be a dictionary of Slot instances.

To correctly type this dictionary, you should set the fields of Slots to Slot or SlotInput:

SlotInput is a union of Slot, string, and function types.

"},{"location":"reference/api/#django_components.Component.TemplateData","title":"TemplateData class-attribute","text":"
TemplateData: Optional[Type] = None\n

See source code

Optional typing for the data to be returned from get_template_data().

If set and not None, then this class will be instantiated with the dictionary returned from get_template_data() to validate the data.

The constructor of this class MUST accept keyword arguments:

TemplateData(**template_data)\n

You can also return an instance of TemplateData directly from get_template_data() to get type hints:

from typing import NamedTuple\nfrom django_components import Component\n\nclass Table(Component):\n    class TemplateData(NamedTuple):\n        color: str\n        size: int\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return Table.TemplateData(\n            color=kwargs[\"color\"],\n            size=kwargs[\"size\"],\n        )\n

A good starting point is to set this field to a subclass of NamedTuple or a dataclass.

Use TemplateData to:

  • Validate the data returned from get_template_data() at runtime.
  • Set type hints for this data.
  • Document the component data.

Read more on Typing and validation.

Info

If you use a custom class for TemplateData, this class needs to be convertable to a dictionary.

You can implement either:

  1. _asdict() method

    class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def _asdict(self):\n        return {'x': self.x, 'y': self.y}\n

  2. Or make the class dict-like with __iter__() and __getitem__()

    class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def __iter__(self):\n        return iter([('x', self.x), ('y', self.y)])\n\n    def __getitem__(self, key):\n        return getattr(self, key)\n

"},{"location":"reference/api/#django_components.Component.View","title":"View class-attribute","text":"
View: Type[ComponentView]\n

See source code

The fields of this class are used to configure the component views and URLs.

This class is a subclass of django.views.View. The Component instance is available via self.component.

Override the methods of this class to define the behavior of the component.

Read more about Component views and URLs.

Example:

class MyComponent(Component):\n    class View:\n        def get(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:\n            return HttpResponse(\"Hello, world!\")\n
"},{"location":"reference/api/#django_components.Component.args","title":"args instance-attribute","text":"
args: Any\n

See source code

Positional arguments passed to the component.

This is part of the Render API.

args has the same behavior as the args argument of Component.get_template_data():

  • If you defined the Component.Args class, then the args property will return an instance of that Args class.
  • Otherwise, args will be a plain list.

Example:

With Args class:

from django_components import Component\n\nclass Table(Component):\n    class Args(NamedTuple):\n        page: int\n        per_page: int\n\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.args.page == 123\n        assert self.args.per_page == 10\n\nrendered = Table.render(\n    args=[123, 10],\n)\n

Without Args class:

from django_components import Component\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.args[0] == 123\n        assert self.args[1] == 10\n
"},{"location":"reference/api/#django_components.Component.cache","title":"cache instance-attribute","text":"
cache: ComponentCache\n

See source code

Instance of ComponentCache available at component render time.

"},{"location":"reference/api/#django_components.Component.class_id","title":"class_id class-attribute","text":"
class_id: str\n

See source code

Unique ID of the component class, e.g. MyComponent_ab01f2.

This is derived from the component class' module import path, e.g. path.to.my.MyComponent.

"},{"location":"reference/api/#django_components.Component.context","title":"context instance-attribute","text":"
context: Context\n

See source code

The context argument as passed to Component.get_template_data().

This is Django's Context with which the component template is rendered.

If the root component or template was rendered with RequestContext then this will be an instance of RequestContext.

Whether the context variables defined in context are available to the template depends on the context behavior mode:

  • In \"django\" context behavior mode, the template will have access to the keys of this context.

  • In \"isolated\" context behavior mode, the template will NOT have access to this context, and data MUST be passed via component's args and kwargs.

"},{"location":"reference/api/#django_components.Component.context_processors_data","title":"context_processors_data property","text":"
context_processors_data: Dict\n

See source code

Retrieve data injected by context_processors.

This data is also available from within the component's template, without having to return this data from get_template_data().

In regular Django templates, you need to use RequestContext to apply context processors.

In Components, the context processors are applied to components either when:

  • The component is rendered with RequestContext (Regular Django behavior)
  • The component is rendered with a regular Context (or none), but the request kwarg of Component.render() is set.
  • The component is nested in another component that matches any of these conditions.

See Component.request on how the request (HTTPRequest) object is passed to and within the components.

NOTE: This dictionary is generated dynamically, so any changes to it will not be persisted.

Example:

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        user = self.context_processors_data['user']\n        return {\n            'is_logged_in': user.is_authenticated,\n        }\n
"},{"location":"reference/api/#django_components.Component.css","title":"css class-attribute instance-attribute","text":"
css: Optional[str] = None\n

See source code

Main CSS associated with this component inlined as string.

Warning

Only one of css or css_file must be defined.

Example:

class MyComponent(Component):\n    css = \"\"\"\n        .my-class {\n            color: red;\n        }\n    \"\"\"\n

Syntax highlighting

When using the inlined template, you can enable syntax highlighting with django_components.types.css.

Learn more about syntax highlighting.

from django_components import Component, types\n\nclass MyComponent(Component):\n    css: types.css = '''\n      .my-class {\n        color: red;\n      }\n    '''\n
"},{"location":"reference/api/#django_components.Component.css_file","title":"css_file class-attribute","text":"
css_file: Optional[str] = None\n

See source code

Main CSS associated with this component as file path.

The filepath must be either:

  • Relative to the directory where the Component's Python file is defined.
  • Relative to one of the component directories, as set by COMPONENTS.dirs or COMPONENTS.app_dirs (e.g. <root>/components/).
  • Relative to the staticfiles directories, as set by Django's STATICFILES_DIRS setting (e.g. <root>/static/).

When you create a Component class with css_file, these will happen:

  1. If the file path is relative to the directory where the component's Python file is, the path is resolved.
  2. The file is read and its contents is set to Component.css.

Warning

Only one of css or css_file must be defined.

Example:

path/to/style.css
.my-class {\n    color: red;\n}\n
path/to/component.py
class MyComponent(Component):\n    css_file = \"path/to/style.css\"\n\nprint(MyComponent.css)\n# Output:\n# .my-class {\n#     color: red;\n# };\n
"},{"location":"reference/api/#django_components.Component.debug_highlight","title":"debug_highlight instance-attribute","text":"
debug_highlight: ComponentDebugHighlight\n
"},{"location":"reference/api/#django_components.Component.defaults","title":"defaults instance-attribute","text":"
defaults: ComponentDefaults\n

See source code

Instance of ComponentDefaults available at component render time.

"},{"location":"reference/api/#django_components.Component.deps_strategy","title":"deps_strategy instance-attribute","text":"
deps_strategy: DependenciesStrategy\n

See source code

Dependencies strategy defines how to handle JS and CSS dependencies of this and child components.

Read more about Dependencies rendering.

This is part of the Render API.

There are six strategies:

  • \"document\" (default)
    • Smartly inserts JS / CSS into placeholders or into <head> and <body> tags.
    • Inserts extra script to allow fragment types to work.
    • Assumes the HTML will be rendered in a JS-enabled browser.
  • \"fragment\"
    • A lightweight HTML fragment to be inserted into a document with AJAX.
    • No JS / CSS included.
  • \"simple\"
    • Smartly insert JS / CSS into placeholders or into <head> and <body> tags.
    • No extra script loaded.
  • \"prepend\"
    • Insert JS / CSS before the rendered HTML.
    • No extra script loaded.
  • \"append\"
    • Insert JS / CSS after the rendered HTML.
    • No extra script loaded.
  • \"ignore\"
    • HTML is left as-is. You can still process it with a different strategy later with render_dependencies().
    • Used for inserting rendered HTML into other components.
"},{"location":"reference/api/#django_components.Component.do_not_call_in_templates","title":"do_not_call_in_templates class-attribute","text":"
do_not_call_in_templates: bool = True\n

See source code

Django special property to prevent calling the instance as a function inside Django templates.

Read more about Django's do_not_call_in_templates.

"},{"location":"reference/api/#django_components.Component.id","title":"id instance-attribute","text":"
id: str\n

See source code

This ID is unique for every time a Component.render() (or equivalent) is called (AKA \"render ID\").

This is useful for logging or debugging.

The ID is a 7-letter alphanumeric string in the format cXXXXXX, where XXXXXX is a random string of 6 alphanumeric characters (case-sensitive).

E.g. c1A2b3c.

A single render ID has a chance of collision 1 in 57 billion. However, due to birthday paradox, the chance of collision increases to 1% when approaching ~33K render IDs.

Thus, there is currently a soft-cap of ~30K components rendered on a single page.

If you need to expand this limit, please open an issue on GitHub.

Example:

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        print(f\"Rendering '{self.id}'\")\n\nMyComponent.render()\n# Rendering 'ab3c4d'\n
"},{"location":"reference/api/#django_components.Component.input","title":"input instance-attribute","text":"
input: ComponentInput\n

See source code

Deprecated. Will be removed in v1.

Input holds the data that were passed to the current component at render time.

This includes:

  • args - List of positional arguments
  • kwargs - Dictionary of keyword arguments
  • slots - Dictionary of slots. Values are normalized to Slot instances
  • context - Context object that should be used to render the component
  • And other kwargs passed to Component.render() like deps_strategy

Example:

class Table(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        # Access component's inputs, slots and context\n        assert self.args == [123, \"str\"]\n        assert self.kwargs == {\"variable\": \"test\", \"another\": 1}\n        footer_slot = self.slots[\"footer\"]\n        some_var = self.input.context[\"some_var\"]\n\nrendered = TestComponent.render(\n    kwargs={\"variable\": \"test\", \"another\": 1},\n    args=[123, \"str\"],\n    slots={\"footer\": \"MY_SLOT\"},\n)\n
"},{"location":"reference/api/#django_components.Component.is_filled","title":"is_filled instance-attribute","text":"
is_filled: SlotIsFilled\n

See source code

Deprecated. Will be removed in v1. Use Component.slots instead. Note that Component.slots no longer escapes the slot names.

Dictionary describing which slots have or have not been filled.

This attribute is available for use only within:

You can also access this variable from within the template as

{{ component_vars.is_filled.slot_name }}

"},{"location":"reference/api/#django_components.Component.js","title":"js class-attribute instance-attribute","text":"
js: Optional[str] = None\n

See source code

Main JS associated with this component inlined as string.

Warning

Only one of js or js_file must be defined.

Example:

class MyComponent(Component):\n    js = \"console.log('Hello, World!');\"\n

Syntax highlighting

When using the inlined template, you can enable syntax highlighting with django_components.types.js.

Learn more about syntax highlighting.

from django_components import Component, types\n\nclass MyComponent(Component):\n    js: types.js = '''\n      console.log('Hello, World!');\n    '''\n
"},{"location":"reference/api/#django_components.Component.js_file","title":"js_file class-attribute","text":"
js_file: Optional[str] = None\n

See source code

Main JS associated with this component as file path.

The filepath must be either:

  • Relative to the directory where the Component's Python file is defined.
  • Relative to one of the component directories, as set by COMPONENTS.dirs or COMPONENTS.app_dirs (e.g. <root>/components/).
  • Relative to the staticfiles directories, as set by Django's STATICFILES_DIRS setting (e.g. <root>/static/).

When you create a Component class with js_file, these will happen:

  1. If the file path is relative to the directory where the component's Python file is, the path is resolved.
  2. The file is read and its contents is set to Component.js.

Warning

Only one of js or js_file must be defined.

Example:

path/to/script.js
console.log('Hello, World!');\n
path/to/component.py
class MyComponent(Component):\n    js_file = \"path/to/script.js\"\n\nprint(MyComponent.js)\n# Output: console.log('Hello, World!');\n
"},{"location":"reference/api/#django_components.Component.kwargs","title":"kwargs instance-attribute","text":"
kwargs: Any\n

See source code

Keyword arguments passed to the component.

This is part of the Render API.

kwargs has the same behavior as the kwargs argument of Component.get_template_data():

  • If you defined the Component.Kwargs class, then the kwargs property will return an instance of that Kwargs class.
  • Otherwise, kwargs will be a plain dict.

Example:

With Kwargs class:

from django_components import Component\n\nclass Table(Component):\n    class Kwargs(NamedTuple):\n        page: int\n        per_page: int\n\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.kwargs.page == 123\n        assert self.kwargs.per_page == 10\n\nrendered = Table.render(\n    kwargs={\n        \"page\": 123,\n        \"per_page\": 10,\n    },\n)\n

Without Kwargs class:

from django_components import Component\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.kwargs[\"page\"] == 123\n        assert self.kwargs[\"per_page\"] == 10\n
"},{"location":"reference/api/#django_components.Component.media","title":"media class-attribute instance-attribute","text":"
media: Optional[Media] = None\n

See source code

Normalized definition of JS and CSS media files associated with this component. None if Component.Media is not defined.

This field is generated from Component.media_class.

Read more on Accessing component's HTML / JS / CSS.

Example:

class MyComponent(Component):\n    class Media:\n        js = \"path/to/script.js\"\n        css = \"path/to/style.css\"\n\nprint(MyComponent.media)\n# Output:\n# <script src=\"/static/path/to/script.js\"></script>\n# <link href=\"/static/path/to/style.css\" media=\"all\" rel=\"stylesheet\">\n
"},{"location":"reference/api/#django_components.Component.media_class","title":"media_class class-attribute","text":"
media_class: Type[Media] = Media\n

See source code

Set the Media class that will be instantiated with the JS and CSS media files from Component.Media.

This is useful when you want to customize the behavior of the media files, like customizing how the JS or CSS files are rendered into <script> or <link> HTML tags.

Read more in Defining HTML / JS / CSS files.

Example:

class MyTable(Component):\n    class Media:\n        js = \"path/to/script.js\"\n        css = \"path/to/style.css\"\n\n    media_class = MyMediaClass\n
"},{"location":"reference/api/#django_components.Component.name","title":"name instance-attribute","text":"
name: str\n

See source code

The name of the component.

If the component was registered, this will be the name under which the component was registered in the ComponentRegistry.

Otherwise, this will be the name of the class.

Example:

@register(\"my_component\")\nclass RegisteredComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"name\": self.name,  # \"my_component\"\n        }\n\nclass UnregisteredComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"name\": self.name,  # \"UnregisteredComponent\"\n        }\n
"},{"location":"reference/api/#django_components.Component.node","title":"node instance-attribute","text":"
node: Optional[ComponentNode]\n

See source code

The ComponentNode instance that was used to render the component.

This will be set only if the component was rendered with the {% component %} tag.

Accessing the ComponentNode is mostly useful for extensions, which can modify their behaviour based on the source of the Component.

class MyComponent(Component):\n    def get_template_data(self, context, template):\n        if self.node is not None:\n            assert self.node.name == \"my_component\"\n

For example, if MyComponent was used in another component - that is, with a {% component \"my_component\" %} tag in a template that belongs to another component - then you can use self.node.template_component to access the owner Component class.

class Parent(Component):\n    template: types.django_html = '''\n        <div>\n            {% component \"my_component\" / %}\n        </div>\n    '''\n\n@register(\"my_component\")\nclass MyComponent(Component):\n    def get_template_data(self, context, template):\n        if self.node is not None:\n            assert self.node.template_component == Parent\n

Info

Component.node is None if the component is created by Component.render() (but you can pass in the node kwarg yourself).

"},{"location":"reference/api/#django_components.Component.outer_context","title":"outer_context instance-attribute","text":"
outer_context: Optional[Context]\n

See source code

When a component is rendered with the {% component %} tag, this is the Django's Context object that was used just outside of the component.

{% with abc=123 %}\n    {{ abc }} {# <--- This is in outer context #}\n    {% component \"my_component\" / %}\n{% endwith %}\n

This is relevant when your components are isolated, for example when using the \"isolated\" context behavior mode or when using the only flag.

When components are isolated, each component has its own instance of Context, so outer_context is different from the context argument.

"},{"location":"reference/api/#django_components.Component.raw_args","title":"raw_args instance-attribute","text":"
raw_args: List[Any]\n

See source code

Positional arguments passed to the component.

This is part of the Render API.

Unlike Component.args, this attribute is not typed and will remain as plain list even if you define the Component.Args class.

Example:

from django_components import Component\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.raw_args[0] == 123\n        assert self.raw_args[1] == 10\n
"},{"location":"reference/api/#django_components.Component.raw_kwargs","title":"raw_kwargs instance-attribute","text":"
raw_kwargs: Dict[str, Any]\n

See source code

Keyword arguments passed to the component.

This is part of the Render API.

Unlike Component.kwargs, this attribute is not typed and will remain as plain dict even if you define the Component.Kwargs class.

Example:

from django_components import Component\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.raw_kwargs[\"page\"] == 123\n        assert self.raw_kwargs[\"per_page\"] == 10\n
"},{"location":"reference/api/#django_components.Component.raw_slots","title":"raw_slots instance-attribute","text":"
raw_slots: Dict[str, Slot]\n

See source code

Slots passed to the component.

This is part of the Render API.

Unlike Component.slots, this attribute is not typed and will remain as plain dict even if you define the Component.Slots class.

Example:

from django_components import Component\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.raw_slots[\"header\"] == \"MY_HEADER\"\n        assert self.raw_slots[\"footer\"] == \"FOOTER: \" + ctx.data[\"user_id\"]\n
"},{"location":"reference/api/#django_components.Component.registered_name","title":"registered_name instance-attribute","text":"
registered_name: Optional[str]\n

See source code

If the component was rendered with the {% component %} template tag, this will be the name under which the component was registered in the ComponentRegistry.

Otherwise, this will be None.

Example:

@register(\"my_component\")\nclass MyComponent(Component):\n    template = \"{{ name }}\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"name\": self.registered_name,\n        }\n

Will print my_component in the template:

{% component \"my_component\" / %}\n

And None when rendered in Python:

MyComponent.render()\n# None\n
"},{"location":"reference/api/#django_components.Component.registry","title":"registry instance-attribute","text":"
registry: ComponentRegistry\n

See source code

The ComponentRegistry instance that was used to render the component.

"},{"location":"reference/api/#django_components.Component.request","title":"request instance-attribute","text":"
request: Optional[HttpRequest]\n

See source code

HTTPRequest object passed to this component.

Example:

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        user_id = self.request.GET['user_id']\n        return {\n            'user_id': user_id,\n        }\n

Passing request to a component:

In regular Django templates, you have to use RequestContext to pass the HttpRequest object to the template.

With Components, you can either use RequestContext, or pass the request object explicitly via Component.render() and Component.render_to_response().

When a component is nested in another, the child component uses parent's request object.

"},{"location":"reference/api/#django_components.Component.response_class","title":"response_class class-attribute","text":"
response_class: Type[HttpResponse] = HttpResponse\n

See source code

This attribute configures what class is used to generate response from Component.render_to_response().

The response class should accept a string as the first argument.

Defaults to django.http.HttpResponse.

Example:

from django.http import HttpResponse\nfrom django_components import Component\n\nclass MyHttpResponse(HttpResponse):\n    ...\n\nclass MyComponent(Component):\n    response_class = MyHttpResponse\n\nresponse = MyComponent.render_to_response()\nassert isinstance(response, MyHttpResponse)\n
"},{"location":"reference/api/#django_components.Component.slots","title":"slots instance-attribute","text":"
slots: Any\n

See source code

Slots passed to the component.

This is part of the Render API.

slots has the same behavior as the slots argument of Component.get_template_data():

  • If you defined the Component.Slots class, then the slots property will return an instance of that class.
  • Otherwise, slots will be a plain dict.

Example:

With Slots class:

from django_components import Component, Slot, SlotInput\n\nclass Table(Component):\n    class Slots(NamedTuple):\n        header: SlotInput\n        footer: SlotInput\n\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert isinstance(self.slots.header, Slot)\n        assert isinstance(self.slots.footer, Slot)\n\nrendered = Table.render(\n    slots={\n        \"header\": \"MY_HEADER\",\n        \"footer\": lambda ctx: \"FOOTER: \" + ctx.data[\"user_id\"],\n    },\n)\n

Without Slots class:

from django_components import Component, Slot, SlotInput\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert isinstance(self.slots[\"header\"], Slot)\n        assert isinstance(self.slots[\"footer\"], Slot)\n
"},{"location":"reference/api/#django_components.Component.template","title":"template class-attribute instance-attribute","text":"
template: Optional[str] = None\n

See source code

Inlined Django template (as a plain string) associated with this component.

Warning

Only one of template_file, template, get_template_name(), or get_template() must be defined.

Example:

class Table(Component):\n    template = '''\n      <div>\n        {{ my_var }}\n      </div>\n    '''\n

Syntax highlighting

When using the inlined template, you can enable syntax highlighting with django_components.types.django_html.

Learn more about syntax highlighting.

from django_components import Component, types\n\nclass MyComponent(Component):\n    template: types.django_html = '''\n      <div>\n        {{ my_var }}\n      </div>\n    '''\n
"},{"location":"reference/api/#django_components.Component.template_file","title":"template_file class-attribute","text":"
template_file: Optional[str] = None\n

See source code

Filepath to the Django template associated with this component.

The filepath must be either:

  • Relative to the directory where the Component's Python file is defined.
  • Relative to one of the component directories, as set by COMPONENTS.dirs or COMPONENTS.app_dirs (e.g. <root>/components/).
  • Relative to the template directories, as set by Django's TEMPLATES setting (e.g. <root>/templates/).

Warning

Only one of template_file, get_template_name, template or get_template must be defined.

Example:

Assuming this project layout:

|- components/\n  |- table/\n    |- table.html\n    |- table.css\n    |- table.js\n

Template name can be either relative to the python file (components/table/table.py):

class Table(Component):\n    template_file = \"table.html\"\n

Or relative to one of the directories in COMPONENTS.dirs or COMPONENTS.app_dirs (components/):

class Table(Component):\n    template_file = \"table/table.html\"\n
"},{"location":"reference/api/#django_components.Component.template_name","title":"template_name class-attribute","text":"
template_name: Optional[str]\n

See source code

Alias for template_file.

For historical reasons, django-components used template_name to align with Django's TemplateView.

template_file was introduced to align with js/js_file and css/css_file.

Setting and accessing this attribute is proxied to template_file.

"},{"location":"reference/api/#django_components.Component.view","title":"view instance-attribute","text":"
view: ComponentView\n

See source code

Instance of ComponentView available at component render time.

"},{"location":"reference/api/#django_components.Component.as_view","title":"as_view classmethod","text":"
as_view(**initkwargs: Any) -> ViewFn\n

See source code

Shortcut for calling Component.View.as_view and passing component instance to it.

Read more on Component views and URLs.

"},{"location":"reference/api/#django_components.Component.get_context_data","title":"get_context_data","text":"
get_context_data(*args: Any, **kwargs: Any) -> Optional[Mapping]\n

See source code

DEPRECATED: Use get_template_data() instead. Will be removed in v2.

Use this method to define variables that will be available in the template.

Receives the args and kwargs as they were passed to the Component.

This method has access to the Render API.

Read more about Template variables.

Example:

class MyComponent(Component):\n    def get_context_data(self, name, *args, **kwargs):\n        return {\n            \"name\": name,\n            \"id\": self.id,\n        }\n\n    template = \"Hello, {{ name }}!\"\n\nMyComponent.render(name=\"World\")\n

Warning

get_context_data() and get_template_data() are mutually exclusive.

If both methods return non-empty dictionaries, an error will be raised.

"},{"location":"reference/api/#django_components.Component.get_css_data","title":"get_css_data","text":"
get_css_data(args: Any, kwargs: Any, slots: Any, context: Context) -> Optional[Mapping]\n

See source code

Use this method to define variables that will be available from within the component's CSS code.

This method has access to the Render API.

The data returned from this method will be serialized to string.

Read more about CSS variables.

Example:

class MyComponent(Component):\n    def get_css_data(self, args, kwargs, slots, context):\n        return {\n            \"color\": kwargs[\"color\"],\n        }\n\n    css = '''\n        .my-class {\n            color: var(--color);\n        }\n    '''\n\nMyComponent.render(color=\"red\")\n

Args:

  • args: Positional arguments passed to the component.
  • kwargs: Keyword arguments passed to the component.
  • slots: Slots passed to the component.
  • context: Context used for rendering the component template.

Pass-through kwargs:

It's best practice to explicitly define what args and kwargs a component accepts.

However, if you want a looser setup, you can easily write components that accept any number of kwargs, and pass them all to the CSS code.

To do that, simply return the kwargs dictionary itself from get_css_data():

class MyComponent(Component):\n    def get_css_data(self, args, kwargs, slots, context):\n        return kwargs\n

Type hints:

To get type hints for the args, kwargs, and slots parameters, you can define the Args, Kwargs, and Slots classes on the component class, and then directly reference them in the function signature of get_css_data().

When you set these classes, the args, kwargs, and slots parameters will be given as instances of these (args instance of Args, etc).

When you omit these classes, or set them to None, then the args, kwargs, and slots parameters will be given as plain lists / dictionaries, unmodified.

Read more on Typing and validation.

Example:

from typing import NamedTuple\nfrom django.template import Context\nfrom django_components import Component, SlotInput\n\nclass MyComponent(Component):\n    class Args(NamedTuple):\n        color: str\n\n    class Kwargs(NamedTuple):\n        size: int\n\n    class Slots(NamedTuple):\n        footer: SlotInput\n\n    def get_css_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        assert isinstance(args, MyComponent.Args)\n        assert isinstance(kwargs, MyComponent.Kwargs)\n        assert isinstance(slots, MyComponent.Slots)\n\n        return {\n            \"color\": args.color,\n            \"size\": kwargs.size,\n        }\n

You can also add typing to the data returned from get_css_data() by defining the CssData class on the component class.

When you set this class, you can return either the data as a plain dictionary, or an instance of CssData.

If you return plain dictionary, the data will be validated against the CssData class by instantiating it with the dictionary.

Example:

class MyComponent(Component):\n    class CssData(NamedTuple):\n        color: str\n        size: int\n\n    def get_css_data(self, args, kwargs, slots, context):\n        return {\n            \"color\": kwargs[\"color\"],\n            \"size\": kwargs[\"size\"],\n        }\n        # or\n        return MyComponent.CssData(\n            color=kwargs[\"color\"],\n            size=kwargs[\"size\"],\n        )\n
"},{"location":"reference/api/#django_components.Component.get_js_data","title":"get_js_data","text":"
get_js_data(args: Any, kwargs: Any, slots: Any, context: Context) -> Optional[Mapping]\n

See source code

Use this method to define variables that will be available from within the component's JavaScript code.

This method has access to the Render API.

The data returned from this method will be serialized to JSON.

Read more about JavaScript variables.

Example:

class MyComponent(Component):\n    def get_js_data(self, args, kwargs, slots, context):\n        return {\n            \"name\": kwargs[\"name\"],\n            \"id\": self.id,\n        }\n\n    js = '''\n        $onLoad(({ name, id }) => {\n            console.log(name, id);\n        });\n    '''\n\nMyComponent.render(name=\"World\")\n

Args:

  • args: Positional arguments passed to the component.
  • kwargs: Keyword arguments passed to the component.
  • slots: Slots passed to the component.
  • context: Context used for rendering the component template.

Pass-through kwargs:

It's best practice to explicitly define what args and kwargs a component accepts.

However, if you want a looser setup, you can easily write components that accept any number of kwargs, and pass them all to the JavaScript code.

To do that, simply return the kwargs dictionary itself from get_js_data():

class MyComponent(Component):\n    def get_js_data(self, args, kwargs, slots, context):\n        return kwargs\n

Type hints:

To get type hints for the args, kwargs, and slots parameters, you can define the Args, Kwargs, and Slots classes on the component class, and then directly reference them in the function signature of get_js_data().

When you set these classes, the args, kwargs, and slots parameters will be given as instances of these (args instance of Args, etc).

When you omit these classes, or set them to None, then the args, kwargs, and slots parameters will be given as plain lists / dictionaries, unmodified.

Read more on Typing and validation.

Example:

from typing import NamedTuple\nfrom django.template import Context\nfrom django_components import Component, SlotInput\n\nclass MyComponent(Component):\n    class Args(NamedTuple):\n        color: str\n\n    class Kwargs(NamedTuple):\n        size: int\n\n    class Slots(NamedTuple):\n        footer: SlotInput\n\n    def get_js_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        assert isinstance(args, MyComponent.Args)\n        assert isinstance(kwargs, MyComponent.Kwargs)\n        assert isinstance(slots, MyComponent.Slots)\n\n        return {\n            \"color\": args.color,\n            \"size\": kwargs.size,\n            \"id\": self.id,\n        }\n

You can also add typing to the data returned from get_js_data() by defining the JsData class on the component class.

When you set this class, you can return either the data as a plain dictionary, or an instance of JsData.

If you return plain dictionary, the data will be validated against the JsData class by instantiating it with the dictionary.

Example:

class MyComponent(Component):\n    class JsData(NamedTuple):\n        color: str\n        size: int\n\n    def get_js_data(self, args, kwargs, slots, context):\n        return {\n            \"color\": kwargs[\"color\"],\n            \"size\": kwargs[\"size\"],\n        }\n        # or\n        return MyComponent.JsData(\n            color=kwargs[\"color\"],\n            size=kwargs[\"size\"],\n        )\n
"},{"location":"reference/api/#django_components.Component.get_template","title":"get_template","text":"
get_template(context: Context) -> Optional[Union[str, Template]]\n

See source code

DEPRECATED: Use instead Component.template_file, Component.template or Component.on_render(). Will be removed in v1.

Same as Component.template, but allows to dynamically resolve the template at render time.

The template can be either plain string or a Template instance.

See Component.template for more info and examples.

Warning

Only one of template template_file, get_template_name(), or get_template() must be defined.

Warning

The context is not fully populated at the point when this method is called.

If you need to access the context, either use Component.on_render_before() or Component.on_render().

Parameters:

  • context (Context) \u2013

    The Django template Context in which the component is rendered.

Returns:

  • Optional[Union[str, Template]] \u2013

    Optional[Union[str, Template]]: The inlined Django template string or a Template instance.

"},{"location":"reference/api/#django_components.Component.get_template_data","title":"get_template_data","text":"
get_template_data(args: Any, kwargs: Any, slots: Any, context: Context) -> Optional[Mapping]\n

See source code

Use this method to define variables that will be available in the template.

This method has access to the Render API.

Read more about Template variables.

Example:

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"name\": kwargs[\"name\"],\n            \"id\": self.id,\n        }\n\n    template = \"Hello, {{ name }}!\"\n\nMyComponent.render(name=\"World\")\n

Args:

  • args: Positional arguments passed to the component.
  • kwargs: Keyword arguments passed to the component.
  • slots: Slots passed to the component.
  • context: Context used for rendering the component template.

Pass-through kwargs:

It's best practice to explicitly define what args and kwargs a component accepts.

However, if you want a looser setup, you can easily write components that accept any number of kwargs, and pass them all to the template (similar to django-cotton).

To do that, simply return the kwargs dictionary itself from get_template_data():

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return kwargs\n

Type hints:

To get type hints for the args, kwargs, and slots parameters, you can define the Args, Kwargs, and Slots classes on the component class, and then directly reference them in the function signature of get_template_data().

When you set these classes, the args, kwargs, and slots parameters will be given as instances of these (args instance of Args, etc).

When you omit these classes, or set them to None, then the args, kwargs, and slots parameters will be given as plain lists / dictionaries, unmodified.

Read more on Typing and validation.

Example:

from typing import NamedTuple\nfrom django.template import Context\nfrom django_components import Component, SlotInput\n\nclass MyComponent(Component):\n    class Args(NamedTuple):\n        color: str\n\n    class Kwargs(NamedTuple):\n        size: int\n\n    class Slots(NamedTuple):\n        footer: SlotInput\n\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        assert isinstance(args, MyComponent.Args)\n        assert isinstance(kwargs, MyComponent.Kwargs)\n        assert isinstance(slots, MyComponent.Slots)\n\n        return {\n            \"color\": args.color,\n            \"size\": kwargs.size,\n            \"id\": self.id,\n        }\n

You can also add typing to the data returned from get_template_data() by defining the TemplateData class on the component class.

When you set this class, you can return either the data as a plain dictionary, or an instance of TemplateData.

If you return plain dictionary, the data will be validated against the TemplateData class by instantiating it with the dictionary.

Example:

class MyComponent(Component):\n    class TemplateData(NamedTuple):\n        color: str\n        size: int\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"color\": kwargs[\"color\"],\n            \"size\": kwargs[\"size\"],\n        }\n        # or\n        return MyComponent.TemplateData(\n            color=kwargs[\"color\"],\n            size=kwargs[\"size\"],\n        )\n

Warning

get_template_data() and get_context_data() are mutually exclusive.

If both methods return non-empty dictionaries, an error will be raised.

"},{"location":"reference/api/#django_components.Component.get_template_name","title":"get_template_name","text":"
get_template_name(context: Context) -> Optional[str]\n

See source code

DEPRECATED: Use instead Component.template_file, Component.template or Component.on_render(). Will be removed in v1.

Same as Component.template_file, but allows to dynamically resolve the template name at render time.

See Component.template_file for more info and examples.

Warning

The context is not fully populated at the point when this method is called.

If you need to access the context, either use Component.on_render_before() or Component.on_render().

Warning

Only one of template_file, get_template_name(), template or get_template() must be defined.

Parameters:

  • context (Context) \u2013

    The Django template Context in which the component is rendered.

Returns:

  • Optional[str] \u2013

    Optional[str]: The filepath to the template.

"},{"location":"reference/api/#django_components.Component.inject","title":"inject","text":"
inject(key: str, default: Optional[Any] = None) -> Any\n

See source code

Use this method to retrieve the data that was passed to a {% provide %} tag with the corresponding key.

To retrieve the data, inject() must be called inside a component that's inside the {% provide %} tag.

You may also pass a default that will be used if the {% provide %} tag with given key was NOT found.

This method is part of the Render API, and raises an error if called from outside the rendering execution.

Read more about Provide / Inject.

Example:

Given this template:

{% provide \"my_provide\" message=\"hello\" %}\n    {% component \"my_comp\" / %}\n{% endprovide %}\n

And given this definition of \"my_comp\" component:

from django_components import Component, register\n\n@register(\"my_comp\")\nclass MyComp(Component):\n    template = \"hi {{ message }}!\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        data = self.inject(\"my_provide\")\n        message = data.message\n        return {\"message\": message}\n

This renders into:

hi hello!\n

As the {{ message }} is taken from the \"my_provide\" provider.

"},{"location":"reference/api/#django_components.Component.on_render","title":"on_render","text":"
on_render(context: Context, template: Optional[Template]) -> Union[SlotResult, OnRenderGenerator, None]\n

See source code

This method does the actual rendering.

Read more about this hook in Component hooks.

You can override this method to:

  • Change what template gets rendered
  • Modify the context
  • Modify the rendered output after it has been rendered
  • Handle errors

The default implementation renders the component's Template with the given Context.

class MyTable(Component):\n    def on_render(self, context, template):\n        if template is None:\n            return None\n        else:\n            return template.render(context)\n

The template argument is None if the component has no template.

Modifying rendered template

To change what gets rendered, you can:

  • Render a different template
  • Render a component
  • Return a different string or SafeString
class MyTable(Component):\n    def on_render(self, context, template):\n        return \"Hello\"\n

Post-processing rendered template

To access the final output, you can yield the result instead of returning it.

This will return a tuple of (rendered HTML, error). The error is None if the rendering succeeded.

class MyTable(Component):\n    def on_render(self, context, template):\n        html, error = yield template.render(context)\n\n        if error is None:\n            # The rendering succeeded\n            return html\n        else:\n            # The rendering failed\n            print(f\"Error: {error}\")\n

At this point you can do 3 things:

  1. Return a new HTML

    The new HTML will be used as the final output.

    If the original template raised an error, it will be ignored.

    class MyTable(Component):\n    def on_render(self, context, template):\n        html, error = yield template.render(context)\n\n        return \"NEW HTML\"\n
  2. Raise a new exception

    The new exception is what will bubble up from the component.

    The original HTML and original error will be ignored.

    class MyTable(Component):\n    def on_render(self, context, template):\n        html, error = yield template.render(context)\n\n        raise Exception(\"Error message\")\n
  3. Return nothing (or None) to handle the result as usual

    If you don't raise an exception, and neither return a new HTML, then original HTML / error will be used:

    • If rendering succeeded, the original HTML will be used as the final output.
    • If rendering failed, the original error will be propagated.
    class MyTable(Component):\n    def on_render(self, context, template):\n        html, error = yield template.render(context)\n\n        if error is not None:\n            # The rendering failed\n            print(f\"Error: {error}\")\n
"},{"location":"reference/api/#django_components.Component.on_render_after","title":"on_render_after","text":"
on_render_after(context: Context, template: Optional[Template], result: Optional[str], error: Optional[Exception]) -> Optional[SlotResult]\n

See source code

Hook that runs when the component was fully rendered, including all its children.

It receives the same arguments as on_render_before(), plus the outcome of the rendering:

  • result: The rendered output of the component. None if the rendering failed.
  • error: The error that occurred during the rendering, or None if the rendering succeeded.

on_render_after() behaves the same way as the second part of on_render() (after the yield).

class MyTable(Component):\n    def on_render_after(self, context, template, result, error):\n        if error is None:\n            # The rendering succeeded\n            return result\n        else:\n            # The rendering failed\n            print(f\"Error: {error}\")\n

Same as on_render(), you can return a new HTML, raise a new exception, or return nothing:

  1. Return a new HTML

    The new HTML will be used as the final output.

    If the original template raised an error, it will be ignored.

    class MyTable(Component):\n    def on_render_after(self, context, template, result, error):\n        return \"NEW HTML\"\n
  2. Raise a new exception

    The new exception is what will bubble up from the component.

    The original HTML and original error will be ignored.

    class MyTable(Component):\n    def on_render_after(self, context, template, result, error):\n        raise Exception(\"Error message\")\n
  3. Return nothing (or None) to handle the result as usual

    If you don't raise an exception, and neither return a new HTML, then original HTML / error will be used:

    • If rendering succeeded, the original HTML will be used as the final output.
    • If rendering failed, the original error will be propagated.
    class MyTable(Component):\n    def on_render_after(self, context, template, result, error):\n        if error is not None:\n            # The rendering failed\n            print(f\"Error: {error}\")\n
"},{"location":"reference/api/#django_components.Component.on_render_before","title":"on_render_before","text":"
on_render_before(context: Context, template: Optional[Template]) -> None\n

See source code

Runs just before the component's template is rendered.

It is called for every component, including nested ones, as part of the component render lifecycle.

Parameters:

  • context (Context) \u2013

    The Django Context that will be used to render the component's template.

  • template (Optional[Template]) \u2013

    The Django Template instance that will be rendered, or None if no template.

Returns:

  • None \u2013

    None. This hook is for side effects only.

Example:

You can use this hook to access the context or the template:

from django.template import Context, Template\nfrom django_components import Component\n\nclass MyTable(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        # Insert value into the Context\n        context[\"from_on_before\"] = \":)\"\n\n        assert isinstance(template, Template)\n

Warning

If you want to pass data to the template, prefer using get_template_data() instead of this hook.

Warning

Do NOT modify the template in this hook. The template is reused across renders.

Since this hook is called for every component, this means that the template would be modified every time a component is rendered.

"},{"location":"reference/api/#django_components.Component.render","title":"render classmethod","text":"
render(\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    args: Optional[Any] = None,\n    kwargs: Optional[Any] = None,\n    slots: Optional[Any] = None,\n    deps_strategy: DependenciesStrategy = \"document\",\n    type: Optional[DependenciesStrategy] = None,\n    render_dependencies: bool = True,\n    request: Optional[HttpRequest] = None,\n    outer_context: Optional[Context] = None,\n    registry: Optional[ComponentRegistry] = None,\n    registered_name: Optional[str] = None,\n    node: Optional[ComponentNode] = None,\n) -> str\n

See source code

Render the component into a string. This is the equivalent of calling the {% component %} tag.

Button.render(\n    args=[\"John\"],\n    kwargs={\n        \"surname\": \"Doe\",\n        \"age\": 30,\n    },\n    slots={\n        \"footer\": \"i AM A SLOT\",\n    },\n)\n

Inputs:

  • args - Optional. A list of positional args for the component. This is the same as calling the component as:

    {% component \"button\" arg1 arg2 ... %}\n
  • kwargs - Optional. A dictionary of keyword arguments for the component. This is the same as calling the component as:

    {% component \"button\" key1=val1 key2=val2 ... %}\n
  • slots - Optional. A dictionary of slot fills. This is the same as passing {% fill %} tags to the component.

    {% component \"button\" %}\n    {% fill \"content\" %}\n        Click me!\n    {% endfill %}\n{% endcomponent %}\n

    Dictionary keys are the slot names. Dictionary values are the slot fills.

    Slot fills can be strings, render functions, or Slot instances:

    Button.render(\n    slots={\n        \"content\": \"Click me!\"\n        \"content2\": lambda ctx: \"Click me!\",\n        \"content3\": Slot(lambda ctx: \"Click me!\"),\n    },\n)\n
  • context - Optional. Plain dictionary or Django's Context. The context within which the component is rendered.

    When a component is rendered within a template with the {% component %} tag, this will be set to the Context instance that is used for rendering the template.

    When you call Component.render() directly from Python, you can ignore this input most of the time. Instead use args, kwargs, and slots to pass data to the component.

    You can pass RequestContext to the context argument, so that the component will gain access to the request object and will use context processors. Read more on Working with HTTP requests.

    Button.render(\n    context=RequestContext(request),\n)\n

    For advanced use cases, you can use context argument to \"pre-render\" the component in Python, and then pass the rendered output as plain string to the template. With this, the inner component is rendered as if it was within the template with {% component %}.

    class Button(Component):\n    def render(self, context, template):\n        # Pass `context` to Icon component so it is rendered\n        # as if nested within Button.\n        icon = Icon.render(\n            context=context,\n            args=[\"icon-name\"],\n            deps_strategy=\"ignore\",\n        )\n        # Update context with icon\n        with context.update({\"icon\": icon}):\n            return template.render(context)\n

    Whether the variables defined in context are available to the template depends on the context behavior mode:

    • In \"django\" context behavior mode, the template will have access to the keys of this context.

    • In \"isolated\" context behavior mode, the template will NOT have access to this context, and data MUST be passed via component's args and kwargs.

  • deps_strategy - Optional. Configure how to handle JS and CSS dependencies. Read more about Dependencies rendering.

    There are six strategies:

    • \"document\" (default)
      • Smartly inserts JS / CSS into placeholders or into <head> and <body> tags.
      • Inserts extra script to allow fragment types to work.
      • Assumes the HTML will be rendered in a JS-enabled browser.
    • \"fragment\"
      • A lightweight HTML fragment to be inserted into a document with AJAX.
      • No JS / CSS included.
    • \"simple\"
      • Smartly insert JS / CSS into placeholders or into <head> and <body> tags.
      • No extra script loaded.
    • \"prepend\"
      • Insert JS / CSS before the rendered HTML.
      • No extra script loaded.
    • \"append\"
      • Insert JS / CSS after the rendered HTML.
      • No extra script loaded.
    • \"ignore\"
      • HTML is left as-is. You can still process it with a different strategy later with render_dependencies().
      • Used for inserting rendered HTML into other components.
  • request - Optional. HTTPRequest object. Pass a request object directly to the component to apply context processors.

    Read more about Working with HTTP requests.

Type hints:

Component.render() is NOT typed. To add type hints, you can wrap the inputs in component's Args, Kwargs, and Slots classes.

Read more on Typing and validation.

from typing import NamedTuple, Optional\nfrom django_components import Component, Slot, SlotInput\n\n# Define the component with the types\nclass Button(Component):\n    class Args(NamedTuple):\n        name: str\n\n    class Kwargs(NamedTuple):\n        surname: str\n        age: int\n\n    class Slots(NamedTuple):\n        my_slot: Optional[SlotInput] = None\n        footer: SlotInput\n\n# Add type hints to the render call\nButton.render(\n    args=Button.Args(\n        name=\"John\",\n    ),\n    kwargs=Button.Kwargs(\n        surname=\"Doe\",\n        age=30,\n    ),\n    slots=Button.Slots(\n        footer=Slot(lambda ctx: \"Click me!\"),\n    ),\n)\n
"},{"location":"reference/api/#django_components.Component.render_to_response","title":"render_to_response classmethod","text":"
render_to_response(\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    args: Optional[Any] = None,\n    kwargs: Optional[Any] = None,\n    slots: Optional[Any] = None,\n    deps_strategy: DependenciesStrategy = \"document\",\n    type: Optional[DependenciesStrategy] = None,\n    render_dependencies: bool = True,\n    request: Optional[HttpRequest] = None,\n    outer_context: Optional[Context] = None,\n    registry: Optional[ComponentRegistry] = None,\n    registered_name: Optional[str] = None,\n    node: Optional[ComponentNode] = None,\n    **response_kwargs: Any\n) -> HttpResponse\n

See source code

Render the component and wrap the content in an HTTP response class.

render_to_response() takes the same inputs as Component.render(). See that method for more information.

After the component is rendered, the HTTP response class is instantiated with the rendered content.

Any additional kwargs are passed to the response class.

Example:

Button.render_to_response(\n    args=[\"John\"],\n    kwargs={\n        \"surname\": \"Doe\",\n        \"age\": 30,\n    },\n    slots={\n        \"footer\": \"i AM A SLOT\",\n    },\n    # HttpResponse kwargs\n    status=201,\n    headers={...},\n)\n# HttpResponse(content=..., status=201, headers=...)\n

Custom response class:

You can set a custom response class on the component via Component.response_class. Defaults to django.http.HttpResponse.

from django.http import HttpResponse\nfrom django_components import Component\n\nclass MyHttpResponse(HttpResponse):\n    ...\n\nclass MyComponent(Component):\n    response_class = MyHttpResponse\n\nresponse = MyComponent.render_to_response()\nassert isinstance(response, MyHttpResponse)\n
"},{"location":"reference/api/#django_components.ComponentCache","title":"ComponentCache","text":"
ComponentCache(component: Component)\n

Bases: django_components.extension.ExtensionComponentConfig

See source code

The interface for Component.Cache.

The fields of this class are used to configure the component caching.

Read more about Component caching.

Example:

from django_components import Component\n\nclass MyComponent(Component):\n    class Cache:\n        enabled = True\n        ttl = 60 * 60 * 24  # 1 day\n        cache_name = \"my_cache\"\n

Methods:

  • get_cache \u2013
  • get_cache_key \u2013
  • get_entry \u2013
  • hash \u2013
  • hash_slots \u2013
  • set_entry \u2013

Attributes:

  • cache_name (Optional[str]) \u2013
  • component (Component) \u2013
  • component_class (Type[Component]) \u2013
  • component_cls (Type[Component]) \u2013
  • enabled (bool) \u2013
  • include_slots (bool) \u2013
  • ttl (Optional[int]) \u2013
"},{"location":"reference/api/#django_components.ComponentCache.cache_name","title":"cache_name class-attribute instance-attribute","text":"
cache_name: Optional[str] = None\n

See source code

The name of the cache to use. If None, the default cache will be used.

"},{"location":"reference/api/#django_components.ComponentCache.component","title":"component instance-attribute","text":"
component: Component = component\n

See source code

See source code

When a Component is instantiated, also the nested extension classes (such as Component.View) are instantiated, receiving the component instance as an argument.

This attribute holds the owner Component instance that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentCache.component_class","title":"component_class instance-attribute","text":"
component_class: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentCache.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentCache.enabled","title":"enabled class-attribute instance-attribute","text":"
enabled: bool = False\n

See source code

Whether this Component should be cached. Defaults to False.

"},{"location":"reference/api/#django_components.ComponentCache.include_slots","title":"include_slots class-attribute instance-attribute","text":"
include_slots: bool = False\n

See source code

Whether the slots should be hashed into the cache key.

If enabled, the following two cases will be treated as different entries:

{% component \"mycomponent\" name=\"foo\" %}\n    FILL ONE\n{% endcomponent %}\n\n{% component \"mycomponent\" name=\"foo\" %}\n    FILL TWO\n{% endcomponent %}\n

Warning

Passing slots as functions to cached components with include_slots=True will raise an error.

Warning

Slot caching DOES NOT account for context variables within the {% fill %} tag.

For example, the following two cases will be treated as the same entry:

{% with my_var=\"foo\" %}\n    {% component \"mycomponent\" name=\"foo\" %}\n        {{ my_var }}\n    {% endcomponent %}\n{% endwith %}\n\n{% with my_var=\"bar\" %}\n    {% component \"mycomponent\" name=\"bar\" %}\n        {{ my_var }}\n    {% endcomponent %}\n{% endwith %}\n

Currently it's impossible to capture used variables. This will be addressed in v2. Read more about it in https://github.com/django-components/django-components/issues/1164.

"},{"location":"reference/api/#django_components.ComponentCache.ttl","title":"ttl class-attribute instance-attribute","text":"
ttl: Optional[int] = None\n

See source code

The time-to-live (TTL) in seconds, i.e. for how long should an entry be valid in the cache.

  • If > 0, the entries will be cached for the given number of seconds.
  • If -1, the entries will be cached indefinitely.
  • If 0, the entries won't be cached.
  • If None, the default TTL will be used.
"},{"location":"reference/api/#django_components.ComponentCache.get_cache","title":"get_cache","text":"
get_cache() -> BaseCache\n
"},{"location":"reference/api/#django_components.ComponentCache.get_cache_key","title":"get_cache_key","text":"
get_cache_key(args: List, kwargs: Dict, slots: Dict) -> str\n
"},{"location":"reference/api/#django_components.ComponentCache.get_entry","title":"get_entry","text":"
get_entry(cache_key: str) -> Any\n
"},{"location":"reference/api/#django_components.ComponentCache.hash","title":"hash","text":"
hash(args: List, kwargs: Dict) -> str\n

See source code

Defines how the input (both args and kwargs) is hashed into a cache key.

By default, hash() serializes the input into a string. As such, the default implementation might NOT be suitable if you need to hash complex objects.

"},{"location":"reference/api/#django_components.ComponentCache.hash_slots","title":"hash_slots","text":"
hash_slots(slots: Dict[str, Slot]) -> str\n
"},{"location":"reference/api/#django_components.ComponentCache.set_entry","title":"set_entry","text":"
set_entry(cache_key: str, value: Any) -> None\n
"},{"location":"reference/api/#django_components.ComponentDebugHighlight","title":"ComponentDebugHighlight","text":"
ComponentDebugHighlight(component: Component)\n

Bases: django_components.extension.ExtensionComponentConfig

See source code

The interface for Component.DebugHighlight.

The fields of this class are used to configure the component debug highlighting for this component and its direct slots.

Read more about Component debug highlighting.

Example:

from django_components import Component\n\nclass MyComponent(Component):\n    class DebugHighlight:\n        highlight_components = True\n        highlight_slots = True\n

To highlight ALL components and slots, set extension defaults in your settings:

from django_components import ComponentsSettings\n\nCOMPONENTS = ComponentsSettings(\n    extensions_defaults={\n        \"debug_highlight\": {\n            \"highlight_components\": True,\n            \"highlight_slots\": True,\n        },\n    },\n)\n

Attributes:

  • component (Component) \u2013
  • component_class (Type[Component]) \u2013
  • component_cls (Type[Component]) \u2013
  • highlight_components \u2013
  • highlight_slots \u2013
"},{"location":"reference/api/#django_components.ComponentDebugHighlight.component","title":"component instance-attribute","text":"
component: Component = component\n

See source code

See source code

When a Component is instantiated, also the nested extension classes (such as Component.View) are instantiated, receiving the component instance as an argument.

This attribute holds the owner Component instance that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentDebugHighlight.component_class","title":"component_class instance-attribute","text":"
component_class: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentDebugHighlight.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentDebugHighlight.highlight_components","title":"highlight_components class-attribute instance-attribute","text":"
highlight_components = HighlightComponentsDescriptor()\n

See source code

Whether to highlight this component in the rendered output.

"},{"location":"reference/api/#django_components.ComponentDebugHighlight.highlight_slots","title":"highlight_slots class-attribute instance-attribute","text":"
highlight_slots = HighlightSlotsDescriptor()\n

See source code

Whether to highlight slots of this component in the rendered output.

"},{"location":"reference/api/#django_components.ComponentDefaults","title":"ComponentDefaults","text":"
ComponentDefaults(component: Component)\n

Bases: django_components.extension.ExtensionComponentConfig

See source code

The interface for Component.Defaults.

The fields of this class are used to set default values for the component's kwargs.

Read more about Component defaults.

Example:

from django_components import Component, Default\n\nclass MyComponent(Component):\n    class Defaults:\n        position = \"left\"\n        selected_items = Default(lambda: [1, 2, 3])\n

Attributes:

  • component (Component) \u2013
  • component_class (Type[Component]) \u2013
  • component_cls (Type[Component]) \u2013
"},{"location":"reference/api/#django_components.ComponentDefaults.component","title":"component instance-attribute","text":"
component: Component = component\n

See source code

See source code

When a Component is instantiated, also the nested extension classes (such as Component.View) are instantiated, receiving the component instance as an argument.

This attribute holds the owner Component instance that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentDefaults.component_class","title":"component_class instance-attribute","text":"
component_class: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentDefaults.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentExtension","title":"ComponentExtension","text":"

Bases: object

See source code

Base class for all extensions.

Read more on Extensions.

Example:

class ExampleExtension(ComponentExtension):\n    name = \"example\"\n\n    # Component-level behavior and settings. User will be able to override\n    # the attributes and methods defined here on the component classes.\n    class ComponentConfig(ComponentExtension.ComponentConfig):\n        foo = \"1\"\n        bar = \"2\"\n\n        def baz(cls):\n            return \"3\"\n\n    # URLs\n    urls = [\n        URLRoute(path=\"dummy-view/\", handler=dummy_view, name=\"dummy\"),\n        URLRoute(path=\"dummy-view-2/<int:id>/<str:name>/\", handler=dummy_view_2, name=\"dummy-2\"),\n    ]\n\n    # Commands\n    commands = [\n        HelloWorldCommand,\n    ]\n\n    # Hooks\n    def on_component_class_created(self, ctx: OnComponentClassCreatedContext) -> None:\n        print(ctx.component_cls.__name__)\n\n    def on_component_class_deleted(self, ctx: OnComponentClassDeletedContext) -> None:\n        print(ctx.component_cls.__name__)\n

Which users then can override on a per-component basis. E.g.:

class MyComp(Component):\n    class Example:\n        foo = \"overridden\"\n\n        def baz(self):\n            return \"overridden baz\"\n

Methods:

  • on_component_class_created \u2013
  • on_component_class_deleted \u2013
  • on_component_data \u2013
  • on_component_input \u2013
  • on_component_registered \u2013
  • on_component_rendered \u2013
  • on_component_unregistered \u2013
  • on_css_loaded \u2013
  • on_js_loaded \u2013
  • on_registry_created \u2013
  • on_registry_deleted \u2013
  • on_slot_rendered \u2013
  • on_template_compiled \u2013
  • on_template_loaded \u2013

Attributes:

  • ComponentConfig (Type[ExtensionComponentConfig]) \u2013
  • class_name (str) \u2013
  • commands (List[Type[ComponentCommand]]) \u2013
  • name (str) \u2013
  • urls (List[URLRoute]) \u2013
"},{"location":"reference/api/#django_components.ComponentExtension.ComponentConfig","title":"ComponentConfig class-attribute","text":"
ComponentConfig: Type[ExtensionComponentConfig] = ExtensionComponentConfig\n

See source code

Base class that the \"component-level\" extension config nested within a Component class will inherit from.

This is where you can define new methods and attributes that will be available to the component instance.

Background:

The extension may add new features to the Component class by allowing users to define and access a nested class in the Component class. E.g.:

class MyComp(Component):\n    class MyExtension:\n        ...\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"my_extension\": self.my_extension.do_something(),\n        }\n

When rendering a component, the nested extension class will be set as a subclass of ComponentConfig. So it will be same as if the user had directly inherited from extension's ComponentConfig. E.g.:

class MyComp(Component):\n    class MyExtension(ComponentExtension.ComponentConfig):\n        ...\n

This setting decides what the extension class will inherit from.

"},{"location":"reference/api/#django_components.ComponentExtension.class_name","title":"class_name class-attribute","text":"
class_name: str\n

See source code

Name of the extension class.

By default, this is set automatically at class creation. The class name is the same as the name attribute, but with snake_case converted to PascalCase.

So if the extension name is \"my_extension\", then the extension class name will be \"MyExtension\".

class MyComp(Component):\n    class MyExtension:  # <--- This is the extension class\n        ...\n

To customize the class name, you can manually set the class_name attribute.

The class name must be a valid Python identifier.

Example:

class MyExt(ComponentExtension):\n    name = \"my_extension\"\n    class_name = \"MyCustomExtension\"\n

This will make the extension class name \"MyCustomExtension\".

class MyComp(Component):\n    class MyCustomExtension:  # <--- This is the extension class\n        ...\n
"},{"location":"reference/api/#django_components.ComponentExtension.commands","title":"commands class-attribute","text":"
commands: List[Type[ComponentCommand]] = []\n

See source code

List of commands that can be run by the extension.

These commands will be available to the user as components ext run <extension> <command>.

Commands are defined as subclasses of ComponentCommand.

Example:

This example defines an extension with a command that prints \"Hello world\". To run the command, the user would run components ext run hello_world hello.

from django_components import ComponentCommand, ComponentExtension, CommandArg, CommandArgGroup\n\nclass HelloWorldCommand(ComponentCommand):\n    name = \"hello\"\n    help = \"Hello world command.\"\n\n    # Allow to pass flags `--foo`, `--bar` and `--baz`.\n    # Argument parsing is managed by `argparse`.\n    arguments = [\n        CommandArg(\n            name_or_flags=\"--foo\",\n            help=\"Foo description.\",\n        ),\n        # When printing the command help message, `bar` and `baz`\n        # will be grouped under \"group bar\".\n        CommandArgGroup(\n            title=\"group bar\",\n            description=\"Group description.\",\n            arguments=[\n                CommandArg(\n                    name_or_flags=\"--bar\",\n                    help=\"Bar description.\",\n                ),\n                CommandArg(\n                    name_or_flags=\"--baz\",\n                    help=\"Baz description.\",\n                ),\n            ],\n        ),\n    ]\n\n    # Callback that receives the parsed arguments and options.\n    def handle(self, *args, **kwargs):\n        print(f\"HelloWorldCommand.handle: args={args}, kwargs={kwargs}\")\n\n# Associate the command with the extension\nclass HelloWorldExtension(ComponentExtension):\n    name = \"hello_world\"\n\n    commands = [\n        HelloWorldCommand,\n    ]\n
"},{"location":"reference/api/#django_components.ComponentExtension.name","title":"name class-attribute","text":"
name: str\n

See source code

Name of the extension.

Name must be lowercase, and must be a valid Python identifier (e.g. \"my_extension\").

The extension may add new features to the Component class by allowing users to define and access a nested class in the Component class.

The extension name determines the name of the nested class in the Component class, and the attribute under which the extension will be accessible.

E.g. if the extension name is \"my_extension\", then the nested class in the Component class will be MyExtension, and the extension will be accessible as MyComp.my_extension.

class MyComp(Component):\n    class MyExtension:\n        ...\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"my_extension\": self.my_extension.do_something(),\n        }\n

Info

The extension class name can be customized by setting the class_name attribute.

"},{"location":"reference/api/#django_components.ComponentExtension.urls","title":"urls class-attribute","text":"
urls: List[URLRoute] = []\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_component_class_created","title":"on_component_class_created","text":"
on_component_class_created(ctx: OnComponentClassCreatedContext) -> None\n

See source code

Called when a new Component class is created.

This hook is called after the Component class is fully defined but before it's registered.

Use this hook to perform any initialization or validation of the Component class.

Example:

from django_components import ComponentExtension, OnComponentClassCreatedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_class_created(self, ctx: OnComponentClassCreatedContext) -> None:\n        # Add a new attribute to the Component class\n        ctx.component_cls.my_attr = \"my_value\"\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_component_class_deleted","title":"on_component_class_deleted","text":"
on_component_class_deleted(ctx: OnComponentClassDeletedContext) -> None\n

See source code

Called when a Component class is being deleted.

This hook is called before the Component class is deleted from memory.

Use this hook to perform any cleanup related to the Component class.

Example:

from django_components import ComponentExtension, OnComponentClassDeletedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_class_deleted(self, ctx: OnComponentClassDeletedContext) -> None:\n        # Remove Component class from the extension's cache on deletion\n        self.cache.pop(ctx.component_cls, None)\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_component_data","title":"on_component_data","text":"
on_component_data(ctx: OnComponentDataContext) -> None\n

See source code

Called when a Component was triggered to render, after a component's context and data methods have been processed.

This hook is called after Component.get_template_data(), Component.get_js_data() and Component.get_css_data().

This hook runs after on_component_input.

Use this hook to modify or validate the component's data before rendering.

Example:

from django_components import ComponentExtension, OnComponentDataContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_data(self, ctx: OnComponentDataContext) -> None:\n        # Add extra template variable to all components when they are rendered\n        ctx.template_data[\"my_template_var\"] = \"my_value\"\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_component_input","title":"on_component_input","text":"
on_component_input(ctx: OnComponentInputContext) -> Optional[str]\n

See source code

Called when a Component was triggered to render, but before a component's context and data methods are invoked.

Use this hook to modify or validate component inputs before they're processed.

This is the first hook that is called when rendering a component. As such this hook is called before Component.get_template_data(), Component.get_js_data(), and Component.get_css_data() methods, and the on_component_data hook.

This hook also allows to skip the rendering of a component altogether. If the hook returns a non-null value, this value will be used instead of rendering the component.

You can use this to implement a caching mechanism for components, or define components that will be rendered conditionally.

Example:

from django_components import ComponentExtension, OnComponentInputContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_input(self, ctx: OnComponentInputContext) -> None:\n        # Add extra kwarg to all components when they are rendered\n        ctx.kwargs[\"my_input\"] = \"my_value\"\n

Warning

In this hook, the components' inputs are still mutable.

As such, if a component defines Args, Kwargs, Slots types, these types are NOT yet instantiated.

Instead, component fields like Component.args, Component.kwargs, Component.slots are plain list / dict objects.

"},{"location":"reference/api/#django_components.ComponentExtension.on_component_registered","title":"on_component_registered","text":"
on_component_registered(ctx: OnComponentRegisteredContext) -> None\n

See source code

Called when a Component class is registered with a ComponentRegistry.

This hook is called after a Component class is successfully registered.

Example:

from django_components import ComponentExtension, OnComponentRegisteredContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_registered(self, ctx: OnComponentRegisteredContext) -> None:\n        print(f\"Component {ctx.component_cls} registered to {ctx.registry} as '{ctx.name}'\")\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_component_rendered","title":"on_component_rendered","text":"
on_component_rendered(ctx: OnComponentRenderedContext) -> Optional[str]\n

See source code

Called when a Component was rendered, including all its child components.

Use this hook to access or post-process the component's rendered output.

This hook works similarly to Component.on_render_after():

  1. To modify the output, return a new string from this hook. The original output or error will be ignored.

  2. To cause this component to return a new error, raise that error. The original output and error will be ignored.

  3. If you neither raise nor return string, the original output or error will be used.

Examples:

Change the final output of a component:

from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n        # Append a comment to the component's rendered output\n        return ctx.result + \"<!-- MyExtension comment -->\"\n

Cause the component to raise a new exception:

from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n        # Raise a new exception\n        raise Exception(\"Error message\")\n

Return nothing (or None) to handle the result as usual:

from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n        if ctx.error is not None:\n            # The component raised an exception\n            print(f\"Error: {ctx.error}\")\n        else:\n            # The component rendered successfully\n            print(f\"Result: {ctx.result}\")\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_component_unregistered","title":"on_component_unregistered","text":"
on_component_unregistered(ctx: OnComponentUnregisteredContext) -> None\n

See source code

Called when a Component class is unregistered from a ComponentRegistry.

This hook is called after a Component class is removed from the registry.

Example:

from django_components import ComponentExtension, OnComponentUnregisteredContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_unregistered(self, ctx: OnComponentUnregisteredContext) -> None:\n        print(f\"Component {ctx.component_cls} unregistered from {ctx.registry} as '{ctx.name}'\")\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_css_loaded","title":"on_css_loaded","text":"
on_css_loaded(ctx: OnCssLoadedContext) -> Optional[str]\n

See source code

Called when a Component's CSS is loaded as a string.

This hook runs only once per Component class and works for both Component.css and Component.css_file.

Use this hook to read or modify the CSS.

To modify the CSS, return a new string from this hook.

Example:

from django_components import ComponentExtension, OnCssLoadedContext\n\nclass MyExtension(ComponentExtension):\n    def on_css_loaded(self, ctx: OnCssLoadedContext) -> Optional[str]:\n        # Modify the CSS\n        return ctx.content.replace(\"Hello\", \"Hi\")\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_js_loaded","title":"on_js_loaded","text":"
on_js_loaded(ctx: OnJsLoadedContext) -> Optional[str]\n

See source code

Called when a Component's JS is loaded as a string.

This hook runs only once per Component class and works for both Component.js and Component.js_file.

Use this hook to read or modify the JS.

To modify the JS, return a new string from this hook.

Example:

from django_components import ComponentExtension, OnCssLoadedContext\n\nclass MyExtension(ComponentExtension):\n    def on_js_loaded(self, ctx: OnJsLoadedContext) -> Optional[str]:\n        # Modify the JS\n        return ctx.content.replace(\"Hello\", \"Hi\")\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_registry_created","title":"on_registry_created","text":"
on_registry_created(ctx: OnRegistryCreatedContext) -> None\n

See source code

Called when a new ComponentRegistry is created.

This hook is called after a new ComponentRegistry instance is initialized.

Use this hook to perform any initialization needed for the registry.

Example:

from django_components import ComponentExtension, OnRegistryCreatedContext\n\nclass MyExtension(ComponentExtension):\n    def on_registry_created(self, ctx: OnRegistryCreatedContext) -> None:\n        # Add a new attribute to the registry\n        ctx.registry.my_attr = \"my_value\"\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_registry_deleted","title":"on_registry_deleted","text":"
on_registry_deleted(ctx: OnRegistryDeletedContext) -> None\n

See source code

Called when a ComponentRegistry is being deleted.

This hook is called before a ComponentRegistry instance is deleted.

Use this hook to perform any cleanup related to the registry.

Example:

from django_components import ComponentExtension, OnRegistryDeletedContext\n\nclass MyExtension(ComponentExtension):\n    def on_registry_deleted(self, ctx: OnRegistryDeletedContext) -> None:\n        # Remove registry from the extension's cache on deletion\n        self.cache.pop(ctx.registry, None)\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_slot_rendered","title":"on_slot_rendered","text":"
on_slot_rendered(ctx: OnSlotRenderedContext) -> Optional[str]\n

See source code

Called when a {% slot %} tag was rendered.

Use this hook to access or post-process the slot's rendered output.

To modify the output, return a new string from this hook.

Example:

from django_components import ComponentExtension, OnSlotRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_slot_rendered(self, ctx: OnSlotRenderedContext) -> Optional[str]:\n        # Append a comment to the slot's rendered output\n        return ctx.result + \"<!-- MyExtension comment -->\"\n

Access slot metadata:

You can access the {% slot %} tag node (SlotNode) and its metadata using ctx.slot_node.

For example, to find the Component class to which belongs the template where the {% slot %} tag is defined, you can use ctx.slot_node.template_component:

from django_components import ComponentExtension, OnSlotRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_slot_rendered(self, ctx: OnSlotRenderedContext) -> Optional[str]:\n        # Access slot metadata\n        slot_node = ctx.slot_node\n        slot_owner = slot_node.template_component\n        print(f\"Slot owner: {slot_owner}\")\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_template_compiled","title":"on_template_compiled","text":"
on_template_compiled(ctx: OnTemplateCompiledContext) -> None\n

See source code

Called when a Component's template is compiled into a Template object.

This hook runs only once per Component class and works for both Component.template and Component.template_file.

Use this hook to read or modify the template (in-place) after it's compiled.

Example:

from django_components import ComponentExtension, OnTemplateCompiledContext\n\nclass MyExtension(ComponentExtension):\n    def on_template_compiled(self, ctx: OnTemplateCompiledContext) -> None:\n        print(f\"Template origin: {ctx.template.origin.name}\")\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_template_loaded","title":"on_template_loaded","text":"
on_template_loaded(ctx: OnTemplateLoadedContext) -> Optional[str]\n

See source code

Called when a Component's template is loaded as a string.

This hook runs only once per Component class and works for both Component.template and Component.template_file.

Use this hook to read or modify the template before it's compiled.

To modify the template, return a new string from this hook.

Example:

from django_components import ComponentExtension, OnTemplateLoadedContext\n\nclass MyExtension(ComponentExtension):\n    def on_template_loaded(self, ctx: OnTemplateLoadedContext) -> Optional[str]:\n        # Modify the template\n        return ctx.content.replace(\"Hello\", \"Hi\")\n
"},{"location":"reference/api/#django_components.ComponentFileEntry","title":"ComponentFileEntry","text":"

Bases: tuple

See source code

Result returned by get_component_files().

Attributes:

  • dot_path (str) \u2013
  • filepath (Path) \u2013
"},{"location":"reference/api/#django_components.ComponentFileEntry.dot_path","title":"dot_path instance-attribute","text":"
dot_path: str\n

See source code

The python import path for the module. E.g. app.components.mycomp

"},{"location":"reference/api/#django_components.ComponentFileEntry.filepath","title":"filepath instance-attribute","text":"
filepath: Path\n

See source code

The filesystem path to the module. E.g. /path/to/project/app/components/mycomp.py

"},{"location":"reference/api/#django_components.ComponentInput","title":"ComponentInput dataclass","text":"
ComponentInput(\n    context: Context,\n    args: List,\n    kwargs: Dict,\n    slots: Dict[SlotName, Slot],\n    deps_strategy: DependenciesStrategy,\n    type: DependenciesStrategy,\n    render_dependencies: bool,\n)\n

Bases: object

See source code

Deprecated. Will be removed in v1.

Object holding the inputs that were passed to Component.render() or the {% component %} template tag.

This object is available only during render under Component.input.

Read more about the Render API.

Attributes:

  • args (List) \u2013
  • context (Context) \u2013
  • deps_strategy (DependenciesStrategy) \u2013
  • kwargs (Dict) \u2013
  • render_dependencies (bool) \u2013
  • slots (Dict[SlotName, Slot]) \u2013
  • type (DependenciesStrategy) \u2013
"},{"location":"reference/api/#django_components.ComponentInput.args","title":"args instance-attribute","text":"
args: List\n

See source code

Positional arguments (as list) passed to Component.render()

"},{"location":"reference/api/#django_components.ComponentInput.context","title":"context instance-attribute","text":"
context: Context\n

See source code

Django's Context passed to Component.render()

"},{"location":"reference/api/#django_components.ComponentInput.deps_strategy","title":"deps_strategy instance-attribute","text":"
deps_strategy: DependenciesStrategy\n

See source code

Dependencies strategy passed to Component.render()

"},{"location":"reference/api/#django_components.ComponentInput.kwargs","title":"kwargs instance-attribute","text":"
kwargs: Dict\n

See source code

Keyword arguments (as dict) passed to Component.render()

"},{"location":"reference/api/#django_components.ComponentInput.render_dependencies","title":"render_dependencies instance-attribute","text":"
render_dependencies: bool\n

See source code

Deprecated. Will be removed in v1. Use deps_strategy=\"ignore\" instead.

"},{"location":"reference/api/#django_components.ComponentInput.slots","title":"slots instance-attribute","text":"
slots: Dict[SlotName, Slot]\n

See source code

Slots (as dict) passed to Component.render()

"},{"location":"reference/api/#django_components.ComponentInput.type","title":"type instance-attribute","text":"
type: DependenciesStrategy\n

See source code

Deprecated. Will be removed in v1. Use deps_strategy instead.

"},{"location":"reference/api/#django_components.ComponentMediaInput","title":"ComponentMediaInput","text":"

Bases: typing.Protocol

See source code

Defines JS and CSS media files associated with a Component.

class MyTable(Component):\n    class Media:\n        js = [\n            \"path/to/script.js\",\n            \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\",  # AlpineJS\n        ]\n        css = {\n            \"all\": [\n                \"path/to/style.css\",\n                \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\",  # TailwindCSS\n            ],\n            \"print\": [\"path/to/style2.css\"],\n        }\n

Attributes:

  • css (Optional[Union[ComponentMediaInputPath, List[ComponentMediaInputPath], Dict[str, ComponentMediaInputPath], Dict[str, List[ComponentMediaInputPath]]]]) \u2013
  • extend (Union[bool, List[Type[Component]]]) \u2013
  • js (Optional[Union[ComponentMediaInputPath, List[ComponentMediaInputPath]]]) \u2013
"},{"location":"reference/api/#django_components.ComponentMediaInput.css","title":"css class-attribute instance-attribute","text":"
css: Optional[\n    Union[\n        ComponentMediaInputPath, List[ComponentMediaInputPath], Dict[str, ComponentMediaInputPath], Dict[str, List[ComponentMediaInputPath]]\n    ]\n] = None\n

See source code

CSS files associated with a Component.

  • If a string, it's assumed to be a path to a CSS file.

  • If a list, each entry is assumed to be a path to a CSS file.

  • If a dict, the keys are media types (e.g. \"all\", \"print\", \"screen\", etc.), and the values are either:

    • A string, assumed to be a path to a CSS file.
    • A list, each entry is assumed to be a path to a CSS file.

Each entry can be a string, bytes, SafeString, PathLike, or a callable that returns one of the former (see ComponentMediaInputPath).

Examples:

class MyComponent(Component):\n    class Media:\n        css = \"path/to/style.css\"\n

class MyComponent(Component):\n    class Media:\n        css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n
class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": \"path/to/style.css\",\n            \"print\": \"path/to/print.css\",\n        }\n
class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": [\"path/to/style1.css\", \"path/to/style2.css\"],\n            \"print\": \"path/to/print.css\",\n        }\n
"},{"location":"reference/api/#django_components.ComponentMediaInput.extend","title":"extend class-attribute instance-attribute","text":"
extend: Union[bool, List[Type[Component]]] = True\n

See source code

Configures whether the component should inherit the media files from the parent component.

  • If True, the component inherits the media files from the parent component.
  • If False, the component does not inherit the media files from the parent component.
  • If a list of components classes, the component inherits the media files ONLY from these specified components.

Read more in Media inheritance section.

Example:

Disable media inheritance:

class ParentComponent(Component):\n    class Media:\n        js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n    class Media:\n        extend = False  # Don't inherit parent media\n        js = [\"script.js\"]\n\nprint(MyComponent.media._js)  # [\"script.js\"]\n

Specify which components to inherit from. In this case, the media files are inherited ONLY from the specified components, and NOT from the original parent components:

class ParentComponent(Component):\n    class Media:\n        js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n    class Media:\n        # Only inherit from these, ignoring the files from the parent\n        extend = [OtherComponent1, OtherComponent2]\n\n        js = [\"script.js\"]\n\nprint(MyComponent.media._js)  # [\"script.js\", \"other1.js\", \"other2.js\"]\n
"},{"location":"reference/api/#django_components.ComponentMediaInput.js","title":"js class-attribute instance-attribute","text":"
js: Optional[Union[ComponentMediaInputPath, List[ComponentMediaInputPath]]] = None\n

See source code

JS files associated with a Component.

  • If a string, it's assumed to be a path to a JS file.

  • If a list, each entry is assumed to be a path to a JS file.

Each entry can be a string, bytes, SafeString, PathLike, or a callable that returns one of the former (see ComponentMediaInputPath).

Examples:

class MyComponent(Component):\n    class Media:\n        js = \"path/to/script.js\"\n

class MyComponent(Component):\n    class Media:\n        js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n
class MyComponent(Component):\n    class Media:\n        js = lambda: [\"path/to/script1.js\", \"path/to/script2.js\"]\n
"},{"location":"reference/api/#django_components.ComponentMediaInputPath","title":"ComponentMediaInputPath module-attribute","text":"
ComponentMediaInputPath = Union[str, bytes, SafeData, Path, PathLike, Callable[[], Union[str, bytes, SafeData, Path, PathLike]]]\n

See source code

A type representing an entry in Media.js or Media.css.

If an entry is a SafeString (or has __html__ method), then entry is assumed to be a formatted HTML tag. Otherwise, it's assumed to be a path to a file.

Example:

class MyComponent\n    class Media:\n        js = [\n            \"path/to/script.js\",\n            b\"script.js\",\n            SafeString(\"<script src='path/to/script.js'></script>\"),\n        ]\n        css = [\n            Path(\"path/to/style.css\"),\n            lambda: \"path/to/style.css\",\n            lambda: Path(\"path/to/style.css\"),\n        ]\n
"},{"location":"reference/api/#django_components.ComponentNode","title":"ComponentNode","text":"
ComponentNode(\n    name: str,\n    registry: ComponentRegistry,\n    params: List[TagAttr],\n    flags: Optional[Dict[str, bool]] = None,\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    contents: Optional[str] = None,\n    template_name: Optional[str] = None,\n    template_component: Optional[Type[Component]] = None,\n)\n

Bases: django_components.node.BaseNode

See source code

Renders one of the components that was previously registered with @register() decorator.

The {% component %} tag takes:

  • Component's registered name as the first positional argument,
  • Followed by any number of positional and keyword arguments.
{% load component_tags %}\n<div>\n    {% component \"button\" name=\"John\" job=\"Developer\" / %}\n</div>\n

The component name must be a string literal.

"},{"location":"reference/api/#django_components.ComponentNode--inserting-slot-fills","title":"Inserting slot fills","text":"

If the component defined any slots, you can \"fill\" these slots by placing the {% fill %} tags within the {% component %} tag:

{% component \"my_table\" rows=rows headers=headers %}\n  {% fill \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endfill %}\n{% endcomponent %}\n

You can even nest {% fill %} tags within {% if %}, {% for %} and other tags:

{% component \"my_table\" rows=rows headers=headers %}\n    {% if rows %}\n        {% fill \"pagination\" %}\n            < 1 | 2 | 3 >\n        {% endfill %}\n    {% endif %}\n{% endcomponent %}\n
"},{"location":"reference/api/#django_components.ComponentNode--isolating-components","title":"Isolating components","text":"

By default, components behave similarly to Django's {% include %}, and the template inside the component has access to the variables defined in the outer template.

You can selectively isolate a component, using the only flag, so that the inner template can access only the data that was explicitly passed to it:

{% component \"name\" positional_arg keyword_arg=value ... only %}\n

Alternatively, you can set all components to be isolated by default, by setting context_behavior to \"isolated\" in your settings:

# settings.py\nCOMPONENTS = {\n    \"context_behavior\": \"isolated\",\n}\n
"},{"location":"reference/api/#django_components.ComponentNode--omitting-the-component-keyword","title":"Omitting the component keyword","text":"

If you would like to omit the component keyword, and simply refer to your components by their registered names:

{% button name=\"John\" job=\"Developer\" / %}\n

You can do so by setting the \"shorthand\" Tag formatter in the settings:

# settings.py\nCOMPONENTS = {\n    \"tag_formatter\": \"django_components.component_shorthand_formatter\",\n}\n

Methods:

  • parse \u2013
  • register \u2013
  • render \u2013
  • unregister \u2013

Attributes:

  • active_flags (List[str]) \u2013
  • allowed_flags \u2013
  • contents (Optional[str]) \u2013
  • end_tag \u2013
  • flags (Dict[str, bool]) \u2013
  • name \u2013
  • node_id (str) \u2013
  • nodelist (NodeList) \u2013
  • params (List[TagAttr]) \u2013
  • registry \u2013
  • tag \u2013
  • template_component (Optional[Type[Component]]) \u2013
  • template_name (Optional[str]) \u2013
"},{"location":"reference/api/#django_components.ComponentNode.active_flags","title":"active_flags property","text":"
active_flags: List[str]\n

See source code

Flags that were set for this specific instance as a list of strings.

E.g. the following tag:

{% slot \"content\" default required / %}\n

Will have the following flags:

[\"default\", \"required\"]\n
"},{"location":"reference/api/#django_components.ComponentNode.allowed_flags","title":"allowed_flags class-attribute instance-attribute","text":"
allowed_flags = [COMP_ONLY_FLAG]\n
"},{"location":"reference/api/#django_components.ComponentNode.contents","title":"contents instance-attribute","text":"
contents: Optional[str] = contents\n

See source code

See source code

The contents of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The contents will be \"<div> ... </div>\".

"},{"location":"reference/api/#django_components.ComponentNode.end_tag","title":"end_tag class-attribute instance-attribute","text":"
end_tag = 'endcomponent'\n
"},{"location":"reference/api/#django_components.ComponentNode.flags","title":"flags instance-attribute","text":"
flags: Dict[str, bool] = flags or {flag: Falsefor flag in (allowed_flags or [])}\n

See source code

See source code

Dictionary of all allowed_flags that were set on the tag.

Flags that were set are True, and the rest are False.

E.g. the following tag:

class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n    allowed_flags = [\"default\", \"required\"]\n
{% slot \"content\" default %}\n

Has 2 flags, default and required, but only default was set.

The flags dictionary will be:

{\n    \"default\": True,\n    \"required\": False,\n}\n

You can check if a flag is set by doing:

if node.flags[\"default\"]:\n    ...\n
"},{"location":"reference/api/#django_components.ComponentNode.name","title":"name instance-attribute","text":"
name = name\n
"},{"location":"reference/api/#django_components.ComponentNode.node_id","title":"node_id instance-attribute","text":"
node_id: str = node_id or gen_id()\n

See source code

See source code

The unique ID of the node.

Extensions can use this ID to store additional information.

"},{"location":"reference/api/#django_components.ComponentNode.nodelist","title":"nodelist instance-attribute","text":"
nodelist: NodeList = nodelist or NodeList()\n

See source code

See source code

The nodelist of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The nodelist will contain the <div> ... </div> part.

Unlike contents, the nodelist contains the actual Nodes, not just the text.

"},{"location":"reference/api/#django_components.ComponentNode.params","title":"params instance-attribute","text":"
params: List[TagAttr] = params\n

See source code

See source code

The parameters to the tag in the template.

A single param represents an arg or kwarg of the template tag.

E.g. the following tag:

{% component \"my_comp\" key=val key2='val2 two' %}\n

Has 3 params:

  • Posiitonal arg \"my_comp\"
  • Keyword arg key=val
  • Keyword arg key2='val2 two'
"},{"location":"reference/api/#django_components.ComponentNode.registry","title":"registry instance-attribute","text":"
registry = registry\n
"},{"location":"reference/api/#django_components.ComponentNode.tag","title":"tag class-attribute instance-attribute","text":"
tag = 'component'\n
"},{"location":"reference/api/#django_components.ComponentNode.template_component","title":"template_component instance-attribute","text":"
template_component: Optional[Type[Component]] = template_component\n

See source code

See source code

If the template that contains this node belongs to a Component, then this will be the Component class.

"},{"location":"reference/api/#django_components.ComponentNode.template_name","title":"template_name instance-attribute","text":"
template_name: Optional[str] = template_name\n

See source code

See source code

The name of the Template that contains this node.

The template name is set by Django's template loaders.

For example, the filesystem template loader will set this to the absolute path of the template file.

\"/home/user/project/templates/my_template.html\"\n
"},{"location":"reference/api/#django_components.ComponentNode.parse","title":"parse classmethod","text":"
parse(parser: Parser, token: Token, registry: ComponentRegistry, name: str, start_tag: str, end_tag: str) -> ComponentNode\n
"},{"location":"reference/api/#django_components.ComponentNode.register","title":"register classmethod","text":"
register(library: Library) -> None\n

See source code

A convenience method for registering the tag with the given library.

class MyNode(BaseNode):\n    tag = \"mynode\"\n\nMyNode.register(library)\n

Allows you to then use the node in templates like so:

{% load mylibrary %}\n{% mynode %}\n
"},{"location":"reference/api/#django_components.ComponentNode.render","title":"render","text":"
render(context: Context, *args: Any, **kwargs: Any) -> str\n
"},{"location":"reference/api/#django_components.ComponentNode.unregister","title":"unregister classmethod","text":"
unregister(library: Library) -> None\n

See source code

Unregisters the node from the given library.

"},{"location":"reference/api/#django_components.ComponentRegistry","title":"ComponentRegistry","text":"
ComponentRegistry(\n    library: Optional[Library] = None, settings: Optional[Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]] = None\n)\n

Bases: object

See source code

Manages components and makes them available in the template, by default as {% component %} tags.

{% component \"my_comp\" key=value %}\n{% endcomponent %}\n

To enable a component to be used in a template, the component must be registered with a component registry.

When you register a component to a registry, behind the scenes the registry automatically adds the component's template tag (e.g. {% component %} to the Library. And the opposite happens when you unregister a component - the tag is removed.

See Registering components.

Parameters:

  • library (Library, default: None ) \u2013

    Django Library associated with this registry. If omitted, the default Library instance from django_components is used.

  • settings (Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]], default: None ) \u2013

    Configure how the components registered with this registry will behave when rendered. See RegistrySettings. Can be either a static value or a callable that returns the settings. If omitted, the settings from COMPONENTS are used.

Notes:

  • The default registry is available as django_components.registry.
  • The default registry is used when registering components with @register decorator.

Example:

# Use with default Library\nregistry = ComponentRegistry()\n\n# Or a custom one\nmy_lib = Library()\nregistry = ComponentRegistry(library=my_lib)\n\n# Usage\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\nregistry.all()\nregistry.clear()\nregistry.get(\"button\")\nregistry.has(\"button\")\n
"},{"location":"reference/api/#django_components.ComponentRegistry--using-registry-to-share-components","title":"Using registry to share components","text":"

You can use component registry for isolating or \"packaging\" components:

  1. Create new instance of ComponentRegistry and Library:

    my_comps = Library()\nmy_comps_reg = ComponentRegistry(library=my_comps)\n

  2. Register components to the registry:

    my_comps_reg.register(\"my_button\", ButtonComponent)\nmy_comps_reg.register(\"my_card\", CardComponent)\n

  3. In your target project, load the Library associated with the registry:

    {% load my_comps %}\n

  4. Use the registered components in your templates:

    {% component \"button\" %}\n{% endcomponent %}\n

Methods:

  • all \u2013
  • clear \u2013
  • get \u2013
  • has \u2013
  • register \u2013
  • unregister \u2013

Attributes:

  • library (Library) \u2013
  • settings (InternalRegistrySettings) \u2013
"},{"location":"reference/api/#django_components.ComponentRegistry.library","title":"library property","text":"
library: Library\n

See source code

The template tag Library that is associated with the registry.

"},{"location":"reference/api/#django_components.ComponentRegistry.settings","title":"settings property","text":"
settings: InternalRegistrySettings\n

See source code

Registry settings configured for this registry.

"},{"location":"reference/api/#django_components.ComponentRegistry.all","title":"all","text":"
all() -> Dict[str, Type[Component]]\n

See source code

Retrieve all registered Component classes.

Returns:

  • Dict[str, Type[Component]] \u2013

    Dict[str, Type[Component]]: A dictionary of component names to component classes

Example:

# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then get all\nregistry.all()\n# > {\n# >   \"button\": ButtonComponent,\n# >   \"card\": CardComponent,\n# > }\n
"},{"location":"reference/api/#django_components.ComponentRegistry.clear","title":"clear","text":"
clear() -> None\n

See source code

Clears the registry, unregistering all components.

Example:

# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then clear\nregistry.clear()\n# Then get all\nregistry.all()\n# > {}\n
"},{"location":"reference/api/#django_components.ComponentRegistry.get","title":"get","text":"
get(name: str) -> Type[Component]\n

See source code

Retrieve a Component class registered under the given name.

Parameters:

  • name (str) \u2013

    The name under which the component was registered. Required.

Returns:

  • Type[Component] \u2013

    Type[Component]: The component class registered under the given name.

Raises:

  • NotRegistered if the given name is not registered.

Example:

# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then get\nregistry.get(\"button\")\n# > ButtonComponent\n
"},{"location":"reference/api/#django_components.ComponentRegistry.has","title":"has","text":"
has(name: str) -> bool\n

See source code

Check if a Component class is registered under the given name.

Parameters:

  • name (str) \u2013

    The name under which the component was registered. Required.

Returns:

  • bool ( bool ) \u2013

    True if the component is registered, False otherwise.

Example:

# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then check\nregistry.has(\"button\")\n# > True\n
"},{"location":"reference/api/#django_components.ComponentRegistry.register","title":"register","text":"
register(name: str, component: Type[Component]) -> None\n

See source code

Register a Component class with this registry under the given name.

A component MUST be registered before it can be used in a template such as:

{% component \"my_comp\" %}\n{% endcomponent %}\n

Parameters:

  • name (str) \u2013

    The name under which the component will be registered. Required.

  • component (Type[Component]) \u2013

    The component class to register. Required.

Raises:

  • AlreadyRegistered if a different component was already registered under the same name.

Example:

registry.register(\"button\", ButtonComponent)\n
"},{"location":"reference/api/#django_components.ComponentRegistry.unregister","title":"unregister","text":"
unregister(name: str) -> None\n

See source code

Unregister the Component class that was registered under the given name.

Once a component is unregistered, it is no longer available in the templates.

Parameters:

  • name (str) \u2013

    The name under which the component is registered. Required.

Raises:

  • NotRegistered if the given name is not registered.

Example:

# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
"},{"location":"reference/api/#django_components.ComponentVars","title":"ComponentVars","text":"

Bases: tuple

See source code

Type for the variables available inside the component templates.

All variables here are scoped under component_vars., so e.g. attribute kwargs on this class is accessible inside the template as:

{{ component_vars.kwargs }}\n

Attributes:

  • args (Any) \u2013
  • is_filled (Dict[str, bool]) \u2013
  • kwargs (Any) \u2013
  • slots (Any) \u2013
"},{"location":"reference/api/#django_components.ComponentVars.args","title":"args instance-attribute","text":"
args: Any\n

See source code

The args argument as passed to Component.get_template_data().

This is the same Component.args that's available on the component instance.

If you defined the Component.Args class, then the args property will return an instance of that class.

Otherwise, args will be a plain list.

Example:

With Args class:

from django_components import Component, register\n\n@register(\"table\")\nclass Table(Component):\n    class Args(NamedTuple):\n        page: int\n        per_page: int\n\n    template = '''\n        <div>\n            <h1>Table</h1>\n            <p>Page: {{ component_vars.args.page }}</p>\n            <p>Per page: {{ component_vars.args.per_page }}</p>\n        </div>\n    '''\n

Without Args class:

from django_components import Component, register\n\n@register(\"table\")\nclass Table(Component):\n    template = '''\n        <div>\n            <h1>Table</h1>\n            <p>Page: {{ component_vars.args.0 }}</p>\n            <p>Per page: {{ component_vars.args.1 }}</p>\n        </div>\n    '''\n
"},{"location":"reference/api/#django_components.ComponentVars.is_filled","title":"is_filled instance-attribute","text":"
is_filled: Dict[str, bool]\n

See source code

Deprecated. Will be removed in v1. Use component_vars.slots instead. Note that component_vars.slots no longer escapes the slot names.

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

New in version 0.70

Use as {{ component_vars.is_filled }}

Example:

{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n    <div class=\"slot-wrapper\">\n        {% slot \"my_slot\" / %}\n    </div>\n{% endif %}\n

This is equivalent to checking if a given key is among the slot fills:

class MyTable(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"my_slot_filled\": \"my_slot\" in slots\n        }\n
"},{"location":"reference/api/#django_components.ComponentVars.kwargs","title":"kwargs instance-attribute","text":"
kwargs: Any\n

See source code

The kwargs argument as passed to Component.get_template_data().

This is the same Component.kwargs that's available on the component instance.

If you defined the Component.Kwargs class, then the kwargs property will return an instance of that class.

Otherwise, kwargs will be a plain dict.

Example:

With Kwargs class:

from django_components import Component, register\n\n@register(\"table\")\nclass Table(Component):\n    class Kwargs(NamedTuple):\n        page: int\n        per_page: int\n\n    template = '''\n        <div>\n            <h1>Table</h1>\n            <p>Page: {{ component_vars.kwargs.page }}</p>\n            <p>Per page: {{ component_vars.kwargs.per_page }}</p>\n        </div>\n    '''\n

Without Kwargs class:

from django_components import Component, register\n\n@register(\"table\")\nclass Table(Component):\n    template = '''\n        <div>\n            <h1>Table</h1>\n            <p>Page: {{ component_vars.kwargs.page }}</p>\n            <p>Per page: {{ component_vars.kwargs.per_page }}</p>\n        </div>\n    '''\n
"},{"location":"reference/api/#django_components.ComponentVars.slots","title":"slots instance-attribute","text":"
slots: Any\n

See source code

The slots argument as passed to Component.get_template_data().

This is the same Component.slots that's available on the component instance.

If you defined the Component.Slots class, then the slots property will return an instance of that class.

Otherwise, slots will be a plain dict.

Example:

With Slots class:

from django_components import Component, SlotInput, register\n\n@register(\"table\")\nclass Table(Component):\n    class Slots(NamedTuple):\n        footer: SlotInput\n\n    template = '''\n        <div>\n            {% component \"pagination\" %}\n                {% fill \"footer\" body=component_vars.slots.footer / %}\n            {% endcomponent %}\n        </div>\n    '''\n

Without Slots class:

from django_components import Component, SlotInput, register\n\n@register(\"table\")\nclass Table(Component):\n    template = '''\n        <div>\n            {% component \"pagination\" %}\n                {% fill \"footer\" body=component_vars.slots.footer / %}\n            {% endcomponent %}\n        </div>\n    '''\n
"},{"location":"reference/api/#django_components.ComponentView","title":"ComponentView","text":"
ComponentView(component: Component, **kwargs: Any)\n

Bases: django_components.extension.ExtensionComponentConfig, django.views.generic.base.View

See source code

The interface for Component.View.

The fields of this class are used to configure the component views and URLs.

This class is a subclass of django.views.View. The Component class is available via self.component_cls.

Override the methods of this class to define the behavior of the component.

Read more about Component views and URLs.

Example:

class MyComponent(Component):\n    class View:\n        def get(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:\n            return HttpResponse(\"Hello, world!\")\n

Component URL:

If the public attribute is set to True, the component will have its own URL that will point to the Component's View.

from django_components import Component\n\nclass MyComponent(Component):\n    class View:\n        public = True\n\n        def get(self, request, *args, **kwargs):\n            return HttpResponse(\"Hello, world!\")\n

Will create a URL route like /components/ext/view/components/a1b2c3/.

To get the URL for the component, use get_component_url():

url = get_component_url(MyComponent)\n

Methods:

  • delete \u2013
  • get \u2013
  • head \u2013
  • options \u2013
  • patch \u2013
  • post \u2013
  • put \u2013
  • trace \u2013

Attributes:

  • component \u2013
  • component_class (Type[Component]) \u2013
  • component_cls \u2013
  • public (bool) \u2013
  • url (str) \u2013
"},{"location":"reference/api/#django_components.ComponentView.component","title":"component class-attribute instance-attribute","text":"
component = cast('Component', None)\n

See source code

DEPRECATED: Will be removed in v1.0. Use component_cls instead.

This is a dummy instance created solely for the View methods.

It is the same as if you instantiated the component class directly:

component = Calendar()\ncomponent.render_to_response(request=request)\n
"},{"location":"reference/api/#django_components.ComponentView.component_class","title":"component_class instance-attribute","text":"
component_class: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentView.component_cls","title":"component_cls class-attribute instance-attribute","text":"
component_cls = cast(Type['Component'], None)\n

See source code

The parent component class.

Example:

class MyComponent(Component):\n    class View:\n        def get(self, request):\n            return self.component_cls.render_to_response(request=request)\n
"},{"location":"reference/api/#django_components.ComponentView.public","title":"public class-attribute","text":"
public: bool = False\n

See source code

Whether the component should be available via a URL.

Example:

from django_components import Component\n\nclass MyComponent(Component):\n    class View:\n        public = True\n

Will create a URL route like /components/ext/view/components/a1b2c3/.

To get the URL for the component, use get_component_url():

url = get_component_url(MyComponent)\n
"},{"location":"reference/api/#django_components.ComponentView.url","title":"url property","text":"
url: str\n

See source code

The URL for the component.

Raises RuntimeError if the component is not public.

This is the same as calling get_component_url() with the parent Component class:

class MyComponent(Component):\n    class View:\n        def get(self, request):\n            assert self.url == get_component_url(self.component_cls)\n
"},{"location":"reference/api/#django_components.ComponentView.delete","title":"delete","text":"
delete(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse\n
"},{"location":"reference/api/#django_components.ComponentView.get","title":"get","text":"
get(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse\n
"},{"location":"reference/api/#django_components.ComponentView.head","title":"head","text":"
head(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse\n
"},{"location":"reference/api/#django_components.ComponentView.options","title":"options","text":"
options(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse\n
"},{"location":"reference/api/#django_components.ComponentView.patch","title":"patch","text":"
patch(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse\n
"},{"location":"reference/api/#django_components.ComponentView.post","title":"post","text":"
post(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse\n
"},{"location":"reference/api/#django_components.ComponentView.put","title":"put","text":"
put(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse\n
"},{"location":"reference/api/#django_components.ComponentView.trace","title":"trace","text":"
trace(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse\n
"},{"location":"reference/api/#django_components.ComponentsSettings","title":"ComponentsSettings","text":"

Bases: tuple

See source code

Settings available for django_components.

Example:

COMPONENTS = ComponentsSettings(\n    autodiscover=False,\n    dirs = [BASE_DIR / \"components\"],\n)\n

Attributes:

  • app_dirs (Optional[Sequence[str]]) \u2013
  • autodiscover (Optional[bool]) \u2013
  • cache (Optional[str]) \u2013
  • context_behavior (Optional[ContextBehaviorType]) \u2013
  • debug_highlight_components (Optional[bool]) \u2013
  • debug_highlight_slots (Optional[bool]) \u2013
  • dirs (Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]]) \u2013
  • dynamic_component_name (Optional[str]) \u2013
  • extensions (Optional[Sequence[Union[Type[ComponentExtension], str]]]) \u2013
  • extensions_defaults (Optional[Dict[str, Any]]) \u2013
  • forbidden_static_files (Optional[List[Union[str, Pattern]]]) \u2013
  • libraries (Optional[List[str]]) \u2013
  • multiline_tags (Optional[bool]) \u2013
  • reload_on_file_change (Optional[bool]) \u2013
  • reload_on_template_change (Optional[bool]) \u2013
  • static_files_allowed (Optional[List[Union[str, Pattern]]]) \u2013
  • static_files_forbidden (Optional[List[Union[str, Pattern]]]) \u2013
  • tag_formatter (Optional[Union[TagFormatterABC, str]]) \u2013
  • template_cache_size (Optional[int]) \u2013
"},{"location":"reference/api/#django_components.ComponentsSettings.app_dirs","title":"app_dirs class-attribute instance-attribute","text":"
app_dirs: Optional[Sequence[str]] = None\n

See source code

Specify the app-level directories that contain your components.

Defaults to [\"components\"]. That is, for each Django app, we search <app>/components/ for components.

The paths must be relative to app, e.g.:

COMPONENTS = ComponentsSettings(\n    app_dirs=[\"my_comps\"],\n)\n

To search for <app>/my_comps/.

These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.

Set to empty list to disable app-level components:

COMPONENTS = ComponentsSettings(\n    app_dirs=[],\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.autodiscover","title":"autodiscover class-attribute instance-attribute","text":"
autodiscover: Optional[bool] = None\n

See source code

Toggle whether to run autodiscovery at the Django server startup.

Defaults to True

COMPONENTS = ComponentsSettings(\n    autodiscover=False,\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.cache","title":"cache class-attribute instance-attribute","text":"
cache: Optional[str] = None\n

See source code

Name of the Django cache to be used for storing component's JS and CSS files.

If None, a LocMemCache is used with default settings.

Defaults to None.

Read more about caching.

COMPONENTS = ComponentsSettings(\n    cache=\"my_cache\",\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.context_behavior","title":"context_behavior class-attribute instance-attribute","text":"
context_behavior: Optional[ContextBehaviorType] = None\n

See source code

Configure whether, inside a component template, you can use variables from the outside (\"django\") or not (\"isolated\"). This also affects what variables are available inside the {% fill %} tags.

Also see Component context and scope.

Defaults to \"django\".

COMPONENTS = ComponentsSettings(\n    context_behavior=\"isolated\",\n)\n

NOTE: context_behavior and slot_context_behavior options were merged in v0.70.

If you are migrating from BEFORE v0.67, set context_behavior to \"django\". From v0.67 to v0.78 (incl) the default value was \"isolated\".

For v0.79 and later, the default is again \"django\". See the rationale for change here.

"},{"location":"reference/api/#django_components.ComponentsSettings.debug_highlight_components","title":"debug_highlight_components class-attribute instance-attribute","text":"
debug_highlight_components: Optional[bool] = None\n

See source code

DEPRECATED. Use extensions_defaults instead. Will be removed in v1.

Enable / disable component highlighting. See Troubleshooting for more details.

Defaults to False.

COMPONENTS = ComponentsSettings(\n    debug_highlight_components=True,\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.debug_highlight_slots","title":"debug_highlight_slots class-attribute instance-attribute","text":"
debug_highlight_slots: Optional[bool] = None\n

See source code

DEPRECATED. Use extensions_defaults instead. Will be removed in v1.

Enable / disable slot highlighting. See Troubleshooting for more details.

Defaults to False.

COMPONENTS = ComponentsSettings(\n    debug_highlight_slots=True,\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.dirs","title":"dirs class-attribute instance-attribute","text":"
dirs: Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]] = None\n

See source code

Specify the directories that contain your components.

Defaults to [Path(settings.BASE_DIR) / \"components\"]. That is, the root components/ app.

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

COMPONENTS = ComponentsSettings(\n    dirs=[BASE_DIR / \"components\"],\n)\n

Set to empty list to disable global components directories:

COMPONENTS = ComponentsSettings(\n    dirs=[],\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.dynamic_component_name","title":"dynamic_component_name class-attribute instance-attribute","text":"
dynamic_component_name: Optional[str] = None\n

See source code

By default, the dynamic component is registered under the name \"dynamic\".

In case of a conflict, you can use this setting to change the component name used for the dynamic components.

# settings.py\nCOMPONENTS = ComponentsSettings(\n    dynamic_component_name=\"my_dynamic\",\n)\n

After which you will be able to use the dynamic component with the new name:

{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/api/#django_components.ComponentsSettings.extensions","title":"extensions class-attribute instance-attribute","text":"
extensions: Optional[Sequence[Union[Type[ComponentExtension], str]]] = None\n

See source code

List of extensions to be loaded.

The extensions can be specified as:

  • Python import path, e.g. \"path.to.my_extension.MyExtension\".
  • Extension class, e.g. my_extension.MyExtension.

Read more about extensions.

Example:

COMPONENTS = ComponentsSettings(\n    extensions=[\n        \"path.to.my_extension.MyExtension\",\n        StorybookExtension,\n    ],\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.extensions_defaults","title":"extensions_defaults class-attribute instance-attribute","text":"
extensions_defaults: Optional[Dict[str, Any]] = None\n

See source code

Global defaults for the extension classes.

Read more about Extension defaults.

Example:

COMPONENTS = ComponentsSettings(\n    extensions_defaults={\n        \"my_extension\": {\n            \"my_setting\": \"my_value\",\n        },\n        \"cache\": {\n            \"enabled\": True,\n            \"ttl\": 60,\n        },\n    },\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.forbidden_static_files","title":"forbidden_static_files class-attribute instance-attribute","text":"
forbidden_static_files: Optional[List[Union[str, Pattern]]] = None\n

See source code

Deprecated. Use COMPONENTS.static_files_forbidden instead.

"},{"location":"reference/api/#django_components.ComponentsSettings.libraries","title":"libraries class-attribute instance-attribute","text":"
libraries: Optional[List[str]] = None\n

See source code

Configure extra python modules that should be loaded.

This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.

Expects a list of python module paths. Defaults to empty list.

Example:

COMPONENTS = ComponentsSettings(\n    libraries=[\n        \"mysite.components.forms\",\n        \"mysite.components.buttons\",\n        \"mysite.components.cards\",\n    ],\n)\n

This would be the equivalent of importing these modules from within Django's AppConfig.ready():

class MyAppConfig(AppConfig):\n    def ready(self):\n        import \"mysite.components.forms\"\n        import \"mysite.components.buttons\"\n        import \"mysite.components.cards\"\n
"},{"location":"reference/api/#django_components.ComponentsSettings.libraries--manually-loading-libraries","title":"Manually loading libraries","text":"

In the rare case that you need to manually trigger the import of libraries, you can use the import_libraries() function:

from django_components import import_libraries\n\nimport_libraries()\n
"},{"location":"reference/api/#django_components.ComponentsSettings.multiline_tags","title":"multiline_tags class-attribute instance-attribute","text":"
multiline_tags: Optional[bool] = None\n

See source code

Enable / disable multiline support for template tags. If True, template tags like {% component %} or {{ my_var }} can span multiple lines.

Defaults to True.

Disable this setting if you are making custom modifications to Django's regular expression for parsing templates at django.template.base.tag_re.

COMPONENTS = ComponentsSettings(\n    multiline_tags=False,\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.reload_on_file_change","title":"reload_on_file_change class-attribute instance-attribute","text":"
reload_on_file_change: Optional[bool] = None\n

See source code

This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.

In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.

Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.

The setting reload_on_file_change fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.

If True, django_components configures Django to reload when files inside COMPONENTS.dirs or COMPONENTS.app_dirs change.

See Reload dev server on component file changes.

Defaults to False.

Warning

This setting should be enabled only for the dev environment!

"},{"location":"reference/api/#django_components.ComponentsSettings.reload_on_template_change","title":"reload_on_template_change class-attribute instance-attribute","text":"
reload_on_template_change: Optional[bool] = None\n

See source code

Deprecated. Use COMPONENTS.reload_on_file_change instead.

"},{"location":"reference/api/#django_components.ComponentsSettings.static_files_allowed","title":"static_files_allowed class-attribute instance-attribute","text":"
static_files_allowed: Optional[List[Union[str, Pattern]]] = None\n

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or 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 = ComponentsSettings(\n    static_files_allowed=[\n        \".css\",\n        \".js\", \".jsx\", \".ts\", \".tsx\",\n        # Images\n        \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n        \".jpeg\",  \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n        \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n        # Fonts\n        \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n    ],\n)\n

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

"},{"location":"reference/api/#django_components.ComponentsSettings.static_files_forbidden","title":"static_files_forbidden class-attribute instance-attribute","text":"
static_files_forbidden: Optional[List[Union[str, Pattern]]] = None\n

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs will NEVER be treated as static files.

If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in static_files_allowed.

Use this setting together with static_files_allowed for a fine control over what file types will be exposed.

You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

By default, any HTML and Python are considered NOT static files:

COMPONENTS = ComponentsSettings(\n    static_files_forbidden=[\n        \".html\", \".django\", \".dj\", \".tpl\",\n        # Python files\n        \".py\", \".pyc\",\n    ],\n)\n

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

"},{"location":"reference/api/#django_components.ComponentsSettings.tag_formatter","title":"tag_formatter class-attribute instance-attribute","text":"
tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n

See source code

Configure what syntax is used inside Django templates to render components. See the available tag formatters.

Defaults to \"django_components.component_formatter\".

Learn more about Customizing component tags with TagFormatter.

Can be set either as direct reference:

from django_components import component_formatter\n\nCOMPONENTS = ComponentsSettings(\n    \"tag_formatter\": component_formatter\n)\n

Or as an import string;

COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_formatter\"\n)\n

Examples:

  • \"django_components.component_formatter\"

    Set

    COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_formatter\"\n)\n

    To write components like this:

    {% component \"button\" href=\"...\" %}\n    Click me!\n{% endcomponent %}\n
  • django_components.component_shorthand_formatter

    Set

    COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_shorthand_formatter\"\n)\n

    To write components like this:

    {% button href=\"...\" %}\n    Click me!\n{% endbutton %}\n
"},{"location":"reference/api/#django_components.ComponentsSettings.template_cache_size","title":"template_cache_size class-attribute instance-attribute","text":"
template_cache_size: Optional[int] = None\n

See source code

DEPRECATED. Template caching will be removed in v1.

Configure the maximum amount of Django templates to be cached.

Defaults to 128.

Each time a Django 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 overriding Component.get_template() to render many dynamic templates, you can increase this number.

COMPONENTS = ComponentsSettings(\n    template_cache_size=256,\n)\n

To remove the cache limit altogether and cache everything, set template_cache_size to None.

COMPONENTS = ComponentsSettings(\n    template_cache_size=None,\n)\n

If you want to add templates to the cache yourself, you can use cached_template():

from django_components import cached_template\n\ncached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n    pass\n\ncached_template(\n    \"Variable: {{ variable }}\",\n    template_cls=MyTemplate,\n    name=...\n    origin=...\n    engine=...\n)\n
"},{"location":"reference/api/#django_components.ContextBehavior","title":"ContextBehavior","text":"

Bases: str, enum.Enum

See source code

Configure how (and whether) the context is passed to the component fills and what variables are available inside the {% fill %} tags.

Also see Component context and scope.

Options:

  • django: With this setting, component fills behave as usual Django tags.
  • isolated: This setting makes the component fills behave similar to Vue or React.

Attributes:

  • DJANGO \u2013
  • ISOLATED \u2013
"},{"location":"reference/api/#django_components.ContextBehavior.DJANGO","title":"DJANGO class-attribute instance-attribute","text":"
DJANGO = 'django'\n

See source code

With this setting, component fills behave as usual Django tags. That is, they enrich the context, and pass it along.

  1. Component fills use the context of the component they are within.
  2. Variables from Component.get_template_data() are available to the component fill.

Example:

Given this template

{% with cheese=\"feta\" %}\n  {% component 'my_comp' %}\n    {{ my_var }}  # my_var\n    {{ cheese }}  # cheese\n  {% endcomponent %}\n{% endwith %}\n

and this context returned from the Component.get_template_data() method

{ \"my_var\": 123 }\n

Then if component \"my_comp\" defines context

{ \"my_var\": 456 }\n

Then this will render:

456   # my_var\nfeta  # cheese\n

Because \"my_comp\" overrides the variable \"my_var\", so {{ my_var }} equals 456.

And variable \"cheese\" will equal feta, because the fill CAN access the current context.

"},{"location":"reference/api/#django_components.ContextBehavior.ISOLATED","title":"ISOLATED class-attribute instance-attribute","text":"
ISOLATED = 'isolated'\n

See source code

This setting makes the component fills behave similar to Vue or React, where the fills use EXCLUSIVELY the context variables defined in Component.get_template_data().

Example:

Given this template

{% with cheese=\"feta\" %}\n  {% component 'my_comp' %}\n    {{ my_var }}  # my_var\n    {{ cheese }}  # cheese\n  {% endcomponent %}\n{% endwith %}\n

and this context returned from the get_template_data() method

{ \"my_var\": 123 }\n

Then if component \"my_comp\" defines context

{ \"my_var\": 456 }\n

Then this will render:

123   # my_var\n      # cheese\n

Because both variables \"my_var\" and \"cheese\" are taken from the root context. Since \"cheese\" is not defined in root context, it's empty.

"},{"location":"reference/api/#django_components.Default","title":"Default dataclass","text":"
Default(value: Callable[[], Any])\n

Bases: object

See source code

Use this class to mark a field on the Component.Defaults class as a factory.

Read more about Component defaults.

Example:

from django_components import Default\n\nclass MyComponent(Component):\n    class Defaults:\n        # Plain value doesn't need a factory\n        position = \"left\"\n        # Lists and dicts need to be wrapped in `Default`\n        # Otherwise all instances will share the same value\n        selected_items = Default(lambda: [1, 2, 3])\n

Attributes:

  • value (Callable[[], Any]) \u2013
"},{"location":"reference/api/#django_components.Default.value","title":"value instance-attribute","text":"
value: Callable[[], Any]\n
"},{"location":"reference/api/#django_components.DependenciesStrategy","title":"DependenciesStrategy module-attribute","text":"
DependenciesStrategy = Literal['document', 'fragment', 'simple', 'prepend', 'append', 'ignore']\n

See source code

Type for the available strategies for rendering JS and CSS dependencies.

Read more about the dependencies strategies.

"},{"location":"reference/api/#django_components.Empty","title":"Empty","text":"

Bases: tuple

See source code

Type for an object with no members.

You can use this to define Component types that accept NO args, kwargs, slots, etc:

from django_components import Component, Empty\n\nclass Table(Component):\n    Args = Empty\n    Kwargs = Empty\n    ...\n

This class is a shorthand for:

class Empty(NamedTuple):\n    pass\n

Read more about Typing and validation.

"},{"location":"reference/api/#django_components.ExtensionComponentConfig","title":"ExtensionComponentConfig","text":"
ExtensionComponentConfig(component: Component)\n

Bases: object

See source code

ExtensionComponentConfig is the base class for all extension component configs.

Extensions can define nested classes on the component class, such as Component.View or Component.Cache:

class MyComp(Component):\n    class View:\n        def get(self, request):\n            ...\n\n    class Cache:\n        ttl = 60\n

This allows users to configure extension behavior per component.

Behind the scenes, the nested classes that users define on their components are merged with the extension's \"base\" class.

So the example above is the same as:

class MyComp(Component):\n    class View(ViewExtension.ComponentConfig):\n        def get(self, request):\n            ...\n\n    class Cache(CacheExtension.ComponentConfig):\n        ttl = 60\n

Where both ViewExtension.ComponentConfig and CacheExtension.ComponentConfig are subclasses of ExtensionComponentConfig.

Attributes:

  • component (Component) \u2013
  • component_class (Type[Component]) \u2013
  • component_cls (Type[Component]) \u2013
"},{"location":"reference/api/#django_components.ExtensionComponentConfig.component","title":"component instance-attribute","text":"
component: Component = component\n

See source code

See source code

When a Component is instantiated, also the nested extension classes (such as Component.View) are instantiated, receiving the component instance as an argument.

This attribute holds the owner Component instance that this extension is defined on.

"},{"location":"reference/api/#django_components.ExtensionComponentConfig.component_class","title":"component_class instance-attribute","text":"
component_class: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.ExtensionComponentConfig.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.FillNode","title":"FillNode","text":"
FillNode(\n    params: List[TagAttr],\n    flags: Optional[Dict[str, bool]] = None,\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    contents: Optional[str] = None,\n    template_name: Optional[str] = None,\n    template_component: Optional[Type[Component]] = None,\n)\n

Bases: django_components.node.BaseNode

See source code

Use {% fill %} tag to insert content into component's slots.

{% fill %} tag may be used only within a {% component %}..{% endcomponent %} block, and raises a TemplateSyntaxError if used outside of a component.

Args:

  • name (str, required): Name of the slot to insert this content into. Use \"default\" for the default slot.
  • data (str, optional): This argument allows you to access the data passed to the slot under the specified variable name. See Slot data.
  • fallback (str, optional): This argument allows you to access the original content of the slot under the specified variable name. See Slot fallback.

Example:

{% component \"my_table\" %}\n  {% fill \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/api/#django_components.FillNode--access-slot-fallback","title":"Access slot fallback","text":"

Use the fallback kwarg to access the original content of the slot.

The fallback kwarg defines the name of the variable that will contain the slot's fallback content.

Read more about Slot fallback.

Component template:

{# my_table.html #}\n<table>\n  ...\n  {% slot \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endslot %}\n</table>\n

Fill:

{% component \"my_table\" %}\n  {% fill \"pagination\" fallback=\"fallback\" %}\n    <div class=\"my-class\">\n      {{ fallback }}\n    </div>\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/api/#django_components.FillNode--access-slot-data","title":"Access slot data","text":"

Use the data kwarg to access the data passed to the slot.

The data kwarg defines the name of the variable that will contain the slot's data.

Read more about Slot data.

Component template:

{# my_table.html #}\n<table>\n  ...\n  {% slot \"pagination\" pages=pages %}\n    < 1 | 2 | 3 >\n  {% endslot %}\n</table>\n

Fill:

{% component \"my_table\" %}\n  {% fill \"pagination\" data=\"slot_data\" %}\n    {% for page in slot_data.pages %}\n        <a href=\"{{ page.link }}\">\n          {{ page.index }}\n        </a>\n    {% endfor %}\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/api/#django_components.FillNode--using-default-slot","title":"Using default slot","text":"

To access slot data and the fallback slot content on the default slot, use {% fill %} with name set to \"default\":

{% component \"button\" %}\n  {% fill name=\"default\" data=\"slot_data\" fallback=\"slot_fallback\" %}\n    You clicked me {{ slot_data.count }} times!\n    {{ slot_fallback }}\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/api/#django_components.FillNode--slot-fills-from-python","title":"Slot fills from Python","text":"

You can pass a slot fill from Python to a component by setting the body kwarg on the {% fill %} tag.

First pass a Slot instance to the template with the get_template_data() method:

from django_components import component, Slot\n\nclass Table(Component):\n  def get_template_data(self, args, kwargs, slots, context):\n    return {\n        \"my_slot\": Slot(lambda ctx: \"Hello, world!\"),\n    }\n

Then pass the slot to the {% fill %} tag:

{% component \"table\" %}\n  {% fill \"pagination\" body=my_slot / %}\n{% endcomponent %}\n

Warning

If you define both the body kwarg and the {% fill %} tag's body, an error will be raised.

{% component \"table\" %}\n  {% fill \"pagination\" body=my_slot %}\n    ...\n  {% endfill %}\n{% endcomponent %}\n

Methods:

  • parse \u2013
  • register \u2013
  • render \u2013
  • unregister \u2013

Attributes:

  • active_flags (List[str]) \u2013
  • allowed_flags \u2013
  • contents (Optional[str]) \u2013
  • end_tag \u2013
  • flags (Dict[str, bool]) \u2013
  • node_id (str) \u2013
  • nodelist (NodeList) \u2013
  • params (List[TagAttr]) \u2013
  • tag \u2013
  • template_component (Optional[Type[Component]]) \u2013
  • template_name (Optional[str]) \u2013
"},{"location":"reference/api/#django_components.FillNode.active_flags","title":"active_flags property","text":"
active_flags: List[str]\n

See source code

Flags that were set for this specific instance as a list of strings.

E.g. the following tag:

{% slot \"content\" default required / %}\n

Will have the following flags:

[\"default\", \"required\"]\n
"},{"location":"reference/api/#django_components.FillNode.allowed_flags","title":"allowed_flags class-attribute instance-attribute","text":"
allowed_flags = []\n
"},{"location":"reference/api/#django_components.FillNode.contents","title":"contents instance-attribute","text":"
contents: Optional[str] = contents\n

See source code

See source code

The contents of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The contents will be \"<div> ... </div>\".

"},{"location":"reference/api/#django_components.FillNode.end_tag","title":"end_tag class-attribute instance-attribute","text":"
end_tag = 'endfill'\n
"},{"location":"reference/api/#django_components.FillNode.flags","title":"flags instance-attribute","text":"
flags: Dict[str, bool] = flags or {flag: Falsefor flag in (allowed_flags or [])}\n

See source code

See source code

Dictionary of all allowed_flags that were set on the tag.

Flags that were set are True, and the rest are False.

E.g. the following tag:

class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n    allowed_flags = [\"default\", \"required\"]\n
{% slot \"content\" default %}\n

Has 2 flags, default and required, but only default was set.

The flags dictionary will be:

{\n    \"default\": True,\n    \"required\": False,\n}\n

You can check if a flag is set by doing:

if node.flags[\"default\"]:\n    ...\n
"},{"location":"reference/api/#django_components.FillNode.node_id","title":"node_id instance-attribute","text":"
node_id: str = node_id or gen_id()\n

See source code

See source code

The unique ID of the node.

Extensions can use this ID to store additional information.

"},{"location":"reference/api/#django_components.FillNode.nodelist","title":"nodelist instance-attribute","text":"
nodelist: NodeList = nodelist or NodeList()\n

See source code

See source code

The nodelist of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The nodelist will contain the <div> ... </div> part.

Unlike contents, the nodelist contains the actual Nodes, not just the text.

"},{"location":"reference/api/#django_components.FillNode.params","title":"params instance-attribute","text":"
params: List[TagAttr] = params\n

See source code

See source code

The parameters to the tag in the template.

A single param represents an arg or kwarg of the template tag.

E.g. the following tag:

{% component \"my_comp\" key=val key2='val2 two' %}\n

Has 3 params:

  • Posiitonal arg \"my_comp\"
  • Keyword arg key=val
  • Keyword arg key2='val2 two'
"},{"location":"reference/api/#django_components.FillNode.tag","title":"tag class-attribute instance-attribute","text":"
tag = 'fill'\n
"},{"location":"reference/api/#django_components.FillNode.template_component","title":"template_component instance-attribute","text":"
template_component: Optional[Type[Component]] = template_component\n

See source code

See source code

If the template that contains this node belongs to a Component, then this will be the Component class.

"},{"location":"reference/api/#django_components.FillNode.template_name","title":"template_name instance-attribute","text":"
template_name: Optional[str] = template_name\n

See source code

See source code

The name of the Template that contains this node.

The template name is set by Django's template loaders.

For example, the filesystem template loader will set this to the absolute path of the template file.

\"/home/user/project/templates/my_template.html\"\n
"},{"location":"reference/api/#django_components.FillNode.parse","title":"parse classmethod","text":"
parse(parser: Parser, token: Token, **kwargs: Any) -> BaseNode\n

See source code

This function is what is passed to Django's Library.tag() when registering the tag.

In other words, this method is called by Django's template parser when we encounter a tag that matches this node's tag, e.g. {% component %} or {% slot %}.

To register the tag, you can use BaseNode.register().

"},{"location":"reference/api/#django_components.FillNode.register","title":"register classmethod","text":"
register(library: Library) -> None\n

See source code

A convenience method for registering the tag with the given library.

class MyNode(BaseNode):\n    tag = \"mynode\"\n\nMyNode.register(library)\n

Allows you to then use the node in templates like so:

{% load mylibrary %}\n{% mynode %}\n
"},{"location":"reference/api/#django_components.FillNode.render","title":"render","text":"
render(\n    context: Context,\n    name: str,\n    *,\n    data: Optional[str] = None,\n    fallback: Optional[str] = None,\n    body: Optional[SlotInput] = None,\n    default: Optional[str] = None\n) -> str\n
"},{"location":"reference/api/#django_components.FillNode.unregister","title":"unregister classmethod","text":"
unregister(library: Library) -> None\n

See source code

Unregisters the node from the given library.

"},{"location":"reference/api/#django_components.OnRenderGenerator","title":"OnRenderGenerator module-attribute","text":"
OnRenderGenerator = Generator[Optional[SlotResult], Tuple[Optional[SlotResult], Optional[Exception]], Optional[SlotResult]]\n

See source code

This is the signature of the Component.on_render() method if it yields (and thus returns a generator).

When on_render() is a generator then it:

  • Yields a rendered template (string or None)

  • Receives back a tuple of (final_output, error).

    The final output is the rendered template that now has all its children rendered too. May be None if you yielded None earlier.

    The error is None if the rendering was successful. Otherwise the error is set and the output is None.

  • At the end it may return a new string to override the final rendered output.

Example:

from django_components import Component, OnRenderGenerator\n\nclass MyTable(Component):\n    def on_render(\n        self,\n        context: Context,\n        template: Optional[Template],\n    ) -> OnRenderGenerator:\n        # Do something BEFORE rendering template\n        # Same as `Component.on_render_before()`\n        context[\"hello\"] = \"world\"\n\n        # Yield rendered template to receive fully-rendered template or error\n        html, error = yield template.render(context)\n\n        # Do something AFTER rendering template, or post-process\n        # the rendered template.\n        # Same as `Component.on_render_after()`\n        return html + \"<p>Hello</p>\"\n
"},{"location":"reference/api/#django_components.ProvideNode","title":"ProvideNode","text":"
ProvideNode(\n    params: List[TagAttr],\n    flags: Optional[Dict[str, bool]] = None,\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    contents: Optional[str] = None,\n    template_name: Optional[str] = None,\n    template_component: Optional[Type[Component]] = None,\n)\n

Bases: django_components.node.BaseNode

See source code

The {% provide %} tag is part of the \"provider\" part of the provide / inject feature.

Pass kwargs to this tag to define the provider's data.

Any components defined within the {% provide %}..{% endprovide %} tags will be able to access this data with Component.inject().

This is similar to React's ContextProvider, or Vue's provide().

Args:

  • name (str, required): Provider name. This is the name you will then use in Component.inject().
  • **kwargs: Any extra kwargs will be passed as the provided data.

Example:

Provide the \"user_data\" in parent component:

@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      <div>\n        {% provide \"user_data\" user=user %}\n          {% component \"child\" / %}\n        {% endprovide %}\n      </div>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"user\": kwargs[\"user\"],\n        }\n

Since the \"child\" component is used within the {% provide %} / {% endprovide %} tags, we can request the \"user_data\" using Component.inject(\"user_data\"):

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        User is: {{ user }}\n      </div>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        user = self.inject(\"user_data\").user\n        return {\n            \"user\": user,\n        }\n

Notice that the keys defined on the {% provide %} tag are then accessed as attributes when accessing them with Component.inject().

\u2705 Do this

user = self.inject(\"user_data\").user\n

\u274c Don't do this

user = self.inject(\"user_data\")[\"user\"]\n

Methods:

  • parse \u2013
  • register \u2013
  • render \u2013
  • unregister \u2013

Attributes:

  • active_flags (List[str]) \u2013
  • allowed_flags \u2013
  • contents (Optional[str]) \u2013
  • end_tag \u2013
  • flags (Dict[str, bool]) \u2013
  • node_id (str) \u2013
  • nodelist (NodeList) \u2013
  • params (List[TagAttr]) \u2013
  • tag \u2013
  • template_component (Optional[Type[Component]]) \u2013
  • template_name (Optional[str]) \u2013
"},{"location":"reference/api/#django_components.ProvideNode.active_flags","title":"active_flags property","text":"
active_flags: List[str]\n

See source code

Flags that were set for this specific instance as a list of strings.

E.g. the following tag:

{% slot \"content\" default required / %}\n

Will have the following flags:

[\"default\", \"required\"]\n
"},{"location":"reference/api/#django_components.ProvideNode.allowed_flags","title":"allowed_flags class-attribute instance-attribute","text":"
allowed_flags = []\n
"},{"location":"reference/api/#django_components.ProvideNode.contents","title":"contents instance-attribute","text":"
contents: Optional[str] = contents\n

See source code

See source code

The contents of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The contents will be \"<div> ... </div>\".

"},{"location":"reference/api/#django_components.ProvideNode.end_tag","title":"end_tag class-attribute instance-attribute","text":"
end_tag = 'endprovide'\n
"},{"location":"reference/api/#django_components.ProvideNode.flags","title":"flags instance-attribute","text":"
flags: Dict[str, bool] = flags or {flag: Falsefor flag in (allowed_flags or [])}\n

See source code

See source code

Dictionary of all allowed_flags that were set on the tag.

Flags that were set are True, and the rest are False.

E.g. the following tag:

class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n    allowed_flags = [\"default\", \"required\"]\n
{% slot \"content\" default %}\n

Has 2 flags, default and required, but only default was set.

The flags dictionary will be:

{\n    \"default\": True,\n    \"required\": False,\n}\n

You can check if a flag is set by doing:

if node.flags[\"default\"]:\n    ...\n
"},{"location":"reference/api/#django_components.ProvideNode.node_id","title":"node_id instance-attribute","text":"
node_id: str = node_id or gen_id()\n

See source code

See source code

The unique ID of the node.

Extensions can use this ID to store additional information.

"},{"location":"reference/api/#django_components.ProvideNode.nodelist","title":"nodelist instance-attribute","text":"
nodelist: NodeList = nodelist or NodeList()\n

See source code

See source code

The nodelist of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The nodelist will contain the <div> ... </div> part.

Unlike contents, the nodelist contains the actual Nodes, not just the text.

"},{"location":"reference/api/#django_components.ProvideNode.params","title":"params instance-attribute","text":"
params: List[TagAttr] = params\n

See source code

See source code

The parameters to the tag in the template.

A single param represents an arg or kwarg of the template tag.

E.g. the following tag:

{% component \"my_comp\" key=val key2='val2 two' %}\n

Has 3 params:

  • Posiitonal arg \"my_comp\"
  • Keyword arg key=val
  • Keyword arg key2='val2 two'
"},{"location":"reference/api/#django_components.ProvideNode.tag","title":"tag class-attribute instance-attribute","text":"
tag = 'provide'\n
"},{"location":"reference/api/#django_components.ProvideNode.template_component","title":"template_component instance-attribute","text":"
template_component: Optional[Type[Component]] = template_component\n

See source code

See source code

If the template that contains this node belongs to a Component, then this will be the Component class.

"},{"location":"reference/api/#django_components.ProvideNode.template_name","title":"template_name instance-attribute","text":"
template_name: Optional[str] = template_name\n

See source code

See source code

The name of the Template that contains this node.

The template name is set by Django's template loaders.

For example, the filesystem template loader will set this to the absolute path of the template file.

\"/home/user/project/templates/my_template.html\"\n
"},{"location":"reference/api/#django_components.ProvideNode.parse","title":"parse classmethod","text":"
parse(parser: Parser, token: Token, **kwargs: Any) -> BaseNode\n

See source code

This function is what is passed to Django's Library.tag() when registering the tag.

In other words, this method is called by Django's template parser when we encounter a tag that matches this node's tag, e.g. {% component %} or {% slot %}.

To register the tag, you can use BaseNode.register().

"},{"location":"reference/api/#django_components.ProvideNode.register","title":"register classmethod","text":"
register(library: Library) -> None\n

See source code

A convenience method for registering the tag with the given library.

class MyNode(BaseNode):\n    tag = \"mynode\"\n\nMyNode.register(library)\n

Allows you to then use the node in templates like so:

{% load mylibrary %}\n{% mynode %}\n
"},{"location":"reference/api/#django_components.ProvideNode.render","title":"render","text":"
render(context: Context, name: str, **kwargs: Any) -> SafeString\n
"},{"location":"reference/api/#django_components.ProvideNode.unregister","title":"unregister classmethod","text":"
unregister(library: Library) -> None\n

See source code

Unregisters the node from the given library.

"},{"location":"reference/api/#django_components.RegistrySettings","title":"RegistrySettings","text":"

Bases: tuple

See source code

Configuration for a ComponentRegistry.

These settings define how the components registered with this registry will behave when rendered.

from django_components import ComponentRegistry, RegistrySettings\n\nregistry_settings = RegistrySettings(\n    context_behavior=\"django\",\n    tag_formatter=\"django_components.component_shorthand_formatter\",\n)\n\nregistry = ComponentRegistry(settings=registry_settings)\n

Attributes:

  • CONTEXT_BEHAVIOR (Optional[ContextBehaviorType]) \u2013
  • TAG_FORMATTER (Optional[Union[TagFormatterABC, str]]) \u2013
  • context_behavior (Optional[ContextBehaviorType]) \u2013
  • tag_formatter (Optional[Union[TagFormatterABC, str]]) \u2013
"},{"location":"reference/api/#django_components.RegistrySettings.CONTEXT_BEHAVIOR","title":"CONTEXT_BEHAVIOR class-attribute instance-attribute","text":"
CONTEXT_BEHAVIOR: Optional[ContextBehaviorType] = None\n

See source code

Deprecated. Use context_behavior instead. Will be removed in v1.

Same as the global COMPONENTS.context_behavior setting, but for this registry.

If omitted, defaults to the global COMPONENTS.context_behavior setting.

"},{"location":"reference/api/#django_components.RegistrySettings.TAG_FORMATTER","title":"TAG_FORMATTER class-attribute instance-attribute","text":"
TAG_FORMATTER: Optional[Union[TagFormatterABC, str]] = None\n

See source code

Deprecated. Use tag_formatter instead. Will be removed in v1.

Same as the global COMPONENTS.tag_formatter setting, but for this registry.

If omitted, defaults to the global COMPONENTS.tag_formatter setting.

"},{"location":"reference/api/#django_components.RegistrySettings.context_behavior","title":"context_behavior class-attribute instance-attribute","text":"
context_behavior: Optional[ContextBehaviorType] = None\n

See source code

Same as the global COMPONENTS.context_behavior setting, but for this registry.

If omitted, defaults to the global COMPONENTS.context_behavior setting.

"},{"location":"reference/api/#django_components.RegistrySettings.tag_formatter","title":"tag_formatter class-attribute instance-attribute","text":"
tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n

See source code

Same as the global COMPONENTS.tag_formatter setting, but for this registry.

If omitted, defaults to the global COMPONENTS.tag_formatter setting.

"},{"location":"reference/api/#django_components.Slot","title":"Slot dataclass","text":"
Slot(\n    contents: Any,\n    content_func: SlotFunc[TSlotData] = cast(SlotFunc[TSlotData], None),\n    component_name: Optional[str] = None,\n    slot_name: Optional[str] = None,\n    nodelist: Optional[NodeList] = None,\n    fill_node: Optional[Union[FillNode, ComponentNode]] = None,\n    extra: Dict[str, Any] = dict(),\n)\n

Bases: typing.Generic

See source code

This class is the main way for defining and handling slots.

It holds the slot content function along with related metadata.

Read more about Slot class.

Example:

Passing slots to components:

from django_components import Slot\n\nslot = Slot(lambda ctx: f\"Hello, {ctx.data['name']}!\")\n\nMyComponent.render(\n    slots={\n        \"my_slot\": slot,\n    },\n)\n

Accessing slots inside the components:

from django_components import Component\n\nclass MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        my_slot = slots[\"my_slot\"]\n        return {\n            \"my_slot\": my_slot,\n        }\n

Rendering slots:

from django_components import Slot\n\nslot = Slot(lambda ctx: f\"Hello, {ctx.data['name']}!\")\nhtml = slot({\"name\": \"John\"})  # Output: Hello, John!\n

Attributes:

  • component_name (Optional[str]) \u2013
  • content_func (SlotFunc[TSlotData]) \u2013
  • contents (Any) \u2013
  • do_not_call_in_templates (bool) \u2013
  • extra (Dict[str, Any]) \u2013
  • fill_node (Optional[Union[FillNode, ComponentNode]]) \u2013
  • nodelist (Optional[NodeList]) \u2013
  • slot_name (Optional[str]) \u2013
"},{"location":"reference/api/#django_components.Slot.component_name","title":"component_name class-attribute instance-attribute","text":"
component_name: Optional[str] = None\n

See source code

Name of the component that originally received this slot fill.

See Slot metadata.

"},{"location":"reference/api/#django_components.Slot.content_func","title":"content_func class-attribute instance-attribute","text":"
content_func: SlotFunc[TSlotData] = cast(SlotFunc[TSlotData], None)\n

See source code

The actual slot function.

Do NOT call this function directly, instead call the Slot instance as a function.

Read more about Rendering slot functions.

"},{"location":"reference/api/#django_components.Slot.contents","title":"contents instance-attribute","text":"
contents: Any\n

See source code

The original value that was passed to the Slot constructor.

  • If Slot was created from {% fill %} tag, Slot.contents will contain the body (string) of that {% fill %} tag.
  • If Slot was created from string as Slot(\"...\"), Slot.contents will contain that string.
  • If Slot was created from a function, Slot.contents will contain that function.

Read more about Slot contents.

"},{"location":"reference/api/#django_components.Slot.do_not_call_in_templates","title":"do_not_call_in_templates property","text":"
do_not_call_in_templates: bool\n

See source code

Django special property to prevent calling the instance as a function inside Django templates.

"},{"location":"reference/api/#django_components.Slot.extra","title":"extra class-attribute instance-attribute","text":"
extra: Dict[str, Any] = field(default_factory=dict)\n

See source code

Dictionary that can be used to store arbitrary metadata about the slot.

See Slot metadata.

See Pass slot metadata for usage for extensions.

Example:

# Either at slot creation\nslot = Slot(lambda ctx: \"Hello, world!\", extra={\"foo\": \"bar\"})\n\n# Or later\nslot.extra[\"baz\"] = \"qux\"\n
"},{"location":"reference/api/#django_components.Slot.fill_node","title":"fill_node class-attribute instance-attribute","text":"
fill_node: Optional[Union[FillNode, ComponentNode]] = None\n

See source code

If the slot was created from a {% fill %} tag, this will be the FillNode instance.

If the slot was a default slot created from a {% component %} tag, this will be the ComponentNode instance.

Otherwise, this will be None.

Extensions can use this info to handle slots differently based on their source.

See Slot metadata.

Example:

You can use this to find the Component in whose template the {% fill %} tag was defined:

class MyTable(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        footer_slot = slots.get(\"footer\")\n        if footer_slot is not None and footer_slot.fill_node is not None:\n            owner_component = footer_slot.fill_node.template_component\n            # ...\n
"},{"location":"reference/api/#django_components.Slot.nodelist","title":"nodelist class-attribute instance-attribute","text":"
nodelist: Optional[NodeList] = None\n

See source code

If the slot was defined with {% fill %} tag, this will be the Nodelist of the fill's content.

See Slot metadata.

"},{"location":"reference/api/#django_components.Slot.slot_name","title":"slot_name class-attribute instance-attribute","text":"
slot_name: Optional[str] = None\n

See source code

Slot name to which this Slot was initially assigned.

See Slot metadata.

"},{"location":"reference/api/#django_components.SlotContent","title":"SlotContent module-attribute","text":"
SlotContent = SlotInput[TSlotData]\n

See source code

DEPRECATED: Use SlotInput instead. Will be removed in v1.

"},{"location":"reference/api/#django_components.SlotContext","title":"SlotContext dataclass","text":"
SlotContext(data: TSlotData, fallback: Optional[Union[str, SlotFallback]] = None, context: Optional[Context] = None)\n

Bases: typing.Generic

See source code

Metadata available inside slot functions.

Read more about Slot functions.

Example:

from django_components import SlotContext, SlotResult\n\ndef my_slot(ctx: SlotContext) -> SlotResult:\n    return f\"Hello, {ctx.data['name']}!\"\n

You can pass a type parameter to the SlotContext to specify the type of the data passed to the slot:

class MySlotData(TypedDict):\n    name: str\n\ndef my_slot(ctx: SlotContext[MySlotData]):\n    return f\"Hello, {ctx.data['name']}!\"\n

Attributes:

  • context (Optional[Context]) \u2013
  • data (TSlotData) \u2013
  • fallback (Optional[Union[str, SlotFallback]]) \u2013
"},{"location":"reference/api/#django_components.SlotContext.context","title":"context class-attribute instance-attribute","text":"
context: Optional[Context] = None\n

See source code

Django template Context available inside the {% fill %} tag.

May be None if you call the slot fill directly, without using {% slot %} tags.

"},{"location":"reference/api/#django_components.SlotContext.data","title":"data instance-attribute","text":"
data: TSlotData\n

See source code

Data passed to the slot.

Read more about Slot data.

Example:

def my_slot(ctx: SlotContext):\n    return f\"Hello, {ctx.data['name']}!\"\n
"},{"location":"reference/api/#django_components.SlotContext.fallback","title":"fallback class-attribute instance-attribute","text":"
fallback: Optional[Union[str, SlotFallback]] = None\n

See source code

Slot's fallback content. Lazily-rendered - coerce this value to string to force it to render.

Read more about Slot fallback.

Example:

def my_slot(ctx: SlotContext):\n    return f\"Hello, {ctx.fallback}!\"\n

May be None if you call the slot fill directly, without using {% slot %} tags.

"},{"location":"reference/api/#django_components.SlotFallback","title":"SlotFallback","text":"
SlotFallback(slot: SlotNode, context: Context)\n

Bases: object

See source code

The content between the {% slot %}..{% endslot %} tags is the fallback content that will be rendered if no fill is given for the slot.

{% slot \"name\" %}\n    Hello, my name is {{ name }}  <!-- Fallback content -->\n{% endslot %}\n

Because the fallback is defined as a piece of the template (NodeList), we want to lazily render it only when needed.

SlotFallback type allows to pass around the slot fallback as a variable.

To force the fallback to render, coerce it to string to trigger the __str__() method.

Example:

def slot_function(self, ctx: SlotContext):\n    return f\"Hello, {ctx.fallback}!\"\n
"},{"location":"reference/api/#django_components.SlotFunc","title":"SlotFunc","text":"

Bases: typing.Protocol

See source code

When rendering components with Component.render() or Component.render_to_response(), the slots can be given either as strings or as functions.

If a slot is given as a function, it will have the signature of SlotFunc.

Read more about Slot functions.

Parameters:

  • ctx (SlotContext) \u2013

    Single named tuple that holds the slot data and metadata.

Returns:

  • str | SafeString \u2013

    The rendered slot content.

Example:

from django_components import SlotContext, SlotResult\n\ndef header(ctx: SlotContext) -> SlotResult:\n    if ctx.data.get(\"name\"):\n        return f\"Hello, {ctx.data['name']}!\"\n    else:\n        return ctx.fallback\n\nhtml = MyTable.render(\n    slots={\n        \"header\": header,\n    },\n)\n
"},{"location":"reference/api/#django_components.SlotInput","title":"SlotInput module-attribute","text":"
SlotInput = Union[SlotResult, SlotFunc[TSlotData], Slot[TSlotData]]\n

See source code

Type representing all forms in which slot content can be passed to a component.

When rendering a component with Component.render() or Component.render_to_response(), the slots may be given a strings, functions, or Slot instances. This type describes that union.

Use this type when typing the slots in your component.

SlotInput accepts an optional type parameter to specify the data dictionary that will be passed to the slot content function.

Example:

from typing import NamedTuple\nfrom typing_extensions import TypedDict\nfrom django_components import Component, SlotInput\n\nclass TableFooterSlotData(TypedDict):\n    page_number: int\n\nclass Table(Component):\n    class Slots(NamedTuple):\n        header: SlotInput\n        footer: SlotInput[TableFooterSlotData]\n\n    template = \"<div>{% slot 'footer' %}</div>\"\n\nhtml = Table.render(\n    slots={\n        # As a string\n        \"header\": \"Hello, World!\",\n\n        # Safe string\n        \"header\": mark_safe(\"<i><am><safe>\"),\n\n        # Function\n        \"footer\": lambda ctx: f\"Page: {ctx.data['page_number']}!\",\n\n        # Slot instance\n        \"footer\": Slot(lambda ctx: f\"Page: {ctx.data['page_number']}!\"),\n\n        # None (Same as no slot)\n        \"header\": None,\n    },\n)\n
"},{"location":"reference/api/#django_components.SlotNode","title":"SlotNode","text":"
SlotNode(\n    params: List[TagAttr],\n    flags: Optional[Dict[str, bool]] = None,\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    contents: Optional[str] = None,\n    template_name: Optional[str] = None,\n    template_component: Optional[Type[Component]] = None,\n)\n

Bases: django_components.node.BaseNode

See source code

{% slot %} tag marks a place inside a component where content can be inserted from outside.

Learn more about using slots.

This is similar to slots as seen in Web components, Vue or React's children.

Args:

  • name (str, required): Registered name of the component to render
  • default: Optional flag. If there is a default slot, you can pass the component slot content without using the {% fill %} tag. See Default slot
  • required: Optional flag. Will raise an error if a slot is required but not given.
  • **kwargs: Any extra kwargs will be passed as the slot data.

Example:

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        {% slot \"content\" default %}\n          This is shown if not overriden!\n        {% endslot %}\n      </div>\n      <aside>\n        {% slot \"sidebar\" required / %}\n      </aside>\n    \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      <div>\n        {% component \"child\" %}\n          {% fill \"content\" %}\n            \ud83d\uddde\ufe0f\ud83d\udcf0\n          {% endfill %}\n\n          {% fill \"sidebar\" %}\n            \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n          {% endfill %}\n        {% endcomponent %}\n      </div>\n    \"\"\"\n
"},{"location":"reference/api/#django_components.SlotNode--slot-data","title":"Slot data","text":"

Any extra kwargs will be considered as slot data, and will be accessible in the {% fill %} tag via fill's data kwarg:

Read more about Slot data.

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        {# Passing data to the slot #}\n        {% slot \"content\" user=user %}\n          This is shown if not overriden!\n        {% endslot %}\n      </div>\n    \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      {# Parent can access the slot data #}\n      {% component \"child\" %}\n        {% fill \"content\" data=\"data\" %}\n          <div class=\"wrapper-class\">\n            {{ data.user }}\n          </div>\n        {% endfill %}\n      {% endcomponent %}\n    \"\"\"\n
"},{"location":"reference/api/#django_components.SlotNode--slot-fallback","title":"Slot fallback","text":"

The content between the {% slot %}..{% endslot %} tags is the fallback content that will be rendered if no fill is given for the slot.

This fallback content can then be accessed from within the {% fill %} tag using the fill's fallback kwarg. This is useful if you need to wrap / prepend / append the original slot's content.

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        {% slot \"content\" %}\n          This is fallback content!\n        {% endslot %}\n      </div>\n    \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      {# Parent can access the slot's fallback content #}\n      {% component \"child\" %}\n        {% fill \"content\" fallback=\"fallback\" %}\n          {{ fallback }}\n        {% endfill %}\n      {% endcomponent %}\n    \"\"\"\n

Methods:

  • parse \u2013
  • register \u2013
  • render \u2013
  • unregister \u2013

Attributes:

  • active_flags (List[str]) \u2013
  • allowed_flags \u2013
  • contents (Optional[str]) \u2013
  • end_tag \u2013
  • flags (Dict[str, bool]) \u2013
  • node_id (str) \u2013
  • nodelist (NodeList) \u2013
  • params (List[TagAttr]) \u2013
  • tag \u2013
  • template_component (Optional[Type[Component]]) \u2013
  • template_name (Optional[str]) \u2013
"},{"location":"reference/api/#django_components.SlotNode.active_flags","title":"active_flags property","text":"
active_flags: List[str]\n

See source code

Flags that were set for this specific instance as a list of strings.

E.g. the following tag:

{% slot \"content\" default required / %}\n

Will have the following flags:

[\"default\", \"required\"]\n
"},{"location":"reference/api/#django_components.SlotNode.allowed_flags","title":"allowed_flags class-attribute instance-attribute","text":"
allowed_flags = [SLOT_DEFAULT_FLAG, SLOT_REQUIRED_FLAG]\n
"},{"location":"reference/api/#django_components.SlotNode.contents","title":"contents instance-attribute","text":"
contents: Optional[str] = contents\n

See source code

See source code

The contents of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The contents will be \"<div> ... </div>\".

"},{"location":"reference/api/#django_components.SlotNode.end_tag","title":"end_tag class-attribute instance-attribute","text":"
end_tag = 'endslot'\n
"},{"location":"reference/api/#django_components.SlotNode.flags","title":"flags instance-attribute","text":"
flags: Dict[str, bool] = flags or {flag: Falsefor flag in (allowed_flags or [])}\n

See source code

See source code

Dictionary of all allowed_flags that were set on the tag.

Flags that were set are True, and the rest are False.

E.g. the following tag:

class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n    allowed_flags = [\"default\", \"required\"]\n
{% slot \"content\" default %}\n

Has 2 flags, default and required, but only default was set.

The flags dictionary will be:

{\n    \"default\": True,\n    \"required\": False,\n}\n

You can check if a flag is set by doing:

if node.flags[\"default\"]:\n    ...\n
"},{"location":"reference/api/#django_components.SlotNode.node_id","title":"node_id instance-attribute","text":"
node_id: str = node_id or gen_id()\n

See source code

See source code

The unique ID of the node.

Extensions can use this ID to store additional information.

"},{"location":"reference/api/#django_components.SlotNode.nodelist","title":"nodelist instance-attribute","text":"
nodelist: NodeList = nodelist or NodeList()\n

See source code

See source code

The nodelist of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The nodelist will contain the <div> ... </div> part.

Unlike contents, the nodelist contains the actual Nodes, not just the text.

"},{"location":"reference/api/#django_components.SlotNode.params","title":"params instance-attribute","text":"
params: List[TagAttr] = params\n

See source code

See source code

The parameters to the tag in the template.

A single param represents an arg or kwarg of the template tag.

E.g. the following tag:

{% component \"my_comp\" key=val key2='val2 two' %}\n

Has 3 params:

  • Posiitonal arg \"my_comp\"
  • Keyword arg key=val
  • Keyword arg key2='val2 two'
"},{"location":"reference/api/#django_components.SlotNode.tag","title":"tag class-attribute instance-attribute","text":"
tag = 'slot'\n
"},{"location":"reference/api/#django_components.SlotNode.template_component","title":"template_component instance-attribute","text":"
template_component: Optional[Type[Component]] = template_component\n

See source code

See source code

If the template that contains this node belongs to a Component, then this will be the Component class.

"},{"location":"reference/api/#django_components.SlotNode.template_name","title":"template_name instance-attribute","text":"
template_name: Optional[str] = template_name\n

See source code

See source code

The name of the Template that contains this node.

The template name is set by Django's template loaders.

For example, the filesystem template loader will set this to the absolute path of the template file.

\"/home/user/project/templates/my_template.html\"\n
"},{"location":"reference/api/#django_components.SlotNode.parse","title":"parse classmethod","text":"
parse(parser: Parser, token: Token, **kwargs: Any) -> BaseNode\n

See source code

This function is what is passed to Django's Library.tag() when registering the tag.

In other words, this method is called by Django's template parser when we encounter a tag that matches this node's tag, e.g. {% component %} or {% slot %}.

To register the tag, you can use BaseNode.register().

"},{"location":"reference/api/#django_components.SlotNode.register","title":"register classmethod","text":"
register(library: Library) -> None\n

See source code

A convenience method for registering the tag with the given library.

class MyNode(BaseNode):\n    tag = \"mynode\"\n\nMyNode.register(library)\n

Allows you to then use the node in templates like so:

{% load mylibrary %}\n{% mynode %}\n
"},{"location":"reference/api/#django_components.SlotNode.render","title":"render","text":"
render(context: Context, name: str, **kwargs: Any) -> SafeString\n
"},{"location":"reference/api/#django_components.SlotNode.unregister","title":"unregister classmethod","text":"
unregister(library: Library) -> None\n

See source code

Unregisters the node from the given library.

"},{"location":"reference/api/#django_components.SlotRef","title":"SlotRef module-attribute","text":"
SlotRef = SlotFallback\n

See source code

DEPRECATED: Use SlotFallback instead. Will be removed in v1.

"},{"location":"reference/api/#django_components.SlotResult","title":"SlotResult module-attribute","text":"
SlotResult = Union[str, SafeString]\n

See source code

Type representing the result of a slot render function.

Example:

from django_components import SlotContext, SlotResult\n\ndef my_slot_fn(ctx: SlotContext) -> SlotResult:\n    return \"Hello, world!\"\n\nmy_slot = Slot(my_slot_fn)\nhtml = my_slot()  # Output: Hello, world!\n

Read more about Slot functions.

"},{"location":"reference/api/#django_components.TagFormatterABC","title":"TagFormatterABC","text":"

Bases: abc.ABC

See source code

Abstract base class for defining custom tag formatters.

Tag formatters define how the component tags are used in the template.

Read more about Tag formatter.

For example, with the default tag formatter (ComponentFormatter), components are written as:

{% component \"comp_name\" %}\n{% endcomponent %}\n

While with the shorthand tag formatter (ShorthandComponentFormatter), components are written as:

{% comp_name %}\n{% endcomp_name %}\n

Example:

Implementation for ShorthandComponentFormatter:

from djagno_components import TagFormatterABC, TagResult\n\nclass ShorthandComponentFormatter(TagFormatterABC):\n    def start_tag(self, name: str) -> str:\n        return name\n\n    def end_tag(self, name: str) -> str:\n        return f\"end{name}\"\n\n    def parse(self, tokens: List[str]) -> TagResult:\n        tokens = [*tokens]\n        name = tokens.pop(0)\n        return TagResult(name, tokens)\n

Methods:

  • end_tag \u2013
  • parse \u2013
  • start_tag \u2013
"},{"location":"reference/api/#django_components.TagFormatterABC.end_tag","title":"end_tag abstractmethod","text":"
end_tag(name: str) -> str\n

See source code

Formats the end tag of a block component.

Parameters:

  • name (str) \u2013

    Component's registered name. Required.

Returns:

  • str ( str ) \u2013

    The formatted end tag.

"},{"location":"reference/api/#django_components.TagFormatterABC.parse","title":"parse abstractmethod","text":"
parse(tokens: List[str]) -> TagResult\n

See source code

Given the tokens (words) passed to a component start tag, this function extracts the component name from the tokens list, and returns TagResult, which is a tuple of (component_name, remaining_tokens).

Parameters:

  • tokens ([List(str]) \u2013

    List of tokens passed to the component tag.

Returns:

  • TagResult ( TagResult ) \u2013

    Parsed component name and remaining tokens.

Example:

Assuming we used a component in a template like this:

{% component \"my_comp\" key=val key2=val2 %}\n{% endcomponent %}\n

This function receives a list of tokens:

['component', '\"my_comp\"', 'key=val', 'key2=val2']\n
  • component is the tag name, which we drop.
  • \"my_comp\" is the component name, but we must remove the extra quotes.
  • The remaining tokens we pass unmodified, as that's the input to the component.

So in the end, we return:

TagResult('my_comp', ['key=val', 'key2=val2'])\n
"},{"location":"reference/api/#django_components.TagFormatterABC.start_tag","title":"start_tag abstractmethod","text":"
start_tag(name: str) -> str\n

See source code

Formats the start tag of a component.

Parameters:

  • name (str) \u2013

    Component's registered name. Required.

Returns:

  • str ( str ) \u2013

    The formatted start tag.

"},{"location":"reference/api/#django_components.TagResult","title":"TagResult","text":"

Bases: tuple

See source code

The return value from TagFormatter.parse().

Read more about Tag formatter.

Attributes:

  • component_name (str) \u2013
  • tokens (List[str]) \u2013
"},{"location":"reference/api/#django_components.TagResult.component_name","title":"component_name instance-attribute","text":"
component_name: str\n

See source code

Component name extracted from the template tag

For example, if we had tag

{% component \"my_comp\" key=val key2=val2 %}\n

Then component_name would be my_comp.

"},{"location":"reference/api/#django_components.TagResult.tokens","title":"tokens instance-attribute","text":"
tokens: List[str]\n

See source code

Remaining tokens (words) that were passed to the tag, with component name removed

For example, if we had tag

{% component \"my_comp\" key=val key2=val2 %}\n

Then tokens would be ['key=val', 'key2=val2'].

"},{"location":"reference/api/#django_components.all_components","title":"all_components","text":"
all_components() -> List[Type[Component]]\n

See source code

Get a list of all created Component classes.

"},{"location":"reference/api/#django_components.all_registries","title":"all_registries","text":"
all_registries() -> List[ComponentRegistry]\n

See source code

Get a list of all created ComponentRegistry instances.

"},{"location":"reference/api/#django_components.autodiscover","title":"autodiscover","text":"
autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n

See source code

Search for all python files in COMPONENTS.dirs and COMPONENTS.app_dirs and import them.

See Autodiscovery.

NOTE: Subdirectories and files starting with an underscore _ (except for __init__.py are ignored.

Parameters:

  • map_module (Callable[[str], str], default: None ) \u2013

    Map the module paths with map_module function. This serves as an escape hatch for when you need to use this function in tests.

Returns:

  • List[str] \u2013

    List[str]: A list of module paths of imported files.

To get the same list of modules that autodiscover() would return, but without importing them, use get_component_files():

from django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
"},{"location":"reference/api/#django_components.cached_template","title":"cached_template","text":"
cached_template(\n    template_string: str,\n    template_cls: Optional[Type[Template]] = None,\n    origin: Optional[Origin] = None,\n    name: Optional[str] = None,\n    engine: Optional[Any] = None,\n) -> Template\n

See source code

DEPRECATED. Template caching will be removed in v1.

Create a Template instance that will be cached as per the COMPONENTS.template_cache_size setting.

Parameters:

  • template_string (str) \u2013

    Template as a string, same as the first argument to Django's Template. Required.

  • template_cls (Type[Template], default: None ) \u2013

    Specify the Template class that should be instantiated. Defaults to Django's Template class.

  • origin (Type[Origin], default: None ) \u2013

    Sets Template.Origin.

  • name (Type[str], default: None ) \u2013

    Sets Template.name

  • engine (Type[Any], default: None ) \u2013

    Sets Template.engine

from django_components import cached_template\n\ntemplate = cached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n    pass\n\ntemplate = cached_template(\n    \"Variable: {{ variable }}\",\n    template_cls=MyTemplate,\n    name=...\n    origin=...\n    engine=...\n)\n
"},{"location":"reference/api/#django_components.format_attributes","title":"format_attributes","text":"
format_attributes(attributes: Mapping[str, Any]) -> str\n

See source code

Format a dict of attributes into an HTML attributes string.

Read more about HTML attributes.

Example:

format_attributes({\"class\": \"my-class\", \"data-id\": \"123\"})\n

will return

'class=\"my-class\" data-id=\"123\"'\n
"},{"location":"reference/api/#django_components.get_component_by_class_id","title":"get_component_by_class_id","text":"
get_component_by_class_id(comp_cls_id: str) -> Type[Component]\n

See source code

Get a component class by its unique ID.

Each component class is associated with a unique hash that's derived from its module import path.

E.g. path.to.my.secret.MyComponent -> MyComponent_ab01f32

This hash is available under class_id on the component class.

Raises KeyError if the component class is not found.

NOTE: This is mainly intended for extensions.

"},{"location":"reference/api/#django_components.get_component_dirs","title":"get_component_dirs","text":"
get_component_dirs(include_apps: bool = True) -> List[Path]\n

See source code

Get directories that may contain component files.

This is the heart of all features that deal with filesystem and file lookup. Autodiscovery, Django template resolution, static file resolution - They all use this.

Parameters:

  • include_apps (bool, default: True ) \u2013

    Include directories from installed Django apps. Defaults to True.

Returns:

  • List[Path] \u2013

    List[Path]: A list of directories that may contain component files.

get_component_dirs() searches for dirs set in COMPONENTS.dirs settings. If none set, defaults to searching for a \"components\" app.

In addition to that, also all installed Django apps are checked whether they contain directories as set in COMPONENTS.app_dirs (e.g. [app]/components).

Notes:

  • Paths that do not point to directories are ignored.

  • BASE_DIR setting is required.

  • The paths in COMPONENTS.dirs must be absolute paths.

"},{"location":"reference/api/#django_components.get_component_files","title":"get_component_files","text":"
get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]\n

See source code

Search for files within the component directories (as defined in get_component_dirs()).

Requires BASE_DIR setting to be set.

Subdirectories and files starting with an underscore _ (except __init__.py) are ignored.

Parameters:

  • suffix (Optional[str], default: None ) \u2013

    The suffix to search for. E.g. .py, .js, .css. Defaults to None, which will search for all files.

Returns:

  • List[ComponentFileEntry] \u2013

    List[ComponentFileEntry] A list of entries that contain both the filesystem path and the python import path (dot path).

Example:

from django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
"},{"location":"reference/api/#django_components.get_component_url","title":"get_component_url","text":"
get_component_url(component: Union[Type[Component], Component], query: Optional[Dict] = None, fragment: Optional[str] = None) -> str\n

See source code

Get the URL for a Component.

Raises RuntimeError if the component is not public.

Read more about Component views and URLs.

get_component_url() optionally accepts query and fragment arguments.

Example:

from django_components import Component, get_component_url\n\nclass MyComponent(Component):\n    class View:\n        public = True\n\n# Get the URL for the component\nurl = get_component_url(\n    MyComponent,\n    query={\"foo\": \"bar\"},\n    fragment=\"baz\",\n)\n# /components/ext/view/components/c1ab2c3?foo=bar#baz\n
"},{"location":"reference/api/#django_components.import_libraries","title":"import_libraries","text":"
import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n

See source code

Import modules set in COMPONENTS.libraries setting.

See Autodiscovery.

Parameters:

  • map_module (Callable[[str], str], default: None ) \u2013

    Map the module paths with map_module function. This serves as an escape hatch for when you need to use this function in tests.

Returns:

  • List[str] \u2013

    List[str]: A list of module paths of imported files.

Examples:

Normal usage - load libraries after Django has loaded

from django_components import import_libraries\n\nclass MyAppConfig(AppConfig):\n    def ready(self):\n        import_libraries()\n

Potential usage in tests

from django_components import import_libraries\n\nimport_libraries(lambda path: path.replace(\"tests.\", \"myapp.\"))\n

"},{"location":"reference/api/#django_components.merge_attributes","title":"merge_attributes","text":"
merge_attributes(*attrs: Dict) -> Dict\n

See source code

Merge a list of dictionaries into a single dictionary.

The dictionaries are treated as HTML attributes and are merged accordingly:

  • If a same key is present in multiple dictionaries, the values are joined with a space character.
  • The class and style keys are handled specially, similar to how Vue does it.

Read more about HTML attributes.

Example:

merge_attributes(\n    {\"my-attr\": \"my-value\", \"class\": \"my-class\"},\n    {\"my-attr\": \"extra-value\", \"data-id\": \"123\"},\n)\n

will result in

{\n    \"my-attr\": \"my-value extra-value\",\n    \"class\": \"my-class\",\n    \"data-id\": \"123\",\n}\n

The class attribute

The class attribute can be given as a string, or a dictionary.

  • If given as a string, it is used as is.
  • If given as a dictionary, only the keys with a truthy value are used.

Example:

merge_attributes(\n    {\"class\": \"my-class extra-class\"},\n    {\"class\": {\"truthy\": True, \"falsy\": False}},\n)\n

will result in

{\n    \"class\": \"my-class extra-class truthy\",\n}\n

The style attribute

The style attribute can be given as a string, a list, or a dictionary.

  • If given as a string, it is used as is.
  • If given as a dictionary, it is converted to a style attribute string.

Example:

merge_attributes(\n    {\"style\": \"color: red; background-color: blue;\"},\n    {\"style\": {\"background-color\": \"green\", \"color\": False}},\n)\n

will result in

{\n    \"style\": \"color: red; background-color: blue; background-color: green;\",\n}\n
"},{"location":"reference/api/#django_components.register","title":"register","text":"
register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[Type[TComponent]], Type[TComponent]]\n

See source code

Class decorator for registering a component to a component registry.

See Registering components.

Parameters:

  • name (str) \u2013

    Registered name. This is the name by which the component will be accessed from within a template when using the {% component %} tag. Required.

  • registry (ComponentRegistry, default: None ) \u2013

    Specify the registry to which to register this component. If omitted, component is registered to the default registry.

Raises:

  • AlreadyRegistered \u2013

    If there is already a component registered under the same name.

Examples:

from django_components import Component, register\n\n@register(\"my_component\")\nclass MyComponent(Component):\n    ...\n

Specifing ComponentRegistry the component should be registered to by setting the registry kwarg:

from django.template import Library\nfrom django_components import Component, ComponentRegistry, register\n\nmy_lib = Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n    ...\n
"},{"location":"reference/api/#django_components.registry","title":"registry module-attribute","text":"
registry: ComponentRegistry = ComponentRegistry()\n

See source code

The default and global component registry. Use this instance to directly register or remove components:

See Registering components.

# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get single\nregistry.get(\"button\")\n\n# Get all\nregistry.all()\n\n# Check if component is registered\nregistry.has(\"button\")\n\n# Unregister single\nregistry.unregister(\"button\")\n\n# Unregister all\nregistry.clear()\n
"},{"location":"reference/api/#django_components.render_dependencies","title":"render_dependencies","text":"
render_dependencies(content: TContent, strategy: DependenciesStrategy = 'document') -> TContent\n

See source code

Given a string that contains parts that were rendered by components, this function inserts all used JS and CSS.

By default, the string is parsed as an HTML and: - CSS is inserted at the end of <head> (if present) - JS is inserted at the end of <body> (if present)

If you used {% component_js_dependencies %} or {% component_css_dependencies %}, then the JS and CSS will be inserted only at these locations.

Example:

def my_view(request):\n    template = Template('''\n        {% load components %}\n        <!doctype html>\n        <html>\n            <head></head>\n            <body>\n                <h1>{{ table_name }}</h1>\n                {% component \"table\" name=table_name / %}\n            </body>\n        </html>\n    ''')\n\n    html = template.render(\n        Context({\n            \"table_name\": request.GET[\"name\"],\n        })\n    )\n\n    # This inserts components' JS and CSS\n    processed_html = render_dependencies(html)\n\n    return HttpResponse(processed_html)\n

"},{"location":"reference/api/#django_components.template_tag","title":"template_tag","text":"
template_tag(\n    library: Library, tag: str, end_tag: Optional[str] = None, allowed_flags: Optional[List[str]] = None\n) -> Callable[[Callable], Callable]\n

See source code

A simplified version of creating a template tag based on BaseNode.

Instead of defining the whole class, you can just define the render() method.

from django.template import Context, Library\nfrom django_components import BaseNode, template_tag\n\nlibrary = Library()\n\n@template_tag(\n    library,\n    tag=\"mytag\",\n    end_tag=\"endmytag\",\n    allowed_flags=[\"required\"],\n)\ndef mytag(node: BaseNode, context: Context, name: str, **kwargs: Any) -> str:\n    return f\"Hello, {name}!\"\n

This will allow the template tag {% mytag %} to be used like this:

{% mytag name=\"John\" %}\n{% mytag name=\"John\" required %} ... {% endmytag %}\n

The given function will be wrapped in a class that inherits from BaseNode.

And this class will be registered with the given library.

The function MUST accept at least two positional arguments: node and context

  • node is the BaseNode instance.
  • context is the Context of the template.

Any extra parameters defined on this function will be part of the tag's input parameters.

For more info, see BaseNode.render().

"},{"location":"reference/commands/","title":"CLI commands","text":""},{"location":"reference/commands/#commands","title":"Commands","text":"

These are all the Django management commands that will be added by installing django_components:

"},{"location":"reference/commands/#components","title":"components","text":"
usage: python manage.py  components [-h] {create,upgrade,ext,list} ...\n

See source code

The entrypoint for the 'components' commands.

Options:

  • -h, --help
    • show this help message and exit

Subcommands:

  • create
    • Create a new django component.
  • upgrade
    • Upgrade django components syntax from '{% component_block ... %}' to '{% component ... %}'.
  • ext
    • Run extension commands.
  • list
    • List all components created in this project.

The entrypoint for the \"components\" commands.

python manage.py components list\npython manage.py components create <name>\npython manage.py components upgrade\npython manage.py components ext list\npython manage.py components ext run <extension> <command>\n
"},{"location":"reference/commands/#components-create","title":"components create","text":"
usage: python manage.py components create [-h] [--path PATH] [--js JS] [--css CSS] [--template TEMPLATE]\n              [--force] [--verbose] [--dry-run]\n              name\n

See source code

Create a new django component.

Positional Arguments:

  • name
    • The name of the component to create. This is a required argument.

Options:

  • -h, --help
    • show this help message and exit
  • --path PATH
    • The path to the component's directory. This is an optional argument. If not provided, the command will use the COMPONENTS.dirs setting from your Django settings.
  • --js JS
    • The name of the JavaScript file. This is an optional argument. The default value is script.js.
  • --css CSS
    • The name of the CSS file. This is an optional argument. The default value is style.css.
  • --template TEMPLATE
    • The name of the template file. This is an optional argument. The default value is template.html.
  • --force
    • This option allows you to overwrite existing files if they exist. This is an optional argument.
  • --verbose
    • This option allows the command to print additional information during component creation. This is an optional argument.
  • --dry-run
    • This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False.
"},{"location":"reference/commands/#usage","title":"Usage","text":"

To use the command, run the following command in your terminal:

python manage.py components create <name> --path <path> --js <js_filename> --css <css_filename> --template <template_filename> --force --verbose --dry-run\n

Replace <name>, <path>, <js_filename>, <css_filename>, and <template_filename> with your desired values.

"},{"location":"reference/commands/#examples","title":"Examples","text":"

Here are some examples of how you can use the command:

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 components create my_component\n

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.

Creating a Component with Custom Settings

You can also create a component with custom settings by providing additional arguments:

python manage.py components create new_component --path my_components --js my_script.js --css my_style.css --template my_template.html\n

This will create a new component named new_component in the my_components directory. The JavaScript, CSS, and template files will be named my_script.js, my_style.css, and my_template.html, respectively.

Overwriting an Existing Component

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

python manage.py components create my_component --force\n

This will overwrite the existing my_component if it exists.

Simulating Component Creation

If you want to simulate the creation of a component without actually creating any files, you can use the --dry-run option:

python manage.py components create my_component --dry-run\n

This will simulate the creation of my_component without creating any files.

"},{"location":"reference/commands/#components-upgrade","title":"components upgrade","text":"
usage: python manage.py components upgrade [-h] [--path PATH]\n

See source code

Upgrade django components syntax from '{% component_block ... %}' to '{% component ... %}'.

Options:

  • -h, --help
    • show this help message and exit
  • --path PATH
    • Path to search for components
"},{"location":"reference/commands/#components-ext","title":"components ext","text":"
usage: python manage.py components ext [-h] {list,run} ...\n

See source code

Run extension commands.

Options:

  • -h, --help
    • show this help message and exit

Subcommands:

  • list
    • List all extensions.
  • run
    • Run a command added by an extension.

Run extension commands.

python manage.py components ext list\npython manage.py components ext run <extension> <command>\n
"},{"location":"reference/commands/#components-ext-list","title":"components ext list","text":"
usage: python manage.py components ext list [-h] [--all] [--columns COLUMNS] [-s]\n

See source code

List all extensions.

Options:

  • -h, --help
    • show this help message and exit
  • --all
    • Show all columns. Same as --columns name.
  • --columns COLUMNS
    • Comma-separated list of columns to show. Available columns: name. Defaults to --columns name.
  • -s, --simple
    • Only show table data, without headers. Use this option for generating machine-readable output.

List all extensions.

python manage.py components ext list\n

Prints the list of installed extensions:

name\n==============\nview\nmy_extension\n

To specify which columns to show, use the --columns flag:

python manage.py components ext list --columns name\n

Which prints:

name\n==============\nview\nmy_extension\n

To print out all columns, use the --all flag:

python manage.py components ext list --all\n

If you need to omit the title in order to programmatically post-process the output, you can use the --simple (or -s) flag:

python manage.py components ext list --simple\n

Which prints just:

view\nmy_extension\n
"},{"location":"reference/commands/#components-ext-run","title":"components ext run","text":"
usage: python manage.py components ext run [-h]\n

See source code

Run a command added by an extension.

Options:

  • -h, --help
    • show this help message and exit

Run a command added by an extension.

Each extension can add its own commands, which will be available to run with this command.

For example, if you define and install the following extension:

from django_components import ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n    name = \"hello\"\n    help = \"Say hello\"\n    def handle(self, *args, **kwargs):\n        print(\"Hello, world!\")\n\nclass MyExt(ComponentExtension):\n    name = \"my_ext\"\n    commands = [HelloCommand]\n

You can run the hello command with:

python manage.py components ext run my_ext hello\n

You can also define arguments for the command, which will be passed to the command's handle method.

from django_components import CommandArg, ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n    name = \"hello\"\n    help = \"Say hello\"\n    arguments = [\n        CommandArg(name=\"name\", help=\"The name to say hello to\"),\n        CommandArg(name=[\"--shout\", \"-s\"], action=\"store_true\"),\n    ]\n\n    def handle(self, name: str, *args, **kwargs):\n        shout = kwargs.get(\"shout\", False)\n        msg = f\"Hello, {name}!\"\n        if shout:\n            msg = msg.upper()\n        print(msg)\n

You can run the command with:

python manage.py components ext run my_ext hello --name John --shout\n

Note

Command arguments and options are based on Python's argparse module.

For more information, see the argparse documentation.

"},{"location":"reference/commands/#components-list","title":"components list","text":"
usage: python manage.py components list [-h] [--all] [--columns COLUMNS] [-s]\n

See source code

List all components created in this project.

Options:

  • -h, --help
    • show this help message and exit
  • --all
    • Show all columns. Same as --columns name,full_name,path.
  • --columns COLUMNS
    • Comma-separated list of columns to show. Available columns: name, full_name, path. Defaults to --columns full_name,path.
  • -s, --simple
    • Only show table data, without headers. Use this option for generating machine-readable output.

List all components.

python manage.py components list\n

Prints the list of available components:

full_name                                                     path\n==================================================================================================\nproject.pages.project.ProjectPage                             ./project/pages/project\nproject.components.dashboard.ProjectDashboard                 ./project/components/dashboard\nproject.components.dashboard_action.ProjectDashboardAction    ./project/components/dashboard_action\n

To specify which columns to show, use the --columns flag:

python manage.py components list --columns name,full_name,path\n

Which prints:

name                      full_name                                                     path\n==================================================================================================\nProjectPage               project.pages.project.ProjectPage                             ./project/pages/project\nProjectDashboard          project.components.dashboard.ProjectDashboard                 ./project/components/dashboard\nProjectDashboardAction    project.components.dashboard_action.ProjectDashboardAction    ./project/components/dashboard_action\n

To print out all columns, use the --all flag:

python manage.py components list --all\n

If you need to omit the title in order to programmatically post-process the output, you can use the --simple (or -s) flag:

python manage.py components list --simple\n

Which prints just:

ProjectPage               project.pages.project.ProjectPage                             ./project/pages/project\nProjectDashboard          project.components.dashboard.ProjectDashboard                 ./project/components/dashboard\nProjectDashboardAction    project.components.dashboard_action.ProjectDashboardAction    ./project/components/dashboard_action\n
"},{"location":"reference/commands/#startcomponent","title":"startcomponent","text":"
usage: startcomponent [-h] [--path PATH] [--js JS] [--css CSS]\n                      [--template TEMPLATE] [--force] [--verbose] [--dry-run]\n                      [--version] [-v {0,1,2,3}] [--settings SETTINGS]\n                      [--pythonpath PYTHONPATH] [--traceback] [--no-color]\n                      [--force-color] [--skip-checks]\n                      name\n

See source code

Deprecated. Use components create instead.

Positional Arguments:

  • name
    • The name of the component to create. This is a required argument.

Options:

  • -h, --help
    • show this help message and exit
  • --path PATH
    • The path to the component's directory. This is an optional argument. If not provided, the command will use the COMPONENTS.dirs setting from your Django settings.
  • --js JS
    • The name of the JavaScript file. This is an optional argument. The default value is script.js.
  • --css CSS
    • The name of the CSS file. This is an optional argument. The default value is style.css.
  • --template TEMPLATE
    • The name of the template file. This is an optional argument. The default value is template.html.
  • --force
    • This option allows you to overwrite existing files if they exist. This is an optional argument.
  • --verbose
    • This option allows the command to print additional information during component creation. This is an optional argument.
  • --dry-run
    • This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False.
  • --version
    • Show program's version number and exit.
  • -v, --verbosity {0,1,2,3}
    • Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output
  • --settings SETTINGS
    • The Python path to a settings module, e.g. \"myproject.settings.main\". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used.
  • --pythonpath PYTHONPATH
    • A directory to add to the Python path, e.g. \"/home/djangoprojects/myproject\".
  • --traceback
    • Raise on CommandError exceptions.
  • --no-color
    • Don't colorize the command output.
  • --force-color
    • Force colorization of the command output.
  • --skip-checks
    • Skip system checks.

Deprecated. Use components create instead.

"},{"location":"reference/commands/#upgradecomponent","title":"upgradecomponent","text":"
usage: upgradecomponent [-h] [--path PATH] [--version] [-v {0,1,2,3}]\n                        [--settings SETTINGS] [--pythonpath PYTHONPATH]\n                        [--traceback] [--no-color] [--force-color]\n                        [--skip-checks]\n

See source code

Deprecated. Use components upgrade instead.

Options:

  • -h, --help
    • show this help message and exit
  • --path PATH
    • Path to search for components
  • --version
    • Show program's version number and exit.
  • -v, --verbosity {0,1,2,3}
    • Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output
  • --settings SETTINGS
    • The Python path to a settings module, e.g. \"myproject.settings.main\". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used.
  • --pythonpath PYTHONPATH
    • A directory to add to the Python path, e.g. \"/home/djangoprojects/myproject\".
  • --traceback
    • Raise on CommandError exceptions.
  • --no-color
    • Don't colorize the command output.
  • --force-color
    • Force colorization of the command output.
  • --skip-checks
    • Skip system checks.

Deprecated. Use components upgrade instead.

"},{"location":"reference/components/","title":"Components","text":""},{"location":"reference/components/#components","title":"Components","text":"

These are the components provided by django_components.

"},{"location":"reference/components/#django_components.components.dynamic.DynamicComponent","title":"DynamicComponent","text":"

Bases: django_components.component.Component

See source code

This component is given a registered name or a reference to another component, and behaves as if the other component was in its place.

The args, kwargs, and slot fills are all passed down to the underlying component.

Parameters:

  • is (str | Type[Component]) \u2013

    Component that should be rendered. Either a registered name of a component, or a Component class directly. Required.

  • registry (ComponentRegistry, default: None ) \u2013

    Specify the registry to search for the registered name. If omitted, all registries are searched until the first match.

  • *args (Optional[Any], default: None ) \u2013

    Additional data passed to the component.

  • **kwargs (Optional[Any], default: None ) \u2013

    Additional data passed to the component.

Slots:

  • Any slots, depending on the actual component.

Examples:

Django

{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% endcomponent %}\n

Or in case you use the django_components.component_shorthand_formatter tag formatter:

{% dynamic is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% enddynamic %}\n

Python

from django_components import DynamicComponent\n\nDynamicComponent.render(\n    kwargs={\n        \"is\": table_comp,\n        \"data\": table_data,\n        \"headers\": table_headers,\n    },\n    slots={\n        \"pagination\": PaginationComponent.render(\n            deps_strategy=\"ignore\",\n        ),\n    },\n)\n

"},{"location":"reference/components/#django_components.components.dynamic.DynamicComponent--use-cases","title":"Use cases","text":"

Dynamic components are suitable if you are writing something like a form component. You may design it such that users give you a list of input types, and you render components depending on the input types.

While you could handle this with a series of if / else statements, that's not an extensible approach. Instead, you can use the dynamic component in place of normal components.

"},{"location":"reference/components/#django_components.components.dynamic.DynamicComponent--component-name","title":"Component name","text":"

By default, the dynamic component is registered under the name \"dynamic\". In case of a conflict, you can set the COMPONENTS.dynamic_component_name setting to change the name used for the dynamic components.

# settings.py\nCOMPONENTS = ComponentsSettings(\n    dynamic_component_name=\"my_dynamic\",\n)\n

After which you will be able to use the dynamic component with the new name:

{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% endcomponent %}\n

"},{"location":"reference/exceptions/","title":"Exceptions","text":""},{"location":"reference/exceptions/#exceptions","title":"Exceptions","text":""},{"location":"reference/exceptions/#django_components.AlreadyRegistered","title":"AlreadyRegistered","text":"

Bases: Exception

See source code

Raised when you try to register a Component, but it's already registered with given ComponentRegistry.

"},{"location":"reference/exceptions/#django_components.NotRegistered","title":"NotRegistered","text":"

Bases: Exception

See source code

Raised when you try to access a Component, but it's NOT registered with given ComponentRegistry.

"},{"location":"reference/exceptions/#django_components.TagProtectedError","title":"TagProtectedError","text":"

Bases: Exception

See source code

The way the TagFormatter works is that, based on which start and end tags are used for rendering components, the ComponentRegistry behind the scenes un-/registers the template tags with the associated instance of Django's Library.

In other words, if I have registered a component \"table\", and I use the shorthand syntax:

{% table ... %}\n{% endtable %}\n

Then ComponentRegistry registers the tag table onto the Django's Library instance.

However, that means that if we registered a component \"slot\", then we would overwrite the {% slot %} tag from django_components.

Thus, this exception is raised when a component is attempted to be registered under a forbidden name, such that it would overwrite one of django_component's own template tags.

"},{"location":"reference/extension_commands/","title":"Extension commands API","text":""},{"location":"reference/extension_commands/#extension-commands-api","title":"Extension commands API","text":"

Overview of all classes, functions, and other objects related to defining extension commands.

Read more on Extensions.

"},{"location":"reference/extension_commands/#django_components.CommandArg","title":"CommandArg dataclass","text":"
CommandArg(\n    name_or_flags: Union[str, Sequence[str]],\n    action: Optional[Union[CommandLiteralAction, Action]] = None,\n    nargs: Optional[Union[int, Literal[\"*\", \"+\", \"?\"]]] = None,\n    const: Any = None,\n    default: Any = None,\n    type: Optional[Union[Type, Callable[[str], Any]]] = None,\n    choices: Optional[Sequence[Any]] = None,\n    required: Optional[bool] = None,\n    help: Optional[str] = None,\n    metavar: Optional[str] = None,\n    dest: Optional[str] = None,\n    version: Optional[str] = None,\n    deprecated: Optional[bool] = None,\n)\n

Bases: object

See source code

Define a single positional argument or an option for a command.

Fields on this class correspond to the arguments for ArgumentParser.add_argument()

Methods:

  • asdict \u2013

Attributes:

  • action (Optional[Union[CommandLiteralAction, Action]]) \u2013
  • choices (Optional[Sequence[Any]]) \u2013
  • const (Any) \u2013
  • default (Any) \u2013
  • deprecated (Optional[bool]) \u2013
  • dest (Optional[str]) \u2013
  • help (Optional[str]) \u2013
  • metavar (Optional[str]) \u2013
  • name_or_flags (Union[str, Sequence[str]]) \u2013
  • nargs (Optional[Union[int, Literal['*', '+', '?']]]) \u2013
  • required (Optional[bool]) \u2013
  • type (Optional[Union[Type, Callable[[str], Any]]]) \u2013
  • version (Optional[str]) \u2013
"},{"location":"reference/extension_commands/#django_components.CommandArg.action","title":"action class-attribute instance-attribute","text":"
action: Optional[Union[CommandLiteralAction, Action]] = None\n

See source code

The basic type of action to be taken when this argument is encountered at the command line.

"},{"location":"reference/extension_commands/#django_components.CommandArg.choices","title":"choices class-attribute instance-attribute","text":"
choices: Optional[Sequence[Any]] = None\n

See source code

A sequence of the allowable values for the argument.

"},{"location":"reference/extension_commands/#django_components.CommandArg.const","title":"const class-attribute instance-attribute","text":"
const: Any = None\n

See source code

A constant value required by some action and nargs selections.

"},{"location":"reference/extension_commands/#django_components.CommandArg.default","title":"default class-attribute instance-attribute","text":"
default: Any = None\n

See source code

The value produced if the argument is absent from the command line and if it is absent from the namespace object.

"},{"location":"reference/extension_commands/#django_components.CommandArg.deprecated","title":"deprecated class-attribute instance-attribute","text":"
deprecated: Optional[bool] = None\n

See source code

Whether or not use of the argument is deprecated.

NOTE: This is supported only in Python 3.13+

"},{"location":"reference/extension_commands/#django_components.CommandArg.dest","title":"dest class-attribute instance-attribute","text":"
dest: Optional[str] = None\n

See source code

The name of the attribute to be added to the object returned by parse_args().

"},{"location":"reference/extension_commands/#django_components.CommandArg.help","title":"help class-attribute instance-attribute","text":"
help: Optional[str] = None\n

See source code

A brief description of what the argument does.

"},{"location":"reference/extension_commands/#django_components.CommandArg.metavar","title":"metavar class-attribute instance-attribute","text":"
metavar: Optional[str] = None\n

See source code

A name for the argument in usage messages.

"},{"location":"reference/extension_commands/#django_components.CommandArg.name_or_flags","title":"name_or_flags instance-attribute","text":"
name_or_flags: Union[str, Sequence[str]]\n

See source code

Either a name or a list of option strings, e.g. 'foo' or '-f', '--foo'.

"},{"location":"reference/extension_commands/#django_components.CommandArg.nargs","title":"nargs class-attribute instance-attribute","text":"
nargs: Optional[Union[int, Literal['*', '+', '?']]] = None\n

See source code

The number of command-line arguments that should be consumed.

"},{"location":"reference/extension_commands/#django_components.CommandArg.required","title":"required class-attribute instance-attribute","text":"
required: Optional[bool] = None\n

See source code

Whether or not the command-line option may be omitted (optionals only).

"},{"location":"reference/extension_commands/#django_components.CommandArg.type","title":"type class-attribute instance-attribute","text":"
type: Optional[Union[Type, Callable[[str], Any]]] = None\n

See source code

The type to which the command-line argument should be converted.

"},{"location":"reference/extension_commands/#django_components.CommandArg.version","title":"version class-attribute instance-attribute","text":"
version: Optional[str] = None\n

See source code

The version string to be added to the object returned by parse_args().

MUST be used with action='version'.

See https://docs.python.org/3/library/argparse.html#action

"},{"location":"reference/extension_commands/#django_components.CommandArg.asdict","title":"asdict","text":"
asdict() -> dict\n

See source code

Convert the dataclass to a dictionary, stripping out fields with None values

"},{"location":"reference/extension_commands/#django_components.CommandArgGroup","title":"CommandArgGroup dataclass","text":"
CommandArgGroup(title: Optional[str] = None, description: Optional[str] = None, arguments: Sequence[CommandArg] = ())\n

Bases: object

See source code

Define a group of arguments for a command.

Fields on this class correspond to the arguments for ArgumentParser.add_argument_group()

Methods:

  • asdict \u2013

Attributes:

  • arguments (Sequence[CommandArg]) \u2013
  • description (Optional[str]) \u2013
  • title (Optional[str]) \u2013
"},{"location":"reference/extension_commands/#django_components.CommandArgGroup.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Sequence[CommandArg] = ()\n
"},{"location":"reference/extension_commands/#django_components.CommandArgGroup.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n

See source code

Description for the argument group in help output, by default None

"},{"location":"reference/extension_commands/#django_components.CommandArgGroup.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = None\n

See source code

Title for the argument group in help output; by default \u201cpositional arguments\u201d if description is provided, otherwise uses title for positional arguments.

"},{"location":"reference/extension_commands/#django_components.CommandArgGroup.asdict","title":"asdict","text":"
asdict() -> dict\n

See source code

Convert the dataclass to a dictionary, stripping out fields with None values

"},{"location":"reference/extension_commands/#django_components.CommandHandler","title":"CommandHandler","text":""},{"location":"reference/extension_commands/#django_components.CommandParserInput","title":"CommandParserInput dataclass","text":"
CommandParserInput(\n    prog: Optional[str] = None,\n    usage: Optional[str] = None,\n    description: Optional[str] = None,\n    epilog: Optional[str] = None,\n    parents: Optional[Sequence[ArgumentParser]] = None,\n    formatter_class: Optional[Type[_FormatterClass]] = None,\n    prefix_chars: Optional[str] = None,\n    fromfile_prefix_chars: Optional[str] = None,\n    argument_default: Optional[Any] = None,\n    conflict_handler: Optional[str] = None,\n    add_help: Optional[bool] = None,\n    allow_abbrev: Optional[bool] = None,\n    exit_on_error: Optional[bool] = None,\n)\n

Bases: object

See source code

Typing for the input to the ArgumentParser constructor.

Methods:

  • asdict \u2013

Attributes:

  • add_help (Optional[bool]) \u2013
  • allow_abbrev (Optional[bool]) \u2013
  • argument_default (Optional[Any]) \u2013
  • conflict_handler (Optional[str]) \u2013
  • description (Optional[str]) \u2013
  • epilog (Optional[str]) \u2013
  • exit_on_error (Optional[bool]) \u2013
  • formatter_class (Optional[Type[_FormatterClass]]) \u2013
  • fromfile_prefix_chars (Optional[str]) \u2013
  • parents (Optional[Sequence[ArgumentParser]]) \u2013
  • prefix_chars (Optional[str]) \u2013
  • prog (Optional[str]) \u2013
  • usage (Optional[str]) \u2013
"},{"location":"reference/extension_commands/#django_components.CommandParserInput.add_help","title":"add_help class-attribute instance-attribute","text":"
add_help: Optional[bool] = None\n

See source code

Add a -h/--help option to the parser (default: True)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.allow_abbrev","title":"allow_abbrev class-attribute instance-attribute","text":"
allow_abbrev: Optional[bool] = None\n

See source code

Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.argument_default","title":"argument_default class-attribute instance-attribute","text":"
argument_default: Optional[Any] = None\n

See source code

The global default value for arguments (default: None)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.conflict_handler","title":"conflict_handler class-attribute instance-attribute","text":"
conflict_handler: Optional[str] = None\n

See source code

The strategy for resolving conflicting optionals (usually unnecessary)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n

See source code

Text to display before the argument help (by default, no text)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.epilog","title":"epilog class-attribute instance-attribute","text":"
epilog: Optional[str] = None\n

See source code

Text to display after the argument help (by default, no text)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.exit_on_error","title":"exit_on_error class-attribute instance-attribute","text":"
exit_on_error: Optional[bool] = None\n

See source code

Determines whether or not ArgumentParser exits with error info when an error occurs. (default: True)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.formatter_class","title":"formatter_class class-attribute instance-attribute","text":"
formatter_class: Optional[Type[_FormatterClass]] = None\n

See source code

A class for customizing the help output

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.fromfile_prefix_chars","title":"fromfile_prefix_chars class-attribute instance-attribute","text":"
fromfile_prefix_chars: Optional[str] = None\n

See source code

The set of characters that prefix files from which additional arguments should be read (default: None)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.parents","title":"parents class-attribute instance-attribute","text":"
parents: Optional[Sequence[ArgumentParser]] = None\n

See source code

A list of ArgumentParser objects whose arguments should also be included

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.prefix_chars","title":"prefix_chars class-attribute instance-attribute","text":"
prefix_chars: Optional[str] = None\n

See source code

The set of characters that prefix optional arguments (default: \u2018-\u2018)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.prog","title":"prog class-attribute instance-attribute","text":"
prog: Optional[str] = None\n

See source code

The name of the program (default: os.path.basename(sys.argv[0]))

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.usage","title":"usage class-attribute instance-attribute","text":"
usage: Optional[str] = None\n

See source code

The string describing the program usage (default: generated from arguments added to parser)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.asdict","title":"asdict","text":"
asdict() -> dict\n

See source code

Convert the dataclass to a dictionary, stripping out fields with None values

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand","title":"CommandSubcommand dataclass","text":"
CommandSubcommand(\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    prog: Optional[str] = None,\n    parser_class: Optional[Type[ArgumentParser]] = None,\n    action: Optional[Union[CommandLiteralAction, Action]] = None,\n    dest: Optional[str] = None,\n    required: Optional[bool] = None,\n    help: Optional[str] = None,\n    metavar: Optional[str] = None,\n)\n

Bases: object

See source code

Define a subcommand for a command.

Fields on this class correspond to the arguments for ArgumentParser.add_subparsers.add_parser()

Methods:

  • asdict \u2013

Attributes:

  • action (Optional[Union[CommandLiteralAction, Action]]) \u2013
  • description (Optional[str]) \u2013
  • dest (Optional[str]) \u2013
  • help (Optional[str]) \u2013
  • metavar (Optional[str]) \u2013
  • parser_class (Optional[Type[ArgumentParser]]) \u2013
  • prog (Optional[str]) \u2013
  • required (Optional[bool]) \u2013
  • title (Optional[str]) \u2013
"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.action","title":"action class-attribute instance-attribute","text":"
action: Optional[Union[CommandLiteralAction, Action]] = None\n

See source code

The basic type of action to be taken when this argument is encountered at the command line.

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n

See source code

Description for the sub-parser group in help output, by default None.

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.dest","title":"dest class-attribute instance-attribute","text":"
dest: Optional[str] = None\n

See source code

Name of the attribute under which sub-command name will be stored; by default None and no value is stored.

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.help","title":"help class-attribute instance-attribute","text":"
help: Optional[str] = None\n

See source code

Help for sub-parser group in help output, by default None.

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.metavar","title":"metavar class-attribute instance-attribute","text":"
metavar: Optional[str] = None\n

See source code

String presenting available subcommands in help; by default it is None and presents subcommands in form {cmd1, cmd2, ..}.

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.parser_class","title":"parser_class class-attribute instance-attribute","text":"
parser_class: Optional[Type[ArgumentParser]] = None\n

See source code

Class which will be used to create sub-parser instances, by default the class of the current parser (e.g. ArgumentParser).

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.prog","title":"prog class-attribute instance-attribute","text":"
prog: Optional[str] = None\n

See source code

Usage information that will be displayed with sub-command help, by default the name of the program and any positional arguments before the subparser argument.

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.required","title":"required class-attribute instance-attribute","text":"
required: Optional[bool] = None\n

See source code

Whether or not a subcommand must be provided, by default False (added in 3.7)

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = None\n

See source code

Title for the sub-parser group in help output; by default \u201csubcommands\u201d if description is provided, otherwise uses title for positional arguments.

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.asdict","title":"asdict","text":"
asdict() -> dict\n

See source code

Convert the dataclass to a dictionary, stripping out fields with None values

"},{"location":"reference/extension_commands/#django_components.ComponentCommand","title":"ComponentCommand","text":"

Bases: object

See source code

Definition of a CLI command.

This class is based on Python's argparse module and Django's BaseCommand class. ComponentCommand allows you to define:

  • Command name, description, and help text
  • Arguments and options (e.g. --name John)
  • Group arguments (see argparse groups)
  • Subcommands (e.g. components ext run my_ext hello)
  • Handler behavior

Each extension can add its own commands, which will be available to run with components ext run.

Extensions use the ComponentCommand class to define their commands.

For example, if you define and install the following extension:

from django_components ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n    name = \"hello\"\n    help = \"Say hello\"\n    def handle(self, *args, **kwargs):\n        print(\"Hello, world!\")\n\nclass MyExt(ComponentExtension):\n    name = \"my_ext\"\n    commands = [HelloCommand]\n

You can run the hello command with:

python manage.py components ext run my_ext hello\n

You can also define arguments for the command, which will be passed to the command's handle method.

from django_components import CommandArg, ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n    name = \"hello\"\n    help = \"Say hello\"\n    arguments = [\n        CommandArg(name=\"name\", help=\"The name to say hello to\"),\n        CommandArg(name=[\"--shout\", \"-s\"], action=\"store_true\"),\n    ]\n\n    def handle(self, name: str, *args, **kwargs):\n        shout = kwargs.get(\"shout\", False)\n        msg = f\"Hello, {name}!\"\n        if shout:\n            msg = msg.upper()\n        print(msg)\n

You can run the command with:

python manage.py components ext run my_ext hello --name John --shout\n

Note

Command arguments and options are based on Python's argparse module.

For more information, see the argparse documentation.

Attributes:

  • arguments (Sequence[Union[CommandArg, CommandArgGroup]]) \u2013
  • handle (Optional[CommandHandler]) \u2013
  • help (Optional[str]) \u2013
  • name (str) \u2013
  • parser_input (Optional[CommandParserInput]) \u2013
  • subcommands (Sequence[Type[ComponentCommand]]) \u2013
  • subparser_input (Optional[CommandSubcommand]) \u2013
"},{"location":"reference/extension_commands/#django_components.ComponentCommand.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Sequence[Union[CommandArg, CommandArgGroup]] = ()\n

See source code

argparse arguments for the command

"},{"location":"reference/extension_commands/#django_components.ComponentCommand.handle","title":"handle class-attribute instance-attribute","text":"
handle: Optional[CommandHandler] = None\n

See source code

The function that is called when the command is run. If None, the command will print the help message.

"},{"location":"reference/extension_commands/#django_components.ComponentCommand.help","title":"help class-attribute instance-attribute","text":"
help: Optional[str] = None\n

See source code

The help text for the command

"},{"location":"reference/extension_commands/#django_components.ComponentCommand.name","title":"name instance-attribute","text":"
name: str\n

See source code

The name of the command - this is what is used to call the command

"},{"location":"reference/extension_commands/#django_components.ComponentCommand.parser_input","title":"parser_input class-attribute instance-attribute","text":"
parser_input: Optional[CommandParserInput] = None\n

See source code

The input to use when creating the ArgumentParser for this command. If None, the default values will be used.

"},{"location":"reference/extension_commands/#django_components.ComponentCommand.subcommands","title":"subcommands class-attribute instance-attribute","text":"
subcommands: Sequence[Type[ComponentCommand]] = ()\n

See source code

Subcommands for the command

"},{"location":"reference/extension_commands/#django_components.ComponentCommand.subparser_input","title":"subparser_input class-attribute instance-attribute","text":"
subparser_input: Optional[CommandSubcommand] = None\n

See source code

The input to use when this command is a subcommand installed with add_subparser(). If None, the default values will be used.

"},{"location":"reference/extension_hooks/","title":"Extension hooks","text":""},{"location":"reference/extension_hooks/#extension-hooks","title":"Extension hooks","text":"

Overview of all the extension hooks available in Django Components.

Read more on Extensions.

"},{"location":"reference/extension_hooks/#hooks","title":"Hooks","text":"

Available data:

name type description component_cls Type[Component] The created Component class

Available data:

name type description component_cls Type[Component] The to-be-deleted Component class

Available data:

name type description component Component The Component instance that is being rendered component_cls Type[Component] The Component class component_id str The unique identifier for this component instance context_data Dict Deprecated. Use template_data instead. Will be removed in v1.0. css_data Dict Dictionary of CSS data from Component.get_css_data() js_data Dict Dictionary of JavaScript data from Component.get_js_data() template_data Dict Dictionary of template data from Component.get_template_data()

Available data:

name type description args List List of positional arguments passed to the component component Component The Component instance that received the input and is being rendered component_cls Type[Component] The Component class component_id str The unique identifier for this component instance context Context The Django template Context object kwargs Dict Dictionary of keyword arguments passed to the component slots Dict[str, Slot] Dictionary of slot definitions

Available data:

name type description component_cls Type[Component] The registered Component class name str The name the component was registered under registry ComponentRegistry The registry the component was registered to

Available data:

name type description component Component The Component instance that is being rendered component_cls Type[Component] The Component class component_id str The unique identifier for this component instance error Optional[Exception] The error that occurred during rendering, or None if rendering was successful result Optional[str] The rendered component, or None if rendering failed

Available data:

name type description component_cls Type[Component] The unregistered Component class name str The name the component was registered under registry ComponentRegistry The registry the component was unregistered from

Available data:

name type description component_cls Type[Component] The Component class whose CSS was loaded content str The CSS content (string)

Available data:

name type description component_cls Type[Component] The Component class whose JS was loaded content str The JS content (string)

Available data:

name type description registry ComponentRegistry The created ComponentRegistry instance

Available data:

name type description registry ComponentRegistry The to-be-deleted ComponentRegistry instance

Available data:

name type description component Component The Component instance that contains the {% slot %} tag component_cls Type[Component] The Component class that contains the {% slot %} tag component_id str The unique identifier for this component instance result SlotResult The rendered result of the slot slot Slot The Slot instance that was rendered slot_is_default bool Whether the slot is default slot_is_required bool Whether the slot is required slot_name str The name of the {% slot %} tag slot_node SlotNode The node instance of the {% slot %} tag

Available data:

name type description component_cls Type[Component] The Component class whose template was loaded template django.template.base.Template The compiled template object

Available data:

name type description component_cls Type[Component] The Component class whose template was loaded content str The template string name Optional[str] The name of the template origin Optional[django.template.base.Origin] The origin of the template"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_component_class_created","title":"on_component_class_created","text":"
on_component_class_created(ctx: OnComponentClassCreatedContext) -> None\n

See source code

Called when a new Component class is created.

This hook is called after the Component class is fully defined but before it's registered.

Use this hook to perform any initialization or validation of the Component class.

Example:

from django_components import ComponentExtension, OnComponentClassCreatedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_class_created(self, ctx: OnComponentClassCreatedContext) -> None:\n        # Add a new attribute to the Component class\n        ctx.component_cls.my_attr = \"my_value\"\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_component_class_deleted","title":"on_component_class_deleted","text":"
on_component_class_deleted(ctx: OnComponentClassDeletedContext) -> None\n

See source code

Called when a Component class is being deleted.

This hook is called before the Component class is deleted from memory.

Use this hook to perform any cleanup related to the Component class.

Example:

from django_components import ComponentExtension, OnComponentClassDeletedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_class_deleted(self, ctx: OnComponentClassDeletedContext) -> None:\n        # Remove Component class from the extension's cache on deletion\n        self.cache.pop(ctx.component_cls, None)\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_component_data","title":"on_component_data","text":"
on_component_data(ctx: OnComponentDataContext) -> None\n

See source code

Called when a Component was triggered to render, after a component's context and data methods have been processed.

This hook is called after Component.get_template_data(), Component.get_js_data() and Component.get_css_data().

This hook runs after on_component_input.

Use this hook to modify or validate the component's data before rendering.

Example:

from django_components import ComponentExtension, OnComponentDataContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_data(self, ctx: OnComponentDataContext) -> None:\n        # Add extra template variable to all components when they are rendered\n        ctx.template_data[\"my_template_var\"] = \"my_value\"\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_component_input","title":"on_component_input","text":"
on_component_input(ctx: OnComponentInputContext) -> Optional[str]\n

See source code

Called when a Component was triggered to render, but before a component's context and data methods are invoked.

Use this hook to modify or validate component inputs before they're processed.

This is the first hook that is called when rendering a component. As such this hook is called before Component.get_template_data(), Component.get_js_data(), and Component.get_css_data() methods, and the on_component_data hook.

This hook also allows to skip the rendering of a component altogether. If the hook returns a non-null value, this value will be used instead of rendering the component.

You can use this to implement a caching mechanism for components, or define components that will be rendered conditionally.

Example:

from django_components import ComponentExtension, OnComponentInputContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_input(self, ctx: OnComponentInputContext) -> None:\n        # Add extra kwarg to all components when they are rendered\n        ctx.kwargs[\"my_input\"] = \"my_value\"\n

Warning

In this hook, the components' inputs are still mutable.

As such, if a component defines Args, Kwargs, Slots types, these types are NOT yet instantiated.

Instead, component fields like Component.args, Component.kwargs, Component.slots are plain list / dict objects.

"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_component_registered","title":"on_component_registered","text":"
on_component_registered(ctx: OnComponentRegisteredContext) -> None\n

See source code

Called when a Component class is registered with a ComponentRegistry.

This hook is called after a Component class is successfully registered.

Example:

from django_components import ComponentExtension, OnComponentRegisteredContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_registered(self, ctx: OnComponentRegisteredContext) -> None:\n        print(f\"Component {ctx.component_cls} registered to {ctx.registry} as '{ctx.name}'\")\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_component_rendered","title":"on_component_rendered","text":"
on_component_rendered(ctx: OnComponentRenderedContext) -> Optional[str]\n

See source code

Called when a Component was rendered, including all its child components.

Use this hook to access or post-process the component's rendered output.

This hook works similarly to Component.on_render_after():

  1. To modify the output, return a new string from this hook. The original output or error will be ignored.

  2. To cause this component to return a new error, raise that error. The original output and error will be ignored.

  3. If you neither raise nor return string, the original output or error will be used.

Examples:

Change the final output of a component:

from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n        # Append a comment to the component's rendered output\n        return ctx.result + \"<!-- MyExtension comment -->\"\n

Cause the component to raise a new exception:

from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n        # Raise a new exception\n        raise Exception(\"Error message\")\n

Return nothing (or None) to handle the result as usual:

from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n        if ctx.error is not None:\n            # The component raised an exception\n            print(f\"Error: {ctx.error}\")\n        else:\n            # The component rendered successfully\n            print(f\"Result: {ctx.result}\")\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_component_unregistered","title":"on_component_unregistered","text":"
on_component_unregistered(ctx: OnComponentUnregisteredContext) -> None\n

See source code

Called when a Component class is unregistered from a ComponentRegistry.

This hook is called after a Component class is removed from the registry.

Example:

from django_components import ComponentExtension, OnComponentUnregisteredContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_unregistered(self, ctx: OnComponentUnregisteredContext) -> None:\n        print(f\"Component {ctx.component_cls} unregistered from {ctx.registry} as '{ctx.name}'\")\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_css_loaded","title":"on_css_loaded","text":"
on_css_loaded(ctx: OnCssLoadedContext) -> Optional[str]\n

See source code

Called when a Component's CSS is loaded as a string.

This hook runs only once per Component class and works for both Component.css and Component.css_file.

Use this hook to read or modify the CSS.

To modify the CSS, return a new string from this hook.

Example:

from django_components import ComponentExtension, OnCssLoadedContext\n\nclass MyExtension(ComponentExtension):\n    def on_css_loaded(self, ctx: OnCssLoadedContext) -> Optional[str]:\n        # Modify the CSS\n        return ctx.content.replace(\"Hello\", \"Hi\")\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_js_loaded","title":"on_js_loaded","text":"
on_js_loaded(ctx: OnJsLoadedContext) -> Optional[str]\n

See source code

Called when a Component's JS is loaded as a string.

This hook runs only once per Component class and works for both Component.js and Component.js_file.

Use this hook to read or modify the JS.

To modify the JS, return a new string from this hook.

Example:

from django_components import ComponentExtension, OnCssLoadedContext\n\nclass MyExtension(ComponentExtension):\n    def on_js_loaded(self, ctx: OnJsLoadedContext) -> Optional[str]:\n        # Modify the JS\n        return ctx.content.replace(\"Hello\", \"Hi\")\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_registry_created","title":"on_registry_created","text":"
on_registry_created(ctx: OnRegistryCreatedContext) -> None\n

See source code

Called when a new ComponentRegistry is created.

This hook is called after a new ComponentRegistry instance is initialized.

Use this hook to perform any initialization needed for the registry.

Example:

from django_components import ComponentExtension, OnRegistryCreatedContext\n\nclass MyExtension(ComponentExtension):\n    def on_registry_created(self, ctx: OnRegistryCreatedContext) -> None:\n        # Add a new attribute to the registry\n        ctx.registry.my_attr = \"my_value\"\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_registry_deleted","title":"on_registry_deleted","text":"
on_registry_deleted(ctx: OnRegistryDeletedContext) -> None\n

See source code

Called when a ComponentRegistry is being deleted.

This hook is called before a ComponentRegistry instance is deleted.

Use this hook to perform any cleanup related to the registry.

Example:

from django_components import ComponentExtension, OnRegistryDeletedContext\n\nclass MyExtension(ComponentExtension):\n    def on_registry_deleted(self, ctx: OnRegistryDeletedContext) -> None:\n        # Remove registry from the extension's cache on deletion\n        self.cache.pop(ctx.registry, None)\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_slot_rendered","title":"on_slot_rendered","text":"
on_slot_rendered(ctx: OnSlotRenderedContext) -> Optional[str]\n

See source code

Called when a {% slot %} tag was rendered.

Use this hook to access or post-process the slot's rendered output.

To modify the output, return a new string from this hook.

Example:

from django_components import ComponentExtension, OnSlotRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_slot_rendered(self, ctx: OnSlotRenderedContext) -> Optional[str]:\n        # Append a comment to the slot's rendered output\n        return ctx.result + \"<!-- MyExtension comment -->\"\n

Access slot metadata:

You can access the {% slot %} tag node (SlotNode) and its metadata using ctx.slot_node.

For example, to find the Component class to which belongs the template where the {% slot %} tag is defined, you can use ctx.slot_node.template_component:

from django_components import ComponentExtension, OnSlotRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_slot_rendered(self, ctx: OnSlotRenderedContext) -> Optional[str]:\n        # Access slot metadata\n        slot_node = ctx.slot_node\n        slot_owner = slot_node.template_component\n        print(f\"Slot owner: {slot_owner}\")\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_template_compiled","title":"on_template_compiled","text":"
on_template_compiled(ctx: OnTemplateCompiledContext) -> None\n

See source code

Called when a Component's template is compiled into a Template object.

This hook runs only once per Component class and works for both Component.template and Component.template_file.

Use this hook to read or modify the template (in-place) after it's compiled.

Example:

from django_components import ComponentExtension, OnTemplateCompiledContext\n\nclass MyExtension(ComponentExtension):\n    def on_template_compiled(self, ctx: OnTemplateCompiledContext) -> None:\n        print(f\"Template origin: {ctx.template.origin.name}\")\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_template_loaded","title":"on_template_loaded","text":"
on_template_loaded(ctx: OnTemplateLoadedContext) -> Optional[str]\n

See source code

Called when a Component's template is loaded as a string.

This hook runs only once per Component class and works for both Component.template and Component.template_file.

Use this hook to read or modify the template before it's compiled.

To modify the template, return a new string from this hook.

Example:

from django_components import ComponentExtension, OnTemplateLoadedContext\n\nclass MyExtension(ComponentExtension):\n    def on_template_loaded(self, ctx: OnTemplateLoadedContext) -> Optional[str]:\n        # Modify the template\n        return ctx.content.replace(\"Hello\", \"Hi\")\n
"},{"location":"reference/extension_hooks/#objects","title":"Objects","text":""},{"location":"reference/extension_hooks/#django_components.extension.OnComponentClassCreatedContext","title":"OnComponentClassCreatedContext","text":"

Attributes:

  • component_cls (Type[Component]) \u2013
"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentClassCreatedContext.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The created Component class

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentClassDeletedContext","title":"OnComponentClassDeletedContext","text":"

Attributes:

  • component_cls (Type[Component]) \u2013
"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentClassDeletedContext.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The to-be-deleted Component class

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentDataContext","title":"OnComponentDataContext","text":"

Attributes:

  • component (Component) \u2013
  • component_cls (Type[Component]) \u2013
  • component_id (str) \u2013
  • context_data (Dict) \u2013
  • css_data (Dict) \u2013
  • js_data (Dict) \u2013
  • template_data (Dict) \u2013
"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentDataContext.component","title":"component instance-attribute","text":"
component: Component\n

See source code

The Component instance that is being rendered

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentDataContext.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The Component class

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentDataContext.component_id","title":"component_id instance-attribute","text":"
component_id: str\n

See source code

The unique identifier for this component instance

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentDataContext.context_data","title":"context_data instance-attribute","text":"
context_data: Dict\n

See source code

Deprecated. Use template_data instead. Will be removed in v1.0.

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentDataContext.css_data","title":"css_data instance-attribute","text":"
css_data: Dict\n

See source code

Dictionary of CSS data from Component.get_css_data()

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentDataContext.js_data","title":"js_data instance-attribute","text":"
js_data: Dict\n

See source code

Dictionary of JavaScript data from Component.get_js_data()

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentDataContext.template_data","title":"template_data instance-attribute","text":"
template_data: Dict\n

See source code

Dictionary of template data from Component.get_template_data()

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentInputContext","title":"OnComponentInputContext","text":"

Attributes:

  • args (List) \u2013
  • component (Component) \u2013
  • component_cls (Type[Component]) \u2013
  • component_id (str) \u2013
  • context (Context) \u2013
  • kwargs (Dict) \u2013
  • slots (Dict[str, Slot]) \u2013
"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentInputContext.args","title":"args instance-attribute","text":"
args: List\n

See source code

List of positional arguments passed to the component

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentInputContext.component","title":"component instance-attribute","text":"
component: Component\n

See source code

The Component instance that received the input and is being rendered

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentInputContext.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The Component class

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentInputContext.component_id","title":"component_id instance-attribute","text":"
component_id: str\n

See source code

The unique identifier for this component instance

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentInputContext.context","title":"context instance-attribute","text":"
context: Context\n

See source code

The Django template Context object

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentInputContext.kwargs","title":"kwargs instance-attribute","text":"
kwargs: Dict\n

See source code

Dictionary of keyword arguments passed to the component

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentInputContext.slots","title":"slots instance-attribute","text":"
slots: Dict[str, Slot]\n

See source code

Dictionary of slot definitions

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentRegisteredContext","title":"OnComponentRegisteredContext","text":"

Attributes:

  • component_cls (Type[Component]) \u2013
  • name (str) \u2013
  • registry (ComponentRegistry) \u2013
"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentRegisteredContext.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The registered Component class

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentRegisteredContext.name","title":"name instance-attribute","text":"
name: str\n

See source code

The name the component was registered under

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentRegisteredContext.registry","title":"registry instance-attribute","text":"
registry: ComponentRegistry\n

See source code

The registry the component was registered to

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentUnregisteredContext","title":"OnComponentUnregisteredContext","text":"

Attributes:

  • component_cls (Type[Component]) \u2013
  • name (str) \u2013
  • registry (ComponentRegistry) \u2013
"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentUnregisteredContext.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The unregistered Component class

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentUnregisteredContext.name","title":"name instance-attribute","text":"
name: str\n

See source code

The name the component was registered under

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentUnregisteredContext.registry","title":"registry instance-attribute","text":"
registry: ComponentRegistry\n

See source code

The registry the component was unregistered from

"},{"location":"reference/extension_hooks/#django_components.extension.OnRegistryCreatedContext","title":"OnRegistryCreatedContext","text":"

Attributes:

  • registry (ComponentRegistry) \u2013
"},{"location":"reference/extension_hooks/#django_components.extension.OnRegistryCreatedContext.registry","title":"registry instance-attribute","text":"
registry: ComponentRegistry\n

See source code

The created ComponentRegistry instance

"},{"location":"reference/extension_hooks/#django_components.extension.OnRegistryDeletedContext","title":"OnRegistryDeletedContext","text":"

Attributes:

  • registry (ComponentRegistry) \u2013
"},{"location":"reference/extension_hooks/#django_components.extension.OnRegistryDeletedContext.registry","title":"registry instance-attribute","text":"
registry: ComponentRegistry\n

See source code

The to-be-deleted ComponentRegistry instance

"},{"location":"reference/extension_urls/","title":"Extension URLs API","text":""},{"location":"reference/extension_urls/#extension-urls-api","title":"Extension URLs API","text":"

Overview of all classes, functions, and other objects related to defining extension URLs.

Read more on Extensions.

"},{"location":"reference/extension_urls/#django_components.URLRoute","title":"URLRoute dataclass","text":"
URLRoute(\n    path: str,\n    handler: Optional[URLRouteHandler] = None,\n    children: Iterable[URLRoute] = list(),\n    name: Optional[str] = None,\n    extra: Dict[str, Any] = dict(),\n)\n

Bases: object

See source code

Framework-agnostic route definition.

This is similar to Django's URLPattern object created with django.urls.path().

The URLRoute must either define a handler function or have a list of child routes children. If both are defined, an error will be raised.

Example:

URLRoute(\"/my/path\", handler=my_handler, name=\"my_name\", extra={\"kwargs\": {\"my_extra\": \"my_value\"}})\n

Is equivalent to:

django.urls.path(\"/my/path\", my_handler, name=\"my_name\", kwargs={\"my_extra\": \"my_value\"})\n

With children:

URLRoute(\n    \"/my/path\",\n    name=\"my_name\",\n    extra={\"kwargs\": {\"my_extra\": \"my_value\"}},\n    children=[\n        URLRoute(\n            \"/child/<str:name>/\",\n            handler=my_handler,\n            name=\"my_name\",\n            extra={\"kwargs\": {\"my_extra\": \"my_value\"}},\n        ),\n        URLRoute(\"/other/<int:id>/\", handler=other_handler),\n    ],\n)\n

Attributes:

  • children (Iterable[URLRoute]) \u2013
  • extra (Dict[str, Any]) \u2013
  • handler (Optional[URLRouteHandler]) \u2013
  • name (Optional[str]) \u2013
  • path (str) \u2013
"},{"location":"reference/extension_urls/#django_components.URLRoute.children","title":"children class-attribute instance-attribute","text":"
children: Iterable[URLRoute] = field(default_factory=list)\n
"},{"location":"reference/extension_urls/#django_components.URLRoute.extra","title":"extra class-attribute instance-attribute","text":"
extra: Dict[str, Any] = field(default_factory=dict)\n
"},{"location":"reference/extension_urls/#django_components.URLRoute.handler","title":"handler class-attribute instance-attribute","text":"
handler: Optional[URLRouteHandler] = None\n
"},{"location":"reference/extension_urls/#django_components.URLRoute.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
"},{"location":"reference/extension_urls/#django_components.URLRoute.path","title":"path instance-attribute","text":"
path: str\n
"},{"location":"reference/extension_urls/#django_components.URLRouteHandler","title":"URLRouteHandler","text":"

Bases: typing.Protocol

See source code

Framework-agnostic 'view' function for routes

"},{"location":"reference/settings/","title":"Settings","text":""},{"location":"reference/settings/#settings","title":"Settings","text":"

You can configure django_components with a global COMPONENTS variable in your Django settings file, e.g. settings.py. By default you don't need it set, there are resonable defaults.

To configure the settings you can instantiate ComponentsSettings for validation and type hints. Or, for backwards compatibility, you can also use plain dictionary:

# settings.py\nfrom django_components import ComponentsSettings\n\nCOMPONENTS = ComponentsSettings(\n    autodiscover=True,\n    ...\n)\n\n# or\n\nCOMPONENTS = {\n    \"autodiscover\": True,\n    ...\n}\n
"},{"location":"reference/settings/#settings-defaults","title":"Settings defaults","text":"

Here's overview of all available settings and their defaults:

defaults = ComponentsSettings(\n    autodiscover=True,\n    cache=None,\n    context_behavior=ContextBehavior.DJANGO.value,  # \"django\" | \"isolated\"\n    # Root-level \"components\" dirs, e.g. `/path/to/proj/components/`\n    dirs=[Path(settings.BASE_DIR) / \"components\"],\n    # App-level \"components\" dirs, e.g. `[app]/components/`\n    app_dirs=[\"components\"],\n    debug_highlight_components=False,\n    debug_highlight_slots=False,\n    dynamic_component_name=\"dynamic\",\n    extensions=[],\n    extensions_defaults={},\n    libraries=[],  # E.g. [\"mysite.components.forms\", ...]\n    multiline_tags=True,\n    reload_on_file_change=False,\n    static_files_allowed=[\n        \".css\",\n        \".js\", \".jsx\", \".ts\", \".tsx\",\n        # Images\n        \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n        \".jpeg\", \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n        \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n        # Fonts\n        \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n    ],\n    static_files_forbidden=[\n        # See https://marketplace.visualstudio.com/items?itemName=junstyle.vscode-django-support\n        \".html\", \".django\", \".dj\", \".tpl\",\n        # Python files\n        \".py\", \".pyc\",\n    ],\n    tag_formatter=\"django_components.component_formatter\",\n    template_cache_size=128,\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.app_dirs","title":"app_dirs","text":"
app_dirs: Optional[Sequence[str]] = None\n

See source code

Specify the app-level directories that contain your components.

Defaults to [\"components\"]. That is, for each Django app, we search <app>/components/ for components.

The paths must be relative to app, e.g.:

COMPONENTS = ComponentsSettings(\n    app_dirs=[\"my_comps\"],\n)\n

To search for <app>/my_comps/.

These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.

Set to empty list to disable app-level components:

COMPONENTS = ComponentsSettings(\n    app_dirs=[],\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.autodiscover","title":"autodiscover","text":"
autodiscover: Optional[bool] = None\n

See source code

Toggle whether to run autodiscovery at the Django server startup.

Defaults to True

COMPONENTS = ComponentsSettings(\n    autodiscover=False,\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.cache","title":"cache","text":"
cache: Optional[str] = None\n

See source code

Name of the Django cache to be used for storing component's JS and CSS files.

If None, a LocMemCache is used with default settings.

Defaults to None.

Read more about caching.

COMPONENTS = ComponentsSettings(\n    cache=\"my_cache\",\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.context_behavior","title":"context_behavior","text":"
context_behavior: Optional[ContextBehaviorType] = None\n

See source code

Configure whether, inside a component template, you can use variables from the outside (\"django\") or not (\"isolated\"). This also affects what variables are available inside the {% fill %} tags.

Also see Component context and scope.

Defaults to \"django\".

COMPONENTS = ComponentsSettings(\n    context_behavior=\"isolated\",\n)\n

NOTE: context_behavior and slot_context_behavior options were merged in v0.70.

If you are migrating from BEFORE v0.67, set context_behavior to \"django\". From v0.67 to v0.78 (incl) the default value was \"isolated\".

For v0.79 and later, the default is again \"django\". See the rationale for change here.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.debug_highlight_components","title":"debug_highlight_components","text":"
debug_highlight_components: Optional[bool] = None\n

See source code

DEPRECATED. Use extensions_defaults instead. Will be removed in v1.

Enable / disable component highlighting. See Troubleshooting for more details.

Defaults to False.

COMPONENTS = ComponentsSettings(\n    debug_highlight_components=True,\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.debug_highlight_slots","title":"debug_highlight_slots","text":"
debug_highlight_slots: Optional[bool] = None\n

See source code

DEPRECATED. Use extensions_defaults instead. Will be removed in v1.

Enable / disable slot highlighting. See Troubleshooting for more details.

Defaults to False.

COMPONENTS = ComponentsSettings(\n    debug_highlight_slots=True,\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.dirs","title":"dirs","text":"
dirs: Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]] = None\n

See source code

Specify the directories that contain your components.

Defaults to [Path(settings.BASE_DIR) / \"components\"]. That is, the root components/ app.

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

COMPONENTS = ComponentsSettings(\n    dirs=[BASE_DIR / \"components\"],\n)\n

Set to empty list to disable global components directories:

COMPONENTS = ComponentsSettings(\n    dirs=[],\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.dynamic_component_name","title":"dynamic_component_name","text":"
dynamic_component_name: Optional[str] = None\n

See source code

By default, the dynamic component is registered under the name \"dynamic\".

In case of a conflict, you can use this setting to change the component name used for the dynamic components.

# settings.py\nCOMPONENTS = ComponentsSettings(\n    dynamic_component_name=\"my_dynamic\",\n)\n

After which you will be able to use the dynamic component with the new name:

{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.extensions","title":"extensions","text":"
extensions: Optional[Sequence[Union[Type[ComponentExtension], str]]] = None\n

See source code

List of extensions to be loaded.

The extensions can be specified as:

  • Python import path, e.g. \"path.to.my_extension.MyExtension\".
  • Extension class, e.g. my_extension.MyExtension.

Read more about extensions.

Example:

COMPONENTS = ComponentsSettings(\n    extensions=[\n        \"path.to.my_extension.MyExtension\",\n        StorybookExtension,\n    ],\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.extensions_defaults","title":"extensions_defaults","text":"
extensions_defaults: Optional[Dict[str, Any]] = None\n

See source code

Global defaults for the extension classes.

Read more about Extension defaults.

Example:

COMPONENTS = ComponentsSettings(\n    extensions_defaults={\n        \"my_extension\": {\n            \"my_setting\": \"my_value\",\n        },\n        \"cache\": {\n            \"enabled\": True,\n            \"ttl\": 60,\n        },\n    },\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.forbidden_static_files","title":"forbidden_static_files","text":"
forbidden_static_files: Optional[List[Union[str, Pattern]]] = None\n

See source code

Deprecated. Use COMPONENTS.static_files_forbidden instead.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.libraries","title":"libraries","text":"
libraries: Optional[List[str]] = None\n

See source code

Configure extra python modules that should be loaded.

This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.

Expects a list of python module paths. Defaults to empty list.

Example:

COMPONENTS = ComponentsSettings(\n    libraries=[\n        \"mysite.components.forms\",\n        \"mysite.components.buttons\",\n        \"mysite.components.cards\",\n    ],\n)\n

This would be the equivalent of importing these modules from within Django's AppConfig.ready():

class MyAppConfig(AppConfig):\n    def ready(self):\n        import \"mysite.components.forms\"\n        import \"mysite.components.buttons\"\n        import \"mysite.components.cards\"\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.libraries--manually-loading-libraries","title":"Manually loading libraries","text":"

In the rare case that you need to manually trigger the import of libraries, you can use the import_libraries() function:

from django_components import import_libraries\n\nimport_libraries()\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.multiline_tags","title":"multiline_tags","text":"
multiline_tags: Optional[bool] = None\n

See source code

Enable / disable multiline support for template tags. If True, template tags like {% component %} or {{ my_var }} can span multiple lines.

Defaults to True.

Disable this setting if you are making custom modifications to Django's regular expression for parsing templates at django.template.base.tag_re.

COMPONENTS = ComponentsSettings(\n    multiline_tags=False,\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.reload_on_file_change","title":"reload_on_file_change","text":"
reload_on_file_change: Optional[bool] = None\n

See source code

This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.

In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.

Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.

The setting reload_on_file_change fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.

If True, django_components configures Django to reload when files inside COMPONENTS.dirs or COMPONENTS.app_dirs change.

See Reload dev server on component file changes.

Defaults to False.

Warning

This setting should be enabled only for the dev environment!

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.reload_on_template_change","title":"reload_on_template_change","text":"
reload_on_template_change: Optional[bool] = None\n

See source code

Deprecated. Use COMPONENTS.reload_on_file_change instead.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.static_files_allowed","title":"static_files_allowed","text":"
static_files_allowed: Optional[List[Union[str, Pattern]]] = None\n

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or 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 = ComponentsSettings(\n    static_files_allowed=[\n        \".css\",\n        \".js\", \".jsx\", \".ts\", \".tsx\",\n        # Images\n        \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n        \".jpeg\",  \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n        \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n        # Fonts\n        \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n    ],\n)\n

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.static_files_forbidden","title":"static_files_forbidden","text":"
static_files_forbidden: Optional[List[Union[str, Pattern]]] = None\n

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs will NEVER be treated as static files.

If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in static_files_allowed.

Use this setting together with static_files_allowed for a fine control over what file types will be exposed.

You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

By default, any HTML and Python are considered NOT static files:

COMPONENTS = ComponentsSettings(\n    static_files_forbidden=[\n        \".html\", \".django\", \".dj\", \".tpl\",\n        # Python files\n        \".py\", \".pyc\",\n    ],\n)\n

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.tag_formatter","title":"tag_formatter","text":"
tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n

See source code

Configure what syntax is used inside Django templates to render components. See the available tag formatters.

Defaults to \"django_components.component_formatter\".

Learn more about Customizing component tags with TagFormatter.

Can be set either as direct reference:

from django_components import component_formatter\n\nCOMPONENTS = ComponentsSettings(\n    \"tag_formatter\": component_formatter\n)\n

Or as an import string;

COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_formatter\"\n)\n

Examples:

  • \"django_components.component_formatter\"

    Set

    COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_formatter\"\n)\n

    To write components like this:

    {% component \"button\" href=\"...\" %}\n    Click me!\n{% endcomponent %}\n
  • django_components.component_shorthand_formatter

    Set

    COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_shorthand_formatter\"\n)\n

    To write components like this:

    {% button href=\"...\" %}\n    Click me!\n{% endbutton %}\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.template_cache_size","title":"template_cache_size","text":"
template_cache_size: Optional[int] = None\n

See source code

DEPRECATED. Template caching will be removed in v1.

Configure the maximum amount of Django templates to be cached.

Defaults to 128.

Each time a Django 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 overriding Component.get_template() to render many dynamic templates, you can increase this number.

COMPONENTS = ComponentsSettings(\n    template_cache_size=256,\n)\n

To remove the cache limit altogether and cache everything, set template_cache_size to None.

COMPONENTS = ComponentsSettings(\n    template_cache_size=None,\n)\n

If you want to add templates to the cache yourself, you can use cached_template():

from django_components import cached_template\n\ncached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n    pass\n\ncached_template(\n    \"Variable: {{ variable }}\",\n    template_cls=MyTemplate,\n    name=...\n    origin=...\n    engine=...\n)\n
"},{"location":"reference/signals/","title":"Signals","text":""},{"location":"reference/signals/#signals","title":"Signals","text":"

Below are the signals that are sent by or during the use of django-components.

"},{"location":"reference/signals/#template_rendered","title":"template_rendered","text":"

Django's template_rendered signal. This signal is sent when a template is rendered.

Django-components triggers this signal when a component is rendered. If there are nested components, the signal is triggered for each component.

Import from django as django.test.signals.template_rendered.

from django.test.signals import template_rendered\n\n# Setup a callback function\ndef my_callback(sender, **kwargs):\n    ...\n\ntemplate_rendered.connect(my_callback)\n\nclass MyTable(Component):\n    template = \"\"\"\n    <table>\n        <tr>\n            <th>Header</th>\n        </tr>\n        <tr>\n            <td>Cell</td>\n        </tr>\n    \"\"\"\n\n# This will trigger the signal\nMyTable().render()\n
"},{"location":"reference/tag_formatters/","title":"Tag formatters","text":""},{"location":"reference/tag_formatters/#tag-formatters","title":"Tag Formatters","text":"

Tag formatters allow you to change the syntax for calling components from within the Django templates.

Tag formatter are set via the tag_formatter setting.

"},{"location":"reference/tag_formatters/#available-tag-formatters","title":"Available tag formatters","text":"
  • django_components.component_formatter for ComponentFormatter

  • django_components.component_shorthand_formatter for ShorthandComponentFormatter

"},{"location":"reference/tag_formatters/#django_components.tag_formatter.ComponentFormatter","title":"ComponentFormatter","text":"

Bases: django_components.tag_formatter.TagFormatterABC

See source code

The original django_component's component tag formatter, it uses the {% component %} and {% endcomponent %} tags, and the component name is given as the first positional arg.

Example as block:

{% component \"mycomp\" abc=123 %}\n    {% fill \"myfill\" %}\n        ...\n    {% endfill %}\n{% endcomponent %}\n

Example as inlined tag:

{% component \"mycomp\" abc=123 / %}\n

"},{"location":"reference/tag_formatters/#django_components.tag_formatter.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":"

Bases: django_components.tag_formatter.TagFormatterABC

See source code

The component tag formatter that uses {% <name> %} / {% end<name> %} tags.

This is similar to django-web-components and django-slippers syntax.

Example as block:

{% mycomp abc=123 %}\n    {% fill \"myfill\" %}\n        ...\n    {% endfill %}\n{% endmycomp %}\n

Example as inlined tag:

{% mycomp abc=123 / %}\n

"},{"location":"reference/template_tags/","title":"Template tags","text":""},{"location":"reference/template_tags/#template-tags","title":"Template tags","text":"

All following template tags are defined in

django_components.templatetags.component_tags

Import as

{% load component_tags %}\n

"},{"location":"reference/template_tags/#component_css_dependencies","title":"component_css_dependencies","text":"
{% component_css_dependencies  %}\n

See source code

Marks location where CSS link tags should be rendered after the whole HTML has been generated.

Generally, this should be inserted into the <head> tag of the HTML.

If the generated HTML does NOT contain any {% component_css_dependencies %} tags, CSS links are by default inserted into the <head> tag of the HTML. (See Default JS / CSS locations)

Note that there should be only one {% component_css_dependencies %} for the whole HTML document. If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.

"},{"location":"reference/template_tags/#component_js_dependencies","title":"component_js_dependencies","text":"
{% component_js_dependencies  %}\n

See source code

Marks location where JS link tags should be rendered after the whole HTML has been generated.

Generally, this should be inserted at the end of the <body> tag of the HTML.

If the generated HTML does NOT contain any {% component_js_dependencies %} tags, JS scripts are by default inserted at the end of the <body> tag of the HTML. (See Default JS / CSS locations)

Note that there should be only one {% component_js_dependencies %} for the whole HTML document. If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.

"},{"location":"reference/template_tags/#component","title":"component","text":"
{% component *args: Any, **kwargs: Any [only] %}\n{% endcomponent %}\n

See source code

Renders one of the components that was previously registered with @register() decorator.

The {% component %} tag takes:

  • Component's registered name as the first positional argument,
  • Followed by any number of positional and keyword arguments.
{% load component_tags %}\n<div>\n    {% component \"button\" name=\"John\" job=\"Developer\" / %}\n</div>\n

The component name must be a string literal.

"},{"location":"reference/template_tags/#inserting-slot-fills","title":"Inserting slot fills","text":"

If the component defined any slots, you can \"fill\" these slots by placing the {% fill %} tags within the {% component %} tag:

{% component \"my_table\" rows=rows headers=headers %}\n  {% fill \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endfill %}\n{% endcomponent %}\n

You can even nest {% fill %} tags within {% if %}, {% for %} and other tags:

{% component \"my_table\" rows=rows headers=headers %}\n    {% if rows %}\n        {% fill \"pagination\" %}\n            < 1 | 2 | 3 >\n        {% endfill %}\n    {% endif %}\n{% endcomponent %}\n
"},{"location":"reference/template_tags/#isolating-components","title":"Isolating components","text":"

By default, components behave similarly to Django's {% include %}, and the template inside the component has access to the variables defined in the outer template.

You can selectively isolate a component, using the only flag, so that the inner template can access only the data that was explicitly passed to it:

{% component \"name\" positional_arg keyword_arg=value ... only %}\n

Alternatively, you can set all components to be isolated by default, by setting context_behavior to \"isolated\" in your settings:

# settings.py\nCOMPONENTS = {\n    \"context_behavior\": \"isolated\",\n}\n
"},{"location":"reference/template_tags/#omitting-the-component-keyword","title":"Omitting the component keyword","text":"

If you would like to omit the component keyword, and simply refer to your components by their registered names:

{% button name=\"John\" job=\"Developer\" / %}\n

You can do so by setting the \"shorthand\" Tag formatter in the settings:

# settings.py\nCOMPONENTS = {\n    \"tag_formatter\": \"django_components.component_shorthand_formatter\",\n}\n
"},{"location":"reference/template_tags/#fill","title":"fill","text":"
{% fill name: str, *, data: Optional[str] = None, fallback: Optional[str] = None, body: Union[str, django.utils.safestring.SafeString, django_components.slots.SlotFunc[~TSlotData], django_components.slots.Slot[~TSlotData], NoneType] = None, default: Optional[str] = None %}\n{% endfill %}\n

See source code

Use {% fill %} tag to insert content into component's slots.

{% fill %} tag may be used only within a {% component %}..{% endcomponent %} block, and raises a TemplateSyntaxError if used outside of a component.

Args:

  • name (str, required): Name of the slot to insert this content into. Use \"default\" for the default slot.
  • data (str, optional): This argument allows you to access the data passed to the slot under the specified variable name. See Slot data.
  • fallback (str, optional): This argument allows you to access the original content of the slot under the specified variable name. See Slot fallback.

Example:

{% component \"my_table\" %}\n  {% fill \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/template_tags/#access-slot-fallback","title":"Access slot fallback","text":"

Use the fallback kwarg to access the original content of the slot.

The fallback kwarg defines the name of the variable that will contain the slot's fallback content.

Read more about Slot fallback.

Component template:

{# my_table.html #}\n<table>\n  ...\n  {% slot \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endslot %}\n</table>\n

Fill:

{% component \"my_table\" %}\n  {% fill \"pagination\" fallback=\"fallback\" %}\n    <div class=\"my-class\">\n      {{ fallback }}\n    </div>\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/template_tags/#access-slot-data","title":"Access slot data","text":"

Use the data kwarg to access the data passed to the slot.

The data kwarg defines the name of the variable that will contain the slot's data.

Read more about Slot data.

Component template:

{# my_table.html #}\n<table>\n  ...\n  {% slot \"pagination\" pages=pages %}\n    < 1 | 2 | 3 >\n  {% endslot %}\n</table>\n

Fill:

{% component \"my_table\" %}\n  {% fill \"pagination\" data=\"slot_data\" %}\n    {% for page in slot_data.pages %}\n        <a href=\"{{ page.link }}\">\n          {{ page.index }}\n        </a>\n    {% endfor %}\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/template_tags/#using-default-slot","title":"Using default slot","text":"

To access slot data and the fallback slot content on the default slot, use {% fill %} with name set to \"default\":

{% component \"button\" %}\n  {% fill name=\"default\" data=\"slot_data\" fallback=\"slot_fallback\" %}\n    You clicked me {{ slot_data.count }} times!\n    {{ slot_fallback }}\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/template_tags/#slot-fills-from-python","title":"Slot fills from Python","text":"

You can pass a slot fill from Python to a component by setting the body kwarg on the {% fill %} tag.

First pass a Slot instance to the template with the get_template_data() method:

from django_components import component, Slot\n\nclass Table(Component):\n  def get_template_data(self, args, kwargs, slots, context):\n    return {\n        \"my_slot\": Slot(lambda ctx: \"Hello, world!\"),\n    }\n

Then pass the slot to the {% fill %} tag:

{% component \"table\" %}\n  {% fill \"pagination\" body=my_slot / %}\n{% endcomponent %}\n

Warning

If you define both the body kwarg and the {% fill %} tag's body, an error will be raised.

{% component \"table\" %}\n  {% fill \"pagination\" body=my_slot %}\n    ...\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/template_tags/#html_attrs","title":"html_attrs","text":"
{% html_attrs attrs: Optional[Dict] = None, defaults: Optional[Dict] = None, **kwargs: Any %}\n

See source code

Generate HTML attributes (key=\"value\"), combining data from multiple sources, whether its template variables or static text.

It is designed to easily merge HTML attributes passed from outside as well as inside the component.

Args:

  • attrs (dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides values in the default dictionary.
  • default (str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden with values in the attrs dictionary.
  • Any extra kwargs will be appended to the corresponding keys

The attributes in attrs and defaults are merged and resulting dict is rendered as HTML attributes (key=\"value\").

Extra kwargs (key=value) are concatenated to existing keys. So if we have

attrs = {\"class\": \"my-class\"}\n

Then

{% html_attrs attrs class=\"extra-class\" %}\n

will result in class=\"my-class extra-class\".

Example:

<div {% html_attrs\n    attrs\n    defaults:class=\"default-class\"\n    class=\"extra-class\"\n    data-id=\"123\"\n%}>\n

renders

<div class=\"my-class extra-class\" data-id=\"123\">\n

See more usage examples in HTML attributes.

"},{"location":"reference/template_tags/#provide","title":"provide","text":"
{% provide name: str, **kwargs: Any %}\n{% endprovide %}\n

See source code

The {% provide %} tag is part of the \"provider\" part of the provide / inject feature.

Pass kwargs to this tag to define the provider's data.

Any components defined within the {% provide %}..{% endprovide %} tags will be able to access this data with Component.inject().

This is similar to React's ContextProvider, or Vue's provide().

Args:

  • name (str, required): Provider name. This is the name you will then use in Component.inject().
  • **kwargs: Any extra kwargs will be passed as the provided data.

Example:

Provide the \"user_data\" in parent component:

@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      <div>\n        {% provide \"user_data\" user=user %}\n          {% component \"child\" / %}\n        {% endprovide %}\n      </div>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"user\": kwargs[\"user\"],\n        }\n

Since the \"child\" component is used within the {% provide %} / {% endprovide %} tags, we can request the \"user_data\" using Component.inject(\"user_data\"):

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        User is: {{ user }}\n      </div>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        user = self.inject(\"user_data\").user\n        return {\n            \"user\": user,\n        }\n

Notice that the keys defined on the {% provide %} tag are then accessed as attributes when accessing them with Component.inject().

\u2705 Do this

user = self.inject(\"user_data\").user\n

\u274c Don't do this

user = self.inject(\"user_data\")[\"user\"]\n

"},{"location":"reference/template_tags/#slot","title":"slot","text":"
{% slot name: str, **kwargs: Any [default] [required] %}\n{% endslot %}\n

See source code

{% slot %} tag marks a place inside a component where content can be inserted from outside.

Learn more about using slots.

This is similar to slots as seen in Web components, Vue or React's children.

Args:

  • name (str, required): Registered name of the component to render
  • default: Optional flag. If there is a default slot, you can pass the component slot content without using the {% fill %} tag. See Default slot
  • required: Optional flag. Will raise an error if a slot is required but not given.
  • **kwargs: Any extra kwargs will be passed as the slot data.

Example:

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        {% slot \"content\" default %}\n          This is shown if not overriden!\n        {% endslot %}\n      </div>\n      <aside>\n        {% slot \"sidebar\" required / %}\n      </aside>\n    \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      <div>\n        {% component \"child\" %}\n          {% fill \"content\" %}\n            \ud83d\uddde\ufe0f\ud83d\udcf0\n          {% endfill %}\n\n          {% fill \"sidebar\" %}\n            \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n          {% endfill %}\n        {% endcomponent %}\n      </div>\n    \"\"\"\n
"},{"location":"reference/template_tags/#slot-data","title":"Slot data","text":"

Any extra kwargs will be considered as slot data, and will be accessible in the {% fill %} tag via fill's data kwarg:

Read more about Slot data.

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        {# Passing data to the slot #}\n        {% slot \"content\" user=user %}\n          This is shown if not overriden!\n        {% endslot %}\n      </div>\n    \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      {# Parent can access the slot data #}\n      {% component \"child\" %}\n        {% fill \"content\" data=\"data\" %}\n          <div class=\"wrapper-class\">\n            {{ data.user }}\n          </div>\n        {% endfill %}\n      {% endcomponent %}\n    \"\"\"\n
"},{"location":"reference/template_tags/#slot-fallback","title":"Slot fallback","text":"

The content between the {% slot %}..{% endslot %} tags is the fallback content that will be rendered if no fill is given for the slot.

This fallback content can then be accessed from within the {% fill %} tag using the fill's fallback kwarg. This is useful if you need to wrap / prepend / append the original slot's content.

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        {% slot \"content\" %}\n          This is fallback content!\n        {% endslot %}\n      </div>\n    \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      {# Parent can access the slot's fallback content #}\n      {% component \"child\" %}\n        {% fill \"content\" fallback=\"fallback\" %}\n          {{ fallback }}\n        {% endfill %}\n      {% endcomponent %}\n    \"\"\"\n
"},{"location":"reference/template_variables/","title":"Template variables","text":""},{"location":"reference/template_variables/#template-variables","title":"Template variables","text":"

Here is a list of all variables that are automatically available from inside the component's template:

"},{"location":"reference/template_variables/#django_components.component.ComponentVars.args","title":"args instance-attribute","text":"
args: Any\n

See source code

The args argument as passed to Component.get_template_data().

This is the same Component.args that's available on the component instance.

If you defined the Component.Args class, then the args property will return an instance of that class.

Otherwise, args will be a plain list.

Example:

With Args class:

from django_components import Component, register\n\n@register(\"table\")\nclass Table(Component):\n    class Args(NamedTuple):\n        page: int\n        per_page: int\n\n    template = '''\n        <div>\n            <h1>Table</h1>\n            <p>Page: {{ component_vars.args.page }}</p>\n            <p>Per page: {{ component_vars.args.per_page }}</p>\n        </div>\n    '''\n

Without Args class:

from django_components import Component, register\n\n@register(\"table\")\nclass Table(Component):\n    template = '''\n        <div>\n            <h1>Table</h1>\n            <p>Page: {{ component_vars.args.0 }}</p>\n            <p>Per page: {{ component_vars.args.1 }}</p>\n        </div>\n    '''\n
"},{"location":"reference/template_variables/#django_components.component.ComponentVars.kwargs","title":"kwargs instance-attribute","text":"
kwargs: Any\n

See source code

The kwargs argument as passed to Component.get_template_data().

This is the same Component.kwargs that's available on the component instance.

If you defined the Component.Kwargs class, then the kwargs property will return an instance of that class.

Otherwise, kwargs will be a plain dict.

Example:

With Kwargs class:

from django_components import Component, register\n\n@register(\"table\")\nclass Table(Component):\n    class Kwargs(NamedTuple):\n        page: int\n        per_page: int\n\n    template = '''\n        <div>\n            <h1>Table</h1>\n            <p>Page: {{ component_vars.kwargs.page }}</p>\n            <p>Per page: {{ component_vars.kwargs.per_page }}</p>\n        </div>\n    '''\n

Without Kwargs class:

from django_components import Component, register\n\n@register(\"table\")\nclass Table(Component):\n    template = '''\n        <div>\n            <h1>Table</h1>\n            <p>Page: {{ component_vars.kwargs.page }}</p>\n            <p>Per page: {{ component_vars.kwargs.per_page }}</p>\n        </div>\n    '''\n
"},{"location":"reference/template_variables/#django_components.component.ComponentVars.slots","title":"slots instance-attribute","text":"
slots: Any\n

See source code

The slots argument as passed to Component.get_template_data().

This is the same Component.slots that's available on the component instance.

If you defined the Component.Slots class, then the slots property will return an instance of that class.

Otherwise, slots will be a plain dict.

Example:

With Slots class:

from django_components import Component, SlotInput, register\n\n@register(\"table\")\nclass Table(Component):\n    class Slots(NamedTuple):\n        footer: SlotInput\n\n    template = '''\n        <div>\n            {% component \"pagination\" %}\n                {% fill \"footer\" body=component_vars.slots.footer / %}\n            {% endcomponent %}\n        </div>\n    '''\n

Without Slots class:

from django_components import Component, SlotInput, register\n\n@register(\"table\")\nclass Table(Component):\n    template = '''\n        <div>\n            {% component \"pagination\" %}\n                {% fill \"footer\" body=component_vars.slots.footer / %}\n            {% endcomponent %}\n        </div>\n    '''\n
"},{"location":"reference/template_variables/#django_components.component.ComponentVars.is_filled","title":"is_filled instance-attribute","text":"
is_filled: Dict[str, bool]\n

See source code

Deprecated. Will be removed in v1. Use component_vars.slots instead. Note that component_vars.slots no longer escapes the slot names.

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

New in version 0.70

Use as {{ component_vars.is_filled }}

Example:

{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n    <div class=\"slot-wrapper\">\n        {% slot \"my_slot\" / %}\n    </div>\n{% endif %}\n

This is equivalent to checking if a given key is among the slot fills:

class MyTable(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"my_slot_filled\": \"my_slot\" in slots\n        }\n
"},{"location":"reference/testing_api/","title":"Testing API","text":""},{"location":"reference/testing_api/#testing-api","title":"Testing API","text":""},{"location":"reference/testing_api/#django_components.testing.djc_test","title":"djc_test","text":"
djc_test(\n    django_settings: Union[Optional[Dict], Callable, Type] = None,\n    components_settings: Optional[Dict] = None,\n    parametrize: Optional[\n        Union[\n            Tuple[Sequence[str], Sequence[Sequence[Any]]],\n            Tuple[\n                Sequence[str],\n                Sequence[Sequence[Any]],\n                Optional[Union[Iterable[Union[None, str, float, int, bool]], Callable[[Any], Optional[object]]]],\n            ],\n        ]\n    ] = None,\n    gc_collect: bool = True,\n) -> Callable\n

See source code

Decorator for testing components from django-components.

@djc_test manages the global state of django-components, ensuring that each test is properly isolated and that components registered in one test do not affect other tests.

This decorator can be applied to a function, method, or a class. If applied to a class, it will search for all methods that start with test_, and apply the decorator to them. This is applied recursively to nested classes as well.

Examples:

Applying to a function:

from django_components.testing import djc_test\n\n@djc_test\ndef test_my_component():\n    @register(\"my_component\")\n    class MyComponent(Component):\n        template = \"...\"\n    ...\n

Applying to a class:

from django_components.testing import djc_test\n\n@djc_test\nclass TestMyComponent:\n    def test_something(self):\n        ...\n\n    class Nested:\n        def test_something_else(self):\n            ...\n

Applying to a class is the same as applying the decorator to each test_ method individually:

from django_components.testing import djc_test\n\nclass TestMyComponent:\n    @djc_test\n    def test_something(self):\n        ...\n\n    class Nested:\n        @djc_test\n        def test_something_else(self):\n            ...\n

To use @djc_test, Django must be set up first:

import django\nfrom django_components.testing import djc_test\n\ndjango.setup()\n\n@djc_test\ndef test_my_component():\n    ...\n

Arguments:

  • django_settings: Django settings, a dictionary passed to Django's @override_settings. The test runs within the context of these overridden settings.

    If django_settings contains django-components settings (COMPONENTS field), these are merged. Other Django settings are simply overridden.

  • components_settings: Instead of defining django-components settings under django_settings[\"COMPONENTS\"], you can simply set the Components settings here.

    These settings are merged with the django-components settings from django_settings[\"COMPONENTS\"].

    Fields in components_settings override fields in django_settings[\"COMPONENTS\"].

  • parametrize: Parametrize the test function with pytest.mark.parametrize. This requires pytest to be installed.

    The input is a tuple of:

    • (param_names, param_values) or
    • (param_names, param_values, ids)

    Example:

    from django_components.testing import djc_test\n\n@djc_test(\n    parametrize=(\n         [\"input\", \"expected\"],\n         [[1, \"<div>1</div>\"], [2, \"<div>2</div>\"]],\n         ids=[\"1\", \"2\"]\n     )\n)\ndef test_component(input, expected):\n    rendered = MyComponent(input=input).render()\n    assert rendered == expected\n

    You can parametrize the Django or Components settings by setting up parameters called django_settings and components_settings. These will be merged with the respetive settings from the decorator.

    Example of parametrizing context_behavior:

    from django_components.testing import djc_test\n\n@djc_test(\n    components_settings={\n        # Settings shared by all tests\n        \"app_dirs\": [\"custom_dir\"],\n    },\n    parametrize=(\n        # Parametrized settings\n        [\"components_settings\"],\n        [\n            [{\"context_behavior\": \"django\"}],\n            [{\"context_behavior\": \"isolated\"}],\n        ],\n        [\"django\", \"isolated\"],\n    )\n)\ndef test_context_behavior(components_settings):\n    rendered = MyComponent.render()\n    ...\n

  • gc_collect: By default djc_test runs garbage collection after each test to force the state cleanup. Set this to False to skip this.

Settings resolution:

@djc_test accepts settings from different sources. The settings are resolved in the following order:

  • Django settings:

    1. The defaults are the Django settings that Django was set up with.
    2. Those are then overriden with fields in the django_settings kwarg.
    3. The parametrized django_settings override the fields on the django_settings kwarg.

    Priority: django_settings (parametrized) > django_settings > django.conf.settings

  • Components settings:

    1. Same as above, except that the django_settings[\"COMPONENTS\"] field is merged instead of overridden.
    2. The components_settings kwarg is then merged with the django_settings[\"COMPONENTS\"] field.
    3. The parametrized components_settings override the fields on the components_settings kwarg.

    Priority: components_settings (parametrized) > components_settings > django_settings[\"COMPONENTS\"] > django.conf.settings.COMPONENTS

"},{"location":"reference/urls/","title":"URLs","text":""},{"location":"reference/urls/#urls","title":"URLs","text":"

Below are all the URL patterns that will be added by adding django_components.urls.

See Installation on how to add these URLs to your Django project.

Django components already prefixes all URLs with components/. So when you are adding the URLs to urlpatterns, you can use an empty string as the first argument:

from django.urls import include, path\n\nurlpatterns = [\n    ...\n    path(\"\", include(\"django_components.urls\")),\n]\n
"},{"location":"reference/urls/#list-of-urls","title":"List of URLs","text":"
  • components/cache/<str:comp_cls_id>.<str:input_hash>.<str:script_type>

  • components/cache/<str:comp_cls_id>.<str:script_type>

"}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Welcome to Django Components","text":"

django-components combines Django's templating system with the modularity seen in modern frontend frameworks like Vue or React.

With django-components you can support Django projects small and large without leaving the Django ecosystem.

"},{"location":"#quickstart","title":"Quickstart","text":"

A component in django-components can be as simple as a Django template and Python code to declare the component:

components/calendar/calendar.html
<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n
components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n

Or a combination of Django template, Python, CSS, and Javascript:

components/calendar/calendar.html
<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n
components/calendar/calendar.css
.calendar {\n  width: 200px;\n  background: pink;\n}\n
components/calendar/calendar.js
document.querySelector(\".calendar\").onclick = () => {\n  alert(\"Clicked calendar!\");\n};\n
components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    js_file = \"calendar.js\"\n    css_file = \"calendar.css\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\"date\": kwargs[\"date\"]}\n

Use the component like this:

{% component \"calendar\" date=\"2024-11-06\" %}{% endcomponent %}\n

And this is what gets rendered:

<div class=\"calendar-component\">\n  Today's date is <span>2024-11-06</span>\n</div>\n

Read on to learn about all the exciting details and configuration possibilities!

(If you instead prefer to jump right into the code, check out the example project)

"},{"location":"#features","title":"Features","text":""},{"location":"#modern-and-modular-ui","title":"Modern and modular UI","text":"
  • Create self-contained, reusable UI elements.
  • Each component can include its own HTML, CSS, and JS, or additional third-party JS and CSS.
  • HTML, CSS, and JS can be defined on the component class, or loaded from files.
from django_components import Component\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template = \"\"\"\n        <div class=\"calendar\">\n            Today's date is\n            <span>{{ date }}</span>\n        </div>\n    \"\"\"\n\n    css = \"\"\"\n        .calendar {\n            width: 200px;\n            background: pink;\n        }\n    \"\"\"\n\n    js = \"\"\"\n        document.querySelector(\".calendar\")\n            .addEventListener(\"click\", () => {\n                alert(\"Clicked calendar!\");\n            });\n    \"\"\"\n\n    # Additional JS and CSS\n    class Media:\n        js = [\"https://cdn.jsdelivr.net/npm/htmx.org@2/dist/htmx.min.js\"]\n        css = [\"bootstrap/dist/css/bootstrap.min.css\"]\n\n    # Variables available in the template\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"date\"]\n        }\n
"},{"location":"#composition-with-slots","title":"Composition with slots","text":"
  • Render components inside templates with {% component %} tag.
  • Compose them with {% slot %} and {% fill %} tags.
  • Vue-like slot system, including scoped slots.
{% component \"Layout\"\n    bookmarks=bookmarks\n    breadcrumbs=breadcrumbs\n%}\n    {% fill \"header\" %}\n        <div class=\"flex justify-between gap-x-12\">\n            <div class=\"prose\">\n                <h3>{{ project.name }}</h3>\n            </div>\n            <div class=\"font-semibold text-gray-500\">\n                {{ project.start_date }} - {{ project.end_date }}\n            </div>\n        </div>\n    {% endfill %}\n\n    {# Access data passed to `{% slot %}` with `data` #}\n    {% fill \"tabs\" data=\"tabs_data\" %}\n        {% component \"TabItem\" header=\"Project Info\" %}\n            {% component \"ProjectInfo\"\n                project=project\n                project_tags=project_tags\n                attrs:class=\"py-5\"\n                attrs:width=tabs_data.width\n            / %}\n        {% endcomponent %}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"#extended-template-tags","title":"Extended template tags","text":"

django-components is designed for flexibility, making working with templates a breeze.

It extends Django's template tags syntax with:

  • Literal lists and dictionaries in the template
  • Self-closing tags {% mytag / %}
  • Multi-line template tags
  • Spread operator ... to dynamically pass args or kwargs into the template tag
  • Template tags inside literal strings like \"{{ first_name }} {{ last_name }}\"
  • Pass dictonaries by their key-value pairs attr:key=val
{% component \"table\"\n    ...default_attrs\n    title=\"Friend list for {{ user.name }}\"\n    headers=[\"Name\", \"Age\", \"Email\"]\n    data=[\n        {\n            \"name\": \"John\"|upper,\n            \"age\": 30|add:1,\n            \"email\": \"john@example.com\",\n            \"hobbies\": [\"reading\"],\n        },\n        {\n            \"name\": \"Jane\"|upper,\n            \"age\": 25|add:1,\n            \"email\": \"jane@example.com\",\n            \"hobbies\": [\"reading\", \"coding\"],\n        },\n    ],\n    attrs:class=\"py-4 ma-2 border-2 border-gray-300 rounded-md\"\n/ %}\n

You too can define template tags with these features by using @template_tag() or BaseNode.

Read more on Custom template tags.

"},{"location":"#full-programmatic-access","title":"Full programmatic access","text":"

When you render a component, you can access everything about the component:

  • Component input: args, kwargs, slots and context
  • Component's template, CSS and JS
  • Django's context processors
  • Unique render ID
class Table(Component):\n    js_file = \"table.js\"\n    css_file = \"table.css\"\n\n    template = \"\"\"\n        <div class=\"table\">\n            <span>{{ variable }}</span>\n        </div>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        # Access component's ID\n        assert self.id == \"djc1A2b3c\"\n\n        # Access component's inputs and slots\n        assert self.args == [123, \"str\"]\n        assert self.kwargs == {\"variable\": \"test\", \"another\": 1}\n        footer_slot = self.slots[\"footer\"]\n        some_var = self.context[\"some_var\"]\n\n        # Access the request object and Django's context processors, if available\n        assert self.request.GET == {\"query\": \"something\"}\n        assert self.context_processors_data['user'].username == \"admin\"\n\n        return {\n            \"variable\": kwargs[\"variable\"],\n        }\n\n# Access component's HTML / JS / CSS\nTable.template\nTable.js\nTable.css\n\n# Render the component\nrendered = Table.render(\n    kwargs={\"variable\": \"test\", \"another\": 1},\n    args=(123, \"str\"),\n    slots={\"footer\": \"MY_FOOTER\"},\n)\n
"},{"location":"#granular-html-attributes","title":"Granular HTML attributes","text":"

Use the {% html_attrs %} template tag to render HTML attributes.

It supports:

  • Defining attributes as whole dictionaries or keyword arguments
  • Merging attributes from multiple sources
  • Boolean attributes
  • Appending attributes
  • Removing attributes
  • Defining default attributes
<div\n    {% html_attrs\n        attrs\n        defaults:class=\"default-class\"\n        class=\"extra-class\"\n    %}\n>\n

{% html_attrs %} offers a Vue-like granular control for class and style HTML attributes, where you can use a dictionary to manage each class name or style property separately.

{% html_attrs\n    class=\"foo bar\"\n    class={\n        \"baz\": True,\n        \"foo\": False,\n    }\n    class=\"extra\"\n%}\n
{% html_attrs\n    style=\"text-align: center; background-color: blue;\"\n    style={\n        \"background-color\": \"green\",\n        \"color\": None,\n        \"width\": False,\n    }\n    style=\"position: absolute; height: 12px;\"\n%}\n

Read more about HTML attributes.

"},{"location":"#html-fragment-support","title":"HTML fragment support","text":"

django-components makes integration with HTMX, AlpineJS or jQuery easy by allowing components to be rendered as HTML fragments:

  • Components's JS and CSS files are loaded automatically when the fragment is inserted into the DOM.

  • Components can be exposed as Django Views with get(), post(), put(), patch(), delete() methods

  • Automatically create an endpoint for a component with Component.View.public

# components/calendar/calendar.py\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n\n    class View:\n        # Register Component with `urlpatterns`\n        public = True\n\n        # Define handlers\n        def get(self, request, *args, **kwargs):\n            page = request.GET.get(\"page\", 1)\n            return self.component.render_to_response(\n                request=request,\n                kwargs={\n                    \"page\": page,\n                },\n            )\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"page\": kwargs[\"page\"],\n        }\n\n# Get auto-generated URL for the component\nurl = get_component_url(Calendar)\n\n# Or define explicit URL in urls.py\npath(\"calendar/\", Calendar.as_view())\n
"},{"location":"#provide-inject","title":"Provide / Inject","text":"

django-components supports the provide / inject pattern, similarly to React's Context Providers or Vue's provide / inject:

  • Use the {% provide %} tag to provide data to the component tree
  • Use the Component.inject() method to inject data into the component

Read more about Provide / Inject.

<body>\n    {% provide \"theme\" variant=\"light\" %}\n        {% component \"header\" / %}\n    {% endprovide %}\n</body>\n
@register(\"header\")\nclass Header(Component):\n    template = \"...\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        theme = self.inject(\"theme\").variant\n        return {\n            \"theme\": theme,\n        }\n
"},{"location":"#input-validation-and-static-type-hints","title":"Input validation and static type hints","text":"

Avoid needless errors with type hints and runtime input validation.

To opt-in to input validation, define types for component's args, kwargs, slots:

from typing import NamedTuple, Optional\nfrom django.template import Context\nfrom django_components import Component, Slot, SlotInput\n\nclass Button(Component):\n    class Args(NamedTuple):\n        size: int\n        text: str\n\n    class Kwargs(NamedTuple):\n        variable: str\n        another: int\n        maybe_var: Optional[int] = None  # May be omitted\n\n    class Slots(NamedTuple):\n        my_slot: Optional[SlotInput] = None\n        another_slot: SlotInput\n\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        args.size  # int\n        kwargs.variable  # str\n        slots.my_slot  # Slot[MySlotData]\n

To have type hints when calling Button.render() or Button.render_to_response(), wrap the inputs in their respective Args, Kwargs, and Slots classes:

Button.render(\n    # Error: First arg must be `int`, got `float`\n    args=Button.Args(\n        size=1.25,\n        text=\"abc\",\n    ),\n    # Error: Key \"another\" is missing\n    kwargs=Button.Kwargs(\n        variable=\"text\",\n    ),\n)\n
"},{"location":"#extensions","title":"Extensions","text":"

Django-components functionality can be extended with Extensions. Extensions allow for powerful customization and integrations. They can:

  • Tap into lifecycle events, such as when a component is created, deleted, or registered
  • Add new attributes and methods to the components
  • Add custom CLI commands
  • Add custom URLs

Some of the extensions include:

  • Component caching
  • Django View integration
  • Component defaults
  • Pydantic integration (input validation)

Some of the planned extensions include:

  • AlpineJS integration
  • Storybook integration
  • Component-level benchmarking with asv
"},{"location":"#caching","title":"Caching","text":"
  • Components can be cached using Django's cache framework.
  • Caching rules can be configured on a per-component basis.
  • Components are cached based on their input. Or you can write custom caching logic.
from django_components import Component\n\nclass MyComponent(Component):\n    class Cache:\n        enabled = True\n        ttl = 60 * 60 * 24  # 1 day\n\n        def hash(self, *args, **kwargs):\n            return hash(f\"{json.dumps(args)}:{json.dumps(kwargs)}\")\n
"},{"location":"#simple-testing","title":"Simple testing","text":"
  • Write tests for components with @djc_test decorator.
  • The decorator manages global state, ensuring that tests don't leak.
  • If using pytest, the decorator allows you to parametrize Django or Components settings.
  • The decorator also serves as a stand-in for Django's @override_settings.
from django_components.testing import djc_test\n\nfrom components.my_table import MyTable\n\n@djc_test\ndef test_my_table():\n    rendered = MyTable.render(\n        kwargs={\n            \"title\": \"My table\",\n        },\n    )\n    assert rendered == \"<table>My table</table>\"\n
"},{"location":"#debugging-features","title":"Debugging features","text":"
  • Visual component inspection: Highlight components and slots directly in your browser.
  • Detailed tracing logs to supply AI-agents with context: The logs include component and slot names and IDs, and their position in the tree.
"},{"location":"#sharing-components","title":"Sharing components","text":"
  • Install and use third-party components from PyPI
  • Or publish your own \"component registry\"
  • Highly customizable - Choose how the components are called in the template (and more):

    {% component \"calendar\" date=\"2024-11-06\" %}\n{% endcomponent %}\n\n{% calendar date=\"2024-11-06\" %}\n{% endcalendar %}\n
"},{"location":"#performance","title":"Performance","text":"

Our aim is to be at least as fast as Django templates.

As of 0.130, django-components is ~4x slower than Django templates.

Render time django 68.9\u00b10.6ms django-components 259\u00b14ms

See the full performance breakdown for more information.

"},{"location":"#release-notes","title":"Release notes","text":"

Read the Release Notes to see the latest features and fixes.

"},{"location":"#community-examples","title":"Community examples","text":"

One of our goals with django-components is to make it easy to share components between projects. Head over to the Community examples to see some examples.

"},{"location":"#contributing-and-development","title":"Contributing and development","text":"

Get involved or sponsor this project - See here

Running django-components locally for development - See here

"},{"location":"migrating_from_safer_staticfiles/","title":"Migrating from safer_staticfiles","text":"

This guide is for you if you're upgrating django_components to v0.100 or later from older versions.

In version 0.100, we changed how components' static JS and CSS files are handled. See more in the \"Static files\" section.

Migration steps:

  1. Remove django_components.safer_staticfiles from INSTALLED_APPS in your settings.py, and replace it with django.contrib.staticfiles.

Before:

INSTALLED_APPS = [\n   \"django.contrib.admin\",\n   ...\n   # \"django.contrib.staticfiles\",  # <-- ADD\n   \"django_components\",\n   \"django_components.safer_staticfiles\",  # <-- REMOVE\n]\n

After:

INSTALLED_APPS = [\n   \"django.contrib.admin\",\n   ...\n   \"django.contrib.staticfiles\",\n   \"django_components\",\n]\n
  1. Add STATICFILES_FINDERS to settings.py, and add django_components.finders.ComponentsFileSystemFinder:
STATICFILES_FINDERS = [\n   # Default finders\n   \"django.contrib.staticfiles.finders.FileSystemFinder\",\n   \"django.contrib.staticfiles.finders.AppDirectoriesFinder\",\n   # Django components\n   \"django_components.finders.ComponentsFileSystemFinder\",  # <-- ADDED\n]\n
  1. Add COMPONENTS.dirs to settings.py.

If you previously defined STATICFILES_DIRS, move only those directories from STATICFILES_DIRS that point to components directories, and keep the rest.

E.g. if you have STATICFILES_DIRS like this:

STATICFILES_DIRS = [\n   BASE_DIR / \"components\",  # <-- MOVE\n   BASE_DIR / \"myapp\" / \"components\",  # <-- MOVE\n   BASE_DIR / \"assets\",\n]\n

Then first two entries point to components dirs, whereas /assets points to non-component static files. In this case move only the first two paths:

COMPONENTS = {\n   \"dirs\": [\n      BASE_DIR / \"components\",  # <-- MOVED\n      BASE_DIR / \"myapp\" / \"components\",  # <-- MOVED\n   ],\n}\n\nSTATICFILES_DIRS = [\n   BASE_DIR / \"assets\",\n]\n

Moreover, if you defined app-level component directories in STATICFILES_DIRS before, you can now define as a RELATIVE path in app_dirs:

COMPONENTS = {\n   \"dirs\": [\n      # Search top-level \"/components/\" dir\n      BASE_DIR / \"components\",\n   ],\n   \"app_dirs\": [\n      # Search \"/[app]/components/\" dirs\n      \"components\",\n   ],\n}\n\nSTATICFILES_DIRS = [\n   BASE_DIR / \"assets\",\n]\n
"},{"location":"release_notes/","title":"Release notes","text":""},{"location":"release_notes/#v01412","title":"v0.141.2","text":""},{"location":"release_notes/#fix","title":"Fix","text":"
  • Fix bug where JS and CSS were missing when {% component %} tag was inside {% include %} tag (#1296)
"},{"location":"release_notes/#v01411","title":"v0.141.1","text":""},{"location":"release_notes/#fix_1","title":"Fix","text":"
  • Components' JS and CSS scripts (e.g. from Component.js or Component.js_file) are now cached at class creation time.

    This means that when you now restart the server while having a page opened in the browser, the JS / CSS files are immediately available.

    Previously, the JS/CSS were cached only after the components were rendered. So you had to reload the page to trigger the rendering, in order to make the JS/CSS files available.

  • Fix the default cache for JS / CSS scripts to be unbounded.

    Previously, the default cache for the JS/CSS scripts (LocMemCache) was accidentally limited to 300 entries (~150 components).

  • Do not send template_rendered signal when rendering a component with no template. (#1277)

"},{"location":"release_notes/#v01410","title":"v0.141.0","text":""},{"location":"release_notes/#feat","title":"Feat","text":"
  • New extension hooks on_template_loaded, on_js_loaded, on_css_loaded, and on_template_compiled

    The first 3 hooks are called when Component's template / JS / CSS is loaded as a string.

    The on_template_compiled hook is called when Component's template is compiled to a Template.

    The on_xx_loaded hooks can modify the content by returning the new value.

    class MyExtension(ComponentExtension):\n    def on_template_loaded(self, ctx: OnTemplateLoadedContext) -> Optional[str]:\n        return ctx.content + \"<!-- Hello! -->\"\n\n    def on_js_loaded(self, ctx: OnJsLoadedContext) -> Optional[str]:\n        return ctx.content + \"// Hello!\"\n\n    def on_css_loaded(self, ctx: OnCssLoadedContext) -> Optional[str]:\n        return ctx.content + \"/* Hello! */\"\n

    See all Extension hooks.

"},{"location":"release_notes/#fix_2","title":"Fix","text":"
  • Subclassing - Previously, if a parent component defined Component.template or Component.template_file, it's subclass would use the same Template instance.

    This could lead to unexpected behavior, where a change to the template of the subclass would also change the template of the parent class.

    Now, each subclass has it's own Template instance, and changes to the template of the subclass do not affect the template of the parent class.

  • Fix Django failing to restart due to \"TypeError: 'Dynamic' object is not iterable\" (#1232)

  • Fix bug when error formatting failed when error value was not a string.

"},{"location":"release_notes/#refactor","title":"Refactor","text":"
  • components ext run CLI command now allows to call only those extensions that actually have subcommands.
"},{"location":"release_notes/#v01401","title":"v0.140.1","text":""},{"location":"release_notes/#fix_3","title":"Fix","text":"
  • Fix typo preventing benchmarking (#1235)
"},{"location":"release_notes/#v01400","title":"\ud83d\udea8\ud83d\udce2 v0.140.0","text":"

\u26a0\ufe0f Major release \u26a0\ufe0f - Please test thoroughly before / after upgrading.

This is the biggest step towards v1. While this version introduces many small API changes, we don't expect to make further changes to the affected parts before v1.

For more details see #433.

Summary:

  • Overhauled typing system
  • Middleware removed, no longer needed
  • get_template_data() is the new canonical way to define template data. get_context_data() is now deprecated but will remain until v2.
  • Slots API polished and prepared for v1.
  • Merged Component.Url with Component.View
  • Added Component.args, Component.kwargs, Component.slots, Component.context
  • Added {{ component_vars.args }}, {{ component_vars.kwargs }}, {{ component_vars.slots }}
  • You should no longer instantiate Component instances. Instead, call Component.render() or Component.render_to_response() directly.
  • Component caching can now consider slots (opt-in)
  • And lot more...
"},{"location":"release_notes/#breaking-changes","title":"\ud83d\udea8\ud83d\udce2 BREAKING CHANGES","text":"

Middleware

  • The middleware ComponentDependencyMiddleware was removed as it is no longer needed.

    The middleware served one purpose - to render the JS and CSS dependencies of components when you rendered templates with Template.render() or django.shortcuts.render() and those templates contained {% component %} tags.

    • NOTE: If you rendered HTML with Component.render() or Component.render_to_response(), the JS and CSS were already rendered.

    Now, the JS and CSS dependencies of components are automatically rendered, even when you render Templates with Template.render() or django.shortcuts.render().

    To disable this behavior, set the DJC_DEPS_STRATEGY context key to \"ignore\" when rendering the template:

    # With `Template.render()`:\ntemplate = Template(template_str)\nrendered = template.render(Context({\"DJC_DEPS_STRATEGY\": \"ignore\"}))\n\n# Or with django.shortcuts.render():\nfrom django.shortcuts import render\nrendered = render(\n    request,\n    \"my_template.html\",\n    context={\"DJC_DEPS_STRATEGY\": \"ignore\"},\n)\n

    In fact, you can set the DJC_DEPS_STRATEGY context key to any of the strategies:

    • \"document\"
    • \"fragment\"
    • \"simple\"
    • \"prepend\"
    • \"append\"
    • \"ignore\"

    See Dependencies rendering for more info.

Typing

  • Component typing no longer uses generics. Instead, the types are now defined as class attributes of the component class.

    Before:

    Args = Tuple[float, str]\n\nclass Button(Component[Args]):\n    pass\n

    After:

    class Button(Component):\n    class Args(NamedTuple):\n        size: float\n        text: str\n

    See Migrating from generics to class attributes for more info. - Removed EmptyTuple and EmptyDict types. Instead, there is now a single Empty type.

    from django_components import Component, Empty\n\nclass Button(Component):\n    template = \"Hello\"\n\n    Args = Empty\n    Kwargs = Empty\n

Component API

  • The interface of the not-yet-released get_js_data() and get_css_data() methods has changed to match get_template_data().

    Before:

    def get_js_data(self, *args, **kwargs):\ndef get_css_data(self, *args, **kwargs):\n

    After:

    def get_js_data(self, args, kwargs, slots, context):\ndef get_css_data(self, args, kwargs, slots, context):\n
  • Arguments in Component.render_to_response() have changed to match that of Component.render().

    Please ensure that you pass the parameters as kwargs, not as positional arguments, to avoid breaking changes.

    The signature changed, moving the args and kwargs parameters to 2nd and 3rd position.

    Next, the render_dependencies parameter was added to match Component.render().

    Lastly:

    • Previously, any extra ARGS and KWARGS were passed to the response_class.
    • Now, only extra KWARGS will be passed to the response_class.

    Before:

      def render_to_response(\n      cls,\n      context: Optional[Union[Dict[str, Any], Context]] = None,\n      slots: Optional[SlotsType] = None,\n      escape_slots_content: bool = True,\n      args: Optional[ArgsType] = None,\n      kwargs: Optional[KwargsType] = None,\n      deps_strategy: DependenciesStrategy = \"document\",\n      request: Optional[HttpRequest] = None,\n      *response_args: Any,\n      **response_kwargs: Any,\n  ) -> HttpResponse:\n

    After:

    def render_to_response(\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    args: Optional[Any] = None,\n    kwargs: Optional[Any] = None,\n    slots: Optional[Any] = None,\n    deps_strategy: DependenciesStrategy = \"document\",\n    type: Optional[DependenciesStrategy] = None,  # Deprecated, use `deps_strategy`\n    render_dependencies: bool = True,  # Deprecated, use `deps_strategy=\"ignore\"`\n    outer_context: Optional[Context] = None,\n    request: Optional[HttpRequest] = None,\n    registry: Optional[ComponentRegistry] = None,\n    registered_name: Optional[str] = None,\n    node: Optional[ComponentNode] = None,\n    **response_kwargs: Any,\n) -> HttpResponse:\n
  • Component.render() and Component.render_to_response() NO LONGER accept escape_slots_content kwarg.

    Instead, slots are now always escaped.

    To disable escaping, wrap the result of slots in mark_safe().

    Before:

    html = component.render(\n    slots={\"my_slot\": \"CONTENT\"},\n    escape_slots_content=False,\n)\n

    After:

    html = component.render(\n    slots={\"my_slot\": mark_safe(\"CONTENT\")}\n)\n
  • Component.template no longer accepts a Template instance, only plain string.

    Before:

    class MyComponent(Component):\n    template = Template(\"{{ my_var }}\")\n

    Instead, either:

    1. Set Component.template to a plain string.

      class MyComponent(Component):\n    template = \"{{ my_var }}\"\n
    2. Move the template to it's own HTML file and set Component.template_file.

      class MyComponent(Component):\n    template_file = \"my_template.html\"\n
    3. Or, if you dynamically created the template, render the template inside Component.on_render().

      class MyComponent(Component):\n    def on_render(self, context, template):\n        dynamic_template = do_something_dynamic()\n        return dynamic_template.render(context)\n
  • Subclassing of components with None values has changed:

    Previously, when a child component's template / JS / CSS attributes were set to None, the child component still inherited the parent's template / JS / CSS.

    Now, the child component will not inherit the parent's template / JS / CSS if it sets the attribute to None.

    Before:

    class Parent(Component):\n    template = \"parent.html\"\n\nclass Child(Parent):\n    template = None\n\n# Child still inherited parent's template\nassert Child.template == Parent.template\n

    After:

    class Parent(Component):\n    template = \"parent.html\"\n\nclass Child(Parent):\n    template = None\n\n# Child does not inherit parent's template\nassert Child.template is None\n
  • The Component.Url class was merged with Component.View.

    Instead of Component.Url.public, use Component.View.public.

    If you imported ComponentUrl from django_components, you need to update your import to ComponentView.

    Before:

    class MyComponent(Component):\n    class Url:\n        public = True\n\n    class View:\n        def get(self, request):\n            return self.render_to_response()\n

    After:

    class MyComponent(Component):\n    class View:\n        public = True\n\n        def get(self, request):\n            return self.render_to_response()\n
  • Caching - The function signatures of Component.Cache.get_cache_key() and Component.Cache.hash() have changed to enable passing slots.

    Args and kwargs are no longer spread, but passed as a list and a dict, respectively.

    Before:

    def get_cache_key(self, *args: Any, **kwargs: Any) -> str:\n\ndef hash(self, *args: Any, **kwargs: Any) -> str:\n

    After:

    def get_cache_key(self, args: Any, kwargs: Any, slots: Any) -> str:\n\ndef hash(self, args: Any, kwargs: Any) -> str:\n

Template tags

  • Component name in the {% component %} tag can no longer be set as a kwarg.

    Instead, the component name MUST be the first POSITIONAL argument only.

    Before, it was possible to set the component name as a kwarg and put it anywhere in the {% component %} tag:

    {% component rows=rows headers=headers name=\"my_table\" ... / %}\n

    Now, the component name MUST be the first POSITIONAL argument:

    {% component \"my_table\" rows=rows headers=headers ... / %}\n

    Thus, the name kwarg can now be used as a regular input.

    {% component \"profile\" name=\"John\" job=\"Developer\" / %}\n

Slots

  • If you instantiated Slot class with kwargs, you should now use contents instead of content_func.

    Before:

    slot = Slot(content_func=lambda *a, **kw: \"CONTENT\")\n

    After:

    slot = Slot(contents=lambda ctx: \"CONTENT\")\n

    Alternatively, pass the function / content as first positional argument:

    slot = Slot(lambda ctx: \"CONTENT\")\n
  • The undocumented Slot.escaped attribute was removed.

    Instead, slots are now always escaped.

    To disable escaping, wrap the result of slots in mark_safe().

  • Slot functions behavior has changed. See the new Slots docs for more info.

    • Function signature:

      1. All parameters are now passed under a single ctx argument.

        You can still access all the same parameters via ctx.context, ctx.data, and ctx.fallback.

      2. context and fallback now may be None if the slot function was called outside of {% slot %} tag.

      Before:

      def slot_fn(context: Context, data: Dict, slot_ref: SlotRef):\n    isinstance(context, Context)\n    isinstance(data, Dict)\n    isinstance(slot_ref, SlotRef)\n\n    return \"CONTENT\"\n

      After:

      def slot_fn(ctx: SlotContext):\n    assert isinstance(ctx.context, Context) # May be None\n    assert isinstance(ctx.data, Dict)\n    assert isinstance(ctx.fallback, SlotFallback) # May be None\n\n    return \"CONTENT\"\n
    • Calling slot functions:

      1. Rather than calling the slot functions directly, you should now call the Slot instances.

      2. All parameters are now optional.

      3. The order of parameters has changed.

      Before:

      def slot_fn(context: Context, data: Dict, slot_ref: SlotRef):\n    return \"CONTENT\"\n\nhtml = slot_fn(context, data, slot_ref)\n

      After:

      def slot_fn(ctx: SlotContext):\n    return \"CONTENT\"\n\nslot = Slot(slot_fn)\nhtml = slot()\nhtml = slot({\"data1\": \"abc\", \"data2\": \"hello\"})\nhtml = slot({\"data1\": \"abc\", \"data2\": \"hello\"}, fallback=\"FALLBACK\")\n
    • Usage in components:

      Before:

      class MyComponent(Component):\n    def get_context_data(self, *args, **kwargs):\n        slots = self.input.slots\n        slot_fn = slots[\"my_slot\"]\n        html = slot_fn(context, data, slot_ref)\n        return {\n            \"html\": html,\n        }\n

      After:

      class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        slot_fn = slots[\"my_slot\"]\n        html = slot_fn(data)\n        return {\n            \"html\": html,\n        }\n

Miscellaneous

  • The second argument to render_dependencies() is now strategy instead of type.

    Before:

    render_dependencies(content, type=\"document\")\n

    After:

    render_dependencies(content, strategy=\"document\")\n
"},{"location":"release_notes/#deprecation","title":"\ud83d\udea8\ud83d\udce2 Deprecation","text":"

Component API

  • Component.get_context_data() is now deprecated. Use Component.get_template_data() instead.

    get_template_data() behaves the same way, but has a different function signature to accept also slots and context.

    Since get_context_data() is widely used, it will remain available until v2.

  • Component.get_template_name() and Component.get_template() are now deprecated. Use Component.template, Component.template_file or Component.on_render() instead.

    Component.get_template_name() and Component.get_template() will be removed in v1.

    In v1, each Component will have at most one static template. This is needed to enable support for Markdown, Pug, or other pre-processing of templates by extensions.

    If you are using the deprecated methods to point to different templates, there's 2 ways to migrate:

    1. Split the single Component into multiple Components, each with its own template. Then switch between them in Component.on_render():

      class MyComponentA(Component):\n    template_file = \"a.html\"\n\nclass MyComponentB(Component):\n    template_file = \"b.html\"\n\nclass MyComponent(Component):\n    def on_render(self, context, template):\n        if context[\"a\"]:\n            return MyComponentA.render(context)\n        else:\n            return MyComponentB.render(context)\n
    2. Alternatively, use Component.on_render() with Django's get_template() to dynamically render different templates:

      from django.template.loader import get_template\n\nclass MyComponent(Component):\n    def on_render(self, context, template):\n        if context[\"a\"]:\n            template_name = \"a.html\"\n        else:\n            template_name = \"b.html\"\n\n        actual_template = get_template(template_name)\n        return actual_template.render(context)\n

    Read more in django-components#1204.

  • The type kwarg in Component.render() and Component.render_to_response() is now deprecated. Use deps_strategy instead. The type kwarg will be removed in v1.

    Before:

    Calendar.render_to_response(type=\"fragment\")\n

    After:

    Calendar.render_to_response(deps_strategy=\"fragment\")\n
  • The render_dependencies kwarg in Component.render() and Component.render_to_response() is now deprecated. Use deps_strategy=\"ignore\" instead. The render_dependencies kwarg will be removed in v1.

    Before:

    Calendar.render_to_response(render_dependencies=False)\n

    After:

    Calendar.render_to_response(deps_strategy=\"ignore\")\n
  • Support for Component constructor kwargs registered_name, outer_context, and registry is deprecated, and will be removed in v1.

    Before, you could instantiate a standalone component, and then call render() on the instance:

    comp = MyComponent(\n    registered_name=\"my_component\",\n    outer_context=my_context,\n    registry=my_registry,\n)\ncomp.render(\n    args=[1, 2, 3],\n    kwargs={\"a\": 1, \"b\": 2},\n    slots={\"my_slot\": \"CONTENT\"},\n)\n

    Now you should instead pass all that data to Component.render() / Component.render_to_response():

    MyComponent.render(\n    args=[1, 2, 3],\n    kwargs={\"a\": 1, \"b\": 2},\n    slots={\"my_slot\": \"CONTENT\"},\n    # NEW\n    registered_name=\"my_component\",\n    outer_context=my_context,\n    registry=my_registry,\n)\n
  • Component.input (and its type ComponentInput) is now deprecated. The input property will be removed in v1.

    Instead, use attributes directly on the Component instance.

    Before:

    class MyComponent(Component):\n    def on_render(self, context, template):\n        assert self.input.args == [1, 2, 3]\n        assert self.input.kwargs == {\"a\": 1, \"b\": 2}\n        assert self.input.slots == {\"my_slot\": \"CONTENT\"}\n        assert self.input.context == {\"my_slot\": \"CONTENT\"}\n        assert self.input.deps_strategy == \"document\"\n        assert self.input.type == \"document\"\n        assert self.input.render_dependencies == True\n

    After:

    class MyComponent(Component):\n    def on_render(self, context, template):\n        assert self.args == [1, 2, 3]\n        assert self.kwargs == {\"a\": 1, \"b\": 2}\n        assert self.slots == {\"my_slot\": \"CONTENT\"}\n        assert self.context == {\"my_slot\": \"CONTENT\"}\n        assert self.deps_strategy == \"document\"\n        assert (self.deps_strategy != \"ignore\") is True\n
  • Component method on_render_after was updated to receive also error field.

    For backwards compatibility, the error field can be omitted until v1.

    Before:

    def on_render_after(\n    self,\n    context: Context,\n    template: Template,\n    html: str,\n) -> None:\n    pass\n

    After:

    def on_render_after(\n    self,\n    context: Context,\n    template: Template,\n    html: Optional[str],\n    error: Optional[Exception],\n) -> None:\n    pass\n
  • If you are using the Components as views, the way to access the component class is now different.

    Instead of self.component, use self.component_cls. self.component will be removed in v1.

    Before:

    class MyView(View):\n    def get(self, request):\n        return self.component.render_to_response(request=request)\n

    After:

    class MyView(View):\n    def get(self, request):\n        return self.component_cls.render_to_response(request=request)\n

Extensions

  • In the on_component_data() extension hook, the context_data field of the context object was superseded by template_data.

    The context_data field will be removed in v1.0.

    Before:

    class MyExtension(ComponentExtension):\n    def on_component_data(self, ctx: OnComponentDataContext) -> None:\n        ctx.context_data[\"my_template_var\"] = \"my_value\"\n

    After:

    class MyExtension(ComponentExtension):\n    def on_component_data(self, ctx: OnComponentDataContext) -> None:\n        ctx.template_data[\"my_template_var\"] = \"my_value\"\n
  • When creating extensions, the ComponentExtension.ExtensionClass attribute was renamed to ComponentConfig.

    The old name is deprecated and will be removed in v1.

    Before:

    from django_components import ComponentExtension\n\nclass MyExtension(ComponentExtension):\n    class ExtensionClass(ComponentExtension.ExtensionClass):\n        pass\n

    After:

    from django_components import ComponentExtension, ExtensionComponentConfig\n\nclass MyExtension(ComponentExtension):\n    class ComponentConfig(ExtensionComponentConfig):\n        pass\n
  • When creating extensions, to access the Component class from within the methods of the extension nested classes, use component_cls.

    Previously this field was named component_class. The old name is deprecated and will be removed in v1.

ComponentExtension.ExtensionClass attribute was renamed to ComponentConfig.

The old name is deprecated and will be removed in v1.\n\nBefore:\n\n```py\nfrom django_components import ComponentExtension, ExtensionComponentConfig\n\nclass LoggerExtension(ComponentExtension):\n    name = \"logger\"\n\n    class ComponentConfig(ExtensionComponentConfig):\n        def log(self, msg: str) -> None:\n            print(f\"{self.component_class.__name__}: {msg}\")\n```\n\nAfter:\n\n```py\nfrom django_components import ComponentExtension, ExtensionComponentConfig\n\nclass LoggerExtension(ComponentExtension):\n    name = \"logger\"\n\n    class ComponentConfig(ExtensionComponentConfig):\n        def log(self, msg: str) -> None:\n            print(f\"{self.component_cls.__name__}: {msg}\")\n```\n

Slots

  • SlotContent was renamed to SlotInput. The old name is deprecated and will be removed in v1.

  • SlotRef was renamed to SlotFallback. The old name is deprecated and will be removed in v1.

  • The default kwarg in {% fill %} tag was renamed to fallback. The old name is deprecated and will be removed in v1.

    Before:

    {% fill \"footer\" default=\"footer\" %}\n    {{ footer }}\n{% endfill %}\n

    After:

    {% fill \"footer\" fallback=\"footer\" %}\n    {{ footer }}\n{% endfill %}\n
  • The template variable {{ component_vars.is_filled }} is now deprecated. Will be removed in v1. Use {{ component_vars.slots }} instead.

    Before:

    {% if component_vars.is_filled.footer %}\n    <div>\n        {% slot \"footer\" / %}\n    </div>\n{% endif %}\n

    After:

    {% if component_vars.slots.footer %}\n    <div>\n        {% slot \"footer\" / %}\n    </div>\n{% endif %}\n

    NOTE: component_vars.is_filled automatically escaped slot names, so that even slot names that are not valid python identifiers could be set as slot names. component_vars.slots no longer does that.

  • Component attribute Component.is_filled is now deprecated. Will be removed in v1. Use Component.slots instead.

    Before:

    class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        if self.is_filled.footer:\n            color = \"red\"\n        else:\n            color = \"blue\"\n\n        return {\n            \"color\": color,\n        }\n

    After:

    class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        if \"footer\" in slots:\n            color = \"red\"\n        else:\n            color = \"blue\"\n\n        return {\n            \"color\": color,\n        }\n

    NOTE: Component.is_filled automatically escaped slot names, so that even slot names that are not valid python identifiers could be set as slot names. Component.slots no longer does that.

Miscellaneous

  • Template caching with cached_template() helper and template_cache_size setting is deprecated. These will be removed in v1.

    This feature made sense if you were dynamically generating templates for components using Component.get_template_string() and Component.get_template().

    However, in v1, each Component will have at most one static template. This static template is cached internally per component class, and reused across renders.

    This makes the template caching feature obsolete.

    If you relied on cached_template(), you should either:

    1. Wrap the templates as Components.
    2. Manage the cache of Templates yourself.
  • The debug_highlight_components and debug_highlight_slots settings are deprecated. These will be removed in v1.

    The debug highlighting feature was re-implemented as an extension. As such, the recommended way for enabling it has changed:

    Before:

    COMPONENTS = ComponentsSettings(\n    debug_highlight_components=True,\n    debug_highlight_slots=True,\n)\n

    After:

    Set extensions_defaults in your settings.py file.

    COMPONENTS = ComponentsSettings(\n    extensions_defaults={\n        \"debug_highlight\": {\n            \"highlight_components\": True,\n            \"highlight_slots\": True,\n        },\n    },\n)\n

    Alternatively, you can enable highlighting for specific components by setting Component.DebugHighlight.highlight_components to True:

    class MyComponent(Component):\n    class DebugHighlight:\n        highlight_components = True\n        highlight_slots = True\n
"},{"location":"release_notes/#feat_1","title":"Feat","text":"
  • New method to render template variables - get_template_data()

    get_template_data() behaves the same way as get_context_data(), but has a different function signature to accept also slots and context.

    class Button(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"val1\": args[0],\n            \"val2\": kwargs[\"field\"],\n        }\n

    If you define Component.Args, Component.Kwargs, Component.Slots, then the args, kwargs, slots arguments will be instances of these classes:

    class Button(Component):\n    class Args(NamedTuple):\n        field1: str\n\n    class Kwargs(NamedTuple):\n        field2: int\n\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots, context):\n        return {\n            \"val1\": args.field1,\n            \"val2\": kwargs.field2,\n        }\n
  • Input validation is now part of the render process.

    When you specify the input types (such as Component.Args, Component.Kwargs, etc), the actual inputs to data methods (Component.get_template_data(), etc) will be instances of the types you specified.

    This practically brings back input validation, because the instantiation of the types will raise an error if the inputs are not valid.

    Read more on Typing and validation

  • Render emails or other non-browser HTML with new \"dependencies strategies\"

    When rendering a component with Component.render() or Component.render_to_response(), the deps_strategy kwarg (previously type) now accepts additional options:

    • \"simple\"
    • \"prepend\"
    • \"append\"
    • \"ignore\"
    Calendar.render_to_response(\n    request=request,\n    kwargs={\n        \"date\": request.GET.get(\"date\", \"\"),\n    },\n    deps_strategy=\"append\",\n)\n

    Comparison of dependencies render strategies:

    • \"document\"
      • Smartly inserts JS / CSS into placeholders or into <head> and <body> tags.
      • Inserts extra script to allow fragment strategy to work.
      • Assumes the HTML will be rendered in a JS-enabled browser.
    • \"fragment\"
      • A lightweight HTML fragment to be inserted into a document with AJAX.
      • Ignores placeholders and any <head> / <body> tags.
      • No JS / CSS included.
    • \"simple\"
      • Smartly insert JS / CSS into placeholders or into <head> and <body> tags.
      • No extra script loaded.
    • \"prepend\"
      • Insert JS / CSS before the rendered HTML.
      • Ignores placeholders and any <head> / <body> tags.
      • No extra script loaded.
    • \"append\"
      • Insert JS / CSS after the rendered HTML.
      • Ignores placeholders and any <head> / <body> tags.
      • No extra script loaded.
    • \"ignore\"
      • Rendered HTML is left as-is. You can still process it with a different strategy later with render_dependencies().
      • Used for inserting rendered HTML into other components.

    See Dependencies rendering for more info.

  • New Component.args, Component.kwargs, Component.slots attributes available on the component class itself.

    These attributes are the same as the ones available in Component.get_template_data().

    You can use these in other methods like Component.on_render_before() or Component.on_render_after().

    from django_components import Component, SlotInput\n\nclass Table(Component):\n    class Args(NamedTuple):\n        page: int\n\n    class Kwargs(NamedTuple):\n        per_page: int\n\n    class Slots(NamedTuple):\n        content: SlotInput\n\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.args.page == 123\n        assert self.kwargs.per_page == 10\n        content_html = self.slots.content()\n

    Same as with the parameters in Component.get_template_data(), they will be instances of the Args, Kwargs, Slots classes if defined, or plain lists / dictionaries otherwise.

  • 4 attributes that were previously available only under the Component.input attribute are now available directly on the Component instance:

    • Component.raw_args
    • Component.raw_kwargs
    • Component.raw_slots
    • Component.deps_strategy

    The first 3 attributes are the same as the deprecated Component.input.args, Component.input.kwargs, Component.input.slots properties.

    Compared to the Component.args / Component.kwargs / Component.slots attributes, these \"raw\" attributes are not typed and will remain as plain lists / dictionaries even if you define the Args, Kwargs, Slots classes.

    The Component.deps_strategy attribute is the same as the deprecated Component.input.deps_strategy property.

  • New template variables {{ component_vars.args }}, {{ component_vars.kwargs }}, {{ component_vars.slots }}

    These attributes are the same as the ones available in Component.get_template_data().

    {# Typed #}\n{% if component_vars.args.page == 123 %}\n    <div>\n        {% slot \"content\" / %}\n    </div>\n{% endif %}\n\n{# Untyped #}\n{% if component_vars.args.0 == 123 %}\n    <div>\n        {% slot \"content\" / %}\n    </div>\n{% endif %}\n

    Same as with the parameters in Component.get_template_data(), they will be instances of the Args, Kwargs, Slots classes if defined, or plain lists / dictionaries otherwise.

  • New component lifecycle hook Component.on_render().

    This hook is called when the component is being rendered.

    You can override this method to:

    • Change what template gets rendered
    • Modify the context
    • Modify the rendered output after it has been rendered
    • Handle errors

    See on_render for more info.

  • get_component_url() now optionally accepts query and fragment arguments.

    from django_components import get_component_url\n\nurl = get_component_url(\n    MyComponent,\n    query={\"foo\": \"bar\"},\n    fragment=\"baz\",\n)\n# /components/ext/view/components/c1ab2c3?foo=bar#baz\n
  • The BaseNode class has a new contents attribute, which contains the raw contents (string) of the tag body.

    This is relevant when you define custom template tags with @template_tag decorator or BaseNode class.

    When you define a custom template tag like so:

    from django_components import BaseNode, template_tag\n\n@template_tag(\n    library,\n    tag=\"mytag\",\n    end_tag=\"endmytag\",\n    allowed_flags=[\"required\"]\n)\ndef mytag(node: BaseNode, context: Context, name: str, **kwargs) -> str:\n    print(node.contents)\n    return f\"Hello, {name}!\"\n

    And render it like so:

    {% mytag name=\"John\" %}\n    Hello, world!\n{% endmytag %}\n

    Then, the contents attribute of the BaseNode instance will contain the string \"Hello, world!\".

  • The BaseNode class also has two new metadata attributes:

    • template_name - the name of the template that rendered the node.
    • template_component - the component class that the template belongs to.

    This is useful for debugging purposes.

  • Slot class now has 3 new metadata fields:

    1. Slot.contents attribute contains the original contents:

      • If Slot was created from {% fill %} tag, Slot.contents will contain the body of the {% fill %} tag.
      • If Slot was created from string via Slot(\"...\"), Slot.contents will contain that string.
      • If Slot was created from a function, Slot.contents will contain that function.
    2. Slot.extra attribute where you can put arbitrary metadata about the slot.

    3. Slot.fill_node attribute tells where the slot comes from:

      • FillNode instance if the slot was created from {% fill %} tag.
      • ComponentNode instance if the slot was created as a default slot from a {% component %} tag.
      • None if the slot was created from a string, function, or Slot instance.

    See Slot metadata.

  • {% fill %} tag now accepts body kwarg to pass a Slot instance to fill.

    First pass a Slot instance to the template with the get_template_data() method:

    from django_components import component, Slot\n\nclass Table(Component):\n  def get_template_data(self, args, kwargs, slots, context):\n    return {\n        \"my_slot\": Slot(lambda ctx: \"Hello, world!\"),\n    }\n

    Then pass the slot to the {% fill %} tag:

    {% component \"table\" %}\n  {% fill \"pagination\" body=my_slot / %}\n{% endcomponent %}\n
  • You can now access the {% component %} tag (ComponentNode instance) from which a Component was created. Use Component.node to access it.

    This is mostly useful for extensions, which can use this to detect if the given Component comes from a {% component %} tag or from a different source (such as Component.render()).

    Component.node is None if the component is created by Component.render() (but you can pass in the node kwarg yourself).

    class MyComponent(Component):\n    def get_template_data(self, context, template):\n        if self.node is not None:\n            assert self.node.name == \"my_component\"\n
  • Node classes ComponentNode, FillNode, ProvideNode, and SlotNode are part of the public API.

    These classes are what is instantiated when you use {% component %}, {% fill %}, {% provide %}, and {% slot %} tags.

    You can for example use these for type hints:

    from django_components import Component, ComponentNode\n\nclass MyTable(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        if kwargs.get(\"show_owner\"):\n            node: Optional[ComponentNode] = self.node\n            owner: Optional[Component] = self.node.template_component\n        else:\n            node = None\n            owner = None\n\n        return {\n            \"owner\": owner,\n            \"node\": node,\n        }\n
  • Component caching can now take slots into account, by setting Component.Cache.include_slots to True.

    class MyComponent(Component):\n    class Cache:\n        enabled = True\n        include_slots = True\n

    In which case the following two calls will generate separate cache entries:

    {% component \"my_component\" position=\"left\" %}\n    Hello, Alice\n{% endcomponent %}\n\n{% component \"my_component\" position=\"left\" %}\n    Hello, Bob\n{% endcomponent %}\n

    Same applies to Component.render() with string slots:

    MyComponent.render(\n    kwargs={\"position\": \"left\"},\n    slots={\"content\": \"Hello, Alice\"}\n)\nMyComponent.render(\n    kwargs={\"position\": \"left\"},\n    slots={\"content\": \"Hello, Bob\"}\n)\n

    Read more on Component caching.

  • New extension hook on_slot_rendered()

    This hook is called when a slot is rendered, and allows you to access and/or modify the rendered result.

    This is used by the \"debug highlight\" feature.

    To modify the rendered result, return the new value:

    class MyExtension(ComponentExtension):\n    def on_slot_rendered(self, ctx: OnSlotRenderedContext) -> Optional[str]:\n        return ctx.result + \"<!-- Hello, world! -->\"\n

    If you don't want to modify the rendered result, return None.

    See all Extension hooks.

  • When creating extensions, the previous syntax with ComponentExtension.ExtensionClass was causing Mypy errors, because Mypy doesn't allow using class attributes as bases:

    Before:

    from django_components import ComponentExtension\n\nclass MyExtension(ComponentExtension):\n    class ExtensionClass(ComponentExtension.ExtensionClass):  # Error!\n        pass\n

    Instead, you can import ExtensionComponentConfig directly:

    After:

    from django_components import ComponentExtension, ExtensionComponentConfig\n\nclass MyExtension(ComponentExtension):\n    class ComponentConfig(ExtensionComponentConfig):\n        pass\n
"},{"location":"release_notes/#refactor_1","title":"Refactor","text":"
  • When a component is being rendered, a proper Component instance is now created.

    Previously, the Component state was managed as half-instance, half-stack.

  • Component's \"Render API\" (args, kwargs, slots, context, inputs, request, context data, etc) can now be accessed also outside of the render call. So now its possible to take the component instance out of get_template_data() (although this is not recommended).

  • Components can now be defined without a template.

    Previously, the following would raise an error:

    class MyComponent(Component):\n    pass\n

    \"Template-less\" components can be used together with Component.on_render() to dynamically pick what to render:

    class TableNew(Component):\n    template_file = \"table_new.html\"\n\nclass TableOld(Component):\n    template_file = \"table_old.html\"\n\nclass Table(Component):\n    def on_render(self, context, template):\n        if self.kwargs.get(\"feat_table_new_ui\"):\n            return TableNew.render(args=self.args, kwargs=self.kwargs, slots=self.slots)\n        else:\n            return TableOld.render(args=self.args, kwargs=self.kwargs, slots=self.slots)\n

    \"Template-less\" components can be also used as a base class for other components, or as mixins.

  • Passing Slot instance to Slot constructor raises an error.

  • Extension hook on_component_rendered now receives error field.

    on_component_rendered now behaves similar to Component.on_render_after:

    • Raising error in this hook overrides what error will be returned from Component.render().
    • Returning new string overrides what will be returned from Component.render().

    Before:

    class OnComponentRenderedContext(NamedTuple):\n    component: \"Component\"\n    component_cls: Type[\"Component\"]\n    component_id: str\n    result: str\n

    After:

    class OnComponentRenderedContext(NamedTuple):\n    component: \"Component\"\n    component_cls: Type[\"Component\"]\n    component_id: str\n    result: Optional[str]\n    error: Optional[Exception]\n
"},{"location":"release_notes/#fix_4","title":"Fix","text":"
  • Fix bug: Context processors data was being generated anew for each component. Now the data is correctly created once and reused across components with the same request (#1165).

  • Fix KeyError on component_context_cache when slots are rendered outside of the component's render context. (#1189)

  • Component classes now have do_not_call_in_templates=True to prevent them from being called as functions in templates.

"},{"location":"release_notes/#v01391","title":"v0.139.1","text":""},{"location":"release_notes/#fix_5","title":"Fix","text":"
  • Fix compatibility of component caching with {% extend %} block (#1135)
"},{"location":"release_notes/#refactor_2","title":"Refactor","text":"
  • Component ID is now prefixed with c, e.g. c123456.

  • When typing a Component, you can now specify as few or as many parameters as you want.

    Component[Args]\nComponent[Args, Kwargs]\nComponent[Args, Kwargs, Slots]\nComponent[Args, Kwargs, Slots, Data]\nComponent[Args, Kwargs, Slots, Data, JsData]\nComponent[Args, Kwargs, Slots, Data, JsData, CssData]\n

    All omitted parameters will default to Any.

  • Added typing_extensions to the project as a dependency

  • Multiple extensions with the same name (case-insensitive) now raise an error

  • Extension names (case-insensitive) also MUST NOT conflict with existing Component class API.

    So if you name an extension render, it will conflict with the render() method of the Component class, and thus raise an error.

"},{"location":"release_notes/#v01390","title":"v0.139.0","text":""},{"location":"release_notes/#fix_6","title":"Fix","text":"
  • Fix bug: Fix compatibility with Finder.find() in Django 5.2 (#1119)
"},{"location":"release_notes/#v0138","title":"v0.138","text":""},{"location":"release_notes/#fix_7","title":"Fix","text":"
  • Fix bug: Allow components with Url.public = True to be defined before django.setup()
"},{"location":"release_notes/#v0137","title":"v0.137","text":""},{"location":"release_notes/#feat_2","title":"Feat","text":"
  • Each Component class now has a class_id attribute, which is unique to the component subclass.

    NOTE: This is different from Component.id, which is unique to each rendered instance.

    To look up a component class by its class_id, use get_component_by_class_id().

  • It's now easier to create URLs for component views.

    Before, you had to call Component.as_view() and pass that to urlpatterns.

    Now this can be done for you if you set Component.Url.public to True:

    class MyComponent(Component):\n    class Url:\n        public = True\n    ...\n

    Then, to get the URL for the component, use get_component_url():

    from django_components import get_component_url\n\nurl = get_component_url(MyComponent)\n

    This way you don't have to mix your app URLs with component URLs.

    Read more on Component views and URLs.

  • Per-component caching - Set Component.Cache.enabled to True to enable caching for a component.

    Component caching allows you to store the rendered output of a component. Next time the component is rendered with the same input, the cached output is returned instead of re-rendering the component.

    class TestComponent(Component):\n    template = \"Hello\"\n\n    class Cache:\n        enabled = True\n        ttl = 0.1  # .1 seconds TTL\n        cache_name = \"custom_cache\"\n\n        # Custom hash method for args and kwargs\n        # NOTE: The default implementation simply serializes the input into a string.\n        #       As such, it might not be suitable for complex objects like Models.\n        def hash(self, *args, **kwargs):\n            return f\"{json.dumps(args)}:{json.dumps(kwargs)}\"\n

    Read more on Component caching.

  • @djc_test can now be called without first calling django.setup(), in which case it does it for you.

  • Expose ComponentInput class, which is a typing for Component.input.

"},{"location":"release_notes/#deprecation_1","title":"Deprecation","text":"
  • Currently, view request handlers such as get() and post() methods can be defined directly on the Component class:

    class MyComponent(Component):\n    def get(self, request):\n        return self.render_to_response()\n

    Or, nested within the Component.View class:

    class MyComponent(Component):\n    class View:\n        def get(self, request):\n            return self.render_to_response()\n

    In v1, these methods should be defined only on the Component.View class instead.

"},{"location":"release_notes/#refactor_3","title":"Refactor","text":"
  • Component.get_context_data() can now omit a return statement or return None.
"},{"location":"release_notes/#v0136","title":"\ud83d\udea8\ud83d\udce2 v0.136","text":""},{"location":"release_notes/#breaking-changes_1","title":"\ud83d\udea8\ud83d\udce2 BREAKING CHANGES","text":"
  • Component input validation was moved to a separate extension djc-ext-pydantic.

    If you relied on components raising errors when inputs were invalid, you need to install djc-ext-pydantic and add it to extensions:

    # settings.py\nCOMPONENTS = {\n    \"extensions\": [\n        \"djc_pydantic.PydanticExtension\",\n    ],\n}\n
"},{"location":"release_notes/#fix_8","title":"Fix","text":"
  • Make it possible to resolve URLs added by extensions by their names
"},{"location":"release_notes/#v0135","title":"v0.135","text":""},{"location":"release_notes/#feat_3","title":"Feat","text":"
  • Add defaults for the component inputs with the Component.Defaults nested class. Defaults are applied if the argument is not given, or if it set to None.

For lists, dictionaries, or other objects, wrap the value in Default() class to mark it as a factory function:

```python\nfrom django_components import Default\n\nclass Table(Component):\n    class Defaults:\n        position = \"left\"\n        width = \"200px\"\n        options = Default(lambda: [\"left\", \"right\", \"center\"])\n\n    def get_context_data(self, position, width, options):\n        return {\n            \"position\": position,\n            \"width\": width,\n            \"options\": options,\n        }\n\n# `position` is used as given, `\"right\"`\n# `width` uses default because it's `None`\n# `options` uses default because it's missing\nTable.render(\n    kwargs={\n        \"position\": \"right\",\n        \"width\": None,\n    }\n)\n```\n
  • {% html_attrs %} now offers a Vue-like granular control over class and style HTML attributes, where each class name or style property can be managed separately.

    {% html_attrs\n    class=\"foo bar\"\n    class={\"baz\": True, \"foo\": False}\n    class=\"extra\"\n%}\n
    {% html_attrs\n    style=\"text-align: center; background-color: blue;\"\n    style={\"background-color\": \"green\", \"color\": None, \"width\": False}\n    style=\"position: absolute; height: 12px;\"\n%}\n

    Read more on HTML attributes.

"},{"location":"release_notes/#fix_9","title":"Fix","text":"
  • Fix compat with Windows when reading component files (#1074)
  • Fix resolution of component media files edge case (#1073)
"},{"location":"release_notes/#v0134","title":"v0.134","text":""},{"location":"release_notes/#fix_10","title":"Fix","text":"
  • HOTFIX: Fix the use of URLs in Component.Media.js and Component.Media.css
"},{"location":"release_notes/#v0133","title":"v0.133","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.134 to fix bugs introduced in v0.132.

"},{"location":"release_notes/#fix_11","title":"Fix","text":"
  • HOTFIX: Fix the use of URLs in Component.Media.js and Component.Media.css
"},{"location":"release_notes/#v0132","title":"v0.132","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.134 to fix bugs introduced in v0.132.

"},{"location":"release_notes/#feat_4","title":"Feat","text":"
  • Allow to use glob patterns as paths for additional JS / CSS in Component.Media.js and Component.Media.css

    class MyComponent(Component):\n    class Media:\n        js = [\"*.js\"]\n        css = [\"*.css\"]\n
"},{"location":"release_notes/#fix_12","title":"Fix","text":"
  • Fix installation for Python 3.13 on Windows.
"},{"location":"release_notes/#v0131","title":"v0.131","text":""},{"location":"release_notes/#feat_5","title":"Feat","text":"
  • Support for extensions (plugins) for django-components!

    • Hook into lifecycle events of django-components
    • Pre-/post-process component inputs, outputs, and templates
    • Add extra methods or attributes to Components
    • Add custom extension-specific CLI commands
    • Add custom extension-specific URL routes

    Read more on Extensions.

  • New CLI commands:

    • components list - List all components
    • components create <name> - Create a new component (supersedes startcomponent)
    • components upgrade - Upgrade a component (supersedes upgradecomponent)
    • components ext list - List all extensions
    • components ext run <extension> <command> - Run a command added by an extension
  • @djc_test decorator for writing tests that involve Components.

    • The decorator manages global state, ensuring that tests don't leak.
    • If using pytest, the decorator allows you to parametrize Django or Components settings.
    • The decorator also serves as a stand-in for Django's @override_settings.

    See the API reference for @djc_test for more details.

  • ComponentRegistry now has a has() method to check if a component is registered without raising an error.

  • Get all created Component classes with all_components().

  • Get all created ComponentRegistry instances with all_registries().

"},{"location":"release_notes/#refactor_4","title":"Refactor","text":"
  • The startcomponent and upgradecomponent commands are deprecated, and will be removed in v1.

    Instead, use components create <name> and components upgrade.

"},{"location":"release_notes/#internal","title":"Internal","text":"
  • Settings are now loaded only once, and thus are considered immutable once loaded. Previously, django-components would load settings from settings.COMPONENTS on each access. The new behavior aligns with Django's settings.
"},{"location":"release_notes/#v0130","title":"v0.130","text":""},{"location":"release_notes/#feat_6","title":"Feat","text":"
  • Access the HttpRequest object under Component.request.

    To pass the request object to a component, either: - Render a template or component with RequestContext, - Or set the request kwarg to Component.render() or Component.render_to_response().

    Read more on HttpRequest.

  • Access the context processors data under Component.context_processors_data.

    Context processors data is available only when the component has access to the request object, either by: - Passing the request to Component.render() or Component.render_to_response(), - Or by rendering a template or component with RequestContext, - Or being nested in another component that has access to the request object.

    The data from context processors is automatically available within the component's template.

    Read more on HttpRequest.

"},{"location":"release_notes/#v0129","title":"v0.129","text":""},{"location":"release_notes/#fix_13","title":"Fix","text":"
  • Fix thread unsafe media resolve validation by moving it to ComponentMedia __post_init (#977
  • Fix bug: Relative path in extends and include does not work when using template_file (#976
  • Fix error when template cache setting (template_cache_size) is set to 0 (#974
"},{"location":"release_notes/#v0128","title":"v0.128","text":""},{"location":"release_notes/#feat_7","title":"Feat","text":"
  • Configurable cache - Set COMPONENTS.cache to change where and how django-components caches JS and CSS files. (#946)

    Read more on Caching.

  • Highlight coponents and slots in the UI - We've added two boolean settings COMPONENTS.debug_highlight_components and COMPONENTS.debug_highlight_slots, which can be independently set to True. First will wrap components in a blue border, the second will wrap slots in a red border. (#942)

    Read more on Troubleshooting.

"},{"location":"release_notes/#refactor_5","title":"Refactor","text":"
  • Removed use of eval for node validation (#944)
"},{"location":"release_notes/#perf","title":"Perf","text":"
  • Components can now be infinitely nested. (#936)

  • Component input validation is now 6-7x faster on CPython and PyPy. This previously made up 10-30% of the total render time. (#945)

"},{"location":"release_notes/#v0127","title":"v0.127","text":""},{"location":"release_notes/#fix_14","title":"Fix","text":"
  • Fix component rendering when using {% cache %} with remote cache and multiple web servers (#930)
"},{"location":"release_notes/#v0126","title":"v0.126","text":""},{"location":"release_notes/#refactor_6","title":"Refactor","text":"
  • Replaced BeautifulSoup4 with a custom HTML parser.
  • The heuristic for inserting JS and CSS dependenies into the default place has changed.
    • JS is still inserted at the end of the <body>, and CSS at the end of <head>.
    • However, we find end of <body> by searching for last occurrence of </body>
    • And for the end of <head> we search for the first occurrence of </head>
"},{"location":"release_notes/#v0125","title":"v0.125","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - We migrated from EmilStenstrom/django-components to django-components/django-components.

Repo name and documentation URL changed. Package name remains the same.

If you see any broken links or other issues, please report them in #922.

"},{"location":"release_notes/#feat_8","title":"Feat","text":"
  • @template_tag and BaseNode - A decorator and a class that allow you to define custom template tags that will behave similarly to django-components' own template tags.

Read more on Template tags.

Template tags defined with @template_tag and BaseNode will have the following features:

  • Accepting args, kwargs, and flags.

  • Allowing literal lists and dicts as inputs as:

    key=[1, 2, 3] or key={\"a\": 1, \"b\": 2} - Using template tags tag inputs as:

    {% my_tag key=\"{% lorem 3 w %}\" / %} - Supporting the flat dictionary definition:

    attr:key=value - Spreading args and kwargs with ...:

    {% my_tag ...args ...kwargs / %} - Being able to call the template tag as:

    {% my_tag %} ... {% endmy_tag %} or {% my_tag / %}

"},{"location":"release_notes/#refactor_7","title":"Refactor","text":"
  • Refactored template tag input validation. When you now call template tags like {% slot %}, {% fill %}, {% html_attrs %}, and others, their inputs are now validated the same way as Python function inputs are.

    So, for example

    {% slot \"my_slot\" name=\"content\" / %}\n

    will raise an error, because the positional argument name is given twice.

    NOTE: Special kwargs whose keys are not valid Python variable names are not affected by this change. So when you define:

    {% component data-id=123 / %}\n

    The data-id will still be accepted as a valid kwarg, assuming that your get_context_data() accepts **kwargs:

    def get_context_data(self, **kwargs):\n    return {\n        \"data_id\": kwargs[\"data-id\"],\n    }\n
"},{"location":"release_notes/#v0124","title":"v0.124","text":""},{"location":"release_notes/#feat_9","title":"Feat","text":"
  • Instead of inlining the JS and CSS under Component.js and Component.css, you can move them to their own files, and link the JS/CSS files with Component.js_file and Component.css_file.

    Even when you specify the JS/CSS with Component.js_file or Component.css_file, then you can still access the content under Component.js or Component.css - behind the scenes, the content of the JS/CSS files will be set to Component.js / Component.css upon first access.

    The same applies to Component.template_file, which will populate Component.template upon first access.

    With this change, the role of Component.js/css and the JS/CSS in Component.Media has changed:

    • The JS/CSS defined in Component.js/css or Component.js/css_file is the \"main\" JS/CSS
    • The JS/CSS defined in Component.Media.js/css are secondary or additional

    See the updated \"Getting Started\" tutorial

"},{"location":"release_notes/#refactor_8","title":"Refactor","text":"
  • The canonical way to define a template file was changed from template_name to template_file, to align with the rest of the API.

    template_name remains for backwards compatibility. When you get / set template_name, internally this is proxied to template_file.

  • The undocumented Component.component_id was removed. Instead, use Component.id. Changes:

    • While component_id was unique every time you instantiated Component, the new id is unique every time you render the component (e.g. with Component.render())
    • The new id is available only during render, so e.g. from within get_context_data()
  • Component's HTML / CSS / JS are now resolved and loaded lazily. That is, if you specify template_name/template_file, js_file, css_file, or Media.js/css, the file paths will be resolved only once you:

    1. Try to access component's HTML / CSS / JS, or
    2. Render the component.

    Read more on Accessing component's HTML / JS / CSS.

  • Component inheritance:

    • When you subclass a component, the JS and CSS defined on parent's Media class is now inherited by the child component.
    • You can disable or customize Media inheritance by setting extend attribute on the Component.Media nested class. This work similarly to Django's Media.extend.
    • When child component defines either template or template_file, both of parent's template and template_file are ignored. The same applies to js_file and css_file.
  • Autodiscovery now ignores files and directories that start with an underscore (_), except __init__.py

  • The Signals emitted by or during the use of django-components are now documented, together the template_rendered signal.

"},{"location":"release_notes/#v0123","title":"v0.123","text":""},{"location":"release_notes/#fix_15","title":"Fix","text":"
  • Fix edge cases around rendering components whose templates used the {% extends %} template tag (#859)
"},{"location":"release_notes/#v0122","title":"v0.122","text":""},{"location":"release_notes/#feat_10","title":"Feat","text":"
  • Add support for HTML fragments. HTML fragments can be rendered by passing type=\"fragment\" to Component.render() or Component.render_to_response(). Read more on how to use HTML fragments with HTMX, AlpineJS, or vanillaJS.
"},{"location":"release_notes/#v0121","title":"v0.121","text":""},{"location":"release_notes/#fix_16","title":"Fix","text":"
  • Fix the use of Django template filters (|lower:\"etc\") with component inputs #855.
"},{"location":"release_notes/#v0120","title":"v0.120","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.121 to fix bugs introduced in v0.119.

"},{"location":"release_notes/#fix_17","title":"Fix","text":"
  • Fix the use of translation strings _(\"bla\") as inputs to components #849.
"},{"location":"release_notes/#v0119","title":"v0.119","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - This release introduced bugs #849, #855. Please update to v0.121.

"},{"location":"release_notes/#fix_18","title":"Fix","text":"
  • Fix compatibility with custom subclasses of Django's Template that need to access origin or other initialization arguments. (https://github.com/django-components/django-components/pull/828)
"},{"location":"release_notes/#refactor_9","title":"Refactor","text":"
  • Compatibility with django-debug-toolbar-template-profiler:
  • Monkeypatching of Django's Template now happens at AppConfig.ready() (https://github.com/django-components/django-components/pull/825)

  • Internal parsing of template tags tag was updated. No API change. (https://github.com/django-components/django-components/pull/827)

"},{"location":"release_notes/#v0118","title":"v0.118","text":""},{"location":"release_notes/#feat_11","title":"Feat","text":"
  • Add support for context_processors and RenderContext inside component templates

Component.render() and Component.render_to_response() now accept an extra kwarg request.

```py\ndef my_view(request)\n    return MyTable.render_to_response(\n        request=request\n    )\n```\n
  • When you pass in request, the component will use RenderContext instead of Context. Thus the context processors will be applied to the context.

  • NOTE: When you pass in both request and context to Component.render(), and context is already an instance of Context, the request kwarg will be ignored.

"},{"location":"release_notes/#v0117","title":"v0.117","text":""},{"location":"release_notes/#fix_19","title":"Fix","text":"
  • The HTML parser no longer erronously inserts <html><head><body> on some occasions, and no longer tries to close unclosed HTML tags.
"},{"location":"release_notes/#refactor_10","title":"Refactor","text":"
  • Replaced Selectolax with BeautifulSoup4 as project dependencies.
"},{"location":"release_notes/#v0116","title":"v0.116","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.117 to fix known bugs. See #791 and #789 and #818.

"},{"location":"release_notes/#fix_20","title":"Fix","text":"
  • Fix the order of execution of JS scripts:
  • Scripts in Component.Media.js are executed in the order they are defined
  • Scripts in Component.js are executed AFTER Media.js scripts

  • Fix compatibility with AlpineJS

  • Scripts in Component.Media.js are now again inserted as <script> tags
  • By default, Component.Media.js are inserted as synchronous <script> tags, so the AlpineJS components registered in the Media.js scripts will now again run BEFORE the core AlpineJS script.

AlpineJS can be configured like so:

Option 1 - AlpineJS loaded in <head> with defer attribute:

<html>\n  <head>\n    {% component_css_dependencies %}\n    <script defer src=\"https://unpkg.com/alpinejs\"></script>\n  </head>\n  <body>\n    {% component 'my_alpine_component' / %}\n    {% component_js_dependencies %}\n  </body>\n</html>\n

Option 2 - AlpineJS loaded in <body> AFTER {% component_js_depenencies %}:

<html>\n    <head>\n        {% component_css_dependencies %}\n    </head>\n    <body>\n        {% component 'my_alpine_component' / %}\n        {% component_js_dependencies %}\n\n        <script src=\"https://unpkg.com/alpinejs\"></script>\n    </body>\n</html>\n

"},{"location":"release_notes/#v0115","title":"v0.115","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.117 to fix known bugs. See #791 and #789 and #818.

"},{"location":"release_notes/#fix_21","title":"Fix","text":"
  • Fix integration with ManifestStaticFilesStorage on Windows by resolving component filepaths (like Component.template_name) to POSIX paths.
"},{"location":"release_notes/#v0114","title":"v0.114","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.117 to fix known bugs. See #791 and #789 and #818.

"},{"location":"release_notes/#fix_22","title":"Fix","text":"
  • Prevent rendering Slot tags during fill discovery stage to fix a case when a component inside a slot fill tried to access provided data too early.
"},{"location":"release_notes/#v0113","title":"v0.113","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.117 to fix known bugs. See #791 and #789 and #818.

"},{"location":"release_notes/#fix_23","title":"Fix","text":"
  • Ensure consistent order of scripts in Component.Media.js
"},{"location":"release_notes/#v0112","title":"v0.112","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.117 to fix known bugs. See #791 and #789 and #818.

"},{"location":"release_notes/#fix_24","title":"Fix","text":"
  • Allow components to accept default fill even if no default slot was encountered during rendering
"},{"location":"release_notes/#v0111","title":"v0.111","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.117 to fix known bugs. See #791 and #789 and #818.

"},{"location":"release_notes/#fix_25","title":"Fix","text":"
  • Prevent rendering Component tags during fill discovery stage to fix a case when a component inside the default slot tried to access provided data too early.
"},{"location":"release_notes/#v0110","title":"\ud83d\udea8\ud83d\udce2 v0.110","text":"

\u26a0\ufe0f Attention \u26a0\ufe0f - Please update to v0.117 to fix known bugs. See #791 and #789 and #818.

"},{"location":"release_notes/#general","title":"General","text":""},{"location":"release_notes/#breaking-changes_2","title":"\ud83d\udea8\ud83d\udce2 BREAKING CHANGES","text":"
  • Installation changes:

    • If your components include JS or CSS, you now must use the middleware and add django-components' URLs to your urlpatterns (See \"Adding support for JS and CSS\")
  • Component typing signature changed from

    Component[Args, Kwargs, Data, Slots]\n

    to

    Component[Args, Kwargs, Slots, Data, JsData, CssData]\n
  • If you rendered a component A with Component.render() and then inserted that into another component B, now you must pass render_dependencies=False to component A:

    prerendered_a = CompA.render(\n    args=[...],\n    kwargs={...},\n    render_dependencies=False,\n)\n\nhtml = CompB.render(\n    kwargs={\n        content=prerendered_a,\n    },\n)\n
"},{"location":"release_notes/#feat_12","title":"Feat","text":"
  • Intellisense and mypy validation for settings:

Instead of defining the COMPONENTS settings as a plain dict, you can use ComponentsSettings:

# settings.py\nfrom django_components import ComponentsSettings\n\nCOMPONENTS = ComponentsSettings(\n    autodiscover=True,\n    ...\n)\n
  • Use get_component_dirs() and get_component_files() to get the same list of dirs / files that would be imported by autodiscover(), but without actually importing them.
"},{"location":"release_notes/#refactor_11","title":"Refactor","text":"
  • For advanced use cases, use can omit the middleware and instead manage component JS and CSS dependencies yourself with render_dependencies

  • The ComponentRegistry settings RegistrySettings were lowercased to align with the global settings:

  • RegistrySettings.CONTEXT_BEHAVIOR -> RegistrySettings.context_behavior
  • RegistrySettings.TAG_FORMATTER -> RegistrySettings.tag_formatter

The old uppercase settings CONTEXT_BEHAVIOR and TAG_FORMATTER are deprecated and will be removed in v1.

  • The setting reload_on_template_change was renamed to reload_on_file_change. And now it properly triggers server reload when any file in the component dirs change. The old name reload_on_template_change is deprecated and will be removed in v1.

  • The setting forbidden_static_files was renamed to static_files_forbidden to align with static_files_allowed The old name forbidden_static_files is deprecated and will be removed in v1.

"},{"location":"release_notes/#tags","title":"Tags","text":""},{"location":"release_notes/#breaking-changes_3","title":"\ud83d\udea8\ud83d\udce2 BREAKING CHANGES","text":"
  • {% component_dependencies %} tag was removed. Instead, use {% component_js_dependencies %} and {% component_css_dependencies %}

    • The combined tag was removed to encourage the best practice of putting JS scripts at the end of <body>, and CSS styles inside <head>.

      On the other hand, co-locating JS script and CSS styles can lead to a flash of unstyled content, as either JS scripts will block the rendering, or CSS will load too late.

  • The undocumented keyword arg preload of {% component_js_dependencies %} and {% component_css_dependencies %} tags was removed. This will be replaced with HTML fragment support.

"},{"location":"release_notes/#fix_26","title":"Fix","text":"
  • Allow using forward slash (/) when defining custom TagFormatter, e.g. {% MyComp %}..{% /MyComp %}.
"},{"location":"release_notes/#refactor_12","title":"Refactor","text":"
  • {% component_dependencies %} tags are now OPTIONAL - If your components use JS and CSS, but you don't use {% component_dependencies %} tags, the JS and CSS will now be, by default, inserted at the end of <body> and at the end of <head> respectively.
"},{"location":"release_notes/#slots","title":"Slots","text":""},{"location":"release_notes/#feat_13","title":"Feat","text":"
  • Fills can now be defined within loops ({% for %}) or other tags (like {% with %}), or even other templates using {% include %}.

Following is now possible

{% component \"table\" %}\n  {% for slot_name in slots %}\n    {% fill name=slot_name %}\n    {% endfill %}\n  {% endfor %}\n{% endcomponent %}\n
  • If you need to access the data or the default content of a default fill, you can set the name kwarg to \"default\".

Previously, a default fill would be defined simply by omitting the {% fill %} tags:

{% component \"child\" %}\n  Hello world\n{% endcomponent %}\n

But in that case you could not access the slot data or the default content, like it's possible for named fills:

{% component \"child\" %}\n  {% fill name=\"header\" data=\"data\" %}\n    Hello {{ data.user.name }}\n  {% endfill %}\n{% endcomponent %}\n

Now, you can specify default tag by using name=\"default\":

{% component \"child\" %}\n  {% fill name=\"default\" data=\"data\" %}\n    Hello {{ data.user.name }}\n  {% endfill %}\n{% endcomponent %}\n
  • When inside get_context_data() or other component methods, the default fill can now be accessed as Component.input.slots[\"default\"], e.g.:
class MyTable(Component):\n    def get_context_data(self, *args, **kwargs):\n        default_slot = self.input.slots[\"default\"]\n        ...\n
  • You can now dynamically pass all slots to a child component. This is similar to passing all slots in Vue:
class MyTable(Component):\n    def get_context_data(self, *args, **kwargs):\n        return {\n            \"slots\": self.input.slots,\n        }\n\n    template: \"\"\"\n      <div>\n        {% component \"child\" %}\n          {% for slot_name in slots %}\n            {% fill name=slot_name data=\"data\" %}\n              {% slot name=slot_name ...data / %}\n            {% endfill %}\n          {% endfor %}\n        {% endcomponent %}\n      </div>\n    \"\"\"\n
"},{"location":"release_notes/#fix_27","title":"Fix","text":"
  • Slots defined with {% fill %} tags are now properly accessible via self.input.slots in get_context_data()

  • Do not raise error if multiple slots with same name are flagged as default

  • Slots can now be defined within loops ({% for %}) or other tags (like {% with %}), or even other templates using {% include %}.

Previously, following would cause the kwarg name to be an empty string:

{% for slot_name in slots %}\n  {% slot name=slot_name %}\n{% endfor %}\n
"},{"location":"release_notes/#refactor_13","title":"Refactor","text":"
  • When you define multiple slots with the same name inside a template, you now have to set the default and required flags individually.
<div class=\"calendar-component\">\n    <div class=\"header\">\n        {% slot \"image\" default required %}Image here{% endslot %}\n    </div>\n    <div class=\"body\">\n        {% slot \"image\" default required %}Image here{% endslot %}\n    </div>\n</div>\n

This means you can also have multiple slots with the same name but different conditions.

E.g. in this example, we have a component that renders a user avatar - a small circular image with a profile picture of name initials.

If the component is given image_src or name_initials variables, the image slot is optional. But if neither of those are provided, you MUST fill the image slot.

<div class=\"avatar\">\n    {% if image_src %}\n        {% slot \"image\" default %}\n            <img src=\"{{ image_src }}\" />\n        {% endslot %}\n    {% elif name_initials %}\n        {% slot \"image\" default required %}\n            <div style=\"\n                border-radius: 25px;\n                width: 50px;\n                height: 50px;\n                background: blue;\n            \">\n                {{ name_initials }}\n            </div>\n        {% endslot %}\n    {% else %}\n        {% slot \"image\" default required / %}\n    {% endif %}\n</div>\n
  • The slot fills that were passed to a component and which can be accessed as Component.input.slots can now be passed through the Django template, e.g. as inputs to other tags.

Internally, django-components handles slot fills as functions.

Previously, if you tried to pass a slot fill within a template, Django would try to call it as a function.

Now, something like this is possible:

class MyTable(Component):\n    def get_context_data(self, *args, **kwargs):\n        return {\n            \"child_slot\": self.input.slots[\"child_slot\"],\n        }\n\n    template: \"\"\"\n      <div>\n        {% component \"child\" content=child_slot / %}\n      </div>\n    \"\"\"\n

NOTE: Using {% slot %} and {% fill %} tags is still the preferred method, but the approach above may be necessary in some complex or edge cases.

  • The is_filled variable (and the {{ component_vars.is_filled }} context variable) now returns False when you try to access a slot name which has not been defined:

Before:

{{ component_vars.is_filled.header }} -> True\n{{ component_vars.is_filled.footer }} -> False\n{{ component_vars.is_filled.nonexist }} -> \"\" (empty string)\n

After:

{{ component_vars.is_filled.header }} -> True\n{{ component_vars.is_filled.footer }} -> False\n{{ component_vars.is_filled.nonexist }} -> False\n

  • Components no longer raise an error if there are extra slot fills

  • Components will raise error when a slot is doubly-filled.

E.g. if we have a component with a default slot:

{% slot name=\"content\" default / %}\n

Now there is two ways how we can target this slot: Either using name=\"default\" or name=\"content\".

In case you specify BOTH, the component will raise an error:

{% component \"child\" %}\n  {% fill slot=\"default\" %}\n    Hello from default slot\n  {% endfill %}\n  {% fill slot=\"content\" data=\"data\" %}\n    Hello from content slot\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"release_notes/#v0100","title":"\ud83d\udea8\ud83d\udce2 v0.100","text":""},{"location":"release_notes/#breaking-changes_4","title":"BREAKING CHANGES","text":"
  • 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

"},{"location":"release_notes/#feat_14","title":"Feat","text":"
  • Beside the top-level /components directory, you can now define also app-level components dirs, e.g. [app]/components (See COMPONENTS.app_dirs).
"},{"location":"release_notes/#refactor_14","title":"Refactor","text":"
  • When you call as_view() on a component instance, that instance will be passed to View.as_view()
"},{"location":"release_notes/#v097","title":"v0.97","text":""},{"location":"release_notes/#fix_28","title":"Fix","text":"
  • Fixed template caching. You can now also manually create cached templates with cached_template()
"},{"location":"release_notes/#refactor_15","title":"Refactor","text":"
  • 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.

"},{"location":"release_notes/#v096","title":"v0.96","text":""},{"location":"release_notes/#feat_15","title":"Feat","text":"
  • 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

"},{"location":"release_notes/#095","title":"0.95","text":""},{"location":"release_notes/#feat_16","title":"Feat","text":"
  • Added support for dynamic components, where the component name is passed as a variable. (See Dynamic components)
"},{"location":"release_notes/#refactor_16","title":"Refactor","text":"
  • Changed Component.input to raise RuntimeError if accessed outside of render context. Previously it returned None if unset.
"},{"location":"release_notes/#v094","title":"v0.94","text":""},{"location":"release_notes/#feat_17","title":"Feat","text":"
  • 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)

"},{"location":"release_notes/#v093","title":"v0.93","text":""},{"location":"release_notes/#feat_18","title":"Feat","text":"
  • 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.

"},{"location":"release_notes/#v092","title":"\ud83d\udea8\ud83d\udce2 v0.92","text":""},{"location":"release_notes/#breaking-changes_5","title":"BREAKING CHANGES","text":"
  • 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)
"},{"location":"release_notes/#feat_19","title":"Feat","text":"
  • 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)

"},{"location":"release_notes/#v090","title":"v0.90","text":""},{"location":"release_notes/#feat_20","title":"Feat","text":"
  • All tags (component, slot, fill, ...) now support \"self-closing\" or \"inline\" form, where you can omit the closing tag:

    {# Before #}\n{% component \"button\" %}{% endcomponent %}\n{# After #}\n{% component \"button\" / %}\n
  • All tags now support the \"dictionary key\" or \"aggregate\" syntax (kwarg:key=val):

    {% component \"button\" attrs:class=\"hidden\" %}\n
  • You can change how the components are written in the template with TagFormatter.

    The default is django_components.component_formatter:

    {% component \"button\" href=\"...\" disabled %}\n    Click me!\n{% endcomponent %}\n

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

    {% button href=\"...\" disabled %}\n    Click me!\n{% endbutton %}\n
"},{"location":"release_notes/#v085","title":"\ud83d\udea8\ud83d\udce2 v0.85","text":""},{"location":"release_notes/#breaking-changes_6","title":"BREAKING CHANGES","text":"
  • 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).

"},{"location":"release_notes/#v081","title":"\ud83d\udea8\ud83d\udce2 v0.81","text":""},{"location":"release_notes/#breaking-changes_7","title":"BREAKING CHANGES","text":"
  • The order of arguments to render_to_response has changed, to align with the (now public) render method of Component class.
"},{"location":"release_notes/#feat_21","title":"Feat","text":"
  • Component.render() is public and documented

  • Slots passed render_to_response and render can now be rendered also as functions.

"},{"location":"release_notes/#v080","title":"v0.80","text":""},{"location":"release_notes/#feat_22","title":"Feat","text":"
  • Vue-like provide/inject with the {% provide %} tag and inject() method.
"},{"location":"release_notes/#v079","title":"\ud83d\udea8\ud83d\udce2 v0.79","text":""},{"location":"release_notes/#breaking-changes_8","title":"BREAKING CHANGES","text":"
  • 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.
"},{"location":"release_notes/#v077","title":"\ud83d\udea8\ud83d\udce2 v0.77","text":""},{"location":"release_notes/#breaking","title":"BREAKING","text":"
  • The syntax for accessing default slot content has changed from

    {% fill \"my_slot\" as \"alias\" %}\n    {{ alias.default }}\n{% endfill %}\n

    to

    {% fill \"my_slot\" default=\"alias\" %}\n    {{ alias }}\n{% endfill %}\n
"},{"location":"release_notes/#v074","title":"v0.74","text":""},{"location":"release_notes/#feat_23","title":"Feat","text":"
  • {% html_attrs %} tag for formatting data as HTML attributes

  • prefix:key=val construct for passing dicts to components

"},{"location":"release_notes/#v070","title":"\ud83d\udea8\ud83d\udce2 v0.70","text":""},{"location":"release_notes/#breaking-changes_9","title":"BREAKING CHANGES","text":"
  • {% 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.

"},{"location":"release_notes/#v067","title":"v0.67","text":""},{"location":"release_notes/#refactor_17","title":"Refactor","text":"
  • Changed the default way how context variables are resolved in slots. See the documentation for more details.
"},{"location":"release_notes/#v050","title":"\ud83d\udea8\ud83d\udce2 v0.50","text":""},{"location":"release_notes/#breaking-changes_10","title":"BREAKING CHANGES","text":"
  • {% 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.

"},{"location":"release_notes/#v034","title":"v0.34","text":""},{"location":"release_notes/#feat_24","title":"Feat","text":"
  • Components as views, which allows you to handle requests and render responses from within a component. See the documentation for more details.
"},{"location":"release_notes/#v028","title":"v0.28","text":""},{"location":"release_notes/#feat_25","title":"Feat","text":"
  • 'implicit' slot filling and the default option for slot tags.
"},{"location":"release_notes/#v027","title":"v0.27","text":""},{"location":"release_notes/#feat_26","title":"Feat","text":"
  • 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).
"},{"location":"release_notes/#v026","title":"\ud83d\udea8\ud83d\udce2 v0.26","text":""},{"location":"release_notes/#breaking-changes_11","title":"BREAKING CHANGES","text":"
  • Changed the syntax for {% slot %} tags. From now on, we separate defining a slot ({% slot %}) from filling a slot with content ({% fill %}). This means you will likely need to change a lot of slot tags to fill.

    We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice feature to have access to. Hoping that this will feel worth it!

"},{"location":"release_notes/#v022","title":"v0.22","text":""},{"location":"release_notes/#feat_27","title":"Feat","text":"
  • All files inside components subdirectores are autoimported 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.

"},{"location":"release_notes/#v017","title":"v0.17","text":""},{"location":"release_notes/#breaking-changes_12","title":"BREAKING CHANGES","text":"
  • Renamed 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.

"},{"location":"concepts/advanced/component_caching/","title":"Component caching","text":"

Component caching allows you to store the rendered output of a component. Next time the component is rendered with the same input, the cached output is returned instead of re-rendering the component.

This is particularly useful for components that are expensive to render or do not change frequently.

Info

Component caching uses Django's cache framework, so you can use any cache backend that is supported by Django.

"},{"location":"concepts/advanced/component_caching/#enabling-caching","title":"Enabling caching","text":"

Caching is disabled by default.

To enable caching for a component, set Component.Cache.enabled to True:

from django_components import Component\n\nclass MyComponent(Component):\n    class Cache:\n        enabled = True\n
"},{"location":"concepts/advanced/component_caching/#time-to-live-ttl","title":"Time-to-live (TTL)","text":"

You can specify a time-to-live (TTL) for the cache entry with Component.Cache.ttl, which determines how long the entry remains valid. The TTL is specified in seconds.

class MyComponent(Component):\n    class Cache:\n        enabled = True\n        ttl = 60 * 60 * 24  # 1 day\n
  • If ttl > 0, entries are cached for the specified number of seconds.
  • If ttl = -1, entries are cached indefinitely.
  • If ttl = 0, entries are not cached.
  • If ttl = None, the default TTL is used.
"},{"location":"concepts/advanced/component_caching/#custom-cache-name","title":"Custom cache name","text":"

Since component caching uses Django's cache framework, you can specify a custom cache name with Component.Cache.cache_name to use a different cache backend:

class MyComponent(Component):\n    class Cache:\n        enabled = True\n        cache_name = \"my_cache\"\n
"},{"location":"concepts/advanced/component_caching/#cache-key-generation","title":"Cache key generation","text":"

By default, the cache key is generated based on the component's input (args and kwargs). So the following two calls would generate separate entries in the cache:

MyComponent.render(name=\"Alice\")\nMyComponent.render(name=\"Bob\")\n

However, you have full control over the cache key generation. As such, you can:

  • Cache the component on all inputs (default)
  • Cache the component on particular inputs
  • Cache the component irrespective of the inputs

To achieve that, you can override the Component.Cache.hash() method to customize how arguments are hashed into the cache key.

class MyComponent(Component):\n    class Cache:\n        enabled = True\n\n        def hash(self, *args, **kwargs):\n            return f\"{json.dumps(args)}:{json.dumps(kwargs)}\"\n

For even more control, you can override other methods available on the ComponentCache class.

Warning

The default implementation of Cache.hash() simply serializes the input into a string. As such, it might not be suitable if you need to hash complex objects like Models.

"},{"location":"concepts/advanced/component_caching/#caching-slots","title":"Caching slots","text":"

By default, the cache key is generated based ONLY on the args and kwargs.

To cache the component based on the slots, set Component.Cache.include_slots to True:

class MyComponent(Component):\n    class Cache:\n        enabled = True\n        include_slots = True\n

with include_slots = True, the cache key will be generated also based on the given slots.

As such, the following two calls would generate separate entries in the cache:

{% component \"my_component\" position=\"left\" %}\n    Hello, Alice\n{% endcomponent %}\n\n{% component \"my_component\" position=\"left\" %}\n    Hello, Bob\n{% endcomponent %}\n

Same when using Component.render() with string slots:

MyComponent.render(\n    kwargs={\"position\": \"left\"},\n    slots={\"content\": \"Hello, Alice\"}\n)\nMyComponent.render(\n    kwargs={\"position\": \"left\"},\n    slots={\"content\": \"Hello, Bob\"}\n)\n

Warning

Passing slots as functions to cached components with include_slots=True will raise an error.

MyComponent.render(\n    kwargs={\"position\": \"left\"},\n    slots={\"content\": lambda ctx: \"Hello, Alice\"}\n)\n

Warning

Slot caching DOES NOT account for context variables within the {% fill %} tag.

For example, the following two cases will be treated as the same entry:

{% with my_var=\"foo\" %}\n    {% component \"mycomponent\" name=\"foo\" %}\n        {{ my_var }}\n    {% endcomponent %}\n{% endwith %}\n\n{% with my_var=\"bar\" %}\n    {% component \"mycomponent\" name=\"bar\" %}\n        {{ my_var }}\n    {% endcomponent %}\n{% endwith %}\n

Currently it's impossible to capture used variables. This will be addressed in v2. Read more about it in django-components/#1164.

"},{"location":"concepts/advanced/component_caching/#example","title":"Example","text":"

Here's a complete example of a component with caching enabled:

from django_components import Component\n\nclass MyComponent(Component):\n    template = \"Hello, {{ name }}\"\n\n    class Cache:\n        enabled = True\n        ttl = 300  # Cache for 5 minutes\n        cache_name = \"my_cache\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\"name\": kwargs[\"name\"]}\n

In this example, the component's rendered output is cached for 5 minutes using the my_cache backend.

"},{"location":"concepts/advanced/component_context_scope/","title":"Component context and scope","text":"

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

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_template_data by accessing the property self.outer_context.

"},{"location":"concepts/advanced/component_context_scope/#example-of-accessing-outer-context","title":"Example of Accessing Outer Context","text":"
<div>\n  {% component \"calender\" / %}\n</div>\n

Assuming that the rendering context has variables such as date, you can use self.outer_context to access them from within get_template_data. Here's how you might implement it:

class Calender(Component):\n\n    ...\n\n    def get_template_data(self, args, kwargs, slots, context):\n        outer_field = self.outer_context[\"date\"]\n        return {\n            \"date\": outer_fields,\n        }\n

However, as a best practice, it\u2019s 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.

"},{"location":"concepts/advanced/component_context_scope/#context-behavior","title":"Context behavior","text":"

django_components supports both Django and Vue-like behavior when it comes to passing data to and through components. This can be configured in context_behavior.

This has two modes:

  • \"django\"

    The default Django template behavior.

    Inside the {% fill %} tag, the context variables you can access are a union of:

    • All the variables that were OUTSIDE the fill tag, including any\\ {% with %} tags.
    • Any loops ({% for ... %}) that the {% fill %} tag is part of.
    • Data returned from Component.get_template_data() of the component that owns the fill tag.
  • \"isolated\"

    Similar behavior to Vue or React, this is useful if you want to make sure that components don't accidentally access variables defined outside of the component.

    Inside the {% fill %} tag, you can ONLY access variables from 2 places:

    • Any loops ({% for ... %}) that the {% fill %} tag is part of.
    • Component.get_template_data() of the component which defined the template (AKA the \"root\" component).

Warning

Notice that the component whose get_template_data() we use inside {% fill %} is NOT the same across the two modes!

Consider this example:

class Outer(Component):\n    template = \"\"\"\n      <div>\n        {% component \"inner\" %}\n          {% fill \"content\" %}\n            {{ my_var }}\n          {% endfill %}\n        {% endcomponent %}\n      </div>\n    \"\"\"\n
  • \"django\" - my_var has access to data from get_template_data() of both Inner and Outer. If there are variables defined in both, then Inner overshadows Outer.

  • \"isolated\" - my_var has access to data from get_template_data() of ONLY Outer.

"},{"location":"concepts/advanced/component_context_scope/#example-django","title":"Example \"django\"","text":"

Given this template:

@register(\"root_comp\")\nclass RootComp(Component):\n    template = \"\"\"\n        {% with cheese=\"feta\" %}\n            {% component 'my_comp' %}\n                {{ my_var }}  # my_var\n                {{ cheese }}  # cheese\n            {% endcomponent %}\n        {% endwith %}\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return { \"my_var\": 123 }\n

Then if get_template_data() of the component \"my_comp\" returns following data:

{ \"my_var\": 456 }\n

Then the template will be rendered as:

456   # my_var\nfeta  # cheese\n

Because \"my_comp\" overshadows the outer 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.

"},{"location":"concepts/advanced/component_context_scope/#example-isolated","title":"Example \"isolated\"","text":"

Given this template:

class RootComp(Component):\n    template = \"\"\"\n        {% with cheese=\"feta\" %}\n            {% component 'my_comp' %}\n                {{ my_var }}  # my_var\n                {{ cheese }}  # cheese\n            {% endcomponent %}\n        {% endwith %}\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return { \"my_var\": 123 }\n

Then if get_template_data() of the component \"my_comp\" returns following data:

{ \"my_var\": 456 }\n

Then the template will be rendered as:

123   # my_var\n    # cheese\n

Because variables \"my_var\" and \"cheese\" are searched only inside RootComponent.get_template_data(). But since \"cheese\" is not defined there, it's empty.

Info

Notice that the variables defined with the {% with %} tag are ignored inside the {% fill %} tag with the \"isolated\" mode.

"},{"location":"concepts/advanced/component_libraries/","title":"Component libraries","text":"

You can publish and share your components for others to use. Below you will find the steps to do so.

For live examples, see the Community examples.

"},{"location":"concepts/advanced/component_libraries/#writing-component-libraries","title":"Writing component libraries","text":"
  1. Create a Django project with a similar structure:

    project/\n  |--  myapp/\n    |--  __init__.py\n    |--  apps.py\n    |--  templates/\n      |--  table/\n        |--  table.py\n        |--  table.js\n        |--  table.css\n        |--  table.html\n    |--  menu.py   <--- single-file component\n  |--  templatetags/\n    |--  __init__.py\n    |--  mytags.py\n
  2. Create custom Library and ComponentRegistry instances in mytags.py

    This will be the entrypoint for using the components inside Django templates.

    Remember that Django requires the Library instance to be accessible under the register variable (See Django docs):

    from django.template import Library\nfrom django_components import ComponentRegistry, RegistrySettings\n\nregister = library = django.template.Library()\ncomp_registry = ComponentRegistry(\n    library=library,\n    settings=RegistrySettings(\n        context_behavior=\"isolated\",\n        tag_formatter=\"django_components.component_formatter\",\n    ),\n)\n

    As you can see above, this is also the place where we configure how our components should behave, using the settings argument. If omitted, default settings are used.

    For library authors, we recommend setting context_behavior to \"isolated\", so that the state cannot leak into the components, and so the components' behavior is configured solely through the inputs. This means that the components will be more predictable and easier to debug.

    Next, you can decide how will others use your components by setting the tag_formatter options.

    If omitted or set to \"django_components.component_formatter\", your components will be used like this:

    {% component \"table\" items=items headers=headers %}\n{% endcomponent %}\n

    Or you can use \"django_components.component_shorthand_formatter\" to use components like so:

    {% table items=items headers=headers %}\n{% endtable %}\n

    Or you can define a custom TagFormatter.

    Either way, these settings will be scoped only to your components. So, in the user code, there may be components side-by-side that use different formatters:

    {% load mytags %}\n\n{# Component from your library \"mytags\", using the \"shorthand\" formatter #}\n{% table items=items headers=header %}\n{% endtable %}\n\n{# User-created components using the default settings #}\n{% component \"my_comp\" title=\"Abc...\" %}\n{% endcomponent %}\n
  3. Write your components and register them with your instance of ComponentRegistry

    There's one difference when you are writing components that are to be shared, and that's that the components must be explicitly registered with your instance of ComponentRegistry from the previous step.

    For better user experience, you can also define the types for the args, kwargs, slots and data.

    It's also a good idea to have a common prefix for your components, so they can be easily distinguished from users' components. In the example below, we use the prefix my_ / My.

    from typing import NamedTuple, Optional\nfrom django_components import Component, SlotInput, register, types\n\nfrom myapp.templatetags.mytags import comp_registry\n\n# Define the component\n# NOTE: Don't forget to set the `registry`!\n@register(\"my_menu\", registry=comp_registry)\nclass MyMenu(Component):\n    # Define the types\n    class Args(NamedTuple):\n        size: int\n        text: str\n\n    class Kwargs(NamedTuple):\n        vertical: Optional[bool] = None\n        klass: Optional[str] = None\n        style: Optional[str] = None\n\n    class Slots(NamedTuple):\n        default: Optional[SlotInput] = None\n\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        attrs = ...\n        return {\n            \"attrs\": attrs,\n        }\n\n    template: types.django_html = \"\"\"\n        {# Load django_components template tags #}\n        {% load component_tags %}\n\n        <div {% html_attrs attrs class=\"my-menu\" %}>\n            <div class=\"my-menu__content\">\n                {% slot \"default\" default / %}\n            </div>\n        </div>\n    \"\"\"\n
  4. Import the components in apps.py

    Normally, users rely on autodiscovery and COMPONENTS.dirs to load the component files.

    Since you, as the library author, are not in control of the file system, it is recommended to load the components manually.

    We recommend doing this in the AppConfig.ready() hook of your apps.py:

    from django.apps import AppConfig\n\nclass MyAppConfig(AppConfig):\n    default_auto_field = \"django.db.models.BigAutoField\"\n    name = \"myapp\"\n\n    # This is the code that gets run when user adds myapp\n    # to Django's INSTALLED_APPS\n    def ready(self) -> None:\n        # Import the components that you want to make available\n        # inside the templates.\n        from myapp.templates import (\n            menu,\n            table,\n        )\n

    Note that you can also include any other startup logic within AppConfig.ready().

And that's it! The next step is to publish it.

"},{"location":"concepts/advanced/component_libraries/#publishing-component-libraries","title":"Publishing component libraries","text":"

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/ .\n

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

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

Notes on publishing:

  • 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).
"},{"location":"concepts/advanced/component_libraries/#installing-and-using-component-libraries","title":"Installing and using component libraries","text":"

After the package has been published, all that remains is to install it in other django projects:

  1. Install the package:

    pip install myapp django_components\n
  2. Add the package to INSTALLED_APPS

    INSTALLED_APPS = [\n    ...\n    \"django_components\",\n    \"myapp\",\n]\n
  3. Optionally add the template tags to the builtins, so you don't have to call {% load mytags %} in every template:

    TEMPLATES = [\n    {\n        ...,\n        'OPTIONS': {\n            'builtins': [\n                'myapp.templatetags.mytags',\n            ]\n        },\n    },\n]\n
  4. And, at last, you can use the components in your own project!

    {% my_menu title=\"Abc...\" %}\n    Hello World!\n{% endmy_menu %}\n
"},{"location":"concepts/advanced/component_registry/","title":"Registering components","text":"

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\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"template.html\"\n\n    # This component takes one parameter, a date string to show in the template\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"date\"],\n        }\n

which we then render in the template as:

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

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.

"},{"location":"concepts/advanced/component_registry/#what-is-componentregistry","title":"What is ComponentRegistry","text":"

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()\n\n@register(registry=my_registry)\nclass MyComponent(Component):\n    ...\n

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

"},{"location":"concepts/advanced/component_registry/#working-with-componentregistry","title":"Working with ComponentRegistry","text":"

The default ComponentRegistry instance can be imported as:

from django_components import registry\n

You can use the registry to manually add/remove/get components:

from django_components import registry\n\n# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get all or single\nregistry.all()  # {\"button\": ButtonComponent, \"card\": CardComponent}\nregistry.get(\"card\")  # CardComponent\n\n# Check if component is registered\nregistry.has(\"button\")  # True\n\n# Unregister single component\nregistry.unregister(\"card\")\n\n# Unregister all components\nregistry.clear()\n
"},{"location":"concepts/advanced/component_registry/#registering-components-to-custom-componentregistry","title":"Registering components to custom ComponentRegistry","text":"

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\nfrom django_components import ComponentRegistry\n\nmy_library = Library(...)\nmy_registry = ComponentRegistry(library=my_library)\n

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\n\n@register(\"my_component\", registry=my_registry)\nclass MyComponent(Component):\n    ...\n

NOTE: The Library instance can be accessed under library attribute of ComponentRegistry.

"},{"location":"concepts/advanced/component_registry/#componentregistry-settings","title":"ComponentRegistry settings","text":"

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\nfrom django_components import ComponentRegistry, RegistrySettings\n\nregister = library = django.template.Library()\ncomp_registry = ComponentRegistry(\n    library=library,\n    settings=RegistrySettings(\n        context_behavior=\"isolated\",\n        tag_formatter=\"django_components.component_formatter\",\n    ),\n)\n

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.

"},{"location":"concepts/advanced/extensions/","title":"Extensions","text":"

New in version 0.131

Django-components functionality can be extended with \"extensions\". Extensions allow for powerful customization and integrations. They can:

  • Tap into lifecycle events, such as when a component is created, deleted, registered, or unregistered.
  • Add new attributes and methods to the components under an extension-specific nested class.
  • Define custom commands that can be executed via the Django management command interface.
"},{"location":"concepts/advanced/extensions/#live-examples","title":"Live examples","text":"
  • djc-ext-pydantic
"},{"location":"concepts/advanced/extensions/#install-extensions","title":"Install extensions","text":"

Extensions are configured in the Django settings under COMPONENTS.extensions.

Extensions can be set by either as an import string or by passing in a class:

# settings.py\n\nclass MyExtension(ComponentExtension):\n    name = \"my_extension\"\n\n    class ComponentConfig(ExtensionComponentConfig):\n        ...\n\nCOMPONENTS = ComponentsSettings(\n    extensions=[\n        MyExtension,\n        \"another_app.extensions.AnotherExtension\",\n        \"my_app.extensions.ThirdExtension\",\n    ],\n)\n
"},{"location":"concepts/advanced/extensions/#lifecycle-hooks","title":"Lifecycle hooks","text":"

Extensions can define methods to hook into lifecycle events, such as:

  • Component creation or deletion
  • Un/registering a component
  • Creating or deleting a registry
  • Pre-processing data passed to a component on render
  • Post-processing data returned from get_template_data() and others.

See the full list in Extension Hooks Reference.

"},{"location":"concepts/advanced/extensions/#per-component-configuration","title":"Per-component configuration","text":"

Each extension has a corresponding nested class within the Component class. These allow to configure the extensions on a per-component basis.

E.g.:

  • \"view\" extension -> Component.View
  • \"cache\" extension -> Component.Cache
  • \"defaults\" extension -> Component.Defaults

Note

Accessing the component instance from inside the nested classes:

Each method of the nested classes has access to the component attribute, which points to the component instance.

class MyTable(Component):\n    class MyExtension:\n        def get(self, request):\n            # `self.component` points to the instance of `MyTable` Component.\n            return self.component.render_to_response(request=request)\n
"},{"location":"concepts/advanced/extensions/#example-component-as-view","title":"Example: Component as View","text":"

The Components as Views feature is actually implemented as an extension that is configured by a View nested class.

You can override the get(), post(), etc methods to customize the behavior of the component as a view:

class MyTable(Component):\n    class View:\n        def get(self, request):\n            return self.component_class.render_to_response(request=request)\n\n        def post(self, request):\n            return self.component_class.render_to_response(request=request)\n\n        ...\n
"},{"location":"concepts/advanced/extensions/#example-storybook-integration","title":"Example: Storybook integration","text":"

The Storybook integration (work in progress) is an extension that is configured by a Storybook nested class.

You can override methods such as title, parameters, etc, to customize how to generate a Storybook JSON file from the component.

class MyTable(Component):\n    class Storybook:\n        def title(self):\n            return self.component_cls.__name__\n\n        def parameters(self) -> Parameters:\n            return {\n                \"server\": {\n                    \"id\": self.component_cls.__name__,\n                }\n            }\n\n        def stories(self) -> List[StoryAnnotations]:\n            return []\n\n        ...\n
"},{"location":"concepts/advanced/extensions/#extension-defaults","title":"Extension defaults","text":"

Extensions are incredibly flexible, but configuring the same extension for every component can be a pain.

For this reason, django-components allows for extension defaults. This is like setting the extension config for every component.

To set extension defaults, use the COMPONENTS.extensions_defaults setting.

The extensions_defaults setting is a dictionary where the key is the extension name and the value is a dictionary of config attributes:

COMPONENTS = ComponentsSettings(\n    extensions=[\n        \"my_extension.MyExtension\",\n        \"storybook.StorybookExtension\",\n    ],\n    extensions_defaults={\n        \"my_extension\": {\n            \"key\": \"value\",\n        },\n        \"view\": {\n            \"public\": True,\n        },\n        \"cache\": {\n            \"ttl\": 60,\n        },\n        \"storybook\": {\n            \"title\": lambda self: self.component_cls.__name__,\n        },\n    },\n)\n

Which is equivalent to setting the following for every component:

class MyTable(Component):\n    class MyExtension:\n        key = \"value\"\n\n    class View:\n        public = True\n\n    class Cache:\n        ttl = 60\n\n    class Storybook:\n        def title(self):\n            return self.component_cls.__name__\n

Info

If you define an attribute as a function, it is like defining a method on the extension class.

E.g. in the example above, title is a method on the Storybook extension class.

As the name suggests, these are defaults, and so you can still selectively override them on a per-component basis:

class MyTable(Component):\n    class View:\n        public = False\n
"},{"location":"concepts/advanced/extensions/#extensions-in-component-instances","title":"Extensions in component instances","text":"

Above, we've configured extensions View and Storybook for the MyTable component.

You can access the instances of these extension classes in the component instance.

Extensions are available under their names (e.g. self.view, self.storybook).

For example, the View extension is available as self.view:

class MyTable(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        # `self.view` points to the instance of `View` extension.\n        return {\n            \"view\": self.view,\n        }\n

And the Storybook extension is available as self.storybook:

class MyTable(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        # `self.storybook` points to the instance of `Storybook` extension.\n        return {\n            \"title\": self.storybook.title(),\n        }\n
"},{"location":"concepts/advanced/extensions/#writing-extensions","title":"Writing extensions","text":"

Creating extensions in django-components involves defining a class that inherits from ComponentExtension. This class can implement various lifecycle hooks and define new attributes or methods to be added to components.

"},{"location":"concepts/advanced/extensions/#extension-class","title":"Extension class","text":"

To create an extension, define a class that inherits from ComponentExtension and implement the desired hooks.

  • Each extension MUST have a name attribute. The name MUST be a valid Python identifier.
  • The extension may implement any of the hook methods.

    Each hook method receives a context object with relevant data.

  • Extension may own URLs or CLI commands.

from django_components.extension import ComponentExtension, OnComponentClassCreatedContext\n\nclass MyExtension(ComponentExtension):\n    name = \"my_extension\"\n\n    def on_component_class_created(self, ctx: OnComponentClassCreatedContext) -> None:\n        # Custom logic for when a component class is created\n        ctx.component_cls.my_attr = \"my_value\"\n

Warning

The name attribute MUST be unique across all extensions.

Moreover, the name attribute MUST NOT conflict with existing Component class API.

So if you name an extension render, it will conflict with the render() method of the Component class.

"},{"location":"concepts/advanced/extensions/#component-config","title":"Component config","text":"

In previous sections we've seen the View and Storybook extensions classes that were nested within the Component class:

class MyComponent(Component):\n    class View:\n        ...\n\n    class Storybook:\n        ...\n

These can be understood as component-specific overrides or configuration.

Whether it's Component.View or Component.Storybook, their respective extensions defined how these nested classes will behave.

For example, the View extension defines the API that users may override in ViewExtension.ComponentConfig:

from django_components.extension import ComponentExtension, ExtensionComponentConfig\n\nclass ViewExtension(ComponentExtension):\n    name = \"view\"\n\n    # The default behavior of the `View` extension class.\n    class ComponentConfig(ExtensionComponentConfig):\n        def get(self, request):\n            raise NotImplementedError(\"You must implement the `get` method.\")\n\n        def post(self, request):\n            raise NotImplementedError(\"You must implement the `post` method.\")\n\n        ...\n

In any component that then defines a nested Component.View extension class, the resulting View class will actually subclass from the ViewExtension.ComponentConfig class.

In other words, when you define a component like this:

class MyTable(Component):\n    class View:\n        def get(self, request):\n            # Do something\n            ...\n

Behind the scenes it is as if you defined the following:

class MyTable(Component):\n    class View(ViewExtension.ComponentConfig):\n        def get(self, request):\n            # Do something\n            ...\n

Warning

When writing an extension, the ComponentConfig MUST subclass the base class ExtensionComponentConfig.

This base class ensures that the extension class will have access to the component instance.

"},{"location":"concepts/advanced/extensions/#install-your-extension","title":"Install your extension","text":"

Once the extension is defined, it needs to be installed in the Django settings to be used by the application.

Extensions can be given either as an extension class, or its import string:

# settings.py\nCOMPONENTS = {\n    \"extensions\": [\n        \"my_app.extensions.MyExtension\",\n    ],\n}\n

Or by reference:

# settings.py\nfrom my_app.extensions import MyExtension\n\nCOMPONENTS = {\n    \"extensions\": [\n        MyExtension,\n    ],\n}\n
"},{"location":"concepts/advanced/extensions/#full-example-custom-logging-extension","title":"Full example: Custom logging extension","text":"

To tie it all together, here's an example of a custom logging extension that logs when components are created, deleted, or rendered:

  • Each component can specify which color to use for the logging by setting Component.ColorLogger.color.
  • The extension will log the component name and color when the component is created, deleted, or rendered.
from django_components.extension import (\n    ComponentExtension,\n    ExtensionComponentConfig,\n    OnComponentClassCreatedContext,\n    OnComponentClassDeletedContext,\n    OnComponentInputContext,\n)\n\n\nclass ColorLoggerExtension(ComponentExtension):\n    name = \"color_logger\"\n\n    # All `Component.ColorLogger` classes will inherit from this class.\n    class ComponentConfig(ExtensionComponentConfig):\n        color: str\n\n    # These hooks don't have access to the Component instance,\n    # only to the Component class, so we access the color\n    # as `Component.ColorLogger.color`.\n    def on_component_class_created(self, ctx: OnComponentClassCreatedContext):\n        log.info(\n            f\"Component {ctx.component_cls} created.\",\n            color=ctx.component_cls.ColorLogger.color,\n        )\n\n    def on_component_class_deleted(self, ctx: OnComponentClassDeletedContext):\n        log.info(\n            f\"Component {ctx.component_cls} deleted.\",\n            color=ctx.component_cls.ColorLogger.color,\n        )\n\n    # This hook has access to the Component instance, so we access the color\n    # as `self.component.color_logger.color`.\n    def on_component_input(self, ctx: OnComponentInputContext):\n        log.info(\n            f\"Rendering component {ctx.component_cls}.\",\n            color=ctx.component.color_logger.color,\n        )\n

To use the ColorLoggerExtension, add it to your settings:

# settings.py\nCOMPONENTS = {\n    \"extensions\": [\n        ColorLoggerExtension,\n    ],\n}\n

Once installed, in any component, you can define a ColorLogger attribute:

class MyComponent(Component):\n    class ColorLogger:\n        color = \"red\"\n

This will log the component name and color when the component is created, deleted, or rendered.

"},{"location":"concepts/advanced/extensions/#utility-functions","title":"Utility functions","text":"

django-components provides a few utility functions to help with writing extensions:

  • all_components() - returns a list of all created component classes.
  • all_registries() - returns a list of all created registry instances.
"},{"location":"concepts/advanced/extensions/#access-component-class","title":"Access component class","text":"

You can access the owner Component class (MyTable) from within methods of the extension class (MyExtension) by using the component_cls attribute:

class MyTable(Component):\n    class MyExtension:\n        def some_method(self):\n            print(self.component_cls)\n

Here is how the component_cls attribute may be used with our ColorLogger extension shown above:

class ColorLoggerComponentConfig(ExtensionComponentConfig):\n    color: str\n\n    def log(self, msg: str) -> None:\n        print(f\"{self.component_cls.__name__}: {msg}\")\n\n\nclass ColorLoggerExtension(ComponentExtension):\n    name = \"color_logger\"\n\n    # All `Component.ColorLogger` classes will inherit from this class.\n    ComponentConfig = ColorLoggerComponentConfig\n
"},{"location":"concepts/advanced/extensions/#pass-slot-metadata","title":"Pass slot metadata","text":"

When a slot is passed to a component, it is copied, so that the original slot is not modified with rendering metadata.

Therefore, don't use slot's identity to associate metadata with the slot:

# \u274c Don't do this:\nslots_cache = {}\n\nclass LoggerExtension(ComponentExtension):\n    name = \"logger\"\n\n    def on_component_input(self, ctx: OnComponentInputContext):\n        for slot in ctx.component.slots.values():\n            slots_cache[id(slot)] = {\"some\": \"metadata\"}\n

Instead, use the Slot.extra attribute, which is copied from the original slot:

# \u2705 Do this:\nclass LoggerExtension(ComponentExtension):\n    name = \"logger\"\n\n    # Save component-level logger settings for each slot when a component is rendered.\n    def on_component_input(self, ctx: OnComponentInputContext):\n        for slot in ctx.component.slots.values():\n            slot.extra[\"logger\"] = ctx.component.logger\n\n    # Then, when a fill is rendered with `{% slot %}`, we can access the logger settings\n    # from the slot's metadata.\n    def on_slot_rendered(self, ctx: OnSlotRenderedContext):\n        logger = ctx.slot.extra[\"logger\"]\n        logger.log(...)\n
"},{"location":"concepts/advanced/extensions/#extension-commands","title":"Extension commands","text":"

Extensions in django-components can define custom commands that can be executed via the Django management command interface. This allows for powerful automation and customization capabilities.

For example, if you have an extension that defines a command that prints \"Hello world\", you can run the command with:

python manage.py components ext run my_ext hello\n

Where:

  • python manage.py components - is the Django entrypoint
  • ext run - is the subcommand to run extension commands
  • my_ext - is the extension name
  • hello - is the command name
"},{"location":"concepts/advanced/extensions/#define-commands","title":"Define commands","text":"

To define a command, subclass from ComponentCommand. This subclass should define:

  • name - the command's name
  • help - the command's help text
  • handle - the logic to execute when the command is run
from django_components import ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n    name = \"hello\"\n    help = \"Say hello\"\n\n    def handle(self, *args, **kwargs):\n        print(\"Hello, world!\")\n\nclass MyExt(ComponentExtension):\n    name = \"my_ext\"\n    commands = [HelloCommand]\n
"},{"location":"concepts/advanced/extensions/#define-arguments-and-options","title":"Define arguments and options","text":"

Commands can accept positional arguments and options (e.g. --foo), which are defined using the arguments attribute of the ComponentCommand class.

The arguments are parsed with argparse into a dictionary of arguments and options. These are then available as keyword arguments to the handle method of the command.

from django_components import CommandArg, ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n    name = \"hello\"\n    help = \"Say hello\"\n\n    arguments = [\n        # Positional argument\n        CommandArg(\n            name_or_flags=\"name\",\n            help=\"The name to say hello to\",\n        ),\n        # Optional argument\n        CommandArg(\n            name_or_flags=[\"--shout\", \"-s\"],\n            action=\"store_true\",\n            help=\"Shout the hello\",\n        ),\n    ]\n\n    def handle(self, name: str, *args, **kwargs):\n        shout = kwargs.get(\"shout\", False)\n        msg = f\"Hello, {name}!\"\n        if shout:\n            msg = msg.upper()\n        print(msg)\n

You can run the command with arguments and options:

python manage.py components ext run my_ext hello John --shout\n>>> HELLO, JOHN!\n

Note

Command definitions are parsed with argparse, so you can use all the features of argparse to define your arguments and options.

See the argparse documentation for more information.

django-components defines types as CommandArg, CommandArgGroup, CommandSubcommand, and CommandParserInput to help with type checking.

Note

If a command doesn't have the handle method defined, the command will print a help message and exit.

"},{"location":"concepts/advanced/extensions/#argument-groups","title":"Argument groups","text":"

Arguments can be grouped using CommandArgGroup to provide better organization and help messages.

Read more on argparse argument groups.

from django_components import CommandArg, CommandArgGroup, ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n    name = \"hello\"\n    help = \"Say hello\"\n\n    # Argument parsing is managed by `argparse`.\n    arguments = [\n        # Positional argument\n        CommandArg(\n            name_or_flags=\"name\",\n            help=\"The name to say hello to\",\n        ),\n        # Optional argument\n        CommandArg(\n            name_or_flags=[\"--shout\", \"-s\"],\n            action=\"store_true\",\n            help=\"Shout the hello\",\n        ),\n        # When printing the command help message, `--bar` and `--baz`\n        # will be grouped under \"group bar\".\n        CommandArgGroup(\n            title=\"group bar\",\n            description=\"Group description.\",\n            arguments=[\n                CommandArg(\n                    name_or_flags=\"--bar\",\n                    help=\"Bar description.\",\n                ),\n                CommandArg(\n                    name_or_flags=\"--baz\",\n                    help=\"Baz description.\",\n                ),\n            ],\n        ),\n    ]\n\n    def handle(self, name: str, *args, **kwargs):\n        shout = kwargs.get(\"shout\", False)\n        msg = f\"Hello, {name}!\"\n        if shout:\n            msg = msg.upper()\n        print(msg)\n
"},{"location":"concepts/advanced/extensions/#subcommands","title":"Subcommands","text":"

Extensions can define subcommands, allowing for more complex command structures.

Subcommands are defined similarly to root commands, as subclasses of ComponentCommand class.

However, instead of defining the subcommands in the commands attribute of the extension, you define them in the subcommands attribute of the parent command:

from django_components import CommandArg, CommandArgGroup, ComponentCommand, ComponentExtension\n\nclass ChildCommand(ComponentCommand):\n    name = \"child\"\n    help = \"Child command\"\n\n    def handle(self, *args, **kwargs):\n        print(\"Child command\")\n\nclass ParentCommand(ComponentCommand):\n    name = \"parent\"\n    help = \"Parent command\"\n    subcommands = [\n        ChildCommand,\n    ]\n\n    def handle(self, *args, **kwargs):\n        print(\"Parent command\")\n

In this example, we can run two commands.

Either the parent command:

python manage.py components ext run parent\n>>> Parent command\n

Or the child command:

python manage.py components ext run parent child\n>>> Child command\n

Warning

Subcommands are independent of the parent command. When a subcommand runs, the parent command is NOT executed.

As such, if you want to pass arguments to both the parent and child commands, e.g.:

python manage.py components ext run parent --foo child --bar\n

You should instead pass all the arguments to the subcommand:

python manage.py components ext run parent child --foo --bar\n
"},{"location":"concepts/advanced/extensions/#help-message","title":"Help message","text":"

By default, all commands will print their help message when run with the --help / -h flag.

python manage.py components ext run my_ext --help\n

The help message prints out all the arguments and options available for the command, as well as any subcommands.

"},{"location":"concepts/advanced/extensions/#testing-commands","title":"Testing commands","text":"

Commands can be tested using Django's call_command() function, which allows you to simulate running the command in tests.

from django.core.management import call_command\n\ncall_command('components', 'ext', 'run', 'my_ext', 'hello', '--name', 'John')\n

To capture the output of the command, you can use the StringIO module to redirect the output to a string:

from io import StringIO\n\nout = StringIO()\nwith patch(\"sys.stdout\", new=out):\n    call_command('components', 'ext', 'run', 'my_ext', 'hello', '--name', 'John')\noutput = out.getvalue()\n

And to temporarily set the extensions, you can use the @djc_test decorator.

Thus, a full test example can then look like this:

from io import StringIO\nfrom unittest.mock import patch\n\nfrom django.core.management import call_command\nfrom django_components.testing import djc_test\n\n@djc_test(\n    components_settings={\n        \"extensions\": [\n            \"my_app.extensions.MyExtension\",\n        ],\n    },\n)\ndef test_hello_command(self):\n    out = StringIO()\n    with patch(\"sys.stdout\", new=out):\n        call_command('components', 'ext', 'run', 'my_ext', 'hello', '--name', 'John')\n    output = out.getvalue()\n    assert output == \"Hello, John!\\n\"\n
"},{"location":"concepts/advanced/extensions/#extension-urls","title":"Extension URLs","text":"

Extensions can define custom views and endpoints that can be accessed through the Django application.

To define URLs for an extension, set them in the urls attribute of your ComponentExtension class. Each URL is defined using the URLRoute class, which specifies the path, handler, and optional name for the route.

Here's an example of how to define URLs within an extension:

from django_components.extension import ComponentExtension, URLRoute\nfrom django.http import HttpResponse\n\ndef my_view(request):\n    return HttpResponse(\"Hello from my extension!\")\n\nclass MyExtension(ComponentExtension):\n    name = \"my_extension\"\n\n    urls = [\n        URLRoute(path=\"my-view/\", handler=my_view, name=\"my_view\"),\n        URLRoute(path=\"another-view/<int:id>/\", handler=my_view, name=\"another_view\"),\n    ]\n

Warning

The URLRoute objects are different from objects created with Django's django.urls.path(). Do NOT use URLRoute objects in Django's urlpatterns and vice versa!

django-components uses a custom URLRoute class to define framework-agnostic routing rules.

As of v0.131, URLRoute objects are directly converted to Django's URLPattern and URLResolver objects.

"},{"location":"concepts/advanced/extensions/#url-paths","title":"URL paths","text":"

The URLs defined in an extension are available under the path

/components/ext/<extension_name>/\n

For example, if you have defined a URL with the path my-view/<str:name>/ in an extension named my_extension, it can be accessed at:

/components/ext/my_extension/my-view/john/\n
"},{"location":"concepts/advanced/extensions/#nested-urls","title":"Nested URLs","text":"

Extensions can also define nested URLs to allow for more complex routing structures.

To define nested URLs, set the children attribute of the URLRoute object to a list of child URLRoute objects:

class MyExtension(ComponentExtension):\n    name = \"my_extension\"\n\n    urls = [\n        URLRoute(\n            path=\"parent/\",\n            name=\"parent_view\",\n            children=[\n                URLRoute(path=\"child/<str:name>/\", handler=my_view, name=\"child_view\"),\n            ],\n        ),\n    ]\n

In this example, the URL

/components/ext/my_extension/parent/child/john/\n

would call the my_view handler with the parameter name set to \"John\".

"},{"location":"concepts/advanced/extensions/#extra-url-data","title":"Extra URL data","text":"

The URLRoute class is framework-agnostic, so that extensions could be used with non-Django frameworks in the future.

However, that means that there may be some extra fields that Django's django.urls.path() accepts, but which are not defined on the URLRoute object.

To address this, the URLRoute object has an extra attribute, which is a dictionary that can be used to pass any extra kwargs to django.urls.path():

URLRoute(\n    path=\"my-view/<str:name>/\",\n    handler=my_view,\n    name=\"my_view\",\n    extra={\"kwargs\": {\"foo\": \"bar\"} },\n)\n

Is the same as:

django.urls.path(\n    \"my-view/<str:name>/\",\n    view=my_view,\n    name=\"my_view\",\n    kwargs={\"foo\": \"bar\"},\n)\n

because URLRoute is converted to Django's route like so:

django.urls.path(\n    route.path,\n    view=route.handler,\n    name=route.name,\n    **route.extra,\n)\n
"},{"location":"concepts/advanced/hooks/","title":"Lifecycle hooks","text":"

New in version 0.96

Intercept the rendering lifecycle with Component hooks.

Unlike the extension hooks, these are defined directly on the Component class.

"},{"location":"concepts/advanced/hooks/#available-hooks","title":"Available hooks","text":""},{"location":"concepts/advanced/hooks/#on_render_before","title":"on_render_before","text":"
def on_render_before(\n    self: Component,\n    context: Context,\n    template: Optional[Template],\n) -> None:\n

Component.on_render_before runs just before the component's template is rendered.

It is called for every component, including nested ones, as part of the component render lifecycle.

It receives the Context and the Template as arguments.

The template argument is None if the component has no template.

Example:

You can use this hook to access the context or the template:

from django.template import Context, Template\nfrom django_components import Component\n\nclass MyTable(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        # Insert value into the Context\n        context[\"from_on_before\"] = \":)\"\n\n        assert isinstance(template, Template)\n

Warning

If you want to pass data to the template, prefer using get_template_data() instead of this hook.

Warning

Do NOT modify the template in this hook. The template is reused across renders.

Since this hook is called for every component, this means that the template would be modified every time a component is rendered.

"},{"location":"concepts/advanced/hooks/#on_render","title":"on_render","text":"

New in version 0.140

def on_render(\n    self: Component,\n    context: Context,\n    template: Optional[Template],\n) -> Union[str, SafeString, OnRenderGenerator, None]:\n

Component.on_render does the actual rendering.

You can override this method to:

  • Change what template gets rendered
  • Modify the context
  • Modify the rendered output after it has been rendered
  • Handle errors

The default implementation renders the component's Template with the given Context.

class MyTable(Component):\n    def on_render(self, context, template):\n        if template is None:\n            return None\n        else:\n            return template.render(context)\n

The template argument is None if the component has no template.

"},{"location":"concepts/advanced/hooks/#modifying-rendered-template","title":"Modifying rendered template","text":"

To change what gets rendered, you can:

  • Render a different template
  • Render a component
  • Return a different string or SafeString
class MyTable(Component):\n    def on_render(self, context, template):\n        return \"Hello\"\n

You can also use on_render() as a router, rendering other components based on the parent component's arguments:

class MyTable(Component):\n    def on_render(self, context, template):\n        # Select different component based on `feature_new_table` kwarg\n        if self.kwargs.get(\"feature_new_table\"):\n            comp_cls = NewTable\n        else:\n            comp_cls = OldTable\n\n        # Render the selected component\n        return comp_cls.render(\n            args=self.args,\n            kwargs=self.kwargs,\n            slots=self.slots,\n            context=context,\n        )\n
"},{"location":"concepts/advanced/hooks/#post-processing-rendered-template","title":"Post-processing rendered template","text":"

When you render the original template in on_render() as:

template.render(context)\n

The result is NOT the final output, but an intermediate result. Nested components are not rendered yet.

Instead, django-components needs to take this result and process it to actually render the child components.

To access the final output, you can yield the result instead of returning it.

This will return a tuple of (rendered HTML, error). The error is None if the rendering succeeded.

class MyTable(Component):\n    def on_render(self, context, template):\n        html, error = yield template.render(context)\n\n        if error is None:\n            # The rendering succeeded\n            return html\n        else:\n            # The rendering failed\n            print(f\"Error: {error}\")\n

At this point you can do 3 things:

  1. Return a new HTML

    The new HTML will be used as the final output.

    If the original template raised an error, it will be ignored.

    class MyTable(Component):\n    def on_render(self, context, template):\n        html, error = yield template.render(context)\n\n        return \"NEW HTML\"\n
  2. Raise a new exception

    The new exception is what will bubble up from the component.

    The original HTML and original error will be ignored.

    class MyTable(Component):\n    def on_render(self, context, template):\n        html, error = yield template.render(context)\n\n        raise Exception(\"Error message\")\n
  3. Return nothing (or None) to handle the result as usual

    If you don't raise an exception, and neither return a new HTML, then original HTML / error will be used:

    • If rendering succeeded, the original HTML will be used as the final output.
    • If rendering failed, the original error will be propagated.
    class MyTable(Component):\n    def on_render(self, context, template):\n        html, error = yield template.render(context)\n\n        if error is not None:\n            # The rendering failed\n            print(f\"Error: {error}\")\n
"},{"location":"concepts/advanced/hooks/#example-errorboundary","title":"Example: ErrorBoundary","text":"

on_render() can be used to implement React's ErrorBoundary.

That is, a component that catches errors in nested components and displays a fallback UI instead:

{% component \"error_boundary\" %}\n  {% fill \"content\" %}\n    {% component \"nested_component\" %}\n  {% endfill %}\n  {% fill \"fallback\" %}\n    Sorry, something went wrong.\n  {% endfill %}\n{% endcomponent %}\n

To implement this, we render the fallback slot in on_render() and return it if an error occured:

class ErrorFallback(Component):\n    template = \"\"\"\n      {% slot \"content\" default / %}\n    \"\"\"\n\n    def on_render(self, context, template):\n        fallback = self.slots.fallback\n\n        if fallback is None:\n            raise ValueError(\"fallback slot is required\")\n\n        html, error = yield template.render(context)\n\n        if error is not None:\n            return fallback()\n        else:\n            return html\n
"},{"location":"concepts/advanced/hooks/#on_render_after","title":"on_render_after","text":"
def on_render_after(\n    self: Component,\n    context: Context,\n    template: Optional[Template],\n    result: Optional[str | SafeString],\n    error: Optional[Exception],\n) -> Union[str, SafeString, None]:\n

on_render_after() runs when the component was fully rendered, including all its children.

It receives the same arguments as on_render_before(), plus the outcome of the rendering:

  • result: The rendered output of the component. None if the rendering failed.
  • error: The error that occurred during the rendering, or None if the rendering succeeded.

on_render_after() behaves the same way as the second part of on_render() (after the yield).

class MyTable(Component):\n    def on_render_after(self, context, template, result, error):\n        if error is None:\n            # The rendering succeeded\n            return result\n        else:\n            # The rendering failed\n            print(f\"Error: {error}\")\n

Same as on_render(), you can return a new HTML, raise a new exception, or return nothing:

  1. Return a new HTML

    The new HTML will be used as the final output.

    If the original template raised an error, it will be ignored.

    class MyTable(Component):\n    def on_render_after(self, context, template, result, error):\n        return \"NEW HTML\"\n
  2. Raise a new exception

    The new exception is what will bubble up from the component.

    The original HTML and original error will be ignored.

    class MyTable(Component):\n    def on_render_after(self, context, template, result, error):\n        raise Exception(\"Error message\")\n
  3. Return nothing (or None) to handle the result as usual

    If you don't raise an exception, and neither return a new HTML, then original HTML / error will be used:

    • If rendering succeeded, the original HTML will be used as the final output.
    • If rendering failed, the original error will be propagated.
    class MyTable(Component):\n    def on_render_after(self, context, template, result, error):\n        if error is not None:\n            # The rendering failed\n            print(f\"Error: {error}\")\n
"},{"location":"concepts/advanced/hooks/#example","title":"Example","text":"

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\" %}\n  {% component \"tab_item\" header=\"Tab 1\" %}\n    <p>\n      hello from tab 1\n    </p>\n    {% component \"button\" %}\n      Click me!\n    {% endcomponent %}\n  {% endcomponent %}\n\n  {% component \"tab_item\" header=\"Tab 2\" %}\n    Hello this is tab 2\n  {% endcomponent %}\n{% endcomponent %}\n
"},{"location":"concepts/advanced/html_fragments/","title":"HTML fragments","text":"

Django-components provides a seamless integration with HTML fragments with AJAX (HTML over the wire), whether you're using jQuery, HTMX, AlpineJS, vanilla JavaScript, or other.

If the fragment component has any JS or CSS, django-components will:

  • Automatically load the associated JS and CSS
  • Ensure that JS is loaded and executed only once even if the fragment is inserted multiple times

Info

What are HTML fragments and \"HTML over the wire\"?

It is one of the methods for updating the state in the browser UI upon user interaction.

How it works is that:

  1. User makes an action - clicks a button or submits a form
  2. The action causes a request to be made from the client to the server.
  3. Server processes the request (e.g. form submission), and responds with HTML of some part of the UI (e.g. a new entry in a table).
  4. A library like HTMX, AlpineJS, or custom function inserts the new HTML into the correct place.
"},{"location":"concepts/advanced/html_fragments/#document-and-fragment-strategies","title":"Document and fragment strategies","text":"

Components support different \"strategies\" for rendering JS and CSS.

Two of them are used to enable HTML fragments - \"document\" and \"fragment\".

What's the difference?

"},{"location":"concepts/advanced/html_fragments/#document-strategy","title":"Document strategy","text":"

Document strategy assumes that the rendered components will be embedded into the HTML of the initial page load. This means that:

  • The JS and CSS is embedded into the HTML as <script> and <style> tags (see Default JS / CSS locations)
  • Django-components injects a JS script for managing JS and CSS assets

A component is rendered as a \"document\" when:

  • It is embedded inside a template as {% component %}
  • It is rendered with Component.render() or Component.render_to_response() with the deps_strategy kwarg set to \"document\" (default)

Example:

MyTable.render(\n    kwargs={...},\n)\n\n# or\n\nMyTable.render(\n    kwargs={...},\n    deps_strategy=\"document\",\n)\n
"},{"location":"concepts/advanced/html_fragments/#fragment-strategy","title":"Fragment strategy","text":"

Fragment strategy assumes that the main HTML has already been rendered and loaded on the page. The component renders HTML that will be inserted into the page as a fragment, at a LATER time:

  • JS and CSS is not directly embedded to avoid duplicately executing the same JS scripts. So template tags like {% component_js_dependencies %} inside of fragments are ignored.
  • Instead, django-components appends the fragment's content with a JSON <script> to trigger a call to its asset manager JS script, which will load the JS and CSS smartly.
  • The asset manager JS script is assumed to be already loaded on the page.

A component is rendered as \"fragment\" when:

  • It is rendered with Component.render() or Component.render_to_response() with the deps_strategy kwarg set to \"fragment\"

Example:

MyTable.render(\n    kwargs={...},\n    deps_strategy=\"fragment\",\n)\n
"},{"location":"concepts/advanced/html_fragments/#live-examples","title":"Live examples","text":"

For live interactive examples, start our demo project (sampleproject).

Then navigate to these URLs:

  • /fragment/base/alpine
  • /fragment/base/htmx
  • /fragment/base/js
"},{"location":"concepts/advanced/html_fragments/#example-htmx","title":"Example - HTMX","text":""},{"location":"concepts/advanced/html_fragments/#1-define-document-html","title":"1. Define document HTML","text":"

This is the HTML into which a fragment will be loaded using HTMX.

[root]/components/demo.py
from django_components import Component, types\n\nclass MyPage(Component):\n    template = \"\"\"\n        {% load component_tags %}\n        <!DOCTYPE html>\n        <html>\n            <head>\n                {% component_css_dependencies %}\n                <script src=\"https://unpkg.com/htmx.org@1.9.12\"></script>\n            </head>\n            <body>\n                <div id=\"target\">OLD</div>\n\n                <button\n                    hx-get=\"/mypage/frag\"\n                    hx-swap=\"outerHTML\"\n                    hx-target=\"#target\"\n                >\n                  Click me!\n                </button>\n\n                {% component_js_dependencies %}\n            </body>\n        </html>\n    \"\"\"\n\n    class View:\n        def get(self, request):\n            return self.component_cls.render_to_response(request=request)\n
"},{"location":"concepts/advanced/html_fragments/#2-define-fragment-html","title":"2. Define fragment HTML","text":"

The fragment to be inserted into the document.

IMPORTANT: Don't forget to set deps_strategy=\"fragment\"

[root]/components/demo.py
class Frag(Component):\n    template = \"\"\"\n        <div class=\"frag\">\n            123\n            <span id=\"frag-text\"></span>\n        </div>\n    \"\"\"\n\n    js = \"\"\"\n        document.querySelector('#frag-text').textContent = 'xxx';\n    \"\"\"\n\n    css = \"\"\"\n        .frag {\n            background: blue;\n        }\n    \"\"\"\n\n    class View:\n        def get(self, request):\n            return self.component_cls.render_to_response(\n                request=request,\n                # IMPORTANT: Don't forget `deps_strategy=\"fragment\"`\n                deps_strategy=\"fragment\",\n            )\n
"},{"location":"concepts/advanced/html_fragments/#3-create-view-and-urls","title":"3. Create view and URLs","text":"[app]/urls.py
from django.urls import path\n\nfrom components.demo import MyPage, Frag\n\nurlpatterns = [\n    path(\"mypage/\", MyPage.as_view())\n    path(\"mypage/frag\", Frag.as_view()),\n]\n
"},{"location":"concepts/advanced/html_fragments/#example-alpinejs","title":"Example - AlpineJS","text":""},{"location":"concepts/advanced/html_fragments/#1-define-document-html_1","title":"1. Define document HTML","text":"

This is the HTML into which a fragment will be loaded using AlpineJS.

[root]/components/demo.py
from django_components import Component, types\n\nclass MyPage(Component):\n    template = \"\"\"\n        {% load component_tags %}\n        <!DOCTYPE html>\n        <html>\n            <head>\n                {% component_css_dependencies %}\n                <script defer src=\"https://unpkg.com/alpinejs\"></script>\n            </head>\n            <body x-data=\"{\n                htmlVar: 'OLD',\n                loadFragment: function () {\n                    const url = '/mypage/frag';\n                    fetch(url)\n                        .then(response => response.text())\n                        .then(html => {\n                            this.htmlVar = html;\n                        });\n                }\n            }\">\n                <div id=\"target\" x-html=\"htmlVar\">OLD</div>\n\n                <button @click=\"loadFragment\">\n                  Click me!\n                </button>\n\n                {% component_js_dependencies %}\n            </body>\n        </html>\n    \"\"\"\n\n    class View:\n        def get(self, request):\n            return self.component_cls.render_to_response(request=request)\n
"},{"location":"concepts/advanced/html_fragments/#2-define-fragment-html_1","title":"2. Define fragment HTML","text":"

The fragment to be inserted into the document.

IMPORTANT: Don't forget to set deps_strategy=\"fragment\"

[root]/components/demo.py
class Frag(Component):\n    # NOTE: We wrap the actual fragment in a template tag with x-if=\"false\" to prevent it\n    #       from being rendered until we have registered the component with AlpineJS.\n    template = \"\"\"\n        <template x-if=\"false\" data-name=\"frag\">\n            <div class=\"frag\">\n                123\n                <span x-data=\"frag\" x-text=\"fragVal\">\n                </span>\n            </div>\n        </template>\n    \"\"\"\n\n    js = \"\"\"\n        Alpine.data('frag', () => ({\n            fragVal: 'xxx',\n        }));\n\n        // Now that the component has been defined in AlpineJS, we can \"activate\"\n        // all instances where we use the `x-data=\"frag\"` directive.\n        document.querySelectorAll('[data-name=\"frag\"]').forEach((el) => {\n            el.setAttribute('x-if', 'true');\n        });\n    \"\"\"\n\n    css = \"\"\"\n        .frag {\n            background: blue;\n        }\n    \"\"\"\n\n    class View:\n        def get(self, request):\n            return self.component_cls.render_to_response(\n                request=request,\n                # IMPORTANT: Don't forget `deps_strategy=\"fragment\"`\n                deps_strategy=\"fragment\",\n            )\n
"},{"location":"concepts/advanced/html_fragments/#3-create-view-and-urls_1","title":"3. Create view and URLs","text":"[app]/urls.py
from django.urls import path\n\nfrom components.demo import MyPage, Frag\n\nurlpatterns = [\n    path(\"mypage/\", MyPage.as_view())\n    path(\"mypage/frag\", Frag.as_view()),\n]\n
"},{"location":"concepts/advanced/html_fragments/#example-vanilla-js","title":"Example - Vanilla JS","text":""},{"location":"concepts/advanced/html_fragments/#1-define-document-html_2","title":"1. Define document HTML","text":"

This is the HTML into which a fragment will be loaded using vanilla JS.

[root]/components/demo.py
from django_components import Component, types\n\nclass MyPage(Component):\n    template = \"\"\"\n        {% load component_tags %}\n        <!DOCTYPE html>\n        <html>\n            <head>\n                {% component_css_dependencies %}\n            </head>\n            <body>\n                <div id=\"target\">OLD</div>\n\n                <button>\n                  Click me!\n                </button>\n                <script>\n                    const url = `/mypage/frag`;\n                    document.querySelector('#loader').addEventListener('click', function () {\n                        fetch(url)\n                            .then(response => response.text())\n                            .then(html => {\n                                document.querySelector('#target').outerHTML = html;\n                            });\n                    });\n                </script>\n\n                {% component_js_dependencies %}\n            </body>\n        </html>\n    \"\"\"\n\n    class View:\n        def get(self, request):\n            return self.component_cls.render_to_response(request=request)\n
"},{"location":"concepts/advanced/html_fragments/#2-define-fragment-html_2","title":"2. Define fragment HTML","text":"

The fragment to be inserted into the document.

IMPORTANT: Don't forget to set deps_strategy=\"fragment\"

[root]/components/demo.py
class Frag(Component):\n    template = \"\"\"\n        <div class=\"frag\">\n            123\n            <span id=\"frag-text\"></span>\n        </div>\n    \"\"\"\n\n    js = \"\"\"\n        document.querySelector('#frag-text').textContent = 'xxx';\n    \"\"\"\n\n    css = \"\"\"\n        .frag {\n            background: blue;\n        }\n    \"\"\"\n\n    class View:\n        def get(self, request):\n            return self.component_cls.render_to_response(\n                request=request,\n                # IMPORTANT: Don't forget `deps_strategy=\"fragment\"`\n                deps_strategy=\"fragment\",\n            )\n
"},{"location":"concepts/advanced/html_fragments/#3-create-view-and-urls_2","title":"3. Create view and URLs","text":"[app]/urls.py
from django.urls import path\n\nfrom components.demo import MyPage, Frag\n\nurlpatterns = [\n    path(\"mypage/\", MyPage.as_view())\n    path(\"mypage/frag\", Frag.as_view()),\n]\n
"},{"location":"concepts/advanced/provide_inject/","title":"Prop drilling and provide / inject","text":"

New in version 0.80:

django-components supports the provide / inject pattern, similarly to React's Context Providers or Vue's provide / inject.

This is achieved with the combination of:

  • {% provide %} tag
  • Component.inject() method
"},{"location":"concepts/advanced/provide_inject/#what-is-prop-drilling","title":"What is \"prop drilling\"","text":"

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.

With provide / inject, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.

This feature is inspired by Vue's Provide / Inject and React's Context / useContext.

As the name suggest, using provide / inject consists of 2 steps

  1. Providing data
  2. Injecting provided data

For examples of advanced uses of provide / inject, see this discussion.

"},{"location":"concepts/advanced/provide_inject/#providing-data","title":"Providing data","text":"

First we use the {% provide %} tag to define the data we want to \"provide\" (make available).

{% provide \"my_data\" hello=\"hi\" another=123 %}\n    {% component \"child\" / %}  <--- Can access \"my_data\"\n{% endprovide %}\n\n{% component \"child\" / %}  <--- Cannot access \"my_data\"\n

The first argument to the {% provide %} tag is the key by which we can later access the data passed to this tag. The key in this case is \"my_data\".

The key must resolve to a valid identifier (AKA a valid Python variable name).

Next you define the data you want to \"provide\" by passing them as keyword arguments. This is similar to how you pass data to the {% with %} tag or the {% slot %} tag.

Note

Kwargs passed to {% provide %} are NOT added to the context. In the example below, the {{ hello }} won't render anything:

{% provide \"my_data\" hello=\"hi\" another=123 %}\n    {{ hello }}\n{% endprovide %}\n

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

{% with my_name=\"my_name\" %}\n    {% provide name=my_name ... %}\n        ...\n    {% endprovide %}\n{% endwith %}\n
"},{"location":"concepts/advanced/provide_inject/#injecting-data","title":"Injecting data","text":"

To \"inject\" (access) the data defined on the {% provide %} tag, you can use the Component.inject() method from within any other component methods.

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: hello=\"hi\" another=123. That means that if we now inject \"my_data\", we get an object with 2 attributes - hello and another.

class ChildComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        my_data = self.inject(\"my_data\")\n        print(my_data.hello)    # hi\n        print(my_data.another)  # 123\n

First argument to Component.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(). This will act as a default value similar to dict.get(key, default):

class ChildComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        my_data = self.inject(\"invalid_key\", DEFAULT_DATA)\n        assert my_data == DEFAULT_DATA\n

Note

The instance returned from inject() is immutable (subclass of NamedTuple). This ensures that the data returned from inject() will always have all the keys that were passed to the {% provide %} tag.

Warning

inject() works strictly only during render execution. If you try to call inject() from outside, it will raise an error.

"},{"location":"concepts/advanced/provide_inject/#full-example","title":"Full example","text":"
@register(\"child\")\nclass ChildComponent(Component):\n    template = \"\"\"\n        <div> {{ my_data.hello }} </div>\n        <div> {{ my_data.another }} </div>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        my_data = self.inject(\"my_data\", \"default\")\n        return {\"my_data\": my_data}\n\ntemplate_str = \"\"\"\n    {% load component_tags %}\n    {% provide \"my_data\" hello=\"hi\" another=123 %}\n        {% component \"child\" / %}\n    {% endprovide %}\n\"\"\"\n

renders:

<div>hi</div>\n<div>123</div>\n
"},{"location":"concepts/advanced/rendering_js_css/","title":"Rendering JS / CSS","text":""},{"location":"concepts/advanced/rendering_js_css/#introduction","title":"Introduction","text":"

Components consist of 3 parts - HTML, JS and CSS.

Handling of HTML is straightforward - it is rendered as is, and inserted where the {% component %} tag is.

However, handling of JS and CSS is more complex:

  • JS and CSS is are inserted elsewhere in the HTML. As a best practice, JS is placed in the <body> HTML tag, and CSS in the <head>.
  • Multiple components may use the same JS and CSS files. We don't want to load the same files multiple times.
  • Fetching of JS and CSS may block the page, so the JS / CSS should be embedded in the HTML.
  • Components inserted as HTML fragments need different handling for JS and CSS.
"},{"location":"concepts/advanced/rendering_js_css/#default-js-css-locations","title":"Default JS / CSS locations","text":"

If your components use JS and CSS then, by default, the JS and CSS will be automatically inserted into the HTML:

  • CSS styles will be inserted at the end of the <head>
  • JS scripts will be inserted at the end of the <body>

If you want to place the dependencies elsewhere in the HTML, you can override the locations by inserting following Django template tags:

  • {% component_js_dependencies %} - Set new location(s) for JS scripts
  • {% component_css_dependencies %} - Set new location(s) for CSS styles

So if you have a component with JS and CSS:

from django_components import Component, types\n\nclass MyButton(Component):\n    template: types.django_html = \"\"\"\n        <button class=\"my-button\">\n            Click me!\n        </button>\n    \"\"\"\n\n    js: types.js = \"\"\"\n        for (const btnEl of document.querySelectorAll(\".my-button\")) {\n            btnEl.addEventListener(\"click\", () => {\n                console.log(\"BUTTON CLICKED!\");\n            });\n        }\n    \"\"\"\n\n    css: types.css \"\"\"\n        .my-button {\n            background: green;\n        }\n    \"\"\"\n\n    class Media:\n        js = [\"/extra/script.js\"]\n        css = [\"/extra/style.css\"]\n

Then:

  • JS from MyButton.js and MyButton.Media.js will be rendered at the default place (<body>), or in {% component_js_dependencies %}.

  • CSS from MyButton.css and MyButton.Media.css will be rendered at the default place (<head>), or in {% component_css_dependencies %}.

And if you don't specify {% component_dependencies %} tags, it is the equivalent of:

<!doctype html>\n<html>\n  <head>\n    <title>MyPage</title>\n    ...\n    {% component_css_dependencies %}\n  </head>\n  <body>\n    <main>\n      ...\n    </main>\n    {% component_js_dependencies %}\n  </body>\n</html>\n

Warning

If the rendered HTML does NOT contain neither {% component_dependencies %} template tags, nor <head> and <body> HTML tags, then the JS and CSS will NOT be inserted!

To force the JS and CSS to be inserted, use the \"append\" or \"prepend\" strategies.

"},{"location":"concepts/advanced/rendering_js_css/#dependencies-strategies","title":"Dependencies strategies","text":"

The rendered HTML may be used in different contexts (browser, email, etc). If your components use JS and CSS scripts, you may need to handle them differently.

The different ways for handling JS / CSS are called \"dependencies strategies\".

render() and render_to_response() accept a deps_strategy parameter, which controls where and how the JS / CSS are inserted into the HTML.

main_page = MainPage.render(deps_strategy=\"document\")\nfragment = MyComponent.render_to_response(deps_strategy=\"fragment\")\n

The deps_strategy parameter is set at the root of a component render tree, which is why it is not available for the {% component %} tag.

When you use Django's django.shortcuts.render() or Template.render() to render templates, you can't directly set the deps_strategy parameter.

In this case, you can set the deps_strategy with the DJC_DEPS_STRATEGY context variable.

from django.template.context import Context\nfrom django.shortcuts import render\n\nctx = Context({\"DJC_DEPS_STRATEGY\": \"fragment\"})\nfragment = render(request, \"my_component.html\", ctx=ctx)\n

Info

The deps_strategy parameter is ultimately passed to render_dependencies().

Why is deps_strategy required?

This is a technical limitation of the current implementation.

When a component is rendered, django-components embeds metadata about the component's JS and CSS into the HTML.

This way we can compose components together, and know which JS / CSS dependencies are needed.

As the last step of rendering, django-components extracts this metadata and uses a selected strategy to insert the JS / CSS into the HTML.

There are six dependencies strategies:

  • document (default)
    • Smartly inserts JS / CSS into placeholders or into <head> and <body> tags.
    • Inserts extra script to allow fragment strategy to work.
    • Assumes the HTML will be rendered in a JS-enabled browser.
  • fragment
    • A lightweight HTML fragment to be inserted into a document with AJAX.
    • No JS / CSS included.
  • simple
    • Smartly insert JS / CSS into placeholders or into <head> and <body> tags.
    • No extra script loaded.
  • prepend
    • Insert JS / CSS before the rendered HTML.
    • No extra script loaded.
  • append
    • Insert JS / CSS after the rendered HTML.
    • No extra script loaded.
  • ignore
    • HTML is left as-is. You can still process it with a different strategy later with render_dependencies().
    • Used for inserting rendered HTML into other components.
"},{"location":"concepts/advanced/rendering_js_css/#document","title":"document","text":"

deps_strategy=\"document\" is the default. Use this if you are rendering a whole page, or if no other option suits better.

html = Button.render(deps_strategy=\"document\")\n

When you render a component tree with the \"document\" strategy, it is expected that:

  • The HTML will be rendered at page load.
  • The HTML will be inserted into a page / browser where JS can be executed.

Location:

JS and CSS is inserted:

  • Preferentially into JS / CSS placeholders like {% component_js_dependencies %}
  • Otherwise, JS into <body> element, and CSS into <head> element
  • If neither found, JS / CSS are NOT inserted

Included scripts:

For the \"document\" strategy, the JS and CSS is set up to avoid any delays when the end user loads the page in the browser:

  • Components' primary JS and CSS scripts (Component.js and Component.css) - fully inlined:

    <script>\n    console.log(\"Hello from Button!\");\n</script>\n<style>\n    .button {\n        background-color: blue;\n    }\n</style>\n
  • Components' secondary JS and CSS scripts (Component.Media) - inserted as links:

    <link rel=\"stylesheet\" href=\"https://example.com/styles.css\" />\n<script src=\"https://example.com/script.js\"></script>\n
  • A JS script is injected to manage component dependencies, enabling lazy loading of JS and CSS for HTML fragments.

Info

This strategy is required for fragments to work properly, as it sets up the dependency manager that fragments rely on.

How the dependency manager works

The dependency manager is a JS script that keeps track of all the JS and CSS dependencies that have already been loaded.

When a fragment is inserted into the page, it will also insert a JSON <script> tag with fragment metadata.

The dependency manager will pick up on that, and check which scripts the fragment needs.

It will then fetch only the scripts that haven't been loaded yet.

"},{"location":"concepts/advanced/rendering_js_css/#fragment","title":"fragment","text":"

deps_strategy=\"fragment\" is used when rendering a piece of HTML that will be inserted into a page that has already been rendered with the \"document\" strategy:

fragment = MyComponent.render(deps_strategy=\"fragment\")\n

The HTML of fragments is very lightweight because it doesn't include the JS and CSS scripts of the rendered components.

With fragments, even if a component has JS and CSS, you can insert the same component into a page hundreds of times, and the JS and CSS will only ever be loaded once.

This is intended for dynamic content that's loaded with AJAX after the initial page load, such as with jQuery, HTMX, AlpineJS or similar libraries.

Location:

None. The fragment's JS and CSS files will be loaded dynamically into the page.

Included scripts:

  • A special JSON <script> tag that tells the dependency manager what JS and CSS to load.
"},{"location":"concepts/advanced/rendering_js_css/#simple","title":"simple","text":"

deps_strategy=\"simple\" is used either for non-browser use cases, or when you don't want to use the dependency manager.

Practically, this is the same as the \"document\" strategy, except that the dependency manager is not used.

html = MyComponent.render(deps_strategy=\"simple\")\n

Location:

JS and CSS is inserted:

  • Preferentially into JS / CSS placeholders like {% component_js_dependencies %}
  • Otherwise, JS into <body> element, and CSS into <head> element
  • If neither found, JS / CSS are NOT inserted

Included scripts:

  • Components' primary JS and CSS scripts (Component.js and Component.css) - fully inlined:

    <script>\n    console.log(\"Hello from Button!\");\n</script>\n<style>\n    .button {\n        background-color: blue;\n    }\n</style>\n
  • Components' secondary JS and CSS scripts (Component.Media) - inserted as links:

    <link rel=\"stylesheet\" href=\"https://example.com/styles.css\" />\n<script src=\"https://example.com/script.js\"></script>\n
  • No extra scripts are inserted.

"},{"location":"concepts/advanced/rendering_js_css/#prepend","title":"prepend","text":"

This is the same as \"simple\", but placeholders like {% component_js_dependencies %} and HTML tags <head> and <body> are all ignored. The JS and CSS are always inserted before the rendered content.

html = MyComponent.render(deps_strategy=\"prepend\")\n

Location:

JS and CSS is always inserted before the rendered content.

Included scripts:

Same as for the \"simple\" strategy.

"},{"location":"concepts/advanced/rendering_js_css/#append","title":"append","text":"

This is the same as \"simple\", but placeholders like {% component_js_dependencies %} and HTML tags <head> and <body> are all ignored. The JS and CSS are always inserted after the rendered content.

html = MyComponent.render(deps_strategy=\"append\")\n

Location:

JS and CSS is always inserted after the rendered content.

Included scripts:

Same as for the \"simple\" strategy.

"},{"location":"concepts/advanced/rendering_js_css/#ignore","title":"ignore","text":"

deps_strategy=\"ignore\" is used when you do NOT want to process JS and CSS of the rendered HTML.

html = MyComponent.render(deps_strategy=\"ignore\")\n

The rendered HTML is left as-is. You can still process it with a different strategy later with render_dependencies().

This is useful when you want to insert rendered HTML into another component.

html = MyComponent.render(deps_strategy=\"ignore\")\nhtml = AnotherComponent.render(slots={\"content\": html})\n
"},{"location":"concepts/advanced/rendering_js_css/#manually-rendering-js-css","title":"Manually rendering JS / CSS","text":"

When rendering templates or components, django-components covers all the traditional ways how components or templates can be rendered:

  • Component.render()
  • Component.render_to_response()
  • Template.render()
  • django.shortcuts.render()

This way you don't need to manually handle rendering of JS / CSS.

However, for advanced or low-level use cases, you may need to control when to render JS / CSS.

In such case you can directly pass rendered HTML to render_dependencies().

This function will extract all used components in the HTML string, and insert the components' JS and CSS based on given strategy.

Info

The truth is that all the methods listed above call render_dependencies() internally.

Example:

To see how render_dependencies() works, let's render a template with a component.

We will render it twice:

  • First time, we let template.render() handle the rendering.
  • Second time, we prevent template.render() from inserting the component's JS and CSS with deps_strategy=\"ignore\".

    Instead, we pass the \"unprocessed\" HTML to render_dependencies() ourselves to insert the component's JS and CSS.

from django.template.base import Template\nfrom django.template.context import Context\nfrom django_components import render_dependencies\n\ntemplate = Template(\"\"\"\n    {% load component_tags %}\n    <!doctype html>\n    <html>\n    <head>\n        <title>MyPage</title>\n    </head>\n    <body>\n        <main>\n            {% component \"my_button\" %}\n                Click me!\n            {% endcomponent %}\n        </main>\n    </body>\n    </html>\n\"\"\")\n\nrendered = template.render(Context({}))\n\nrendered2_raw = template.render(Context({\"DJC_DEPS_STRATEGY\": \"ignore\"}))\nrendered2 = render_dependencies(rendered2_raw)\n\nassert rendered == rendered2\n

Same applies to other strategies and other methods of rendering:

raw_html = MyComponent.render(deps_strategy=\"ignore\")\nhtml = render_dependencies(raw_html, deps_strategy=\"document\")\n\nhtml2 = MyComponent.render(deps_strategy=\"document\")\n\nassert html == html2\n
"},{"location":"concepts/advanced/rendering_js_css/#html-fragments","title":"HTML fragments","text":"

Django-components provides a seamless integration with HTML fragments with AJAX (HTML over the wire), whether you're using jQuery, HTMX, AlpineJS, vanilla JavaScript, or other.

This is achieved by the combination of the \"document\" and \"fragment\" strategies.

Read more about HTML fragments.

"},{"location":"concepts/advanced/tag_formatters/","title":"Tag formatters","text":""},{"location":"concepts/advanced/tag_formatters/#customizing-component-tags-with-tagformatter","title":"Customizing component tags with TagFormatter","text":"

New in version 0.89

By default, components are rendered using the pair of {% component %} / {% endcomponent %} template tags:

{% component \"button\" href=\"...\" disabled %}\nClick me!\n{% endcomponent %}\n\n{# or #}\n\n{% component \"button\" href=\"...\" disabled / %}\n

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

then the components' names will be used as the template tags:

{% button href=\"...\" disabled %}\n  Click me!\n{% endbutton %}\n\n{# or #}\n\n{% button href=\"...\" disabled / %}\n
"},{"location":"concepts/advanced/tag_formatters/#available-tagformatters","title":"Available TagFormatters","text":"

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=\"...\" %}\n    {% fill \"content\" %}\n        ...\n    {% endfill %}\n{% endcomponent %}\n

Example as inlined tag:

{% component \"button\" href=\"...\" / %}\n
  • ShorthandComponentFormatter (django_components.component_shorthand_formatter)

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

Example as block:

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

Example as inlined tag:

{% button href=\"...\" / %}\n
"},{"location":"concepts/advanced/tag_formatters/#writing-your-own-tagformatter","title":"Writing your own TagFormatter","text":""},{"location":"concepts/advanced/tag_formatters/#background","title":"Background","text":"

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:

{% component \"button\" href=\"...\" disabled %}\n{% endcomponent %}\n

Then TagFormatter.parse() will receive a following input:

[\"component\", '\"button\"', 'href=\"...\"', 'disabled']\n
  1. TagFormatter extracts the component name and the remaining input.

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

TagResult(\n    component_name=\"button\",\n    tokens=['href=\"...\"', 'disabled']\n)\n
  1. 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 %}\n
  1. Tag handler looks up the component button, and passes the args, kwargs, and slots to it.
"},{"location":"concepts/advanced/tag_formatters/#tagformatter","title":"TagFormatter","text":"

TagFormatter handles following parts of the process above:

  • Generates start/end tags, given a component. This is what you then call from within your template as {% component %}.

  • When you {% component %}, tag formatter pre-processes the tag contents, so it can link back the custom template tag to the right component.

To do so, subclass from TagFormatterABC and implement following method:

  • start_tag
  • end_tag
  • parse

For example, this is the implementation of ShorthandComponentFormatter

class ShorthandComponentFormatter(TagFormatterABC):\n    # Given a component name, generate the start template tag\n    def start_tag(self, name: str) -> str:\n        return name  # e.g. 'button'\n\n    # Given a component name, generate the start template tag\n    def end_tag(self, name: str) -> str:\n        return f\"end{name}\"  # e.g. 'endbutton'\n\n    # Given a tag, e.g.\n    # `{% button href=\"...\" disabled %}`\n    #\n    # The parser receives:\n    # `['button', 'href=\"...\"', 'disabled']`\n    def parse(self, tokens: List[str]) -> TagResult:\n        tokens = [*tokens]\n        name = tokens.pop(0)\n        return TagResult(\n            name,  # e.g. 'button'\n            tokens  # e.g. ['href=\"...\"', 'disabled']\n        )\n

That's it! And once your TagFormatter is ready, don't forget to update the settings!

"},{"location":"concepts/advanced/template_tags/","title":"Custom template tags","text":"

Template tags introduced by django-components, such as {% component %} and {% slot %}, offer additional features over the default Django template tags:

  • Self-closing tags {% mytag / %}
  • Allowing the use of :, - (and more) in keys
  • Spread operator ...
  • Using template tags as inputs to other template tags
  • Flat definition of dictionaries attr:key=val
  • Function-like input validation

You too can easily create custom template tags that use the above features.

"},{"location":"concepts/advanced/template_tags/#defining-template-tags-with-template_tag","title":"Defining template tags with @template_tag","text":"

The simplest way to create a custom template tag is using the template_tag decorator. This decorator allows you to define a template tag by just writing a function that returns the rendered content.

from django.template import Context, Library\nfrom django_components import BaseNode, template_tag\n\nlibrary = Library()\n\n@template_tag(\n    library,\n    tag=\"mytag\",\n    end_tag=\"endmytag\",\n    allowed_flags=[\"required\"]\n)\ndef mytag(node: BaseNode, context: Context, name: str, **kwargs) -> str:\n    return f\"Hello, {name}!\"\n

This will allow you to use the tag in your templates like this:

{% mytag name=\"John\" %}\n{% endmytag %}\n\n{# or with self-closing syntax #}\n{% mytag name=\"John\" / %}\n\n{# or with flags #}\n{% mytag name=\"John\" required %}\n{% endmytag %}\n
"},{"location":"concepts/advanced/template_tags/#parameters","title":"Parameters","text":"

The @template_tag decorator accepts the following parameters:

  • library: The Django template library to register the tag with
  • tag: The name of the template tag (e.g. \"mytag\" for {% mytag %})
  • end_tag: Optional. The name of the end tag (e.g. \"endmytag\" for {% endmytag %})
  • allowed_flags: Optional. List of flags that can be used with the tag (e.g. [\"required\"] for {% mytag required %})
"},{"location":"concepts/advanced/template_tags/#function-signature","title":"Function signature","text":"

The function decorated with @template_tag must accept at least two arguments:

  1. node: The node instance (we'll explain this in detail in the next section)
  2. context: The Django template context

Any additional parameters in your function's signature define what inputs your template tag accepts. For example:

@template_tag(library, tag=\"greet\")\ndef greet(\n    node: BaseNode,\n    context: Context,\n    name: str,                    # required positional argument\n    count: int = 1,              # optional positional argument\n    *,                           # keyword-only arguments marker\n    msg: str,                    # required keyword argument\n    mode: str = \"default\",       # optional keyword argument\n) -> str:\n    return f\"{msg}, {name}!\" * count\n

This allows the tag to be used like:

{# All parameters #}\n{% greet \"John\" count=2 msg=\"Hello\" mode=\"custom\" %}\n\n{# Only required parameters #}\n{% greet \"John\" msg=\"Hello\" %}\n\n{# Missing required parameter - will raise error #}\n{% greet \"John\" %}  {# Error: missing 'msg' #}\n

When you pass input to a template tag, it behaves the same way as if you passed the input to a function:

  • If required parameters are missing, an error is raised
  • If unexpected parameters are passed, an error is raised

To accept keys that are not valid Python identifiers (e.g. data-id), or would conflict with Python keywords (e.g. is), you can use the **kwargs syntax:

@template_tag(library, tag=\"greet\")\ndef greet(\n    node: BaseNode,\n    context: Context,\n    **kwargs,\n) -> str:\n    attrs = kwargs.copy()\n    is_var = attrs.pop(\"is\", None)\n    attrs_str = \" \".join(f'{k}=\"{v}\"' for k, v in attrs.items())\n\n    return mark_safe(f\"\"\"\n        <div {attrs_str}>\n            Hello, {is_var}!\n        </div>\n    \"\"\")\n

This allows you to use the tag like this:

{% greet is=\"John\" data-id=\"123\" %}\n
"},{"location":"concepts/advanced/template_tags/#defining-template-tags-with-basenode","title":"Defining template tags with BaseNode","text":"

For more control over your template tag, you can subclass BaseNode directly instead of using the decorator. This gives you access to additional features like the node's internal state and parsing details.

from django_components import BaseNode\n\nclass GreetNode(BaseNode):\n    tag = \"greet\"\n    end_tag = \"endgreet\"\n    allowed_flags = [\"required\"]\n\n    def render(self, context: Context, name: str, **kwargs) -> str:\n        # Access node properties\n        if self.flags[\"required\"]:\n            return f\"Required greeting: Hello, {name}!\"\n        return f\"Hello, {name}!\"\n\n# Register the node\nGreetNode.register(library)\n
"},{"location":"concepts/advanced/template_tags/#node-properties","title":"Node properties","text":"

When using BaseNode, you have access to several useful properties:

  • node_id: A unique identifier for this node instance
  • flags: Dictionary of flag values (e.g. {\"required\": True})
  • params: List of raw parameters passed to the tag
  • nodelist: The template nodes between the start and end tags
  • contents: The raw contents between the start and end tags
  • active_flags: List of flags that are currently set to True
  • template_name: The name of the Template instance inside which the node was defined
  • template_component: The component class that the Template belongs to

This is what the node parameter in the @template_tag decorator gives you access to - it's the instance of the node class that was automatically created for your template tag.

"},{"location":"concepts/advanced/template_tags/#rendering-content-between-tags","title":"Rendering content between tags","text":"

When your tag has an end tag, you can access and render the content between the tags using nodelist:

class WrapNode(BaseNode):\n    tag = \"wrap\"\n    end_tag = \"endwrap\"\n\n    def render(self, context: Context, tag: str = \"div\", **attrs) -> str:\n        # Render the content between tags\n        inner = self.nodelist.render(context)\n        attrs_str = \" \".join(f'{k}=\"{v}\"' for k, v in attrs.items())\n        return f\"<{tag} {attrs_str}>{inner}</{tag}>\"\n\n# Usage:\n{% wrap tag=\"section\" class=\"content\" %}\n    Hello, world!\n{% endwrap %}\n
"},{"location":"concepts/advanced/template_tags/#unregistering-nodes","title":"Unregistering nodes","text":"

You can unregister a node from a library using the unregister method:

GreetNode.unregister(library)\n

This is particularly useful in testing when you want to clean up after registering temporary tags.

"},{"location":"concepts/advanced/testing/","title":"Testing","text":"

New in version 0.131

The @djc_test decorator is a powerful tool for testing components created with django-components. It ensures that each test is properly isolated, preventing components registered in one test from affecting others.

"},{"location":"concepts/advanced/testing/#usage","title":"Usage","text":"

The @djc_test decorator can be applied to functions, methods, or classes.

When applied to a class, it decorates all methods starting with test_, and all nested classes starting with Test, recursively.

"},{"location":"concepts/advanced/testing/#applying-to-a-function","title":"Applying to a Function","text":"

To apply djc_test to a function, simply decorate the function as shown below:

import django\nfrom django_components.testing import djc_test\n\n@djc_test\ndef test_my_component():\n    @register(\"my_component\")\n    class MyComponent(Component):\n        template = \"...\"\n    ...\n
"},{"location":"concepts/advanced/testing/#applying-to-a-class","title":"Applying to a Class","text":"

When applied to a class, djc_test decorates each test_ method, as well as all nested classes starting with Test.

import django\nfrom django_components.testing import djc_test\n\n@djc_test\nclass TestMyComponent:\n    def test_something(self):\n        ...\n\n    class TestNested:\n        def test_something_else(self):\n            ...\n

This is equivalent to applying the decorator to both of the methods individually:

import django\nfrom django_components.testing import djc_test\n\nclass TestMyComponent:\n    @djc_test\n    def test_something(self):\n        ...\n\n    class TestNested:\n        @djc_test\n        def test_something_else(self):\n            ...\n
"},{"location":"concepts/advanced/testing/#arguments","title":"Arguments","text":"

See the API reference for @djc_test for more details.

"},{"location":"concepts/advanced/testing/#setting-up-django","title":"Setting Up Django","text":"

If you want to define a common Django settings that would be the baseline for all tests, you can call django.setup() before the @djc_test decorator:

import django\nfrom django_components.testing import djc_test\n\ndjango.setup(...)\n\n@djc_test\ndef test_my_component():\n    ...\n

Info

If you omit django.setup() in the example above, @djc_test will call it for you, so you don't need to do it manually.

"},{"location":"concepts/advanced/testing/#example-parametrizing-context-behavior","title":"Example: Parametrizing Context Behavior","text":"

You can parametrize the context behavior using djc_test:

from django_components.testing import djc_test\n\n@djc_test(\n    # Settings applied to all cases\n    components_settings={\n        \"app_dirs\": [\"custom_dir\"],\n    },\n    # Parametrized settings\n    parametrize=(\n        [\"components_settings\"],\n        [\n            [{\"context_behavior\": \"django\"}],\n            [{\"context_behavior\": \"isolated\"}],\n        ],\n        [\"django\", \"isolated\"],\n    )\n)\ndef test_context_behavior(components_settings):\n    rendered = MyComponent.render()\n    ...\n
"},{"location":"concepts/fundamentals/autodiscovery/","title":"Autodiscovery","text":"

django-components automatically searches for files containing components in the COMPONENTS.dirs and COMPONENTS.app_dirs directories.

"},{"location":"concepts/fundamentals/autodiscovery/#manually-register-components","title":"Manually register components","text":"

Every component that you want to use in the template with the {% component %} tag needs to be registered with the ComponentRegistry.

We use the @register decorator for that:

from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    ...\n

But for the component to be registered, the code needs to be executed - and for that, the file needs to be imported as a module.

This is the \"discovery\" part of the process.

One way to do that is by importing all your components in apps.py:

from django.apps import AppConfig\n\nclass MyAppConfig(AppConfig):\n    name = \"my_app\"\n\n    def ready(self) -> None:\n        from components.card.card import Card\n        from components.list.list import List\n        from components.menu.menu import Menu\n        from components.button.button import Button\n        ...\n

However, there's a simpler way!

"},{"location":"concepts/fundamentals/autodiscovery/#autodiscovery","title":"Autodiscovery","text":"

By default, the Python files found in the COMPONENTS.dirs and COMPONENTS.app_dirs are auto-imported in order to execute the code that registers the components.

Autodiscovery occurs when Django is loaded, during the AppConfig.ready() hook of the apps.py file.

If you are using autodiscovery, keep a few points in mind:

  • Avoid defining any logic on the module-level inside the components directories, that you would not want to run anyway.
  • Components inside the auto-imported files still need to be registered with @register
  • Auto-imported component files must be valid Python modules, they must use suffix .py, and module name should follow PEP-8.
  • Subdirectories and files starting with an underscore _ (except __init__.py) are ignored.

Autodiscovery can be disabled in the settings with autodiscover=False.

"},{"location":"concepts/fundamentals/autodiscovery/#manually-trigger-autodiscovery","title":"Manually trigger autodiscovery","text":"

Autodiscovery can be also triggered manually, using the autodiscover() function. This is useful if you want to run autodiscovery at a custom point of the lifecycle:

from django_components import autodiscover\n\nautodiscover()\n

To get the same list of modules that autodiscover() would return, but without importing them, use get_component_files():

from django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
"},{"location":"concepts/fundamentals/component_defaults/","title":"Component defaults","text":"

When a component is being rendered, the component inputs are passed to various methods like get_template_data(), get_js_data(), or get_css_data().

It can be cumbersome to specify default values for each input in each method.

To make things easier, Components can specify their defaults. Defaults are used when no value is provided, or when the value is set to None for a particular input.

"},{"location":"concepts/fundamentals/component_defaults/#defining-defaults","title":"Defining defaults","text":"

To define defaults for a component, you create a nested Defaults class within your Component class. Each attribute in the Defaults class represents a default value for a corresponding input.

from django_components import Component, Default, register\n\n@register(\"my_table\")\nclass MyTable(Component):\n\n    class Defaults:\n        position = \"left\"\n        selected_items = Default(lambda: [1, 2, 3])\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"position\": kwargs[\"position\"],\n            \"selected_items\": kwargs[\"selected_items\"],\n        }\n\n    ...\n

In this example, position is a simple default value, while selected_items uses a factory function wrapped in Default to ensure a new list is created each time the default is used.

Now, when we render the component, the defaults will be applied:

{% component \"my_table\" position=\"right\" / %}\n

In this case:

  • position input is set to right, so no defaults applied
  • selected_items is not set, so it will be set to [1, 2, 3].

Same applies to rendering the Component in Python with the render() method:

MyTable.render(\n    kwargs={\n        \"position\": \"right\",\n        \"selected_items\": None,\n    },\n)\n

Notice that we've set selected_items to None. None values are treated as missing values, and so selected_items will be set to [1, 2, 3].

Warning

The defaults are aplied only to keyword arguments. They are NOT applied to positional arguments!

Warning

When typing your components with Args, Kwargs, or Slots classes, you may be inclined to define the defaults in the classes.

class ProfileCard(Component):\n    class Kwargs(NamedTuple):\n        show_details: bool = True\n

This is NOT recommended, because:

  • The defaults will NOT be applied to inputs when using self.raw_kwargs property.
  • The defaults will NOT be applied when a field is given but set to None.

Instead, define the defaults in the Defaults class.

"},{"location":"concepts/fundamentals/component_defaults/#default-factories","title":"Default factories","text":"

For objects such as lists, dictionaries or other instances, you have to be careful - if you simply set a default value, this instance will be shared across all instances of the component!

from django_components import Component\n\nclass MyTable(Component):\n    class Defaults:\n        # All instances will share the same list!\n        selected_items = [1, 2, 3]\n

To avoid this, you can use a factory function wrapped in Default.

from django_components import Component, Default\n\nclass MyTable(Component):\n    class Defaults:\n        # A new list is created for each instance\n        selected_items = Default(lambda: [1, 2, 3])\n

This is similar to how the dataclass fields work.

In fact, you can also use the dataclass's field function to define the factories:

from dataclasses import field\nfrom django_components import Component\n\nclass MyTable(Component):\n    class Defaults:\n        selected_items = field(default_factory=lambda: [1, 2, 3])\n
"},{"location":"concepts/fundamentals/component_defaults/#accessing-defaults","title":"Accessing defaults","text":"

Since the defaults are defined on the component class, you can access the defaults for a component with the Component.Defaults property.

So if we have a component like this:

from django_components import Component, Default, register\n\n@register(\"my_table\")\nclass MyTable(Component):\n\n    class Defaults:\n        position = \"left\"\n        selected_items = Default(lambda: [1, 2, 3])\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"position\": kwargs[\"position\"],\n            \"selected_items\": kwargs[\"selected_items\"],\n        }\n

We can access individual defaults like this:

print(MyTable.Defaults.position)\nprint(MyTable.Defaults.selected_items)\n
"},{"location":"concepts/fundamentals/component_views_urls/","title":"Component views and URLs","text":"

New in version 0.34

Note: Since 0.92, Component is no longer a subclass of Django's View. Instead, the nested Component.View class is a subclass of Django's View.

For web applications, it's common to define endpoints that serve HTML content (AKA views).

django-components has a suite of features that help you write and manage views and their URLs:

  • For each component, you can define methods for handling HTTP requests (GET, POST, etc.) - get(), post(), etc.

  • Use Component.as_view() to be able to use your Components with Django's urlpatterns. This works the same way as View.as_view().

  • To avoid having to manually define the endpoints for each component, you can set the component to be \"public\" with Component.View.public = True. This will automatically create a URL for the component. To retrieve the component URL, use get_component_url().

  • In addition, Component has a render_to_response() method that renders the component template based on the provided input and returns an HttpResponse object.

"},{"location":"concepts/fundamentals/component_views_urls/#define-handlers","title":"Define handlers","text":"

Here's an example of a calendar component defined as a view. Simply define a View class with your custom get() method to handle GET requests:

[project root]/components/calendar.py
from django_components import Component, ComponentView, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template = \"\"\"\n        <div class=\"calendar-component\">\n            <div class=\"header\">\n                {% slot \"header\" / %}\n            </div>\n            <div class=\"body\">\n                Today's date is <span>{{ date }}</span>\n            </div>\n        </div>\n    \"\"\"\n\n    class View:\n        # Handle GET requests\n        def get(self, request, *args, **kwargs):\n            # Return HttpResponse with the rendered content\n            return Calendar.render_to_response(\n                request=request,\n                kwargs={\n                    \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n                },\n                slots={\n                    \"header\": \"Calendar header\",\n                },\n            )\n

Info

The View class supports all the same HTTP methods as Django's View class. These are:

get(), post(), put(), patch(), delete(), head(), options(), trace()

Each of these receive the HttpRequest object as the first argument.

Warning

Deprecation warning:

Previously, the handler methods such as get() and post() could be defined directly on the Component class:

class Calendar(Component):\n    def get(self, request, *args, **kwargs):\n        return self.render_to_response(\n            kwargs={\n                \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n            }\n        )\n

This is deprecated from v0.137 onwards, and will be removed in v1.0.

"},{"location":"concepts/fundamentals/component_views_urls/#acccessing-component-class","title":"Acccessing component class","text":"

You can access the component class from within the View methods by using the View.component_cls attribute:

class Calendar(Component):\n    ...\n\n    class View:\n        def get(self, request):\n            return self.component_cls.render_to_response(request=request)\n
"},{"location":"concepts/fundamentals/component_views_urls/#register-urls-manually","title":"Register URLs manually","text":"

To register the component as a route / endpoint in Django, add an entry to your urlpatterns. In place of the view function, create a view object with Component.as_view():

[project root]/urls.py
from django.urls import path\nfrom components.calendar.calendar import Calendar\n\nurlpatterns = [\n    path(\"calendar/\", Calendar.as_view()),\n]\n

Component.as_view() internally calls View.as_view(), passing the component instance as one of the arguments.

"},{"location":"concepts/fundamentals/component_views_urls/#register-urls-automatically","title":"Register URLs automatically","text":"

If you don't care about the exact URL of the component, you can let django-components manage the URLs for you by setting the Component.View.public attribute to True:

class MyComponent(Component):\n    class View:\n        public = True\n\n        def get(self, request):\n            return self.component_cls.render_to_response(request=request)\n    ...\n

Then, to get the URL for the component, use get_component_url():

from django_components import get_component_url\n\nurl = get_component_url(MyComponent)\n

This way you don't have to mix your app URLs with component URLs.

Info

If you need to pass query parameters or a fragment to the component URL, you can do so by passing the query and fragment arguments to get_component_url():

url = get_component_url(\n    MyComponent,\n    query={\"foo\": \"bar\"},\n    fragment=\"baz\",\n)\n# /components/ext/view/components/c1ab2c3?foo=bar#baz\n
"},{"location":"concepts/fundamentals/html_attributes/","title":"HTML attributes","text":"

New in version 0.74:

You can use the {% html_attrs %} tag to render various data as key=\"value\" HTML attributes.

{% html_attrs %} tag is versatile, allowing you to define HTML attributes however you need:

  • Define attributes within the HTML template
  • Define attributes in Python code
  • Merge attributes from multiple sources
  • Boolean attributes
  • Append attributes
  • Remove attributes
  • Define default attributes

From v0.135 onwards, {% html_attrs %} tag also supports merging style and class attributes the same way how Vue does.

To get started, let's consider a simple example. If you have a template:

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

You can rewrite it with the {% html_attrs %} tag:

<div {% html_attrs class=classes data-id=my_id %}>\n</div>\n

The {% html_attrs %} tag accepts any number of keyword arguments, which will be merged and rendered as HTML attributes:

<div class=\"text-red\" data-id=\"123\">\n</div>\n

Moreover, the {% html_attrs %} tag accepts two positional arguments:

  • attrs - a dictionary of attributes to be rendered
  • defaults - a dictionary of default attributes

You can use this for example to allow users of your component to add extra attributes. We achieve this by capturing the extra attributes and passing them to the {% html_attrs %} tag as a dictionary:

@register(\"my_comp\")\nclass MyComp(Component):\n    # Pass all kwargs as `attrs`\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"attrs\": kwargs,\n            \"classes\": \"text-red\",\n            \"my_id\": 123,\n        }\n\n    template: t.django_html = \"\"\"\n        {# Pass the extra attributes to `html_attrs` #}\n        <div {% html_attrs attrs class=classes data-id=my_id %}>\n        </div>\n    \"\"\"\n

This way you can render MyComp with extra attributes:

Either via Django template:

{% component \"my_comp\"\n  id=\"example\"\n  class=\"pa-4\"\n  style=\"color: red;\"\n%}\n

Or via Python:

MyComp.render(\n    kwargs={\n        \"id\": \"example\",\n        \"class\": \"pa-4\",\n        \"style\": \"color: red;\",\n    }\n)\n

In both cases, the attributes will be merged and rendered as:

<div id=\"example\" class=\"text-red pa-4\" style=\"color: red;\" data-id=\"123\"></div>\n
"},{"location":"concepts/fundamentals/html_attributes/#summary","title":"Summary","text":"
  1. The two arguments, attrs and defaults, can be passed as positional args:

    {% html_attrs attrs defaults key=val %}\n

    or as kwargs:

    {% html_attrs key=val defaults=defaults attrs=attrs %}\n
  2. Both attrs and defaults are optional and can be omitted.

  3. Both attrs and defaults are dictionaries. As such, there's multiple ways to define them:

    • By referencing a variable:

      {% html_attrs attrs=attrs %}\n
    • By defining a literal dictionary:

      {% html_attrs attrs={\"key\": value} %}\n
    • Or by defining the dictionary keys:

      {% html_attrs attrs:key=value %}\n
  4. All other kwargs are merged and can be repeated.

    {% html_attrs class=\"text-red\" class=\"pa-4\" %}\n

    Will render:

    <div class=\"text-red pa-4\"></div>\n
"},{"location":"concepts/fundamentals/html_attributes/#usage","title":"Usage","text":""},{"location":"concepts/fundamentals/html_attributes/#boolean-attributes","title":"Boolean attributes","text":"

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>\n<button>Click me!</button>\n

HTML rendering with html_attrs tag or format_attributes works the same way - an attribute set to True is rendered without the value, and an attribute set to False is not rendered at all.

So given this input:

attrs = {\n    \"disabled\": True,\n    \"autofocus\": False,\n}\n

And template:

<div {% html_attrs attrs %}>\n</div>\n

Then this renders:

<div disabled></div>\n
"},{"location":"concepts/fundamentals/html_attributes/#removing-attributes","title":"Removing attributes","text":"

Given how the boolean attributes work, you can \"remove\" or prevent an attribute from being rendered by setting it to False or None.

So given this input:

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

And template:

<div {% html_attrs attrs %}>\n</div>\n

Then this renders:

<div class=\"text-green\"></div>\n
"},{"location":"concepts/fundamentals/html_attributes/#default-attributes","title":"Default attributes","text":"

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

<div {% html_attrs attrs defaults %}>\n    ...\n</div>\n

In the example above, if attrs contains a certain key, e.g. the class key, {% html_attrs %} will render:

<div class=\"{{ attrs.class }}\">\n    ...\n</div>\n

Otherwise, {% html_attrs %} will render:

<div class=\"{{ defaults.class }}\">\n    ...\n</div>\n
"},{"location":"concepts/fundamentals/html_attributes/#appending-attributes","title":"Appending attributes","text":"

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

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 = {\n    \"class\": \"my-class pa-4\",\n}\n

And on {% html_attrs %} tag, we set the key class:

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

Then these will be merged and rendered as:

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

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\" #}\n<div {% html_attrs attrs class=\"some-class another-class\" class=my_var %}>\n</div>\n

Renders:

<div\n  data-value=\"my-class pa-4 some-class another-class class-from-var text-red\"\n></div>\n
"},{"location":"concepts/fundamentals/html_attributes/#merging-class-attributes","title":"Merging class attributes","text":"

The class attribute can be specified as a string of class names as usual.

If you want granular control over individual class names, you can use a dictionary.

  • String: Used as is.

    {% html_attrs class=\"my-class other-class\" %}\n

    Renders:

    <div class=\"my-class other-class\"></div>\n
  • Dictionary: Keys are the class names, and values are booleans. Only keys with truthy values are rendered.

    {% html_attrs class={\n    \"extra-class\": True,\n    \"other-class\": False,\n} %}\n

    Renders:

    <div class=\"extra-class\"></div>\n

If a certain class is specified multiple times, it's the last instance that decides whether the class is rendered or not.

Example:

In this example, the other-class is specified twice. The last instance is {\"other-class\": False}, so the class is not rendered.

{% html_attrs\n    class=\"my-class other-class\"\n    class={\"extra-class\": True, \"other-class\": False}\n%}\n

Renders:

<div class=\"my-class extra-class\"></div>\n
"},{"location":"concepts/fundamentals/html_attributes/#merging-style-attributes","title":"Merging style attributes","text":"

The style attribute can be specified as a string of style properties as usual.

If you want granular control over individual style properties, you can use a dictionary.

  • String: Used as is.

    {% html_attrs style=\"color: red; background-color: blue;\" %}\n

    Renders:

    <div style=\"color: red; background-color: blue;\"></div>\n
  • Dictionary: Keys are the style properties, and values are their values.

    {% html_attrs style={\n    \"color\": \"red\",\n    \"background-color\": \"blue\",\n} %}\n

    Renders:

    <div style=\"color: red; background-color: blue;\"></div>\n

If a style property is specified multiple times, the last value is used.

  • Properties set to None are ignored.
  • If the last non-None instance of the property is set to False, the property is removed.

Example:

In this example, the width property is specified twice. The last instance is {\"width\": False}, so the property is removed.

Secondly, the background-color property is also set twice. But the second time it's set to None, so that instance is ignored, leaving us only with background-color: blue.

The color property is set to a valid value in both cases, so the latter (green) is used.

{% html_attrs\n    style=\"color: red; background-color: blue; width: 100px;\"\n    style={\"color\": \"green\", \"background-color\": None, \"width\": False}\n%}\n

Renders:

<div style=\"color: green; background-color: blue;\"></div>\n
"},{"location":"concepts/fundamentals/html_attributes/#usage-outside-of-templates","title":"Usage outside of templates","text":"

In some cases, you want to prepare HTML attributes outside of templates.

To achieve the same behavior as {% html_attrs %} tag, you can use the merge_attributes() and format_attributes() helper functions.

"},{"location":"concepts/fundamentals/html_attributes/#merging-attributes","title":"Merging attributes","text":"

merge_attributes() accepts any number of dictionaries and merges them together, using the same merge strategy as {% html_attrs %}.

from django_components import merge_attributes\n\nmerge_attributes(\n    {\"class\": \"my-class\", \"data-id\": 123},\n    {\"class\": \"extra-class\"},\n    {\"class\": {\"cool-class\": True, \"uncool-class\": False} },\n)\n

Which will output:

{\n    \"class\": \"my-class extra-class cool-class\",\n    \"data-id\": 123,\n}\n

Warning

Unlike {% html_attrs %}, where you can pass extra kwargs, merge_attributes() requires each argument to be a dictionary.

"},{"location":"concepts/fundamentals/html_attributes/#formatting-attributes","title":"Formatting attributes","text":"

format_attributes() serializes attributes the same way as {% html_attrs %} tag does.

from django_components import format_attributes\n\nformat_attributes({\n    \"class\": \"my-class text-red pa-4\",\n    \"data-id\": 123,\n    \"required\": True,\n    \"disabled\": False,\n    \"ignored-attr\": None,\n})\n

Which will output:

'class=\"my-class text-red pa-4\" data-id=\"123\" required'\n

Note

Prior to v0.135, the format_attributes() function was named attributes_to_string().

This function is now deprecated and will be removed in v1.0.

"},{"location":"concepts/fundamentals/html_attributes/#cheat-sheet","title":"Cheat sheet","text":"

Assuming that:

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

Then:

  • Empty tag

    <div {% html_attr %}></div>\n

    renders nothing:

    <div></div>\n
  • Only kwargs

    <div {% html_attr class=\"some-class\" class=class_from_var data-id=\"123\" %}></div>\n

    renders:

    <div class=\"some-class from-var\" data-id=\"123\"></div>\n
  • Only attrs

    <div {% html_attr attrs %}></div>\n

    renders:

    <div class=\"from-attrs\" type=\"submit\"></div>\n
  • Attrs as kwarg

    <div {% html_attr attrs=attrs %}></div>\n

    renders:

    <div class=\"from-attrs\" type=\"submit\"></div>\n
  • Only defaults (as kwarg)

    <div {% html_attr defaults=defaults %}></div>\n

    renders:

    <div class=\"from-defaults\" role=\"button\"></div>\n
  • Attrs using the prefix:key=value construct

    <div {% html_attr attrs:class=\"from-attrs\" attrs:type=\"submit\" %}></div>\n

    renders:

    <div class=\"from-attrs\" type=\"submit\"></div>\n
  • Defaults using the prefix:key=value construct

    <div {% html_attr defaults:class=\"from-defaults\" %}></div>\n

    renders:

    <div class=\"from-defaults\" role=\"button\"></div>\n
  • All together (1) - attrs and defaults as positional args:

    <div {% html_attrs attrs defaults class=\"added_class\" class=class_from_var data-id=123 %}></div>\n

    renders:

    <div class=\"from-attrs added_class from-var\" type=\"submit\" role=\"button\" data-id=123></div>\n
  • All together (2) - attrs and defaults as kwargs args:

    <div {% html_attrs class=\"added_class\" class=class_from_var data-id=123 attrs=attrs defaults=defaults %}></div>\n

    renders:

    <div class=\"from-attrs added_class from-var\" type=\"submit\" role=\"button\" data-id=123></div>\n
  • All together (3) - mixed:

    <div {% html_attrs attrs defaults:class=\"default-class\" class=\"added_class\" class=class_from_var data-id=123 %}></div>\n

    renders:

    <div class=\"from-attrs added_class from-var\" type=\"submit\" data-id=123></div>\n
"},{"location":"concepts/fundamentals/html_attributes/#full-example","title":"Full example","text":"
@register(\"my_comp\")\nclass MyComp(Component):\n    template: t.django_html = \"\"\"\n        <div\n            {% html_attrs attrs\n                defaults:class=\"pa-4 text-red\"\n                class=\"my-comp-date\"\n                class=class_from_var\n                data-id=\"123\"\n            %}\n        >\n            Today's date is <span>{{ date }}</span>\n        </div>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        date = kwargs.pop(\"date\")\n        return {\n            \"date\": date,\n            \"attrs\": kwargs,\n            \"class_from_var\": \"extra-class\"\n        }\n\n@register(\"parent\")\nclass Parent(Component):\n    template: t.django_html = \"\"\"\n        {% component \"my_comp\"\n            date=date\n            attrs:class=\"pa-0 border-solid border-red\"\n            attrs:data-json=json_data\n            attrs:@click=\"(e) => onClick(e, 'from_parent')\"\n        / %}\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": datetime.now(),\n            \"json_data\": json.dumps({\"value\": 456})\n        }\n

Note: For readability, we've split the tags across multiple lines.

Inside MyComp, we defined a default attribute

defaults:class=\"pa-4 text-red\"\n

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

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\"\n    attrs:data-json=json_data\n    attrs:@click=\"(e) => onClick(e, 'from_parent')\"\n

And get_template_data of MyComp will receive a kwarg named attrs with following keys:

attrs = {\n    \"class\": \"pa-0 border-solid\",\n    \"data-json\": '{\"value\": 456}',\n    \"@click\": \"(e) => onClick(e, 'from_parent')\",\n}\n

attrs[\"class\"] overrides the default value for class, whereas other keys will be merged.

So in the end MyComp will render:

<div\n  class=\"pa-0 border-solid my-comp-date extra-class\"\n  data-id=\"123\"\n  data-json='{\"value\": 456}'\n  @click=\"(e) => onClick(e, 'from_parent')\"\n>\n  ...\n</div>\n
"},{"location":"concepts/fundamentals/html_js_css_files/","title":"HTML / JS / CSS files","text":""},{"location":"concepts/fundamentals/html_js_css_files/#overview","title":"Overview","text":"

Each component can have single \"primary\" HTML, CSS and JS file associated with them.

Each of these can be either defined inline, or in a separate file:

  • HTML files are defined using Component.template or Component.template_file
  • CSS files are defined using Component.css or Component.css_file
  • JS files are defined using Component.js or Component.js_file
@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    css_file = \"calendar.css\"\n    js_file = \"calendar.js\"\n

or

@register(\"calendar\")\nclass Calendar(Component):\n    template = \"\"\"\n        <div class=\"welcome\">\n            Hi there!\n        </div>\n    \"\"\"\n    css = \"\"\"\n        .welcome {\n            color: red;\n        }\n    \"\"\"\n    js = \"\"\"\n        console.log(\"Hello, world!\");\n    \"\"\"\n

These \"primary\" files will have special behavior. For example, each will receive variables from the component's data methods. Read more about each file type below:

  • HTML
  • CSS
  • JS

In addition, you can define extra \"secondary\" CSS / JS files using the nested Component.Media class, by setting Component.Media.js and Component.Media.css.

Single component can have many secondary files. There is no special behavior for them.

You can use these for third-party libraries, or for shared CSS / JS files.

Read more about Secondary JS / CSS files.

Warning

You cannot use both inlined code and separate file for a single language type (HTML, CSS, JS).

However, you can freely mix these for different languages:

class MyTable(Component):\n    template: types.django_html = \"\"\"\n      <div class=\"welcome\">\n        Hi there!\n      </div>\n    \"\"\"\n    js_file = \"my_table.js\"\n    css_file = \"my_table.css\"\n
"},{"location":"concepts/fundamentals/html_js_css_files/#html","title":"HTML","text":"

Components use Django's template system to define their HTML. This means that you can use Django's template syntax to define your HTML.

Inside the template, you can access the data returned from the get_template_data() method.

You can define the HTML directly in your Python code using the template attribute:

class Button(Component):\n    template = \"\"\"\n        <button class=\"btn\">\n            {% if icon %}\n                <i class=\"{{ icon }}\"></i>\n            {% endif %}\n            {{ text }}\n        </button>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"text\": kwargs.get(\"text\", \"Click me\"),\n            \"icon\": kwargs.get(\"icon\", None),\n        }\n

Or you can define the HTML in a separate file and reference it using template_file:

class Button(Component):\n    template_file = \"button.html\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"text\": kwargs.get(\"text\", \"Click me\"),\n            \"icon\": kwargs.get(\"icon\", None),\n        }\n
button.html
<button class=\"btn\">\n    {% if icon %}\n        <i class=\"{{ icon }}\"></i>\n    {% endif %}\n    {{ text }}\n</button>\n
"},{"location":"concepts/fundamentals/html_js_css_files/#dynamic-templates","title":"Dynamic templates","text":"

Each component has only a single template associated with it.

However, whether it's for A/B testing or for preserving public API when sharing your components, sometimes you may need to render different templates based on the input to your component.

You can use Component.on_render() to dynamically override what template gets rendered.

By default, the component's template is rendered as-is.

class Table(Component):\n    def on_render(self, context: Context, template: Optional[Template]):\n        if template is not None:\n            return template.render(context)\n

If you want to render a different template in its place, we recommended you to:

  1. Wrap the substitute templates as new Components
  2. Then render those Components inside Component.on_render():
class TableNew(Component):\n    template_file = \"table_new.html\"\n\nclass TableOld(Component):\n    template_file = \"table_old.html\"\n\nclass Table(Component):\n    def on_render(self, context, template):\n        if self.kwargs.get(\"feat_table_new_ui\"):\n            return TableNew.render(\n                args=self.args,\n                kwargs=self.kwargs,\n                slots=self.slots,\n            )\n        else:\n            return TableOld.render(\n                args=self.args,\n                kwargs=self.kwargs,\n                slots=self.slots,\n            )\n

Warning

If you do not wrap the templates as Components, there is a risk that some extensions will not work as expected.

new_template = Template(\"\"\"\n    {% load django_components %}\n    <div>\n        {% slot \"content\" %}\n            Other template\n        {% endslot %}\n    </div>\n\"\"\")\n\nclass Table(Component):\n    def on_render(self, context, template):\n        if self.kwargs.get(\"feat_table_new_ui\"):\n            return new_template.render(context)\n        else:\n            return template.render(context)\n
"},{"location":"concepts/fundamentals/html_js_css_files/#template-less-components","title":"Template-less components","text":"

Since you can use Component.on_render() to render other components, there is no need to define a template for the component.

So even an empty component like this is valid:

class MyComponent(Component):\n    pass\n

These \"template-less\" components can be useful as base classes for other components, or as mixins.

"},{"location":"concepts/fundamentals/html_js_css_files/#html-processing","title":"HTML processing","text":"

Django Components expects the rendered template to be a valid HTML. This is needed to enable features like CSS / JS variables.

Here is how the HTML is post-processed:

  1. Insert component ID: Each root element in the rendered HTML automatically receives a data-djc-id-cxxxxxx attribute containing a unique component instance ID.

    <!-- Output HTML -->\n<div class=\"card\" data-djc-id-c1a2b3c>\n    ...\n</div>\n<div class=\"backdrop\" data-djc-id-c1a2b3c>\n    ...\n</div>\n
  2. Insert CSS ID: If the component defines CSS variables through get_css_data(), the root elements also receive a data-djc-css-xxxxxx attribute. This attribute links the element to its specific CSS variables.

    <!-- Output HTML -->\n<div class=\"card\" data-djc-id-c1a2b3c data-djc-css-d4e5f6>\n    <!-- Component content -->\n</div>\n
  3. Insert JS and CSS: After the HTML is rendered, Django Components handles inserting JS and CSS dependencies into the page based on the dependencies rendering strategy (document, fragment, or inline).

    For example, if your component contains the {% component_js_dependencies %} or {% component_css_dependencies %} tags, or the <head> and <body> elements, the JS and CSS scripts will be inserted into the HTML.

    For more information on how JS and CSS dependencies are rendered, see Rendering JS / CSS.

"},{"location":"concepts/fundamentals/html_js_css_files/#js","title":"JS","text":"

The component's JS script is executed in the browser:

  • It is executed AFTER the \"secondary\" JS files from Component.Media.js are loaded.
  • The script is only executed once, even if there are multiple instances of the component on the page.
  • Component JS scripts are executed in the order how they appeared in the template / HTML (top to bottom).

You can define the JS directly in your Python code using the js attribute:

class Button(Component):\n    js = \"\"\"\n        console.log(\"Hello, world!\");\n    \"\"\"\n\n    def get_js_data(self, args, kwargs, slots, context):\n        return {\n            \"text\": kwargs.get(\"text\", \"Click me\"),\n        }\n

Or you can define the JS in a separate file and reference it using js_file:

class Button(Component):\n    js_file = \"button.js\"\n\n    def get_js_data(self, args, kwargs, slots, context):\n        return {\n            \"text\": kwargs.get(\"text\", \"Click me\"),\n        }\n
button.js
console.log(\"Hello, world!\");\n
"},{"location":"concepts/fundamentals/html_js_css_files/#css","title":"CSS","text":"

You can define the CSS directly in your Python code using the css attribute:

class Button(Component):\n    css = \"\"\"\n        .btn {\n            width: 100px;\n            color: var(--color);\n        }\n    \"\"\"\n\n    def get_css_data(self, args, kwargs, slots, context):\n        return {\n            \"color\": kwargs.get(\"color\", \"red\"),\n        }\n

Or you can define the CSS in a separate file and reference it using css_file:

class Button(Component):\n    css_file = \"button.css\"\n\n    def get_css_data(self, args, kwargs, slots, context):\n        return {\n            \"text\": kwargs.get(\"text\", \"Click me\"),\n        }\n
button.css
.btn {\n    color: red;\n}\n
"},{"location":"concepts/fundamentals/html_js_css_files/#file-paths","title":"File paths","text":"

Compared to the secondary JS / CSS files, the definition of file paths for the main HTML / JS / CSS files is quite simple - just strings, without any lists, objects, or globs.

However, similar to the secondary JS / CSS files, you can specify the file paths relative to the component's directory.

So if you have a directory with following files:

[project root]/components/calendar/\n\u251c\u2500\u2500 calendar.html\n\u251c\u2500\u2500 calendar.css\n\u251c\u2500\u2500 calendar.js\n\u2514\u2500\u2500 calendar.py\n

You can define the component like this:

[project root]/components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    css_file = \"calendar.css\"\n    js_file = \"calendar.js\"\n

Assuming that COMPONENTS.dirs contains path [project root]/components, the example above is the same as writing out:

[project root]/components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar/template.html\"\n    css_file = \"calendar/style.css\"\n    js_file = \"calendar/script.js\"\n

If the path cannot be resolved relative to the component, django-components will attempt to resolve the path relative to the component directories, as set in COMPONENTS.dirs or COMPONENTS.app_dirs.

Read more about file path resolution.

"},{"location":"concepts/fundamentals/html_js_css_files/#access-component-definition","title":"Access component definition","text":"

Component's HTML / CSS / JS is resolved and loaded lazily.

This means that, when you specify any of template_file, js_file, css_file, or Media.js/css, these file paths will be resolved only once you either:

  1. Access any of the following attributes on the component:

    • media, template, template_file, js, js_file, css, css_file
  2. Render the component.

Once the component's media files have been loaded once, they will remain in-memory on the Component class:

  • HTML from Component.template_file will be available under Component.template
  • CSS from Component.css_file will be available under Component.css
  • JS from Component.js_file will be available under Component.js

Thus, whether you define HTML via Component.template_file or Component.template, you can always access the HTML content under Component.template. And the same applies for JS and CSS.

Example:

# When we create Calendar component, the files like `calendar/template.html`\n# are not yet loaded!\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar/template.html\"\n    css_file = \"calendar/style.css\"\n    js_file = \"calendar/script.js\"\n\n    class Media:\n        css = \"calendar/style1.css\"\n        js = \"calendar/script2.js\"\n\n# It's only at this moment that django-components reads the files like `calendar/template.html`\nprint(Calendar.css)\n# Output:\n# .calendar {\n#   width: 200px;\n#   background: pink;\n# }\n

Warning

Do NOT modify HTML / CSS / JS after it has been loaded

django-components assumes that the component's media files like js_file or Media.js/css are static.

If you need to dynamically change these media files, consider instead defining multiple Components.

Modifying these files AFTER the component has been loaded at best does nothing. However, this is an untested behavior, which may lead to unexpected errors.

"},{"location":"concepts/fundamentals/html_js_css_variables/","title":"HTML / JS / CSS variables","text":"

When a component recieves input through {% component %} tag, or the Component.render() or Component.render_to_response() methods, you can define how the input is handled, and what variables will be available to the template, JavaScript and CSS.

"},{"location":"concepts/fundamentals/html_js_css_variables/#overview","title":"Overview","text":"

Django Components offers three key methods for passing variables to different parts of your component:

  • get_template_data() - Provides variables to your HTML template
  • get_js_data() - Provides variables to your JavaScript code
  • get_css_data() - Provides variables to your CSS styles

These methods let you pre-process inputs before they're used in rendering.

Each method handles the data independently - you can define different data for the template, JS, and CSS.

class ProfileCard(Component):\n    class Kwargs(NamedTuple):\n        user_id: int\n        show_details: bool\n\n    class Defaults:\n        show_details = True\n\n    def get_template_data(self, args, kwargs: Kwargs, slots, context):\n        user = User.objects.get(id=kwargs.user_id)\n        return {\n            \"user\": user,\n            \"show_details\": kwargs.show_details,\n        }\n\n    def get_js_data(self, args, kwargs: Kwargs, slots, context):\n        return {\n            \"user_id\": kwargs.user_id,\n        }\n\n    def get_css_data(self, args, kwargs: Kwargs, slots, context):\n        text_color = \"red\" if kwargs.show_details else \"blue\"\n        return {\n            \"text_color\": text_color,\n        }\n
"},{"location":"concepts/fundamentals/html_js_css_variables/#template-variables","title":"Template variables","text":"

The get_template_data() method is the primary way to provide variables to your HTML template. It receives the component inputs and returns a dictionary of data that will be available in the template.

If get_template_data() returns None, an empty dictionary will be used.

class ProfileCard(Component):\n    template_file = \"profile_card.html\"\n\n    class Kwargs(NamedTuple):\n        user_id: int\n        show_details: bool\n\n    def get_template_data(self, args, kwargs: Kwargs, slots, context):\n        user = User.objects.get(id=kwargs.user_id)\n\n        # Process and transform inputs\n        return {\n            \"user\": user,\n            \"show_details\": kwargs.show_details,\n            \"user_joined_days\": (timezone.now() - user.date_joined).days,\n        }\n

In your template, you can then use these variables:

<div class=\"profile-card\">\n    <h2>{{ user.username }}</h2>\n\n    {% if show_details %}\n        <p>Member for {{ user_joined_days }} days</p>\n        <p>Email: {{ user.email }}</p>\n    {% endif %}\n</div>\n
"},{"location":"concepts/fundamentals/html_js_css_variables/#legacy-get_context_data","title":"Legacy get_context_data()","text":"

The get_context_data() method is the legacy way to provide variables to your HTML template. It serves the same purpose as get_template_data() - it receives the component inputs and returns a dictionary of data that will be available in the template.

However, get_context_data() has a few drawbacks:

  • It does NOT receive the slots and context parameters.
  • The args and kwargs parameters are given as variadic *args and **kwargs parameters. As such, they cannot be typed.
class ProfileCard(Component):\n    template_file = \"profile_card.html\"\n\n    def get_context_data(self, user_id, show_details=False, *args, **kwargs):\n        user = User.objects.get(id=user_id)\n        return {\n            \"user\": user,\n            \"show_details\": show_details,\n        }\n

There is a slight difference between get_context_data() and get_template_data() when rendering a component with the {% component %} tag.

For example if you have component that accepts kwarg date:

class MyComponent(Component):\n    def get_context_data(self, date, *args, **kwargs):\n        return {\n            \"date\": date,\n        }\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"date\"],\n        }\n

The difference is that:

  • With get_context_data(), you can pass date either as arg or kwarg:

    \u2705\n{% component \"my_component\" date=some_date %}\n{% component \"my_component\" some_date %}\n
  • But with get_template_data(), date MUST be passed as kwarg:

    \u2705\n{% component \"my_component\" date=some_date %}\n\n\u274c\n{% component \"my_component\" some_date %}\n

Warning

get_template_data() and get_context_data() are mutually exclusive.

If both methods return non-empty dictionaries, an error will be raised.

Note

The get_context_data() method will be removed in v2.

"},{"location":"concepts/fundamentals/html_js_css_variables/#accessing-component-inputs","title":"Accessing component inputs","text":"

The component inputs are available in 3 ways:

"},{"location":"concepts/fundamentals/html_js_css_variables/#function-arguments","title":"Function arguments","text":"

The data methods receive the inputs as parameters directly.

class ProfileCard(Component):\n    # Access inputs directly as parameters\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"user_id\": args[0],\n            \"show_details\": kwargs[\"show_details\"],\n        }\n

Info

By default, the args parameter is a list, while kwargs and slots are dictionaries.

If you add typing to your component with Args, Kwargs, or Slots classes, the respective inputs will be given as instances of these classes.

Learn more about Component typing.

class ProfileCard(Component):\n    class Args(NamedTuple):\n        user_id: int\n\n    class Kwargs(NamedTuple):\n        show_details: bool\n\n    # Access inputs directly as parameters\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots, context):\n        return {\n            \"user_id\": args.user_id,\n            \"show_details\": kwargs.show_details,\n        }\n
"},{"location":"concepts/fundamentals/html_js_css_variables/#args-kwargs-slots-properties","title":"args, kwargs, slots properties","text":"

In other methods, you can access the inputs via self.args, self.kwargs, and self.slots properties:

class ProfileCard(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]):\n        # Access inputs via self.args, self.kwargs, self.slots\n        self.args[0]\n        self.kwargs.get(\"show_details\", False)\n        self.slots[\"footer\"]\n

Info

These properties work the same way as args, kwargs, and slots parameters in the data methods:

By default, the args property is a list, while kwargs and slots are dictionaries.

If you add typing to your component with Args, Kwargs, or Slots classes, the respective inputs will be given as instances of these classes.

Learn more about Component typing.

class ProfileCard(Component):\n    class Args(NamedTuple):\n        user_id: int\n\n    class Kwargs(NamedTuple):\n        show_details: bool\n\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots, context):\n        return {\n            \"user_id\": self.args.user_id,\n            \"show_details\": self.kwargs.show_details,\n        }\n
"},{"location":"concepts/fundamentals/html_js_css_variables/#input-property-low-level","title":"input property (low-level)","text":"

Warning

The input property is deprecated and will be removed in v1.

Instead, use properties defined on the Component class directly like self.context.

To access the unmodified inputs, use self.raw_args, self.raw_kwargs, and self.raw_slots properties.

The previous two approaches allow you to access only the most important inputs.

There are additional settings that may be passed to components. If you need to access these, you can use self.input property for a low-level access to all the inputs.

The input property contains all the inputs passed to the component (instance of ComponentInput).

This includes:

  • input.args - List of positional arguments
  • input.kwargs - Dictionary of keyword arguments
  • input.slots - Dictionary of slots. Values are normalized to Slot instances
  • input.context - Context object that should be used to render the component
  • input.type - The type of the component (document, fragment)
  • input.render_dependencies - Whether to render dependencies (CSS, JS)
class ProfileCard(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        # Access positional arguments\n        user_id = self.input.args[0] if self.input.args else None\n\n        # Access keyword arguments\n        show_details = self.input.kwargs.get(\"show_details\", False)\n\n        # Render component differently depending on the type\n        if self.input.type == \"fragment\":\n            ...\n\n        return {\n            \"user_id\": user_id,\n            \"show_details\": show_details,\n        }\n

Info

Unlike the parameters passed to the data methods, the args, kwargs, and slots in self.input property are always lists and dictionaries, regardless of whether you added typing classes to your component (like Args, Kwargs, or Slots).

"},{"location":"concepts/fundamentals/html_js_css_variables/#default-values","title":"Default values","text":"

You can use Defaults class to provide default values for your inputs.

These defaults will be applied either when:

  • The input is not provided at rendering time
  • The input is provided as None

When you then access the inputs in your data methods, the default values will be already applied.

Read more about Component Defaults.

from django_components import Component, Default, register\n\n@register(\"profile_card\")\nclass ProfileCard(Component):\n    class Kwargs(NamedTuple):\n        show_details: bool\n\n    class Defaults:\n        show_details = True\n\n    # show_details will be set to True if `None` or missing\n    def get_template_data(self, args, kwargs: Kwargs, slots, context):\n        return {\n            \"show_details\": kwargs.show_details,\n        }\n\n    ...\n

Warning

When typing your components with Args, Kwargs, or Slots classes, you may be inclined to define the defaults in the classes.

class ProfileCard(Component):\n    class Kwargs(NamedTuple):\n        show_details: bool = True\n

This is NOT recommended, because:

  • The defaults will NOT be applied to inputs when using self.raw_kwargs property.
  • The defaults will NOT be applied when a field is given but set to None.

Instead, define the defaults in the Defaults class.

"},{"location":"concepts/fundamentals/html_js_css_variables/#accessing-render-api","title":"Accessing Render API","text":"

All three data methods have access to the Component's Render API, which includes:

  • self.args - The positional arguments for the current render call
  • self.kwargs - The keyword arguments for the current render call
  • self.slots - The slots for the current render call
  • self.raw_args - Unmodified positional arguments for the current render call
  • self.raw_kwargs - Unmodified keyword arguments for the current render call
  • self.raw_slots - Unmodified slots for the current render call
  • self.context - The context for the current render call
  • self.id - The unique ID for the current render call
  • self.request - The request object
  • self.context_processors_data - Data from Django's context processors
  • self.inject() - Inject data into the component
  • self.registry - The ComponentRegistry instance
  • self.registered_name - The name under which the component was registered
  • self.outer_context - The context outside of the {% component %} tag
  • self.deps_strategy - The strategy for rendering dependencies
"},{"location":"concepts/fundamentals/html_js_css_variables/#type-hints","title":"Type hints","text":""},{"location":"concepts/fundamentals/html_js_css_variables/#typing-inputs","title":"Typing inputs","text":"

You can add type hints for the component inputs to ensure that the component logic is correct.

For this, define the Args, Kwargs, and Slots classes, and then add type hints to the data methods.

This will also validate the inputs at runtime, as the type classes will be instantiated with the inputs.

Read more about Component typing.

from typing import NamedTuple, Optional\nfrom django_components import Component, SlotInput\n\nclass Button(Component):\n    class Args(NamedTuple):\n        name: str\n\n    class Kwargs(NamedTuple):\n        surname: str\n        maybe_var: Optional[int] = None  # May be omitted\n\n    class Slots(NamedTuple):\n        my_slot: Optional[SlotInput] = None\n        footer: SlotInput\n\n    # Use the above classes to add type hints to the data method\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        # The parameters are instances of the classes we defined\n        assert isinstance(args, Button.Args)\n        assert isinstance(kwargs, Button.Kwargs)\n        assert isinstance(slots, Button.Slots)\n

Note

To access \"untyped\" inputs, use self.raw_args, self.raw_kwargs, and self.raw_slots properties.

These are plain lists and dictionaries, even when you added typing to your component.

"},{"location":"concepts/fundamentals/html_js_css_variables/#typing-data","title":"Typing data","text":"

In the same fashion, you can add types and validation for the data that should be RETURNED from each data method.

For this, set the TemplateData, JsData, and CssData classes on the component class.

For each data method, you can either return a plain dictionary with the data, or an instance of the respective data class.

from typing import NamedTuple\nfrom django_components import Component\n\nclass Button(Component):\n    class TemplateData(NamedTuple):\n        data1: str\n        data2: int\n\n    class JsData(NamedTuple):\n        js_data1: str\n        js_data2: int\n\n    class CssData(NamedTuple):\n        css_data1: str\n        css_data2: int\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return Button.TemplateData(\n            data1=\"...\",\n            data2=123,\n        )\n\n    def get_js_data(self, args, kwargs, slots, context):\n        return Button.JsData(\n            js_data1=\"...\",\n            js_data2=123,\n        )\n\n    def get_css_data(self, args, kwargs, slots, context):\n        return Button.CssData(\n            css_data1=\"...\",\n            css_data2=123,\n        )\n
"},{"location":"concepts/fundamentals/html_js_css_variables/#pass-through-kwargs","title":"Pass-through kwargs","text":"

It's best practice to explicitly define what args and kwargs a component accepts.

However, if you want a looser setup, you can easily write components that accept any number of kwargs, and pass them all to the template (similar to django-cotton).

To do that, simply return the kwargs dictionary itself from get_template_data():

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return kwargs\n

You can do the same for get_js_data() and get_css_data(), if needed:

class MyComponent(Component):\n    def get_js_data(self, args, kwargs, slots, context):\n        return kwargs\n\n    def get_css_data(self, args, kwargs, slots, context):\n        return kwargs\n
"},{"location":"concepts/fundamentals/http_request/","title":"HTTP Request","text":"

The most common use of django-components is to render HTML when the server receives a request. As such, there are a few features that are dependent on the request object.

"},{"location":"concepts/fundamentals/http_request/#passing-the-httprequest-object","title":"Passing the HttpRequest object","text":"

In regular Django templates, the request object is available only within the RequestContext.

In Components, you can either use RequestContext, or pass the request object explicitly to Component.render() and Component.render_to_response().

So the request object is available to components either when:

  • The component is rendered with RequestContext (Regular Django behavior)
  • The component is rendered with a regular Context (or none), but you set the request kwarg of Component.render().
  • The component is nested and the parent has access to the request object.
# \u2705 With request\nMyComponent.render(request=request)\nMyComponent.render(context=RequestContext(request, {}))\n\n# \u274c Without request\nMyComponent.render()\nMyComponent.render(context=Context({}))\n

When a component is rendered within a template with {% component %} tag, the request object is available depending on whether the template is rendered with RequestContext or not.

template = Template(\"\"\"\n<div>\n  {% component \"MyComponent\" / %}\n</div>\n\"\"\")\n\n# \u274c No request\nrendered = template.render(Context({}))\n\n# \u2705 With request\nrendered = template.render(RequestContext(request, {}))\n
"},{"location":"concepts/fundamentals/http_request/#accessing-the-httprequest-object","title":"Accessing the HttpRequest object","text":"

When the component has access to the request object, the request object will be available in Component.request.

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            'user_id': self.request.GET['user_id'],\n        }\n
"},{"location":"concepts/fundamentals/http_request/#context-processors","title":"Context Processors","text":"

Components support Django's context processors.

In regular Django templates, the context processors are applied only when the template is rendered with RequestContext.

In Components, the context processors are applied when the component has access to the request object.

"},{"location":"concepts/fundamentals/http_request/#accessing-context-processors-data","title":"Accessing context processors data","text":"

The data from context processors is automatically available within the component's template.

class MyComponent(Component):\n    template = \"\"\"\n        <div>\n            {{ csrf_token }}\n        </div>\n    \"\"\"\n\nMyComponent.render(request=request)\n

You can also access the context processors data from within get_template_data() and other methods under Component.context_processors_data.

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        csrf_token = self.context_processors_data['csrf_token']\n        return {\n            'csrf_token': csrf_token,\n        }\n

This is a dictionary with the context processors data.

If the request object is not available, then self.context_processors_data will be an empty dictionary.

Warning

The self.context_processors_data object is generated dynamically, so changes to it are not persisted.

"},{"location":"concepts/fundamentals/render_api/","title":"Render API","text":"

When a component is being rendered, whether with Component.render() or {% component %}, a component instance is populated with the current inputs and context. This allows you to access things like component inputs.

We refer to these render-time-only methods and attributes as the \"Render API\".

Render API is available inside these Component methods:

  • get_template_data()
  • get_js_data()
  • get_css_data()
  • get_context_data()
  • on_render_before()
  • on_render()
  • on_render_after()

Example:

class Table(Component):\n    def on_render_before(self, context, template):\n        # Access component's ID\n        assert self.id == \"c1A2b3c\"\n\n        # Access component's inputs, slots and context\n        assert self.args == [123, \"str\"]\n        assert self.kwargs == {\"variable\": \"test\", \"another\": 1}\n        footer_slot = self.slots[\"footer\"]\n        some_var = self.context[\"some_var\"]\n\n    def get_template_data(self, args, kwargs, slots, context):\n        # Access the request object and Django's context processors, if available\n        assert self.request.GET == {\"query\": \"something\"}\n        assert self.context_processors_data['user'].username == \"admin\"\n\nrendered = Table.render(\n    kwargs={\"variable\": \"test\", \"another\": 1},\n    args=(123, \"str\"),\n    slots={\"footer\": \"MY_SLOT\"},\n)\n
"},{"location":"concepts/fundamentals/render_api/#overview","title":"Overview","text":"

The Render API includes:

  • Component inputs:

    • self.args - The positional arguments for the current render call
    • self.kwargs - The keyword arguments for the current render call
    • self.slots - The slots for the current render call
    • self.raw_args - Unmodified positional arguments for the current render call
    • self.raw_kwargs - Unmodified keyword arguments for the current render call
    • self.raw_slots - Unmodified slots for the current render call
    • self.context - The context for the current render call
    • self.deps_strategy - The strategy for rendering dependencies
  • Request-related:

    • self.request - The request object (if available)
    • self.context_processors_data - Data from Django's context processors
  • Provide / inject:

    • self.inject() - Inject data into the component
  • Template tag metadata:

    • self.node - The ComponentNode instance
    • self.registry - The ComponentRegistry instance
    • self.registered_name - The name under which the component was registered
    • self.outer_context - The context outside of the {% component %} tag
  • Other metadata:

    • self.id - The unique ID for the current render call
"},{"location":"concepts/fundamentals/render_api/#component-inputs","title":"Component inputs","text":""},{"location":"concepts/fundamentals/render_api/#args","title":"Args","text":"

The args argument as passed to Component.get_template_data().

If you defined the Component.Args class, then the Component.args property will return an instance of that class.

Otherwise, args will be a plain list.

Use self.raw_args to access the positional arguments as a plain list irrespective of Component.Args.

Example:

With Args class:

from django_components import Component\n\nclass Table(Component):\n    class Args(NamedTuple):\n        page: int\n        per_page: int\n\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.args.page == 123\n        assert self.args.per_page == 10\n\nrendered = Table.render(\n    args=[123, 10],\n)\n

Without Args class:

from django_components import Component\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.args[0] == 123\n        assert self.args[1] == 10\n
"},{"location":"concepts/fundamentals/render_api/#kwargs","title":"Kwargs","text":"

The kwargs argument as passed to Component.get_template_data().

If you defined the Component.Kwargs class, then the Component.kwargs property will return an instance of that class.

Otherwise, kwargs will be a plain dictionary.

Use self.raw_kwargs to access the keyword arguments as a plain dictionary irrespective of Component.Kwargs.

Example:

With Kwargs class:

from django_components import Component\n\nclass Table(Component):\n    class Kwargs(NamedTuple):\n        page: int\n        per_page: int\n\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.kwargs.page == 123\n        assert self.kwargs.per_page == 10\n\nrendered = Table.render(\n    kwargs={\"page\": 123, \"per_page\": 10},\n)\n

Without Kwargs class:

from django_components import Component\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.kwargs[\"page\"] == 123\n        assert self.kwargs[\"per_page\"] == 10\n
"},{"location":"concepts/fundamentals/render_api/#slots","title":"Slots","text":"

The slots argument as passed to Component.get_template_data().

If you defined the Component.Slots class, then the Component.slots property will return an instance of that class.

Otherwise, slots will be a plain dictionary.

Use self.raw_slots to access the slots as a plain dictionary irrespective of Component.Slots.

Example:

With Slots class:

from django_components import Component, Slot, SlotInput\n\nclass Table(Component):\n    class Slots(NamedTuple):\n        header: SlotInput\n        footer: SlotInput\n\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert isinstance(self.slots.header, Slot)\n        assert isinstance(self.slots.footer, Slot)\n\nrendered = Table.render(\n    slots={\n        \"header\": \"MY_HEADER\",\n        \"footer\": lambda ctx: \"FOOTER: \" + ctx.data[\"user_id\"],\n    },\n)\n

Without Slots class:

from django_components import Component, Slot, SlotInput\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert isinstance(self.slots[\"header\"], Slot)\n        assert isinstance(self.slots[\"footer\"], Slot)\n
"},{"location":"concepts/fundamentals/render_api/#context","title":"Context","text":"

The context argument as passed to Component.get_template_data().

This is Django's Context with which the component template is rendered.

If the root component or template was rendered with RequestContext then this will be an instance of RequestContext.

Whether the context variables defined in context are available to the template depends on the context behavior mode:

  • In \"django\" context behavior mode, the template will have access to the keys of this context.

  • In \"isolated\" context behavior mode, the template will NOT have access to this context, and data MUST be passed via component's args and kwargs.

"},{"location":"concepts/fundamentals/render_api/#component-id","title":"Component ID","text":"

Component ID (or render ID) is a unique identifier for the current render call.

That means that if you call Component.render() multiple times, the ID will be different for each call.

It is available as self.id.

The ID is a 7-letter alphanumeric string in the format cXXXXXX, where XXXXXX is a random string of 6 alphanumeric characters (case-sensitive).

E.g. c1a2b3c.

A single render ID has a chance of collision 1 in 57 billion. However, due to birthday paradox, the chance of collision increases to 1% when approaching ~33K render IDs.

Thus, there is currently a soft-cap of ~30K components rendered on a single page.

If you need to expand this limit, please open an issue on GitHub.

class Table(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        # Access component's ID\n        assert self.id == \"c1A2b3c\"\n
"},{"location":"concepts/fundamentals/render_api/#request-and-context-processors","title":"Request and context processors","text":"

Components have access to the request object and context processors data if the component was:

  • Given a request kwarg directly
  • Rendered with RenderContext
  • Nested in another component for which any of these conditions is true

Then the request object will be available in self.request.

If the request object is available, you will also be able to access the context processors data in self.context_processors_data.

This is a dictionary with the context processors data.

If the request object is not available, then self.context_processors_data will be an empty dictionary.

Read more about the request object and context processors in the HTTP Request section.

from django.http import HttpRequest\n\nclass Table(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        # Access the request object and Django's context processors\n        assert self.request.GET == {\"query\": \"something\"}\n        assert self.context_processors_data['user'].username == \"admin\"\n\nrendered = Table.render(\n    request=HttpRequest(),\n)\n
"},{"location":"concepts/fundamentals/render_api/#provide-inject","title":"Provide / Inject","text":"

Components support a provide / inject system as known from Vue or React.

When rendering the component, you can call self.inject() with the key of the data you want to inject.

The object returned by self.inject()

To provide data to components, use the {% provide %} template tag.

Read more about Provide / Inject.

class Table(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        # Access provided data\n        data = self.inject(\"some_data\")\n        assert data.some_data == \"some_data\"\n
"},{"location":"concepts/fundamentals/render_api/#template-tag-metadata","title":"Template tag metadata","text":"

If the component is rendered with {% component %} template tag, the following metadata is available:

  • self.node - The ComponentNode instance
  • self.registry - The ComponentRegistry instance that was used to render the component
  • self.registered_name - The name under which the component was registered
  • self.outer_context - The context outside of the {% component %} tag

    {% with abc=123 %}\n    {{ abc }} {# <--- This is in outer context #}\n    {% component \"my_component\" / %}\n{% endwith %}\n

You can use these to check whether the component was rendered inside a template with {% component %} tag or in Python with Component.render().

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        if self.registered_name is None:\n            # Do something for the render() function\n        else:\n            # Do something for the {% component %} template tag\n

You can access the ComponentNode under Component.node:

class MyComponent(Component):\n    def get_template_data(self, context, template):\n        if self.node is not None:\n            assert self.node.name == \"my_component\"\n

Accessing the ComponentNode is mostly useful for extensions, which can modify their behaviour based on the source of the Component.

For example, if MyComponent was used in another component - that is, with a {% component \"my_component\" %} tag in a template that belongs to another component - then you can use self.node.template_component to access the owner Component class.

class Parent(Component):\n    template: types.django_html = \"\"\"\n        <div>\n            {% component \"my_component\" / %}\n        </div>\n    \"\"\"\n\n@register(\"my_component\")\nclass MyComponent(Component):\n    def get_template_data(self, context, template):\n        if self.node is not None:\n            assert self.node.template_component == Parent\n

Info

Component.node is None if the component is created by Component.render() (but you can pass in the node kwarg yourself).

"},{"location":"concepts/fundamentals/rendering_components/","title":"Rendering components","text":"

Your components can be rendered either within your Django templates, or directly in Python code.

"},{"location":"concepts/fundamentals/rendering_components/#overview","title":"Overview","text":"

Django Components provides three main methods to render components:

  • {% component %} tag - Renders the component within your Django templates
  • Component.render() method - Renders the component to a string
  • Component.render_to_response() method - Renders the component and wraps it in an HTTP response
"},{"location":"concepts/fundamentals/rendering_components/#component-tag","title":"{% component %} tag","text":"

Use the {% component %} tag to render a component within your Django templates.

The {% component %} tag takes:

  • Component's registered name as the first positional argument,
  • Followed by any number of positional and keyword arguments.
{% load component_tags %}\n<div>\n  {% component \"button\" name=\"John\" job=\"Developer\" / %}\n</div>\n

To pass in slots content, you can insert {% fill %} tags, directly within the {% component %} tag to \"fill\" the slots:

{% component \"my_table\" rows=rows headers=headers %}\n    {% fill \"pagination\" %}\n      < 1 | 2 | 3 >\n    {% endfill %}\n{% endcomponent %}\n

You can even nest {% fill %} tags within {% if %}, {% for %} and other tags:

{% component \"my_table\" rows=rows headers=headers %}\n    {% if rows %}\n        {% fill \"pagination\" %}\n            < 1 | 2 | 3 >\n        {% endfill %}\n    {% endif %}\n{% endcomponent %}\n

Omitting the component keyword

If you would like to omit the component keyword, and simply refer to your components by their registered names:

{% button name=\"John\" job=\"Developer\" / %}\n

You can do so by setting the \"shorthand\" Tag formatter in the settings:

# settings.py\nCOMPONENTS = {\n    \"tag_formatter\": \"django_components.component_shorthand_formatter\",\n}\n

Extended template tag syntax

Unlike regular Django template tags, django-components' tags offer extra features like defining literal lists and dicts, and more. Read more about Template tag syntax.

"},{"location":"concepts/fundamentals/rendering_components/#registering-components","title":"Registering components","text":"

For a component to be renderable with the {% component %} tag, it must be first registered with the @register() decorator.

For example, if you register a component under the name \"button\":

from typing import NamedTuple\nfrom django_components import Component, register\n\n@register(\"button\")\nclass Button(Component):\n    template_file = \"button.html\"\n\n    class Kwargs(NamedTuple):\n        name: str\n        job: str\n\n    def get_template_data(self, args, kwargs, slots, context):\n        ...\n

Then you can render this component by using its registered name \"button\" in the template:

{% component \"button\" name=\"John\" job=\"Developer\" / %}\n

As you can see above, the args and kwargs passed to the {% component %} tag correspond to the component's input.

For more details, read Registering components.

Why do I need to register components?

TL;DR: To be able to share components as libraries, and because components can be registed with multiple registries / libraries.

Django-components allows to share components across projects.

However, different projects may use different settings. For example, one project may prefer the \"long\" format:

{% component \"button\" name=\"John\" job=\"Developer\" / %}\n

While the other may use the \"short\" format:

{% button name=\"John\" job=\"Developer\" / %}\n

Both approaches are supported simultaneously for backwards compatibility, because django-components started out with only the \"long\" format.

To avoid ambiguity, when you use a 3rd party library, it uses the syntax that the author had configured for it.

So when you are creating a component, django-components need to know which registry the component belongs to, so it knows which syntax to use.

"},{"location":"concepts/fundamentals/rendering_components/#rendering-templates","title":"Rendering templates","text":"

If you have embedded the component in a Django template using the {% component %} tag:

[project root]/templates/my_template.html
{% load component_tags %}\n<div>\n  {% component \"calendar\" date=\"2024-12-13\" / %}\n</div>\n

You can simply render the template with the Django's API:

  • django.shortcuts.render()

    from django.shortcuts import render\n\ncontext = {\"date\": \"2024-12-13\"}\nrendered_template = render(request, \"my_template.html\", context)\n
  • Template.render()

    from django.template import Template\nfrom django.template.loader import get_template\n\n# Either from a file\ntemplate = get_template(\"my_template.html\")\n\n# or inlined\ntemplate = Template(\"\"\"\n    {% load component_tags %}\n    <div>\n        {% component \"calendar\" date=\"2024-12-13\" / %}\n    </div>\n\"\"\")\n\nrendered_template = template.render()\n
"},{"location":"concepts/fundamentals/rendering_components/#isolating-components","title":"Isolating components","text":"

By default, components behave similarly to Django's {% include %}, and the template inside the component has access to the variables defined in the outer template.

You can selectively isolate a component, using the only flag, so that the inner template can access only the data that was explicitly passed to it:

{% component \"name\" positional_arg keyword_arg=value ... only / %}\n

Alternatively, you can set all components to be isolated by default, by setting context_behavior to \"isolated\" in your settings:

# settings.py\nCOMPONENTS = {\n    \"context_behavior\": \"isolated\",\n}\n
"},{"location":"concepts/fundamentals/rendering_components/#render-method","title":"render() method","text":"

The Component.render() method renders a component to a string.

This is the equivalent of calling the {% component %} tag.

from typing import NamedTuple, Optional\nfrom django_components import Component, SlotInput\n\nclass Button(Component):\n    template_file = \"button.html\"\n\n    class Args(NamedTuple):\n        name: str\n\n    class Kwargs(NamedTuple):\n        surname: str\n        age: int\n\n    class Slots(NamedTuple):\n        footer: Optional[SlotInput] = None\n\n    def get_template_data(self, args, kwargs, slots, context):\n        ...\n\nButton.render(\n    args=[\"John\"],\n    kwargs={\n        \"surname\": \"Doe\",\n        \"age\": 30,\n    },\n    slots={\n        \"footer\": \"i AM A SLOT\",\n    },\n)\n

Component.render() accepts the following arguments:

  • args - Positional arguments to pass to the component (as a list or tuple)
  • kwargs - Keyword arguments to pass to the component (as a dictionary)
  • slots - Slot content to pass to the component (as a dictionary)
  • context - Django context for rendering (can be a dictionary or a Context object)
  • deps_strategy - Dependencies rendering strategy (default: \"document\")
  • request - HTTP request object, used for context processors (optional)

All arguments are optional. If not provided, they default to empty values or sensible defaults.

See the API reference for Component.render() for more details on the arguments.

"},{"location":"concepts/fundamentals/rendering_components/#render_to_response-method","title":"render_to_response() method","text":"

The Component.render_to_response() method works just like Component.render(), but wraps the result in an HTTP response.

It accepts all the same arguments as Component.render().

Any extra arguments are passed to the HttpResponse constructor.

from typing import NamedTuple, Optional\nfrom django_components import Component, SlotInput\n\nclass Button(Component):\n    template_file = \"button.html\"\n\n    class Args(NamedTuple):\n        name: str\n\n    class Kwargs(NamedTuple):\n        surname: str\n        age: int\n\n    class Slots(NamedTuple):\n        footer: Optional[SlotInput] = None\n\n    def get_template_data(self, args, kwargs, slots, context):\n        ...\n\n# Render the component to an HttpResponse\nresponse = Button.render_to_response(\n    args=[\"John\"],\n    kwargs={\n        \"surname\": \"Doe\",\n        \"age\": 30,\n    },\n    slots={\n        \"footer\": \"i AM A SLOT\",\n    },\n    # Additional response arguments\n    status=200,\n    headers={\"X-Custom-Header\": \"Value\"},\n)\n

This method is particularly useful in view functions, as you can return the result of the component directly:

def profile_view(request, user_id):\n    return Button.render_to_response(\n        kwargs={\n            \"surname\": \"Doe\",\n            \"age\": 30,\n        },\n        request=request,\n    )\n
"},{"location":"concepts/fundamentals/rendering_components/#custom-response-classes","title":"Custom response classes","text":"

By default, Component.render_to_response() returns a standard Django HttpResponse.

You can customize this by setting the response_class attribute on your component:

from django.http import HttpResponse\nfrom django_components import Component\n\nclass MyHttpResponse(HttpResponse):\n    ...\n\nclass MyComponent(Component):\n    response_class = MyHttpResponse\n\nresponse = MyComponent.render_to_response()\nassert isinstance(response, MyHttpResponse)\n
"},{"location":"concepts/fundamentals/rendering_components/#dependencies-rendering","title":"Dependencies rendering","text":"

The rendered HTML may be used in different contexts (browser, email, etc), and each may need different handling of JS and CSS scripts.

render() and render_to_response() accept a deps_strategy parameter, which controls where and how the JS / CSS are inserted into the HTML.

The deps_strategy parameter is ultimately passed to render_dependencies().

Learn more about Rendering JS / CSS.

There are six dependencies rendering strategies:

  • document (default)
    • Smartly inserts JS / CSS into placeholders ({% component_js_dependencies %}) or into <head> and <body> tags.
    • Inserts extra script to allow fragment components to work.
    • Assumes the HTML will be rendered in a JS-enabled browser.
  • fragment
    • A lightweight HTML fragment to be inserted into a document with AJAX.
    • Assumes the page was already rendered with \"document\" strategy.
    • No JS / CSS included.
  • simple
    • Smartly insert JS / CSS into placeholders ({% component_js_dependencies %}) or into <head> and <body> tags.
    • No extra script loaded.
  • prepend
    • Insert JS / CSS before the rendered HTML.
    • Ignores the placeholders ({% component_js_dependencies %}) and any <head>/<body> HTML tags.
    • No extra script loaded.
  • append
    • Insert JS / CSS after the rendered HTML.
    • Ignores the placeholders ({% component_js_dependencies %}) and any <head>/<body> HTML tags.
    • No extra script loaded.
  • ignore
    • HTML is left as-is. You can still process it with a different strategy later with render_dependencies().
    • Used for inserting rendered HTML into other components.

Info

You can use the \"prepend\" and \"append\" strategies to force to output JS / CSS for components that don't have neither the placeholders like {% component_js_dependencies %}, nor any <head>/<body> HTML tags:

rendered = Calendar.render_to_response(\n    request=request,\n    kwargs={\n        \"date\": request.GET.get(\"date\", \"\"),\n    },\n    deps_strategy=\"append\",\n)\n

Renders something like this:

<!-- Calendar component -->\n<div class=\"calendar\">\n    ...\n</div>\n<!-- Appended JS / CSS -->\n<script src=\"...\"></script>\n<link href=\"...\"></link>\n
"},{"location":"concepts/fundamentals/rendering_components/#passing-context","title":"Passing context","text":"

The render() and render_to_response() methods accept an optional context argument. This sets the context within which the component is rendered.

When a component is rendered within a template with the {% component %} tag, this will be automatically set to the Context instance that is used for rendering the template.

When you call Component.render() directly from Python, there is no context object, so you can ignore this input most of the time. Instead, use args, kwargs, and slots to pass data to the component.

However, you can pass RequestContext to the context argument, so that the component will gain access to the request object and will use context processors. Read more on Working with HTTP requests.

Button.render(\n    context=RequestContext(request),\n)\n

For advanced use cases, you can use context argument to \"pre-render\" the component in Python, and then pass the rendered output as plain string to the template. With this, the inner component is rendered as if it was within the template with {% component %}.

class Button(Component):\n    def render(self, context, template):\n        # Pass `context` to Icon component so it is rendered\n        # as if nested within Button.\n        icon = Icon.render(\n            context=context,\n            args=[\"icon-name\"],\n            deps_strategy=\"ignore\",\n        )\n        # Update context with icon\n        with context.update({\"icon\": icon}):\n            return template.render(context)\n

Warning

Whether the variables defined in context are actually available in the template depends on the context behavior mode:

  • In \"django\" context behavior mode, the template will have access to the keys of this context.

  • In \"isolated\" context behavior mode, the template will NOT have access to this context, and data MUST be passed via component's args and kwargs.

Therefore, it's strongly recommended to not rely on defining variables on the context object, but instead passing them through as args and kwargs

\u274c Don't do this:

html = ProfileCard.render(\n    context={\"name\": \"John\"},\n)\n

\u2705 Do this:

html = ProfileCard.render(\n    kwargs={\"name\": \"John\"},\n)\n
"},{"location":"concepts/fundamentals/rendering_components/#typing-render-methods","title":"Typing render methods","text":"

Neither Component.render() nor Component.render_to_response() are typed, due to limitations of Python's type system.

To add type hints, you can wrap the inputs in component's Args, Kwargs, and Slots classes.

Read more on Typing and validation.

from typing import NamedTuple, Optional\nfrom django_components import Component, Slot, SlotInput\n\n# Define the component with the types\nclass Button(Component):\n    class Args(NamedTuple):\n        name: str\n\n    class Kwargs(NamedTuple):\n        surname: str\n        age: int\n\n    class Slots(NamedTuple):\n        my_slot: Optional[SlotInput] = None\n        footer: SlotInput\n\n# Add type hints to the render call\nButton.render(\n    args=Button.Args(\n        name=\"John\",\n    ),\n    kwargs=Button.Kwargs(\n        surname=\"Doe\",\n        age=30,\n    ),\n    slots=Button.Slots(\n        footer=Slot(lambda ctx: \"Click me!\"),\n    ),\n)\n
"},{"location":"concepts/fundamentals/rendering_components/#components-as-input","title":"Components as input","text":"

django_components makes it possible to compose components in a \"React-like\" way, where you can render one component and use its output as input to another component:

from django.utils.safestring import mark_safe\n\n# Render the inner component\ninner_html = InnerComponent.render(\n    kwargs={\"some_data\": \"value\"},\n    deps_strategy=\"ignore\",  # Important for nesting!\n)\n\n# Use inner component's output in the outer component\nouter_html = OuterComponent.render(\n    kwargs={\n        \"content\": mark_safe(inner_html),  # Mark as safe to prevent escaping\n    },\n)\n

The key here is setting deps_strategy=\"ignore\" for the inner component. This prevents duplicate rendering of JS / CSS dependencies when the outer component is rendered.

When deps_strategy=\"ignore\":

  • No JS or CSS dependencies will be added to the output HTML
  • The component's content is rendered as-is
  • The outer component will take care of including all needed dependencies

Read more about Rendering JS / CSS.

"},{"location":"concepts/fundamentals/rendering_components/#dynamic-components","title":"Dynamic components","text":"

Django components defines a special \"dynamic\" component (DynamicComponent).

Normally, you have to hard-code the component name in the template:

{% component \"button\" / %}\n

The dynamic component allows you to dynamically render any component based on the is kwarg. This is similar to Vue's dynamic components (<component :is>).

{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% endcomponent %}\n

The args, kwargs, and slot fills are all passed down to the underlying component.

As with other components, the dynamic component can be rendered from Python:

from django_components import DynamicComponent\n\nDynamicComponent.render(\n    kwargs={\n        \"is\": table_comp,\n        \"data\": table_data,\n        \"headers\": table_headers,\n    },\n    slots={\n        \"pagination\": PaginationComponent.render(\n            deps_strategy=\"ignore\",\n        ),\n    },\n)\n
"},{"location":"concepts/fundamentals/rendering_components/#dynamic-component-name","title":"Dynamic component name","text":"

By default, the dynamic component is registered under the name \"dynamic\". In case of a conflict, you can set the COMPONENTS.dynamic_component_name setting to change the name used for the dynamic components.

# settings.py\nCOMPONENTS = ComponentsSettings(\n    dynamic_component_name=\"my_dynamic\",\n)\n

After which you will be able to use the dynamic component with the new name:

{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"concepts/fundamentals/rendering_components/#html-fragments","title":"HTML fragments","text":"

Django-components provides a seamless integration with HTML fragments with AJAX (HTML over the wire), whether you're using jQuery, HTMX, AlpineJS, vanilla JavaScript, or other.

This is achieved by the combination of the \"document\" and \"fragment\" dependencies rendering strategies.

Read more about HTML fragments and Rendering JS / CSS.

"},{"location":"concepts/fundamentals/secondary_js_css_files/","title":"Secondary JS / CSS files","text":""},{"location":"concepts/fundamentals/secondary_js_css_files/#overview","title":"Overview","text":"

Each component can define extra or \"secondary\" CSS / JS files using the nested Component.Media class, by setting Component.Media.js and Component.Media.css.

The main HTML / JS / CSS files are limited to 1 per component. This is not the case for the secondary files, where components can have many of them.

There is also no special behavior or post-processing for these secondary files, they are loaded as is.

You can use these for third-party libraries, or for shared CSS / JS files.

These must be set as paths, URLs, or custom objects.

@register(\"calendar\")\nclass Calendar(Component):\n    class Media:\n        js = [\n            \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\",\n            \"calendar/script.js\",\n        ]\n        css = [\n            \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\",\n            \"calendar/style.css\",\n        ]\n

Note

django-component's management of files is inspired by Django's Media class.

To be familiar with how Django handles static files, we recommend reading also:

  • How to manage static files (e.g. images, JavaScript, CSS)
"},{"location":"concepts/fundamentals/secondary_js_css_files/#media-class","title":"Media class","text":"

Use the Media class to define secondary JS / CSS files for a component.

This Media class behaves similarly to Django's Media class:

  • Static paths - Paths are handled as static file paths, and are resolved to URLs with Django's {% static %} template tag.
  • URLs - A path that starts with http, https, or / is considered a URL. URLs are NOT resolved with {% static %}.
  • HTML tags - Both static paths and URLs are rendered to <script> and <link> HTML tags with media_class.render_js() and media_class.render_css().
  • Bypass formatting - A SafeString, or a function (with __html__ method) is considered an already-formatted HTML tag, skipping both static file resolution and rendering with media_class.render_js() or media_class.render_css().
  • Inheritance - You can set extend to configure whether to inherit JS / CSS from parent components. See Media inheritance.

However, there's a few differences from Django's Media class:

  1. Our Media class accepts various formats for the JS and CSS files: either a single file, a list, or (CSS-only) a dictonary (See ComponentMediaInput).
  2. Individual JS / CSS files can be any of str, bytes, Path, SafeString, or a function (See ComponentMediaInputPath).
  3. Individual JS / CSS files can be glob patterns, e.g. *.js or styles/**/*.css.
  4. If you set Media.extend to a list, it should be a list of Component classes.
from components.layout import LayoutComp\n\nclass MyTable(Component):\n    class Media:\n        js = [\n            \"path/to/script.js\",\n            \"path/to/*.js\",  # Or as a glob\n            \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\",  # AlpineJS\n        ]\n        css = {\n            \"all\": [\n                \"path/to/style.css\",\n                \"path/to/*.css\",  # Or as a glob\n                \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\",  # TailwindCSS\n            ],\n            \"print\": [\"path/to/style2.css\"],\n        }\n\n        # Reuse JS / CSS from LayoutComp\n        extend = [\n            LayoutComp,\n        ]\n
"},{"location":"concepts/fundamentals/secondary_js_css_files/#css-media-types","title":"CSS media types","text":"

You can define which stylesheets will be associated with which CSS media types. You do so by defining CSS files as a dictionary.

See the corresponding Django Documentation.

Again, you can set either a single file or a list of files per media type:

class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": \"path/to/style1.css\",\n            \"print\": [\"path/to/style2.css\", \"path/to/style3.css\"],\n        }\n

Which will render the following HTML:

<link href=\"/static/path/to/style1.css\" media=\"all\" rel=\"stylesheet\">\n<link href=\"/static/path/to/style2.css\" media=\"print\" rel=\"stylesheet\">\n<link href=\"/static/path/to/style3.css\" media=\"print\" rel=\"stylesheet\">\n

Note

When you define CSS as a string or a list, the all media type is implied.

So these two examples are the same:

class MyComponent(Component):\n    class Media:\n        css = \"path/to/style1.css\"\n
class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": [\"path/to/style1.css\"],\n        }\n
"},{"location":"concepts/fundamentals/secondary_js_css_files/#media-inheritance","title":"Media inheritance","text":"

By default, the media files are inherited from the parent component.

class ParentComponent(Component):\n    class Media:\n        js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n    class Media:\n        js = [\"script.js\"]\n\nprint(MyComponent.media._js)  # [\"parent.js\", \"script.js\"]\n

You can set the component NOT to inherit from the parent component by setting the extend attribute to False:

class ParentComponent(Component):\n    class Media:\n        js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n    class Media:\n        extend = False  # Don't inherit parent media\n        js = [\"script.js\"]\n\nprint(MyComponent.media._js)  # [\"script.js\"]\n

Alternatively, you can specify which components to inherit from. In such case, the media files are inherited ONLY from the specified components, and NOT from the original parent components:

class ParentComponent(Component):\n    class Media:\n        js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n    class Media:\n        # Only inherit from these, ignoring the files from the parent\n        extend = [OtherComponent1, OtherComponent2]\n\n        js = [\"script.js\"]\n\nprint(MyComponent.media._js)  # [\"script.js\", \"other1.js\", \"other2.js\"]\n

Info

The extend behaves consistently with Django's Media class, with one exception:

  • When you set extend to a list, the list is expected to contain Component classes (or other classes that have a nested Media class).
"},{"location":"concepts/fundamentals/secondary_js_css_files/#accessing-media-files","title":"Accessing Media files","text":"

To access the files that you defined under Component.Media, use Component.media (lowercase).

This is consistent behavior with Django's Media class.

class MyComponent(Component):\n    class Media:\n        js = \"path/to/script.js\"\n        css = \"path/to/style.css\"\n\nprint(MyComponent.media)\n# Output:\n# <script src=\"/static/path/to/script.js\"></script>\n# <link href=\"/static/path/to/style.css\" media=\"all\" rel=\"stylesheet\">\n

When working with component media files, it is important to understand the difference:

  • Component.Media

    • Is the \"raw\" media definition, or the input, which holds only the component's own media definition
    • This class is NOT instantiated, it merely holds the JS / CSS files.
  • Component.media

    • Returns all resolved media files, including those inherited from parent components
    • Is an instance of Component.media_class
class ParentComponent(Component):\n    class Media:\n        js = [\"parent.js\"]\n\nclass ChildComponent(ParentComponent):\n    class Media:\n        js = [\"child.js\"]\n\n# Access only this component's media\nprint(ChildComponent.Media.js)  # [\"child.js\"]\n\n# Access all inherited media\nprint(ChildComponent.media._js)  # [\"parent.js\", \"child.js\"]\n

Note

You should not manually modify Component.media or Component.Media after the component has been resolved, as this may lead to unexpected behavior.

If you want to modify the class that is instantiated for Component.media, you can configure Component.media_class (See example).

"},{"location":"concepts/fundamentals/secondary_js_css_files/#file-paths","title":"File paths","text":"

Unlike the main HTML / JS / CSS files, the path definition for the secondary files are quite ergonomic.

"},{"location":"concepts/fundamentals/secondary_js_css_files/#relative-to-component","title":"Relative to component","text":"

As seen in the getting started example, to associate HTML / JS / CSS files with a component, you can set them as Component.template_file, Component.js_file and Component.css_file respectively:

[project root]/components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"template.html\"\n    css_file = \"style.css\"\n    js_file = \"script.js\"\n

In the example above, we defined the files relative to the directory where the component file is defined.

Alternatively, you can specify the file paths relative to the directories set in COMPONENTS.dirs or COMPONENTS.app_dirs.

If you specify the paths relative to component's directory, django-componenents does the conversion automatically for you.

Thus, assuming that COMPONENTS.dirs contains path [project root]/components, the example above is the same as writing:

[project root]/components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar/template.html\"\n    css_file = \"calendar/style.css\"\n    js_file = \"calendar/script.js\"\n

Important

File path resolution in-depth

At component class creation, django-components checks all file paths defined on the component (e.g. Component.template_file).

For each file path, it checks if the file path is relative to the component's directory. And such file exists, the component's file path is re-written to be defined relative to a first matching directory in COMPONENTS.dirs or COMPONENTS.app_dirs.

Example:

[root]/components/mytable/mytable.py
class MyTable(Component):\n    template_file = \"mytable.html\"\n
  1. Component MyTable is defined in file [root]/components/mytable/mytable.py.
  2. The component's directory is thus [root]/components/mytable/.
  3. Because MyTable.template_file is mytable.html, django-components tries to resolve it as [root]/components/mytable/mytable.html.
  4. django-components checks the filesystem. If there's no such file, nothing happens.
  5. If there IS such file, django-components tries to rewrite the path.
  6. django-components searches COMPONENTS.dirs and COMPONENTS.app_dirs for a first directory that contains [root]/components/mytable/mytable.html.
  7. It comes across [root]/components/, which DOES contain the path to mytable.html.
  8. Thus, it rewrites template_file from mytable.html to mytable/mytable.html.

NOTE: In case of ambiguity, the preference goes to resolving the files relative to the component's directory.

"},{"location":"concepts/fundamentals/secondary_js_css_files/#globs","title":"Globs","text":"

Components can have many secondary files. To simplify their declaration, you can use globs.

Globs MUST be relative to the component's directory.

[project root]/components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    class Media:\n        js = [\n            \"path/to/*.js\",\n            \"another/path/*.js\",\n        ]\n        css = \"*.css\"\n

How this works is that django-components will detect that the path is a glob, and will try to resolve all files matching the glob pattern relative to the component's directory.

After that, the file paths are handled the same way as if you defined them explicitly.

"},{"location":"concepts/fundamentals/secondary_js_css_files/#supported-types","title":"Supported types","text":"

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

To help with typing the union, use ComponentMediaInputPath.

from pathlib import Path\n\nfrom django.utils.safestring import mark_safe\n\nclass SimpleComponent(Component):\n    class Media:\n        css = [\n            mark_safe('<link href=\"/static/calendar/style1.css\" rel=\"stylesheet\" />'),\n            Path(\"calendar/style1.css\"),\n            \"calendar/style2.css\",\n            b\"calendar/style3.css\",\n            lambda: \"calendar/style4.css\",\n        ]\n        js = [\n            mark_safe('<script src=\"/static/calendar/script1.js\"></script>'),\n            Path(\"calendar/script1.js\"),\n            \"calendar/script2.js\",\n            b\"calendar/script3.js\",\n            lambda: \"calendar/script4.js\",\n        ]\n
"},{"location":"concepts/fundamentals/secondary_js_css_files/#paths-as-objects","title":"Paths as objects","text":"

In the example above, you can see that when we used Django's mark_safe() to mark a string as a SafeString, we had to define the URL / path as an HTML <script>/<link> elements.

This is an extension of Django's Paths as objects feature, where \"safe\" strings are taken as is, and are accessed only at render time.

Because of that, the paths defined as \"safe\" strings are NEVER resolved, neither relative to component's directory, nor relative to COMPONENTS.dirs. It is assumed that you will define the full <script>/<link> tag with the correct URL / path.

\"Safe\" strings can be used to lazily resolve a path, or to customize the <script> or <link> tag for individual paths:

In the example below, we make use of \"safe\" strings to add type=\"module\" to the script tag that will fetch calendar/script2.js. In this case, we implemented a \"safe\" string by defining a __html__ method.

# Path object\nclass ModuleJsPath:\n    def __init__(self, static_path: str) -> None:\n        self.static_path = static_path\n\n    # Lazily resolve the path\n    def __html__(self):\n        full_path = static(self.static_path)\n        return format_html(\n            f'<script type=\"module\" src=\"{full_path}\"></script>'\n        )\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar/template.html\"\n\n    class Media:\n        css = \"calendar/style1.css\"\n        js = [\n            # <script> tag constructed by Media class\n            \"calendar/script1.js\",\n            # Custom <script> tag\n            ModuleJsPath(\"calendar/script2.js\"),\n        ]\n
"},{"location":"concepts/fundamentals/secondary_js_css_files/#rendering-paths","title":"Rendering paths","text":"

As part of the rendering process, the secondary JS / CSS files are resolved and rendered into <link> and <script> HTML tags, so they can be inserted into the render.

In the Paths as objects section, we saw that we can use that to selectively change how the HTML tags are constructed.

However, if you need to change how ALL CSS and JS files are rendered for a given component, you can provide your own subclass of Django's Media class to the Component.media_class attribute.

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\nfrom django_components import Component, register\n\nclass MyMedia(Media):\n    # Same as original Media.render_js, except\n    # the `<script>` tag has also `type=\"module\"`\n    def render_js(self):\n        tags = []\n        for path in self._js:\n            if hasattr(path, \"__html__\"):\n                tag = path.__html__()\n            else:\n                tag = format_html(\n                    '<script type=\"module\" src=\"{}\"></script>',\n                    self.absolute_path(path)\n                )\n        return tags\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar/template.html\"\n    css_file = \"calendar/style.css\"\n    js_file = \"calendar/script.js\"\n\n    class Media:\n        css = \"calendar/style1.css\"\n        js = \"calendar/script2.js\"\n\n    # Override the behavior of Media class\n    media_class = MyMedia\n
"},{"location":"concepts/fundamentals/single_file_components/","title":"Single-file components","text":"

Components can be defined in a single file, inlining the HTML, JS and CSS within the Python code.

"},{"location":"concepts/fundamentals/single_file_components/#writing-single-file-components","title":"Writing single file components","text":"

To do this, you can use the template, js, and css class attributes instead of the template_file, js_file, and css_file.

For example, here's the calendar component from the Getting started tutorial:

calendar.py
from django_components import Component\n\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    js_file = \"calendar.js\"\n    css_file = \"calendar.css\"\n

And here is the same component, rewritten in a single file:

[project root]/components/calendar.py
from django_components import Component, register, types\n\n@register(\"calendar\")\nclass Calendar(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"date\"],\n        }\n\n    template: types.django_html = \"\"\"\n        <div class=\"calendar\">\n            Today's date is <span>{{ date }}</span>\n        </div>\n    \"\"\"\n\n    css: types.css = \"\"\"\n        .calendar {\n            width: 200px;\n            background: pink;\n        }\n        .calendar span {\n            font-weight: bold;\n        }\n    \"\"\"\n\n    js: types.js = \"\"\"\n        (function(){\n            if (document.querySelector(\".calendar\")) {\n                document.querySelector(\".calendar\").onclick = () => {\n                    alert(\"Clicked calendar!\");\n                };\n            }\n        })()\n    \"\"\"\n

You can mix and match, so you can have a component with inlined HTML, while the JS and CSS are in separate files:

[project root]/components/calendar.py
from django_components import Component, register, types\n\n@register(\"calendar\")\nclass Calendar(Component):\n    js_file = \"calendar.js\"\n    css_file = \"calendar.css\"\n\n    template: types.django_html = \"\"\"\n        <div class=\"calendar\">\n            Today's date is <span>{{ date }}</span>\n        </div>\n    \"\"\"\n
"},{"location":"concepts/fundamentals/single_file_components/#syntax-highlighting","title":"Syntax highlighting","text":"

If you \"inline\" the HTML, JS and CSS code into the Python class, you should set up syntax highlighting to let your code editor know that the inlined code is HTML, JS and CSS.

In the examples above, we've annotated the template, js, and css attributes with the types.django_html, types.js and types.css types. These are used for syntax highlighting in VSCode.

Warning

Autocompletion / intellisense does not work in the inlined code.

Help us add support for intellisense in the inlined code! Start a conversation in the GitHub Discussions.

"},{"location":"concepts/fundamentals/single_file_components/#vscode","title":"VSCode","text":"
  1. First install Python Inline Source Syntax Highlighting extension, it will give you syntax highlighting for the template, CSS, and JS.

  2. Next, in your component, set typings of Component.template, Component.js, Component.css to types.django_html, types.css, and types.js respectively. The extension will recognize these and will activate syntax highlighting.

[project root]/components/calendar.py
from django_components import Component, register, types\n\n@register(\"calendar\")\nclass Calendar(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"date\"],\n        }\n\n    template: types.django_html = \"\"\"\n        <div class=\"calendar-component\">\n            Today's date is <span>{{ date }}</span>\n        </div>\n    \"\"\"\n\n    css: types.css = \"\"\"\n        .calendar-component {\n            width: 200px;\n            background: pink;\n        }\n        .calendar-component span {\n            font-weight: bold;\n        }\n    \"\"\"\n\n    js: types.js = \"\"\"\n        (function(){\n            if (document.querySelector(\".calendar-component\")) {\n                document.querySelector(\".calendar-component\").onclick = function(){ alert(\"Clicked calendar!\"); };\n            }\n        })()\n    \"\"\"\n
"},{"location":"concepts/fundamentals/single_file_components/#pycharm-or-other-jetbrains-ides","title":"Pycharm (or other Jetbrains IDEs)","text":"

With PyCharm (or any other editor from Jetbrains), you don't need to use types.django_html, types.css, types.js since Pycharm uses language injections.

You only need to write the comments # language=<lang> above the variables.

from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"date\"],\n        }\n\n    # language=HTML\n    template= \"\"\"\n        <div class=\"calendar-component\">\n            Today's date is <span>{{ date }}</span>\n        </div>\n    \"\"\"\n\n    # language=CSS\n    css = \"\"\"\n        .calendar-component {\n            width: 200px;\n            background: pink;\n        }\n        .calendar-component span {\n            font-weight: bold;\n        }\n    \"\"\"\n\n    # language=JS\n    js = \"\"\"\n        (function(){\n            if (document.querySelector(\".calendar-component\")) {\n                document.querySelector(\".calendar-component\").onclick = function(){ alert(\"Clicked calendar!\"); };\n            }\n        })()\n    \"\"\"\n
"},{"location":"concepts/fundamentals/single_file_components/#markdown-code-blocks-with-pygments","title":"Markdown code blocks with Pygments","text":"

Pygments is a syntax highlighting library written in Python. It's also what's used by this documentation site (mkdocs-material) to highlight code blocks.

To write code blocks with syntax highlighting, you need to install the pygments-djc package.

pip install pygments-djc\n

And then initialize it by importing pygments_djc somewhere in your project:

import pygments_djc\n

Now you can use the djc_py code block to write code blocks with syntax highlighting for components.

\\```djc_py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template = \"\"\"\n        <div class=\"calendar-component\">\n            Today's date is <span>{{ date }}</span>\n        </div>\n    \"\"\"\n\n    css = \"\"\"\n        .calendar-component {\n            width: 200px;\n            background: pink;\n        }\n        .calendar-component span {\n            font-weight: bold;\n        }\n    \"\"\"\n\\```\n

Will be rendered as below. Notice that the CSS and HTML are highlighted correctly:

from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template= \"\"\"\n        <div class=\"calendar-component\">\n            Today's date is <span>{{ date }}</span>\n        </div>\n    \"\"\"\n\n    css = \"\"\"\n        .calendar-component {\n            width: 200px;\n            background: pink;\n        }\n        .calendar-component span {\n            font-weight: bold;\n        }\n    \"\"\"\n
"},{"location":"concepts/fundamentals/slots/","title":"Slots","text":"

django-components has the most extensive slot system of all the popular Python templating engines.

The slot system is based on Vue, and works across both Django templates and Python code.

"},{"location":"concepts/fundamentals/slots/#what-are-slots","title":"What are slots?","text":"

Components support something called 'slots'.

When you write a component, you define its template. The template will always be the same each time you render the component.

However, sometimes you may want to customize the component slightly to change the content of the component. This is where slots come in.

Slots allow you to insert parts of HTML into the component. This makes components more reusable and composable.

<div class=\"calendar-component\">\n    <div class=\"header\">\n        {# This is where the component will insert the content #}\n        {% slot \"header\" / %}\n    </div>\n</div>\n
"},{"location":"concepts/fundamentals/slots/#slot-anatomy","title":"Slot anatomy","text":"

Slots consists of two parts:

  1. {% slot %} tag - Inside your component you decide where you want to insert the content.
  2. {% fill %} tag - In the parent template (outside the component) you decide what content to insert into the slot. It \"fills\" the slot with the specified content.

Let's look at an example:

First, we define the component template. This component contains two slots, header and body.

<!-- calendar.html -->\n<div class=\"calendar-component\">\n    <div class=\"header\">\n        {% slot \"header\" %}\n            Calendar header\n        {% endslot %}\n    </div>\n    <div class=\"body\">\n        {% slot \"body\" %}\n            Today's date is <span>{{ date }}</span>\n        {% endslot %}\n    </div>\n</div>\n

Next, when using the component, we can insert our own content into the slots. It looks like this:

{% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"body\" %}\n        Can you believe it's already\n        <span>{{ date }}</span>??\n    {% endfill %}\n{% endcomponent %}\n

Since the 'header' fill is unspecified, it's default value is used.

When rendered, notice that:

  • The body is filled with the content we specified,
  • The header is still the default value we defined in the component template.
<div class=\"calendar-component\">\n    <div class=\"header\">\n        Calendar header\n    </div>\n    <div class=\"body\">\n        Can you believe it's already <span>2020-06-06</span>??\n    </div>\n</div>\n
"},{"location":"concepts/fundamentals/slots/#slots-overview","title":"Slots overview","text":""},{"location":"concepts/fundamentals/slots/#slot-definition","title":"Slot definition","text":"

Slots are defined with the {% slot %} tag:

{% slot \"name\" %}\n    Default content\n{% endslot %}\n

Single component can have multiple slots:

{% slot \"name\" %}\n    Default content\n{% endslot %}\n\n{% slot \"other_name\" / %}\n

And you can even define the same slot in multiple places:

<div>\n    {% slot \"name\" %}\n        First content\n    {% endslot %}\n</div>\n<div>\n    {% slot \"name\" %}\n        Second content\n    {% endslot %}\n</div>\n

Info

If you define the same slot in multiple places, you must mark each slot individually when setting default or required flags, e.g.:

<div class=\"calendar-component\">\n    <div class=\"header\">\n        {% slot \"image\" default required %}Image here{% endslot %}\n    </div>\n    <div class=\"body\">\n        {% slot \"image\" default required %}Image here{% endslot %}\n    </div>\n</div>\n
"},{"location":"concepts/fundamentals/slots/#slot-filling","title":"Slot filling","text":"

Fill can be defined with the {% fill %} tag:

{% component \"calendar\" %}\n    {% fill \"name\" %}\n        Filled content\n    {% endfill %}\n    {% fill \"other_name\" %}\n        Filled content\n    {% endfill %}\n{% endcomponent %}\n

Or in Python with the slots argument:

Calendar.render(\n    slots={\n        \"name\": \"Filled content\",\n        \"other_name\": \"Filled content\",\n    },\n)\n
"},{"location":"concepts/fundamentals/slots/#default-slot","title":"Default slot","text":"

You can make the syntax shorter by marking the slot as default:

{% slot \"name\" default %}\n    Default content\n{% endslot %}\n

This allows you to fill the slot directly in the {% component %} tag, omitting the {% fill %} tag:

{% component \"calendar\" %}\n    Filled content\n{% endcomponent %}\n

To target the default slot in Python, you can use the \"default\" slot name:

Calendar.render(\n    slots={\"default\": \"Filled content\"},\n)\n

Accessing default slot in Python

Since the default slot is stored under the slot name default, you can access the default slot in Python under the \"default\" key:

class MyTable(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        default_slot = slots[\"default\"]\n        return {\n            \"default_slot\": default_slot,\n        }\n

Warning

Only one {% slot %} can be marked as default. But you can have multiple slots with the same name all marked as default.

If you define multiple different slots as default, this will raise an error.

\u274c Don't do this

{% slot \"name\" default %}\n    Default content\n{% endslot %}\n{% slot \"other_name\" default %}\n    Default content\n{% endslot %}\n

\u2705 Do this instead

{% slot \"name\" default %}\n    Default content\n{% endslot %}\n{% slot \"name\" default %}\n    Default content\n{% endslot %}\n

Warning

Do NOT combine default fills with explicit named {% fill %} tags.

The following component template will raise an error when rendered:

\u274c Don't do this

{% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"header\" %}Totally new header!{% endfill %}\n    Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n

\u2705 Do this instead

{% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"header\" %}Totally new header!{% endfill %}\n    {% fill \"default\" %}\n        Can you believe it's already <span>{{ date }}</span>??\n    {% endfill %}\n{% endcomponent %}\n

Warning

You cannot double-fill a slot.

That is, if both {% fill \"default\" %} and {% fill \"header\" %} point to the same slot, this will raise an error when rendered.

"},{"location":"concepts/fundamentals/slots/#required-slot","title":"Required slot","text":"

You can make the slot required by adding the required keyword:

{% slot \"name\" required %}\n    Default content\n{% endslot %}\n

This will raise an error if the slot is not filled.

"},{"location":"concepts/fundamentals/slots/#access-fills","title":"Access fills","text":"

You can access the fills with the {{ component_vars.slots.<name> }} template variable:

{% if component_vars.slots.my_slot %}\n    <div>\n        {% fill \"my_slot\" %}\n            Filled content\n        {% endfill %}\n    </div>\n{% endif %}\n

And in Python with the Component.slots property:

class Calendar(Component):\n    # `get_template_data` receives the `slots` argument directly\n    def get_template_data(self, args, kwargs, slots, context):\n        if \"my_slot\" in slots:\n            content = \"Filled content\"\n        else:\n            content = \"Default content\"\n\n        return {\n            \"my_slot\": content,\n        }\n\n    # In other methods you can still access the slots with `Component.slots`\n    def on_render_before(self, context, template):\n        if \"my_slot\" in self.slots:\n            # Do something\n
"},{"location":"concepts/fundamentals/slots/#dynamic-fills","title":"Dynamic fills","text":"

The slot and fill names can be set as variables. This way you can fill slots dynamically:

{% with \"body\" as slot_name %}\n    {% component \"calendar\" %}\n        {% fill slot_name %}\n            Filled content\n        {% endfill %}\n    {% endcomponent %}\n{% endwith %}\n

You can even use {% if %} and {% for %} tags inside the {% component %} tag to fill slots with more control:

{% component \"calendar\" %}\n    {% if condition %}\n        {% fill \"name\" %}\n            Filled content\n        {% endfill %}\n    {% endif %}\n\n    {% for item in items %}\n        {% fill item.name %}\n            Item: {{ item.value }}\n        {% endfill %}\n    {% endfor %}\n{% endcomponent %}\n

You can also use {% with %} or even custom tags to generate the fills dynamically:

{% component \"calendar\" %}\n    {% with item.name as name %}\n        {% fill name %}\n            Item: {{ item.value }}\n        {% endfill %}\n    {% endwith %}\n{% endcomponent %}\n

Warning

If you dynamically generate {% fill %} tags, be careful to render text only inside the {% fill %} tags.

Any text rendered outside {% fill %} tags will be considered a default fill and will raise an error if combined with explicit fills. (See Default slot)

"},{"location":"concepts/fundamentals/slots/#slot-data","title":"Slot data","text":"

Sometimes the slots need to access data from the component. Imagine an HTML table component which has a slot to configure how to render the rows. Each row has a different data, so you need to pass the data to the slot.

Similarly to Vue's scoped slots, you can pass data to the slot, and then access it in the fill.

This consists of two steps:

  1. Passing data to {% slot %} tag
  2. Accessing data in {% fill %} tag

The data is passed to the slot as extra keyword arguments. Below we set two extra arguments: first_name and job.

{# Pass data to the slot #}\n{% slot \"name\" first_name=\"John\" job=\"Developer\" %}\n    {# Fallback implementation #}\n    Name: {{ first_name }}\n    Job: {{ job }}\n{% endslot %}\n

Note

name kwarg is already used for slot name, so you cannot pass it as slot data.

To access the slot's data in the fill, use the data keyword. This sets the name of the variable that holds the data in the fill:

{# Access data in the fill #}\n{% component \"profile\" %}\n    {% fill \"name\" data=\"d\" %}\n        Hello, my name is <h1>{{ d.first_name }}</h1>\n        and I'm a <h2>{{ d.job }}</h2>\n    {% endfill %}\n{% endcomponent %}\n

To access the slot data in Python, use the data attribute in slot functions.

def my_slot(ctx):\n    return f\"\"\"\n        Hello, my name is <h1>{ctx.data[\"first_name\"]}</h1>\n        and I'm a <h2>{ctx.data[\"job\"]}</h2>\n    \"\"\"\n\nProfile.render(\n    slots={\n        \"name\": my_slot,\n    },\n)\n

Slot data can be set also when rendering a slot in Python:

slot = Slot(lambda ctx: f\"Hello, {ctx.data['name']}!\")\n\n# Render the slot\nhtml = slot({\"name\": \"John\"})\n

Info

To access slot data on a default slot, you have to explictly define the {% fill %} tags with name \"default\".

{% component \"my_comp\" %}\n    {% fill \"default\" data=\"slot_data\" %}\n        {{ slot_data.input }}\n    {% endfill %}\n{% endcomponent %}\n

Warning

You cannot set the data attribute and fallback attribute to the same name. This raises an error:

{% component \"my_comp\" %}\n    {% fill \"content\" data=\"slot_var\" fallback=\"slot_var\" %}\n        {{ slot_var.input }}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"concepts/fundamentals/slots/#slot-fallback","title":"Slot fallback","text":"

The content between the {% slot %}..{% endslot %} tags is the fallback content that will be rendered if no fill is given for the slot.

{% slot \"name\" %}\n    Hello, my name is {{ name }}  <!-- Fallback content -->\n{% endslot %}\n

Sometimes you may want to keep the fallback content, but only wrap it in some other content.

To do so, you can access the fallback content via the fallback kwarg. This sets the name of the variable that holds the fallback content in the fill:

{% component \"profile\" %}\n    {% fill \"name\" fallback=\"fb\" %}\n        Original content:\n        <div>\n            {{ fb }}  <!-- fb = 'Hello, my name...' -->\n        </div>\n    {% endfill %}\n{% endcomponent %}\n

To access the fallback content in Python, use the fallback attribute in slot functions.

The fallback value is rendered lazily. Coerce the fallback to a string to render it.

def my_slot(ctx):\n    # Coerce the fallback to a string\n    fallback = str(ctx.fallback)\n    return f\"Original content: \" + fallback\n\nProfile.render(\n    slots={\n        \"name\": my_slot,\n    },\n)\n

Fallback can be set also when rendering a slot in Python:

slot = Slot(lambda ctx: f\"Hello, {ctx.data['name']}!\")\n\n# Render the slot\nhtml = slot({\"name\": \"John\"}, fallback=\"Hello, world!\")\n

Info

To access slot fallback on a default slot, you have to explictly define the {% fill %} tags with name \"default\".

{% component \"my_comp\" %}\n    {% fill \"default\" fallback=\"fallback\" %}\n        {{ fallback }}\n    {% endfill %}\n{% endcomponent %}\n

Warning

You cannot set the data attribute and fallback attribute to the same name. This raises an error:

{% component \"my_comp\" %}\n    {% fill \"content\" data=\"slot_var\" fallback=\"slot_var\" %}\n        {{ slot_var.input }}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"concepts/fundamentals/slots/#slot-functions","title":"Slot functions","text":"

In Python code, slot fills can be defined as strings, functions, or Slot instances that wrap the two. Slot functions have access to slot data, fallback, and context.

def row_slot(ctx):\n    if ctx.data[\"disabled\"]:\n        return ctx.fallback\n\n    item = ctx.data[\"item\"]\n    if ctx.data[\"type\"] == \"table\":\n        return f\"<tr><td>{item}</td></tr>\"\n    else:\n        return f\"<li>{item}</li>\"\n\nTable.render(\n    slots={\n        \"prepend\": \"Ice cream selection:\",\n        \"append\": Slot(\"\u00a9 2025\"),\n        \"row\": row_slot,\n        \"column_title\": Slot(lambda ctx: f\"<th>{ctx.data['name']}</th>\"),\n    },\n)\n

Inside the component, these will all be normalized to Slot instances:

class Table(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        assert isinstance(slots[\"prepend\"], Slot)\n        assert isinstance(slots[\"row\"], Slot)\n        assert isinstance(slots[\"header\"], Slot)\n        assert isinstance(slots[\"footer\"], Slot)\n

You can render Slot instances by simply calling them with data:

class Table(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        prepend_slot = slots[\"prepend\"]\n        return {\n            \"prepend\": prepend_slot({\"item\": \"ice cream\"}),\n        }\n
"},{"location":"concepts/fundamentals/slots/#filling-slots-with-functions","title":"Filling slots with functions","text":"

You can \"fill\" slots by passing a string or Slot instance directly to the {% fill %} tag:

class Table(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        def my_fill(ctx):\n            return f\"Hello, {ctx.data['name']}!\"\n\n        return {\n            \"my_fill\": Slot(my_fill),\n        }\n
{% component \"table\" %}\n    {% fill \"name\" body=my_fill / %}\n{% endcomponent %}\n

Note

Django automatically executes functions when it comes across them in templates.

Because of this you MUST wrap the function in Slot instance to prevent it from being called.

Read more about Django's do_not_call_in_templates.

"},{"location":"concepts/fundamentals/slots/#slot-class","title":"Slot class","text":"

The Slot class is a wrapper around a function that can be used to fill a slot.

from django_components import Component, Slot\n\ndef footer(ctx):\n    return f\"Hello, {ctx.data['name']}!\"\n\nTable.render(\n    slots={\n        \"footer\": Slot(footer),\n    },\n)\n

Slot class can be instantiated with a function or a string:

slot1 = Slot(lambda ctx: f\"Hello, {ctx.data['name']}!\")\nslot2 = Slot(\"Hello, world!\")\n

Warning

Passing a Slot instance to the Slot constructor results in an error:

slot = Slot(\"Hello\")\n\n# Raises an error\nslot2 = Slot(slot)\n
"},{"location":"concepts/fundamentals/slots/#rendering-slots","title":"Rendering slots","text":"

Python

You can render a Slot instance by simply calling it with data:

slot = Slot(lambda ctx: f\"Hello, {ctx.data['name']}!\")\n\n# Render the slot with data\nhtml = slot({\"name\": \"John\"})\n

Optionally you can pass the fallback value to the slot. Fallback should be a string.

html = slot({\"name\": \"John\"}, fallback=\"Hello, world!\")\n

Template

Alternatively, you can pass the Slot instance to the {% fill %} tag:

{% fill \"name\" body=slot / %}\n
"},{"location":"concepts/fundamentals/slots/#slot-context","title":"Slot context","text":"

If a slot function is rendered by the {% slot %} tag, you can access the current Context using the context attribute.

class Table(Component):\n    template = \"\"\"\n        {% with \"abc\" as my_var %}\n            {% slot \"name\" %}\n                Hello!\n            {% endslot %}\n        {% endwith %}\n    \"\"\"\n\ndef slot_func(ctx):\n    return f\"Hello, {ctx.context['my_var']}!\"\n\nslot = Slot(slot_func)\nhtml = slot()\n

Warning

While available, try to avoid using the context attribute in slot functions.

Instead, prefer using the data and fallback attributes.

Access to context may be removed in future versions (v2, v3).

"},{"location":"concepts/fundamentals/slots/#slot-metadata","title":"Slot metadata","text":"

When accessing slots from within Component methods, the Slot instances are populated with extra metadata:

  • component_name
  • slot_name
  • nodelist
  • fill_node
  • extra

These are populated the first time a slot is passed to a component.

So if you pass the same slot through multiple nested components, the metadata will still point to the first component that received the slot.

You can use these for debugging, such as printing out the slot's component name and slot name.

Fill node

Components or extensions can use Slot.fill_node to handle slots differently based on whether the slot was defined in the template with {% fill %} and {% component %} tags, or in the component's Python code.

If the slot was created from a {% fill %} tag, this will be the FillNode instance.

If the slot was a default slot created from a {% component %} tag, this will be the ComponentNode instance.

You can use this to find the Component in whose template the {% fill %} tag was defined:

class MyTable(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        footer_slot = slots.get(\"footer\")\n        if footer_slot is not None and footer_slot.fill_node is not None:\n            owner_component = footer_slot.fill_node.template_component\n            # ...\n

Extra

You can also pass any additional data along with the slot by setting it in Slot.extra:

slot = Slot(\n    lambda ctx: f\"Hello, {ctx.data['name']}!\",\n    extra={\"foo\": \"bar\"},\n)\n

When you create a slot, you can set any of these fields too:

# Either at slot creation\nslot = Slot(\n    lambda ctx: f\"Hello, {ctx.data['name']}!\",\n    # Optional\n    component_name=\"table\",\n    slot_name=\"name\",\n    extra={},\n)\n\n# Or later\nslot.component_name = \"table\"\nslot.slot_name = \"name\"\nslot.extra[\"foo\"] = \"bar\"\n

Read more in Pass slot metadata.

"},{"location":"concepts/fundamentals/slots/#slot-contents","title":"Slot contents","text":"

Whether you create a slot from a function, a string, or from the {% fill %} tags, the Slot class normalizes its contents to a function.

Use Slot.contents to access the original value that was passed to the Slot constructor.

slot = Slot(\"Hello!\")\nprint(slot.contents)  # \"Hello!\"\n

If the slot was created from a string or from the {% fill %} tags, the contents will be accessible also as a Nodelist under Slot.nodelist.

slot = Slot(\"Hello!\")\nprint(slot.nodelist)  # <django.template.Nodelist: ['Hello!']>\n
"},{"location":"concepts/fundamentals/slots/#escaping-slots-content","title":"Escaping slots content","text":"

Slots content are automatically escaped by default to prevent XSS attacks.

In other words, it's as if you would be using Django's escape() on the slot contents / result:

from django.utils.html import escape\n\nclass Calendar(Component):\n    template = \"\"\"\n        <div>\n            {% slot \"date\" default date=date / %}\n        </div>\n    \"\"\"\n\nCalendar.render(\n    slots={\n        \"date\": escape(\"<b>Hello</b>\"),\n    }\n)\n

To disable escaping, you can wrap the slot string or slot result in Django's mark_safe():

Calendar.render(\n    slots={\n        # string\n        \"date\": mark_safe(\"<b>Hello</b>\"),\n\n        # function\n        \"date\": lambda ctx: mark_safe(\"<b>Hello</b>\"),\n    }\n)\n

Info

Read more about Django's format_html and mark_safe.

"},{"location":"concepts/fundamentals/slots/#examples","title":"Examples","text":""},{"location":"concepts/fundamentals/slots/#pass-through-all-the-slots","title":"Pass through all the slots","text":"

You can dynamically pass all slots to a child component. This is similar to passing all slots in Vue:

class MyTable(Component):\n    template = \"\"\"\n        <div>\n          {% component \"child\" %}\n            {% for slot_name, slot in component_vars.slots.items %}\n              {% fill name=slot_name body=slot / %}\n            {% endfor %}\n          {% endcomponent %}\n        </div>\n    \"\"\"\n
"},{"location":"concepts/fundamentals/slots/#required-and-default-slots","title":"Required and default slots","text":"

Since each {% slot %} is tagged with required and default individually, you can have multiple slots with the same name but different conditions.

In this example, we have a component that renders a user avatar - a small circular image with a profile picture or name initials.

If the component is given image_src or name_initials variables, the image slot is optional.

But if neither of those are provided, you MUST fill the image slot.

<div class=\"avatar\">\n    {# Image given, so slot is optional #}\n    {% if image_src %}\n        {% slot \"image\" default %}\n            <img src=\"{{ image_src }}\" />\n        {% endslot %}\n\n    {# Image not given, but we can make image from initials, so slot is optional #}    \n    {% elif name_initials %}\n        {% slot \"image\" default %}\n            <div style=\"\n                border-radius: 25px;\n                width: 50px;\n                height: 50px;\n                background: blue;\n            \">\n                {{ name_initials }}\n            </div>\n        {% endslot %}\n\n    {# Neither image nor initials given, so slot is required #}\n    {% else %}\n        {% slot \"image\" default required / %}\n    {% endif %}\n</div>\n
"},{"location":"concepts/fundamentals/slots/#dynamic-slots-in-table-component","title":"Dynamic slots in table component","text":"

Sometimes you may want to generate slots based on the given input. One example of this is Vuetify's table component, which creates a header and an item slots for each user-defined column.

So if you pass columns named name and age to the table component:

[\n    {\"key\": \"name\", \"title\": \"Name\"},\n    {\"key\": \"age\", \"title\": \"Age\"},\n]\n

Then the component will accept fills named header-name and header-age (among others):

{% fill \"header-name\" data=\"data\" %}\n    <b>{{ data.value }}</b>\n{% endfill %}\n\n{% fill \"header-age\" data=\"data\" %}\n    <b>{{ data.value }}</b>\n{% endfill %}\n

In django-components you can achieve the same, simply by using a variable or a template expression instead of a string literal:

<table>\n  <tr>\n    {% for header in headers %}\n      <th>\n        {% slot \"header-{{ header.key }}\" value=header.title %}\n          {{ header.title }}\n        {% endslot %}\n      </th>\n    {% endfor %}\n  </tr>\n</table>\n

When using the component, you can either set the fill explicitly:

{% component \"table\" headers=headers items=items %}\n    {% fill \"header-name\" data=\"data\" %}\n        <b>{{ data.value }}</b>\n    {% endfill %}\n{% endcomponent %}\n

Or also use a variable:

{% component \"table\" headers=headers items=items %}\n    {% fill \"header-{{ active_header_name }}\" data=\"data\" %}\n        <b>{{ data.value }}</b>\n    {% endfill %}\n{% endcomponent %}\n

Note

It's better to use literal slot names whenever possible for clarity. The dynamic slot names should be reserved for advanced use only.

"},{"location":"concepts/fundamentals/slots/#spread-operator","title":"Spread operator","text":"

Lastly, you can also pass the slot name through the spread operator.

When you define a slot name, it's actually a shortcut for a name keyword argument.

So this:

{% slot \"content\" / %}\n

is the same as:

{% slot name=\"content\" / %}\n

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

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

Full example:

class MyTable(Component):\n    template = \"\"\"\n        {% slot ...slot_props / %}\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"slot_props\": {\"name\": \"content\", \"extra_field\": 123},\n        }\n

Info

This applies for both {% slot %} and {% fill %} tags.

"},{"location":"concepts/fundamentals/slots/#legacy-conditional-slots","title":"Legacy conditional slots","text":"

Since version 0.70, you could check if a slot was filled with

{{ component_vars.is_filled.<name> }}

Since version 0.140, this has been deprecated and superseded with

{% component_vars.slots.<name> %}

The component_vars.is_filled variable is still available, but will be removed in v1.0.

NOTE: component_vars.slots no longer escapes special characters in slot names.

You can use {{ component_vars.is_filled.<name> }} 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\">\n    <div class=\"title\">\n        {% slot \"title\" %}\n            Title\n        {% endslot %}\n    </div>\n    {% if component_vars.is_filled.subtitle %}\n        <div class=\"subtitle\">\n            {% slot \"subtitle\" %}\n                {# Optional subtitle #}\n            {% endslot %}\n        </div>\n    {% elif component_vars.is_filled.title %}\n        ...\n    {% elif component_vars.is_filled.<name> %}\n        ...\n    {% endif %}\n</div>\n
"},{"location":"concepts/fundamentals/slots/#accessing-is_filled-of-slot-names-with-special-characters","title":"Accessing is_filled of slot names with special characters","text":"

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

Same applies when you are accessing is_filled from within the Python, e.g.:

class MyTable(Component):\n    def on_render_before(self, context, template) -> None:\n        # \u2705 Works\n        if self.is_filled[\"my_super_slot___\"]:\n            # Do something\n\n        # \u274c Does not work\n        if self.is_filled[\"my super-slot :)\"]:\n            # Do something\n
"},{"location":"concepts/fundamentals/subclassing_components/","title":"Subclassing components","text":"

In larger projects, you might need to write multiple components with similar behavior. In such cases, you can extract shared behavior into a standalone component class to keep things DRY.

When subclassing a component, there's a couple of things to keep in mind:

"},{"location":"concepts/fundamentals/subclassing_components/#template-js-and-css-inheritance","title":"Template, JS, and CSS inheritance","text":"

When it comes to the pairs:

  • Component.template/Component.template_file
  • Component.js/Component.js_file
  • Component.css/Component.css_file

inheritance follows these rules:

  • If a child component class defines either member of a pair (e.g., either template or template_file), it takes precedence and the parent's definition is ignored completely.
  • For example, if a child component defines template_file, the parent's template or template_file will be ignored.
  • This applies independently to each pair - you can inherit the JS while overriding the template, for instance.

For example:

class BaseCard(Component):\n    template = \"\"\"\n        <div class=\"card\">\n            <div class=\"card-content\">{{ content }}</div>\n        </div>\n    \"\"\"\n    css = \"\"\"\n        .card {\n            border: 1px solid gray;\n        }\n    \"\"\"\n    js = \"\"\"console.log('Base card loaded');\"\"\"\n\n# This class overrides parent's template, but inherits CSS and JS\nclass SpecialCard(BaseCard):\n    template = \"\"\"\n        <div class=\"card special\">\n            <div class=\"card-content\">\u2728 {{ content }} \u2728</div>\n        </div>\n    \"\"\"\n\n# This class overrides parent's template and CSS, but inherits JS\nclass CustomCard(BaseCard):\n    template_file = \"custom_card.html\"\n    css = \"\"\"\n        .card {\n            border: 2px solid gold;\n        }\n    \"\"\"\n
"},{"location":"concepts/fundamentals/subclassing_components/#media-inheritance","title":"Media inheritance","text":"

The Component.Media nested class follows Django's media inheritance rules:

  • If both parent and child define a Media class, the child's media will automatically include both its own and the parent's JS and CSS files.
  • This behavior can be configured using the extend attribute in the Media class, similar to Django's forms. Read more on this in Media inheritance.

For example:

class BaseModal(Component):\n    template = \"<div>Modal content</div>\"\n\n    class Media:\n        css = [\"base_modal.css\"]\n        js = [\"base_modal.js\"]  # Contains core modal functionality\n\nclass FancyModal(BaseModal):\n    class Media:\n        # Will include both base_modal.css/js AND fancy_modal.css/js\n        css = [\"fancy_modal.css\"]  # Additional styling\n        js = [\"fancy_modal.js\"]    # Additional animations\n\nclass SimpleModal(BaseModal):\n    class Media:\n        extend = False  # Don't inherit parent's media\n        css = [\"simple_modal.css\"]  # Only this CSS will be included\n        js = [\"simple_modal.js\"]    # Only this JS will be included\n
"},{"location":"concepts/fundamentals/subclassing_components/#opt-out-of-inheritance","title":"Opt out of inheritance","text":"

For the following media attributes, when you don't want to inherit from the parent, but you also don't need to set the template / JS / CSS to any specific value, you can set these attributes to None.

  • template / template_file
  • js / js_file
  • css / css_file
  • Media class

For example:

class BaseForm(Component):\n    template = \"...\"\n    css = \"...\"\n    js = \"...\"\n\n    class Media:\n        js = [\"form.js\"]\n\n# Use parent's template and CSS, but no JS\nclass ContactForm(BaseForm):\n    js = None\n    Media = None\n
"},{"location":"concepts/fundamentals/subclassing_components/#regular-python-inheritance","title":"Regular Python inheritance","text":"

All other attributes and methods (including the Component.View class and its methods) follow standard Python inheritance rules.

For example:

class BaseForm(Component):\n    template = \"\"\"\n        <form>\n            {{ form_content }}\n            <button type=\"submit\">\n                {{ submit_text }}\n            </button>\n        </form>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"form_content\": self.get_form_content(),\n            \"submit_text\": \"Submit\"\n        }\n\n    def get_form_content(self):\n        return \"<input type='text' name='data'>\"\n\nclass ContactForm(BaseForm):\n    # Extend parent's \"context\"\n    # but override \"submit_text\"\n    def get_template_data(self, args, kwargs, slots, context):\n        context = super().get_template_data(args, kwargs, slots, context)\n        context[\"submit_text\"] = \"Send Message\"  \n        return context\n\n    # Completely override parent's get_form_content\n    def get_form_content(self):\n        return \"\"\"\n            <input type='text' name='name' placeholder='Your Name'>\n            <input type='email' name='email' placeholder='Your Email'>\n            <textarea name='message' placeholder='Your Message'></textarea>\n        \"\"\"\n
"},{"location":"concepts/fundamentals/template_tag_syntax/","title":"Template tag syntax","text":"

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

"},{"location":"concepts/fundamentals/template_tag_syntax/#self-closing-tags","title":"Self-closing tags","text":"

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

becomes

{% component \"button\" / %}\n
"},{"location":"concepts/fundamentals/template_tag_syntax/#special-characters","title":"Special characters","text":"

New in version 0.71:

Keyword arguments can contain special characters # @ . - _, so keywords like so are still valid:

<body>\n    {% component \"calendar\" my-date=\"2015-06-19\" @click.native=do_something #some_id=True / %}\n</body>\n

These can then be accessed inside get_template_data so:

@register(\"calendar\")\nclass Calendar(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"my-date\"],\n            \"id\": kwargs[\"#some_id\"],\n            \"on_click\": kwargs[\"@click.native\"]\n        }\n
"},{"location":"concepts/fundamentals/template_tag_syntax/#spread-operator","title":"Spread operator","text":"

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\" / %}\n

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

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

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

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

"},{"location":"concepts/fundamentals/template_tag_syntax/#template-tags-inside-literal-strings","title":"Template tags inside literal strings","text":"

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_template_data(). But this can get messy if your components contain a lot of logic.

@register(\"calendar\")\nclass Calendar(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"editable\": kwargs[\"editable\"],\n            \"readonly\": not kwargs[\"editable\"],\n            \"input_id\": f\"input-{kwargs['id']}\",\n            \"icon_id\": f\"icon-{kwargs['id']}\",\n            ...\n        }\n

Instead, template tags in django_components ({% component %}, {% slot %}, {% provide %}, etc) allow you to treat literal string values as templates:

{% component 'blog_post'\n  \"As positional arg {# yay #}\"\n  title=\"{{ person.first_name }} {{ person.last_name }}\"\n  id=\"{% random_int 10 20 %}\"\n  readonly=\"{{ editable|not }}\"\n  author=\"John Wick {# TODO: parametrize #}\"\n/ %}\n

In the example above, the component receives:

  • Positional argument \"As positional arg \" (Comment omitted)
  • title - passed as str, e.g. John Doe
  • id - passed as int, e.g. 15
  • readonly - passed as bool, e.g. False
  • author - passed as str, e.g. John Wick (Comment omitted)

This is inspired by django-cotton.

"},{"location":"concepts/fundamentals/template_tag_syntax/#passing-data-as-string-vs-original-values","title":"Passing data as string vs original values","text":"

In the example above, the kwarg id was passed as an integer, NOT a string.

When the string literal contains only a single template tag, with no extra text (and no extra whitespace), 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 %}\" / %}\n

Here, page is a string:

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

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

Here, items is a list:

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

Here, items is a string:

{% component 'cat_list' items=\"{{ cats|slice:':2' }} See more\" / %}\n
"},{"location":"concepts/fundamentals/template_tag_syntax/#evaluating-python-expressions-in-template","title":"Evaluating Python expressions in template","text":"

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} />\n

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\"\n  value=\"{% expr 'input_value if is_enabled else None' %}\"\n/ %}\n

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

"},{"location":"concepts/fundamentals/template_tag_syntax/#pass-dictonary-by-its-key-value-pairs","title":"Pass dictonary by its key-value pairs","text":"

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\")\nclass MyComp(Component):\n    template = \"\"\"\n        {% component \"other\" attrs=attrs / %}\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        attrs = {\n            \"class\": \"pa-4 flex\",\n            \"data-some-id\": kwargs[\"some_id\"],\n            \"@click.stop\": \"onClickHandler\",\n        }\n        return {\"attrs\": attrs}\n

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\")\nclass MyComp(Component):\n    template = \"\"\"\n        {% component \"other\"\n            attrs:class=\"pa-4 flex\"\n            attrs:data-some-id=some_id\n            attrs:@click.stop=\"onClickHandler\"\n        / %}\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\"some_id\": kwargs[\"some_id\"]}\n

Sweet! Now all the relevant HTML is inside the template, and we can move it to a separate file with confidence:

{% component \"other\"\n    attrs:class=\"pa-4 flex\"\n    attrs:data-some-id=some_id\n    attrs:@click.stop=\"onClickHandler\"\n/ %}\n

Note: It is NOT possible to define nested dictionaries, so attrs:my_key:two=2 would be interpreted as:

{\"attrs\": {\"my_key:two\": 2}}\n
"},{"location":"concepts/fundamentals/template_tag_syntax/#multiline-tags","title":"Multiline tags","text":"

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

Instead, when you install django_components, it automatically configures Django to suport multi-line tags.

So we can rewrite the above as:

{% component \"card\"\n    title=\"Joanne Arc\"\n    subtitle=\"Head of Kitty Relations\"\n    date_last_active=\"2024-09-03\"\n    ...\n%}\n

Much better!

To disable this behavior, set COMPONENTS.multiline_tag to False

"},{"location":"concepts/fundamentals/typing_and_validation/","title":"Typing and validation","text":""},{"location":"concepts/fundamentals/typing_and_validation/#typing-overview","title":"Typing overview","text":"

Warning

In versions 0.92 to 0.139 (inclusive), the component typing was specified through generics.

Since v0.140, the types must be specified as class attributes of the Component class - Args, Kwargs, Slots, TemplateData, JsData, and CssData.

See Migrating from generics to class attributes for more info.

Warning

Input validation was NOT part of Django Components between versions 0.136 and 0.139 (inclusive).

The Component class optionally accepts class attributes that allow you to define the types of args, kwargs, slots, as well as the data returned from the data methods.

Use this to add type hints to your components, to validate the inputs at runtime, and to document them.

from typing import NamedTuple, Optional\nfrom django.template import Context\nfrom django_components import Component, SlotInput\n\nclass Button(Component):\n    class Args(NamedTuple):\n        size: int\n        text: str\n\n    class Kwargs(NamedTuple):\n        variable: str\n        maybe_var: Optional[int] = None  # May be omitted\n\n    class Slots(NamedTuple):\n        my_slot: Optional[SlotInput] = None\n\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        ...\n\n    template_file = \"button.html\"\n

The class attributes are:

  • Args - Type for positional arguments.
  • Kwargs - Type for keyword arguments.
  • Slots - Type for slots.
  • TemplateData - Type for data returned from get_template_data().
  • JsData - Type for data returned from get_js_data().
  • CssData - Type for data returned from get_css_data().

You can specify as many or as few of these as you want, the rest will default to None.

"},{"location":"concepts/fundamentals/typing_and_validation/#typing-inputs","title":"Typing inputs","text":"

You can use Component.Args, Component.Kwargs, and Component.Slots to type the component inputs.

When you set these classes, at render time the args, kwargs, and slots parameters of the data methods (get_template_data(), get_js_data(), get_css_data()) will be instances of these classes.

This way, each component can have runtime validation of the inputs:

  • When you use NamedTuple or @dataclass, instantiating these classes will check ONLY for the presence of the attributes.
  • When you use Pydantic models, instantiating these classes will check for the presence AND type of the attributes.

If you omit the Args, Kwargs, or Slots classes, or set them to None, the inputs will be passed as plain lists or dictionaries, and will not be validated.

from typing_extensions import NamedTuple, TypedDict\nfrom django.template import Context\nfrom django_components import Component, Slot, SlotInput\n\n# The data available to the `footer` scoped slot\nclass ButtonFooterSlotData(TypedDict):\n    value: int\n\n# Define the component with the types\nclass Button(Component):\n    class Args(NamedTuple):\n        name: str\n\n    class Kwargs(NamedTuple):\n        surname: str\n        age: int\n        maybe_var: Optional[int] = None  # May be omitted\n\n    class Slots(NamedTuple):\n        # Use `SlotInput` to allow slots to be given as `Slot` instance,\n        # plain string, or a function that returns a string.\n        my_slot: Optional[SlotInput] = None\n        # Use `Slot` to allow ONLY `Slot` instances.\n        # The generic is optional, and it specifies the data available\n        # to the slot function.\n        footer: Slot[ButtonFooterSlotData]\n\n    # Add type hints to the data method\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        # The parameters are instances of the classes we defined\n        assert isinstance(args, Button.Args)\n        assert isinstance(kwargs, Button.Kwargs)\n        assert isinstance(slots, Button.Slots)\n\n        args.name  # str\n        kwargs.age  # int\n        slots.footer  # Slot[ButtonFooterSlotData]\n\n# Add type hints to the render call\nButton.render(\n    args=Button.Args(\n        name=\"John\",\n    ),\n    kwargs=Button.Kwargs(\n        surname=\"Doe\",\n        age=30,\n    ),\n    slots=Button.Slots(\n        footer=Slot(lambda ctx: \"Click me!\"),\n    ),\n)\n

If you don't want to validate some parts, set them to None or omit them.

The following will validate only the keyword inputs:

class Button(Component):\n    # We could also omit these\n    Args = None\n    Slots = None\n\n    class Kwargs(NamedTuple):\n        name: str\n        age: int\n\n    # Only `kwargs` is instantiated. `args` and `slots` are not.\n    def get_template_data(self, args, kwargs: Kwargs, slots, context: Context):\n        assert isinstance(args, list)\n        assert isinstance(slots, dict)\n        assert isinstance(kwargs, Button.Kwargs)\n\n        args[0]  # str\n        slots[\"footer\"]  # Slot[ButtonFooterSlotData]\n        kwargs.age  # int\n

Info

Components can receive slots as strings, functions, or instances of Slot.

Internally these are all normalized to instances of Slot.

Therefore, the slots dictionary available in data methods (like get_template_data()) will always be a dictionary of Slot instances.

To correctly type this dictionary, you should set the fields of Slots to Slot or SlotInput:

SlotInput is a union of Slot, string, and function types.

"},{"location":"concepts/fundamentals/typing_and_validation/#typing-data","title":"Typing data","text":"

You can use Component.TemplateData, Component.JsData, and Component.CssData to type the data returned from get_template_data(), get_js_data(), and get_css_data().

When you set these classes, at render time they will be instantiated with the data returned from these methods.

This way, each component can have runtime validation of the returned data:

  • When you use NamedTuple or @dataclass, instantiating these classes will check ONLY for the presence of the attributes.
  • When you use Pydantic models, instantiating these classes will check for the presence AND type of the attributes.

If you omit the TemplateData, JsData, or CssData classes, or set them to None, the validation and instantiation will be skipped.

from typing import NamedTuple\nfrom django_components import Component\n\nclass Button(Component):\n    class TemplateData(NamedTuple):\n        data1: str\n        data2: int\n\n    class JsData(NamedTuple):\n        js_data1: str\n        js_data2: int\n\n    class CssData(NamedTuple):\n        css_data1: str\n        css_data2: int\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"data1\": \"...\",\n            \"data2\": 123,\n        }\n\n    def get_js_data(self, args, kwargs, slots, context):\n        return {\n            \"js_data1\": \"...\",\n            \"js_data2\": 123,\n        }\n\n    def get_css_data(self, args, kwargs, slots, context):\n        return {\n            \"css_data1\": \"...\",\n            \"css_data2\": 123,\n        }\n

For each data method, you can either return a plain dictionary with the data, or an instance of the respective data class directly.

from typing import NamedTuple\nfrom django_components import Component\n\nclass Button(Component):\n    class TemplateData(NamedTuple):\n        data1: str\n        data2: int\n\n    class JsData(NamedTuple):\n        js_data1: str\n        js_data2: int\n\n    class CssData(NamedTuple):\n        css_data1: str\n        css_data2: int\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return Button.TemplateData(\n            data1=\"...\",\n            data2=123,\n        )\n\n    def get_js_data(self, args, kwargs, slots, context):\n        return Button.JsData(\n            js_data1=\"...\",\n            js_data2=123,\n        )\n\n    def get_css_data(self, args, kwargs, slots, context):\n        return Button.CssData(\n            css_data1=\"...\",\n            css_data2=123,\n        )\n
"},{"location":"concepts/fundamentals/typing_and_validation/#custom-types","title":"Custom types","text":"

We recommend to use NamedTuple for the Args class, and NamedTuple, dataclasses, or Pydantic models for Kwargs, Slots, TemplateData, JsData, and CssData classes.

However, you can use any class, as long as they meet the conditions below.

For example, here is how you can use Pydantic models to validate the inputs at runtime.

from django_components import Component\nfrom pydantic import BaseModel\n\nclass Table(Component):\n    class Kwargs(BaseModel):\n        name: str\n        age: int\n\n    def get_template_data(self, args, kwargs, slots, context):\n        assert isinstance(kwargs, Table.Kwargs)\n\nTable.render(\n    kwargs=Table.Kwargs(name=\"John\", age=30),\n)\n
"},{"location":"concepts/fundamentals/typing_and_validation/#args-class","title":"Args class","text":"

The Args class represents a list of positional arguments. It must meet two conditions:

  1. The constructor for the Args class must accept positional arguments.

    Args(*args)\n
  2. The Args instance must be convertable to a list.

    list(Args(1, 2, 3))\n

To implement the conversion to a list, you can implement the __iter__() method:

class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def __iter__(self):\n        return iter([('x', self.x), ('y', self.y)])\n
"},{"location":"concepts/fundamentals/typing_and_validation/#dictionary-classes","title":"Dictionary classes","text":"

On the other hand, other types (Kwargs, Slots, TemplateData, JsData, and CssData) represent dictionaries. They must meet these two conditions:

  1. The constructor must accept keyword arguments.

    Kwargs(**kwargs)\nSlots(**slots)\n
  2. The instance must be convertable to a dictionary.

    dict(Kwargs(a=1, b=2))\ndict(Slots(a=1, b=2))\n

To implement the conversion to a dictionary, you can implement either:

  1. _asdict() method

    class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def _asdict(self):\n        return {'x': self.x, 'y': self.y}\n

  2. Or make the class dict-like with __iter__() and __getitem__()

    class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def __iter__(self):\n        return iter([('x', self.x), ('y', self.y)])\n\n    def __getitem__(self, key):\n        return getattr(self, key)\n

"},{"location":"concepts/fundamentals/typing_and_validation/#passing-variadic-args-and-kwargs","title":"Passing variadic args and kwargs","text":"

You may have a component that accepts any number of args or kwargs.

However, this cannot be described with the current Python's typing system (as of v0.140).

As a workaround:

  • For a variable number of positional arguments (*args), set a positional argument that accepts a list of values:

    class Table(Component):\n    class Args(NamedTuple):\n        args: List[str]\n\nTable.render(\n    args=Table.Args(args=[\"a\", \"b\", \"c\"]),\n)\n
  • For a variable number of keyword arguments (**kwargs), set a keyword argument that accepts a dictionary of values:

    class Table(Component):\n    class Kwargs(NamedTuple):\n        variable: str\n        another: int\n        # Pass any extra keys under `extra`\n        extra: Dict[str, any]\n\nTable.render(\n    kwargs=Table.Kwargs(\n        variable=\"a\",\n        another=1,\n        extra={\"foo\": \"bar\"},\n    ),\n)\n
"},{"location":"concepts/fundamentals/typing_and_validation/#handling-no-args-or-no-kwargs","title":"Handling no args or no kwargs","text":"

To declare that a component accepts no args, kwargs, etc, define the types with no attributes using the pass keyword:

from typing import NamedTuple\nfrom django_components import Component\n\nclass Button(Component):\n    class Args(NamedTuple):\n        pass\n\n    class Kwargs(NamedTuple):\n        pass\n\n    class Slots(NamedTuple):\n        pass\n

This can get repetitive, so we added a Empty type to make it easier:

from django_components import Component, Empty\n\nclass Button(Component):\n    Args = Empty\n    Kwargs = Empty\n    Slots = Empty\n
"},{"location":"concepts/fundamentals/typing_and_validation/#subclassing","title":"Subclassing","text":"

Subclassing components with types is simple.

Since each type class is a separate class attribute, you can just override them in the Component subclass.

In the example below, ButtonExtra inherits Kwargs from Button, but overrides the Args class.

from django_components import Component, Empty\n\nclass Button(Component):\n    class Args(NamedTuple):\n        size: int\n\n    class Kwargs(NamedTuple):\n        color: str\n\nclass ButtonExtra(Button):\n    class Args(NamedTuple):\n        name: str\n        size: int\n\n# Stil works the same way!\nButtonExtra.render(\n    args=ButtonExtra.Args(name=\"John\", size=30),\n    kwargs=ButtonExtra.Kwargs(color=\"red\"),\n)\n

The only difference is when it comes to type hints to the data methods like get_template_data().

When you define the nested classes like Args and Kwargs directly on the class, you can reference them just by their class name (Args and Kwargs).

But when you have a Component subclass, and it uses Args or Kwargs from the parent, you will have to reference the type as a forward reference, including the full name of the component (Button.Args and Button.Kwargs).

Compare the following:

class Button(Component):\n    class Args(NamedTuple):\n        size: int\n\n    class Kwargs(NamedTuple):\n        color: str\n\n    # Both `Args` and `Kwargs` are defined on the class\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots, context):\n        pass\n\nclass ButtonExtra(Button):\n    class Args(NamedTuple):\n        name: str\n        size: int\n\n    # `Args` is defined on the subclass, `Kwargs` is defined on the parent\n    def get_template_data(self, args: Args, kwargs: \"ButtonExtra.Kwargs\", slots, context):\n        pass\n\nclass ButtonSame(Button):\n    # Both `Args` and `Kwargs` are defined on the parent\n    def get_template_data(self, args: \"ButtonSame.Args\", kwargs: \"ButtonSame.Kwargs\", slots, context):\n        pass\n
"},{"location":"concepts/fundamentals/typing_and_validation/#runtime-type-validation","title":"Runtime type validation","text":"

When you add types to your component, and implement them as NamedTuple or dataclass, the validation will check only for the presence of the attributes.

So this will not catch if you pass a string to an int attribute.

To enable runtime type validation, you need to use Pydantic models, and install the djc-ext-pydantic extension.

The djc-ext-pydantic extension ensures compatibility between django-components' classes such as Component, or Slot and Pydantic models.

First install the extension:

pip install djc-ext-pydantic\n

And then add the extension to your project:

COMPONENTS = {\n    \"extensions\": [\n        \"djc_pydantic.PydanticExtension\",\n    ],\n}\n
"},{"location":"concepts/fundamentals/typing_and_validation/#migrating-from-generics-to-class-attributes","title":"Migrating from generics to class attributes","text":"

In versions 0.92 to 0.139 (inclusive), the component typing was specified through generics.

Since v0.140, the types must be specified as class attributes of the Component class - Args, Kwargs, Slots, TemplateData, JsData, and CssData.

This change was necessary to make it possible to subclass components. Subclassing with generics was otherwise too complicated. Read the discussion here.

Because of this change, the Component.render() method is no longer typed. To type-check the inputs, you should wrap the inputs in Component.Args, Component.Kwargs, Component.Slots, etc.

For example, if you had a component like this:

from typing import NotRequired, Tuple, TypedDict\nfrom django_components import Component, Slot, SlotInput\n\nButtonArgs = Tuple[int, str]\n\nclass ButtonKwargs(TypedDict):\n    variable: str\n    another: int\n    maybe_var: NotRequired[int] # May be omitted\n\nclass ButtonSlots(TypedDict):\n    # Use `SlotInput` to allow slots to be given as `Slot` instance,\n    # plain string, or a function that returns a string.\n    my_slot: NotRequired[SlotInput]\n    # Use `Slot` to allow ONLY `Slot` instances.\n    another_slot: Slot\n\nButtonType = Component[ButtonArgs, ButtonKwargs, ButtonSlots]\n\nclass Button(ButtonType):\n    def get_context_data(self, *args, **kwargs):\n        self.input.args[0]  # int\n        self.input.kwargs[\"variable\"]  # str\n        self.input.slots[\"my_slot\"]  # Slot[MySlotData]\n\nButton.render(\n    args=(1, \"hello\"),\n    kwargs={\n        \"variable\": \"world\",\n        \"another\": 123,\n    },\n    slots={\n        \"my_slot\": \"...\",\n        \"another_slot\": Slot(lambda ctx: ...),\n    },\n)\n

The steps to migrate are:

  1. Convert all the types (ButtonArgs, ButtonKwargs, ButtonSlots) to subclasses of NamedTuple.
  2. Move these types inside the Component class (Button), and rename them to Args, Kwargs, and Slots.
  3. If you defined typing for the data methods (like get_context_data()), move them inside the Component class, and rename them to TemplateData, JsData, and CssData.
  4. Remove the Component generic.
  5. If you accessed the args, kwargs, or slots attributes via self.input, you will need to add the type hints yourself, because self.input is no longer typed.

    Otherwise, you may use Component.get_template_data() instead of get_context_data(), as get_template_data() receives args, kwargs, slots and context as arguments. You will still need to add the type hints yourself.

  6. Lastly, you will need to update the Component.render() calls to wrap the inputs in Component.Args, Component.Kwargs, and Component.Slots, to manually add type hints.

Thus, the code above will become:

from typing import NamedTuple, Optional\nfrom django.template import Context\nfrom django_components import Component, Slot, SlotInput\n\n# The Component class does not take any generics\nclass Button(Component):\n    # Types are now defined inside the component class\n    class Args(NamedTuple):\n        size: int\n        text: str\n\n    class Kwargs(NamedTuple):\n        variable: str\n        another: int\n        maybe_var: Optional[int] = None  # May be omitted\n\n    class Slots(NamedTuple):\n        # Use `SlotInput` to allow slots to be given as `Slot` instance,\n        # plain string, or a function that returns a string.\n        my_slot: Optional[SlotInput] = None\n        # Use `Slot` to allow ONLY `Slot` instances.\n        another_slot: Slot\n\n    # The args, kwargs, slots are instances of the component's Args, Kwargs, and Slots classes\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        args.size  # int\n        kwargs.variable  # str\n        slots.my_slot  # Slot[MySlotData]\n\nButton.render(\n    # Wrap the inputs in the component's Args, Kwargs, and Slots classes\n    args=Button.Args(1, \"hello\"),\n    kwargs=Button.Kwargs(\n        variable=\"world\",\n        another=123,\n    ),\n    slots=Button.Slots(\n        my_slot=\"...\",\n        another_slot=Slot(lambda ctx: ...),\n    ),\n)\n
"},{"location":"getting_started/adding_js_and_css/","title":"Adding JS and CSS","text":"

Next we will add CSS and JavaScript to our template.

Info

In django-components, using JS and CSS is as simple as defining them on the Component class. You don't have to insert the <script> and <link> tags into the HTML manually.

Behind the scenes, django-components keeps track of which components use which JS and CSS files. Thus, when a component is rendered on the page, the page will contain only the JS and CSS used by the components, and nothing more!

"},{"location":"getting_started/adding_js_and_css/#1-update-project-structure","title":"1. Update project structure","text":"

Start by creating empty calendar.js and calendar.css files:

sampleproject/\n\u251c\u2500\u2500 calendarapp/\n\u251c\u2500\u2500 components/\n\u2502   \u2514\u2500\u2500 calendar/\n\u2502       \u251c\u2500\u2500 calendar.py\n\u2502       \u251c\u2500\u2500 calendar.js       \ud83c\udd95\n\u2502       \u251c\u2500\u2500 calendar.css      \ud83c\udd95\n\u2502       \u2514\u2500\u2500 calendar.html\n\u251c\u2500\u2500 sampleproject/\n\u251c\u2500\u2500 manage.py\n\u2514\u2500\u2500 requirements.txt\n
"},{"location":"getting_started/adding_js_and_css/#2-write-css","title":"2. Write CSS","text":"

Inside calendar.css, write:

[project root]/components/calendar/calendar.css
.calendar {\n  width: 200px;\n  background: pink;\n}\n.calendar span {\n  font-weight: bold;\n}\n

Be sure to prefix your rules with unique CSS class like calendar, so the CSS doesn't clash with other rules.

Note

Soon, django-components will automatically scope your CSS by default, so you won't have to worry about CSS class clashes.

This CSS will be inserted into the page as an inlined <style> tag, at the position defined by {% component_css_dependencies %}, or at the end of the inside the <head> tag (See Default JS / CSS locations).

So in your HTML, you may see something like this:

<html>\n  <head>\n    ...\n    <style>\n      .calendar {\n        width: 200px;\n        background: pink;\n      }\n      .calendar span {\n        font-weight: bold;\n      }\n    </style>\n  </head>\n  <body>\n    ...\n  </body>\n</html>\n
"},{"location":"getting_started/adding_js_and_css/#3-write-js","title":"3. Write JS","text":"

Next we write a JavaScript file that specifies how to interact with this component.

You are free to use any javascript framework you want.

[project root]/components/calendar/calendar.js
(function () {\n  document.querySelector(\".calendar\").onclick = () => {\n    alert(\"Clicked calendar!\");\n  };\n})();\n

A good way to make sure the JS of this component doesn't clash with other components is to define all JS code inside an anonymous self-invoking function ((() => { ... })()). This makes all variables defined only be defined inside this component and not affect other components.

Note

Soon, django-components will automatically wrap your JS in a self-invoking function by default (except for JS defined with <script type=\"module\">).

Similarly to CSS, JS will be inserted into the page as an inlined <script> tag, at the position defined by {% component_js_dependencies %}, or at the end of the inside the <body> tag (See Default JS / CSS locations).

So in your HTML, you may see something like this:

<html>\n  <head>\n    ...\n  </head>\n  <body>\n    ...\n    <script>\n      (function () {\n        document.querySelector(\".calendar\").onclick = () => {\n          alert(\"Clicked calendar!\");\n        };\n      })();\n    </script>\n  </body>\n</html>\n
"},{"location":"getting_started/adding_js_and_css/#rules-of-js-execution","title":"Rules of JS execution","text":"
  1. JS is executed in the order in which the components are found in the HTML

    By default, the JS is inserted as a synchronous script (<script> ... </script>)

    So if you define multiple components on the same page, their JS will be executed in the order in which the components are found in the HTML.

    So if we have a template like so:

    <html>\n  <head>\n    ...\n  </head>\n  <body>\n    {% component \"calendar\" / %}\n    {% component \"table\" / %}\n  </body>\n</html>\n

    Then the JS file of the component calendar will be executed first, and the JS file of component table will be executed second.

  2. JS will be executed only once, even if there is multiple instances of the same component

    In this case, the JS of calendar will STILL execute first (because it was found first), and will STILL execute only once, even though it's present twice:

    <html>\n  <head>\n    ...\n  </head>\n  <body>\n    {% component \"calendar\" / %}\n    {% component \"table\" / %}\n    {% component \"calendar\" / %}\n  </body>\n</html>\n
"},{"location":"getting_started/adding_js_and_css/#4-link-js-and-css-to-a-component","title":"4. Link JS and CSS to a component","text":"

Finally, we return to our Python component in calendar.py to tie this together.

To link JS and CSS defined in other files, use js_file and css_file attributes:

[project root]/components/calendar/calendar.py
from django_components import Component\n\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    js_file = \"calendar.js\"   # <--- new\n    css_file = \"calendar.css\"   # <--- new\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": \"1970-01-01\",\n        }\n

And that's it! If you were to embed this component in an HTML, django-components will automatically embed the associated JS and CSS.

Note

Similarly to the template file, the JS and CSS file paths can be either:

  1. Relative to the Python component file (as seen above),
  2. Relative to any of the component directories as defined by COMPONENTS.dirs and/or COMPONENTS.app_dirs (e.g. [your apps]/components dir and [project root]/components)
  3. Relative to any of the directories defined by STATICFILES_DIRS.
"},{"location":"getting_started/adding_js_and_css/#5-link-additional-js-and-css-to-a-component","title":"5. Link additional JS and CSS to a component","text":"

Your components may depend on third-party packages or styling, or other shared logic. To load these additional dependencies, you can use a nested Media class.

This Media class behaves similarly to Django's Media class, with a few differences:

  1. Our Media class accepts various formats for the JS and CSS files: either a single file, a list, or (CSS-only) a dictonary (see below).
  2. Individual JS / CSS files can be any of str, bytes, Path, SafeString, or a function.
  3. Individual JS / CSS files can be glob patterns, e.g. *.js or styles/**/*.css.
  4. If you set Media.extend to a list, it should be a list of Component classes.

Learn more about using Media.

[project root]/components/calendar/calendar.py
from django_components import Component\n\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    js_file = \"calendar.js\"\n    css_file = \"calendar.css\"\n\n    class Media:   # <--- new\n        js = [\n            \"path/to/shared.js\",\n            \"path/to/*.js\",  # Or as a glob\n            \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\",  # AlpineJS\n        ]\n        css = [\n            \"path/to/shared.css\",\n            \"path/to/*.css\",  # Or as a glob\n            \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\",  # Tailwind\n        ]\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": \"1970-01-01\",\n        }\n

Note

Same as with the \"primary\" JS and CSS, the file paths files can be either:

  1. Relative to the Python component file (as seen above),
  2. Relative to any of the component directories as defined by COMPONENTS.dirs and/or COMPONENTS.app_dirs (e.g. [your apps]/components dir and [project root]/components)

Info

The Media nested class is shaped based on Django's Media class.

As such, django-components allows multiple formats to define the nested Media class:

# Single files\nclass Media:\n    js = \"calendar.js\"\n    css = \"calendar.css\"\n\n# Lists of files\nclass Media:\n    js = [\"calendar.js\", \"calendar2.js\"]\n    css = [\"calendar.css\", \"calendar2.css\"]\n\n# Dictionary of media types for CSS\nclass Media:\n    js = [\"calendar.js\", \"calendar2.js\"]\n    css = {\n      \"all\": [\"calendar.css\", \"calendar2.css\"],\n    }\n

If you define a list of JS files, they will be executed one-by-one, left-to-right.

"},{"location":"getting_started/adding_js_and_css/#rules-of-execution-of-scripts-in-mediajs","title":"Rules of execution of scripts in Media.js","text":"

The scripts defined in Media.js still follow the rules outlined above:

  1. JS is executed in the order in which the components are found in the HTML.
  2. JS will be executed only once, even if there is multiple instances of the same component.

Additionally to Media.js applies that:

  1. JS in Media.js is executed before the component's primary JS.
  2. JS in Media.js is executed in the same order as it was defined.
  3. If there is multiple components that specify the same JS path or URL in Media.js, this JS will be still loaded and executed only once.

Putting all of this together, our Calendar component above would render HTML like so:

<html>\n  <head>\n    ...\n    <!-- CSS from Media.css -->\n    <link href=\"/static/path/to/shared.css\" media=\"all\" rel=\"stylesheet\" />\n    <link\n      href=\"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\"\n      media=\"all\"\n      rel=\"stylesheet\"\n    />\n    <!-- CSS from Component.css_file -->\n    <style>\n      .calendar {\n        width: 200px;\n        background: pink;\n      }\n      .calendar span {\n        font-weight: bold;\n      }\n    </style>\n  </head>\n  <body>\n    ...\n    <!-- JS from Media.js -->\n    <script src=\"/static/path/to/shared.js\"></script>\n    <script src=\"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\"></script>\n    <!-- JS from Component.js_file -->\n    <script>\n      (function () {\n        document.querySelector(\".calendar\").onclick = () => {\n          alert(\"Clicked calendar!\");\n        };\n      })();\n    </script>\n  </body>\n</html>\n

Now that we have a fully-defined component, next let's use it in a Django template \u27a1\ufe0f.

"},{"location":"getting_started/adding_slots/","title":"Adding slots","text":"

Our calendar component's looking great! But we just got a new assignment from our colleague - The calendar date needs to be shown on 3 different pages:

  1. On one page, it needs to be shown as is
  2. On the second, the date needs to be bold
  3. On the third, the date needs to be in italics

As a reminder, this is what the component's template looks like:

<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n

There's many ways we could approach this:

  • Expose the date in a slot
  • Style .calendar > span differently on different pages
  • Pass a variable to the component that decides how the date is rendered
  • Create a new component

First two options are more flexible, because the custom styling is not baked into a component's implementation. And for the sake of demonstration, we'll solve this challenge with slots.

"},{"location":"getting_started/adding_slots/#1-what-are-slots","title":"1. What are slots","text":"

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 tags that work hand in hand to make this work. These are...

  • {% slot <name> %}/{% endslot %}: Declares a new slot in the component template.
  • {% fill <name> %}/{% endfill %}: (Used inside a {% component %} tag pair.) Fills a declared slot with the specified content.
"},{"location":"getting_started/adding_slots/#2-add-a-slot-tag","title":"2. Add a slot tag","text":"

Let's update our calendar component to support more customization. We'll add {% slot %} tag to the template:

<div class=\"calendar\">\n  Today's date is\n  {% slot \"date\" default %}  {# <--- new #}\n    <span>{{ date }}</span>\n  {% endslot %}\n</div>\n

Notice that:

  1. We named the slot date - so we can fill this slot by using {% fill \"date\" %}

  2. We also made it the default slot.

  3. We placed our original implementation inside the {% slot %} tag - this is what will be rendered when the slot is NOT overriden.

"},{"location":"getting_started/adding_slots/#3-add-fill-tag","title":"3. Add fill tag","text":"

Now we can use {% fill %} tags inside the {% component %} tags to override the date slot to generate the bold and italics variants:

{# Default #}\n{% component \"calendar\" date=\"2024-12-13\" / %}\n\n{# Bold #}\n{% component \"calendar\" date=\"2024-12-13\" %}\n  <b> 2024-12-13 </b>\n{% endcomponent %}\n\n{# Italics #}\n{% component \"calendar\" date=\"2024-12-13\" %}\n  <i> 2024-12-13 </i>\n{% endcomponent %}\n

Which will render as:

<!-- Default -->\n<div class=\"calendar\">\n  Today's date is <span>2024-12-13</span>\n</div>\n\n<!-- Bold -->\n<div class=\"calendar\">\n  Today's date is <b>2024-12-13</b>\n</div>\n\n<!-- Italics -->\n<div class=\"calendar\">\n  Today's date is <i>2024-12-13</i>\n</div>\n

Info

Since we used the default flag on {% slot \"date\" %} inside our calendar component, we can target the date component in multiple ways:

  1. Explicitly by it's name

    {% component \"calendar\" date=\"2024-12-13\" %}\n  {% fill \"date\" %}\n    <i> 2024-12-13 </i>\n  {% endfill %}\n{% endcomponent %}\n

  2. Implicitly as the default slot (Omitting the {% fill %} tag)

    {% component \"calendar\" date=\"2024-12-13\" %}\n  <i> 2024-12-13 </i>\n{% endcomponent %}\n

  3. Explicitly as the default slot (Setting fill name to default)

    {% component \"calendar\" date=\"2024-12-13\" %}\n  {% fill \"default\" %}\n    <i> 2024-12-13 </i>\n  {% endfill %}\n{% endcomponent %}\n

"},{"location":"getting_started/adding_slots/#4-wait-theres-a-bug","title":"4. Wait, there's a bug","text":"

There is a mistake in our code! 2024-12-13 is Friday, so that's fine. But if we updated the to 2024-12-14, which is Saturday, our template from previous step would render this:

<!-- Default -->\n<div class=\"calendar\">\n  Today's date is <span>2024-12-16</span>\n</div>\n\n<!-- Bold -->\n<div class=\"calendar\">\n  Today's date is <b>2024-12-14</b>\n</div>\n\n<!-- Italics -->\n<div class=\"calendar\">\n  Today's date is <i>2024-12-14</i>\n</div>\n

The first instance rendered 2024-12-16, while the rest rendered 2024-12-14!

Why? Remember that in the get_template_data() method of our Calendar component, we pre-process the date. If the date falls on Saturday or Sunday, we shift it to next Monday:

[project root]/components/calendar/calendar.py
from datetime import date\n\nfrom django_components import Component, register\n\n# If date is Sat or Sun, shift it to next Mon, so the date is always workweek.\ndef to_workweek_date(d: date):\n    ...\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    ...\n    def get_template_data(self, args, kwargs, slots, context):\n        workweek_date = to_workweek_date(kwargs[\"date\"])\n        return {\n            \"date\": workweek_date,\n            \"extra_class\": kwargs.get(\"extra_class\", \"text-blue\"),\n        }\n

And the issue is that in our template, we used the date value that we used as input, which is NOT the same as the date variable used inside Calendar's template.

"},{"location":"getting_started/adding_slots/#5-adding-data-to-slots","title":"5. Adding data to slots","text":"

We want to use the same date variable that's used inside Calendar's template.

Luckily, django-components allows passing data to slots, also known as Scoped slots.

This consists of two steps:

  1. Pass the date variable to the {% slot %} tag
  2. Access the date variable in the {% fill %} tag by using the special data kwarg

Let's update the Calendar's template:

<div class=\"calendar\">\n  Today's date is\n  {% slot \"date\" default date=date %}  {# <--- changed #}\n    <span>{{ date }}</span>\n  {% endslot %}\n</div>\n

Info

The {% slot %} tag has one special kwarg, name. When you write

{% slot \"date\" / %}\n

It's the same as:

{% slot name=\"date\" / %}\n

Other than the name kwarg, you can pass any extra kwargs to the {% slot %} tag, and these will be exposed as the slot's data.

{% slot name=\"date\" kwarg1=123 kwarg2=\"text\" kwarg3=my_var / %}\n
"},{"location":"getting_started/adding_slots/#6-accessing-slot-data-in-fills","title":"6. Accessing slot data in fills","text":"

Now, on the {% fill %} tags, we can use the data kwarg to specify the variable under which the slot data will be available.

The variable from the data kwarg contains all the extra kwargs passed to the {% slot %} tag.

So if we set data=\"slot_data\", then we can access the date variable under slot_data.date:

{# Default #}\n{% component \"calendar\" date=\"2024-12-13\" / %}\n\n{# Bold #}\n{% component \"calendar\" date=\"2024-12-13\" %}\n  {% fill \"date\" data=\"slot_data\" %}\n    <b> {{ slot_data.date }} </b>\n  {% endfill %}\n{% endcomponent %}\n\n{# Italics #}\n{% component \"calendar\" date=\"2024-12-13\" %}\n  {% fill \"date\" data=\"slot_data\" %}\n    <i> {{ slot_data.date }} </i>\n  {% endfill %}\n{% endcomponent %}\n

By using the date variable from the slot, we'll render the correct date each time:

<!-- Default -->\n<div class=\"calendar\">\n  Today's date is <span>2024-12-16</span>\n</div>\n\n<!-- Bold -->\n<div class=\"calendar\">\n  Today's date is <b>2024-12-16</b>\n</div>\n\n<!-- Italics -->\n<div class=\"calendar\">\n  Today's date is <i>2024-12-16</i>\n</div>\n

Info

When to use slots vs variables?

Generally, slots are more flexible - you can access the slot data, even the original slot content. Thus, slots behave more like functions that render content based on their context.

On the other hand, variables are simpler - the variable you pass to a component is what will be used.

Moreover, slots are treated as part of the template - for example the CSS scoping (work in progress) is applied to the slot content too.

So far we've rendered components using template tag. [Next, let\u2019s explore other ways to render components \u27a1\ufe0f] (./rendering_components.md)

"},{"location":"getting_started/components_in_templates/","title":"Components in templates","text":"

By the end of this section, we want to be able to use our components in Django templates like so:

{% load component_tags %}\n<!DOCTYPE html>\n<html>\n  <head>\n    <title>My example calendar</title>\n  </head>\n  <body>\n    {% component \"calendar\" / %}\n  </body>\n<html>\n
"},{"location":"getting_started/components_in_templates/#1-register-component","title":"1. Register component","text":"

First, however, we need to register our component class with ComponentRegistry.

To register a component with a ComponentRegistry, we will use the @register decorator, and give it a name under which the component will be accessible from within the template:

[project root]/components/calendar/calendar.py
from django_components import Component, register  # <--- new\n\n@register(\"calendar\")  # <--- new\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    js_file = \"calendar.js\"\n    css_file = \"calendar.css\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": \"1970-01-01\",\n        }\n

This will register the component to the default registry. Default registry is loaded into the template by calling {% load component_tags %} inside the template.

Info

Why do we have to register components?

We want to use our component as a template tag ({% ... %}) in Django template.

In Django, template tags are managed by the Library instances. Whenever you include {% load xxx %} in your template, you are loading a Library instance into your template.

ComponentRegistry acts like a router and connects the registered components with the associated Library.

That way, when you include {% load component_tags %} in your template, you are able to \"call\" components like {% component \"calendar\" / %}.

ComponentRegistries also make it possible to group and share components as standalone packages. Learn more here.

Note

You can create custom ComponentRegistry instances, which will use different Library instances. In that case you will have to load different libraries depending on which components you want to use:

Example 1 - Using component defined in the default registry

{% load component_tags %}\n<div>\n  {% component \"calendar\" / %}\n</div>\n

Example 2 - Using component defined in a custom registry

{% load my_custom_tags %}\n<div>\n  {% my_component \"table\" / %}\n</div>\n

Note that, because the tag name component is use by the default ComponentRegistry, the custom registry was configured to use the tag my_component instead. Read more here

"},{"location":"getting_started/components_in_templates/#2-load-and-use-the-component-in-template","title":"2. Load and use the component in template","text":"

The component is now registered under the name calendar. All that remains to do is to load and render the component inside a template:

{% load component_tags %}  {# Load the default registry #}\n<!DOCTYPE html>\n<html>\n  <head>\n    <title>My example calendar</title>\n  </head>\n  <body>\n    {% component \"calendar\" / %}  {# Render the component #}\n  </body>\n<html>\n

Info

Component tags should end with / if they do not contain any Slot fills. But you can also use {% endcomponent %} instead:

{% component \"calendar\" %}{% endcomponent %}\n

We defined the Calendar's template as

<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n

and the variable date as \"1970-01-01\".

Thus, the final output will look something like this:

<!DOCTYPE html>\n<html>\n  <head>\n    <title>My example calendar</title>\n    <style>\n      .calendar {\n        width: 200px;\n        background: pink;\n      }\n      .calendar span {\n        font-weight: bold;\n      }\n    </style>\n  </head>\n  <body>\n    <div class=\"calendar\">\n      Today's date is <span>1970-01-01</span>\n    </div>\n    <script>\n      (function () {\n        document.querySelector(\".calendar\").onclick = () => {\n          alert(\"Clicked calendar!\");\n        };\n      })();\n    </script>\n  </body>\n<html>\n

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.

Info

Remember that you can use {% component_js_dependencies %} and {% component_css_dependencies %} to change where the <script> and <style> tags will be rendered (See Default JS / CSS locations).

Info

How does django-components pick up registered components?

Notice that it was enough to add @register to the component. We didn't need to import the component file anywhere to execute it.

This is because django-components automatically imports all Python files found in the component directories during an event called Autodiscovery.

So with Autodiscovery, it's the same as if you manually imported the component files on the ready() hook:

class MyApp(AppConfig):\n    default_auto_field = \"django.db.models.BigAutoField\"\n    name = \"myapp\"\n\n    def ready(self):\n        import myapp.components.calendar\n        import myapp.components.table\n        ...\n

You can now render the components in templates!

Currently our component always renders the same content. Let's parametrise it, so that our Calendar component is configurable from within the template \u27a1\ufe0f

"},{"location":"getting_started/parametrising_components/","title":"Parametrising components","text":"

So far, our Calendar component will always render the date 1970-01-01. Let's make it more useful and flexible by being able to pass in custom date.

What we want is to be able to use the Calendar component within the template like so:

{% component \"calendar\" date=\"2024-12-13\" extra_class=\"text-red\" / %}\n
"},{"location":"getting_started/parametrising_components/#1-understading-component-inputs","title":"1. Understading component inputs","text":"

In section Create your first component, we defined the get_template_data() method that defines what variables will be available within the template:

[project root]/components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    ...\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": \"1970-01-01\",\n        }\n

What we didn't say is that get_template_data() actually receives the args and kwargs that were passed to a component.

So if we call a component with a date and extra_class keywords:

{% component \"calendar\" date=\"2024-12-13\" extra_class=\"text-red\" / %}\n

This is the same as calling:

Calendar.get_template_data(\n    args=[],\n    kwargs={\"date\": \"2024-12-13\", \"extra_class\": \"text-red\"},\n)\n

And same applies to positional arguments, or mixing args and kwargs, where:

{% component \"calendar\" \"2024-12-13\" extra_class=\"text-red\" / %}\n

is same as

Calendar.get_template_data(\n    args=[\"2024-12-13\"],\n    kwargs={\"extra_class\": \"text-red\"},\n)\n
"},{"location":"getting_started/parametrising_components/#2-define-inputs","title":"2. Define inputs","text":"

Let's put this to test. We want to pass date and extra_class kwargs to the component. And so, we can write the get_template_data() method such that it expects those parameters:

[project root]/components/calendar/calendar.py
from datetime import date\n\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    ...\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"date\"],\n            \"extra_class\": kwargs.get(\"extra_class\", \"text-blue\"),\n        }\n

Since extra_class is optional in the function signature, it's optional also in the template. So both following calls are valid:

{% component \"calendar\" date=\"2024-12-13\" / %}\n{% component \"calendar\" date=\"2024-12-13\" extra_class=\"text-red\" / %}\n

Warning

get_template_data() differentiates between positional and keyword arguments, so you have to make sure to pass the arguments correctly.

Since date is expected to be a keyword argument, it MUST be provided as such:

\u2705 `date` is kwarg\n{% component \"calendar\" date=\"2024-12-13\" / %}\n\n\u274c `date` is arg\n{% component \"calendar\" \"2024-12-13\" / %}\n
"},{"location":"getting_started/parametrising_components/#3-process-inputs","title":"3. Process inputs","text":"

The get_template_data() method is powerful, because it allows us to decouple component inputs from the template variables. In other words, we can pre-process the component inputs, and massage them into a shape that's most appropriate for what the template needs. And it also allows us to pass in static data into the template.

Imagine our component receives data from the database that looks like below (taken from Django).

cities = [\n    {\"name\": \"Mumbai\", \"population\": \"19,000,000\", \"country\": \"India\"},\n    {\"name\": \"Calcutta\", \"population\": \"15,000,000\", \"country\": \"India\"},\n    {\"name\": \"New York\", \"population\": \"20,000,000\", \"country\": \"USA\"},\n    {\"name\": \"Chicago\", \"population\": \"7,000,000\", \"country\": \"USA\"},\n    {\"name\": \"Tokyo\", \"population\": \"33,000,000\", \"country\": \"Japan\"},\n]\n

We need to group the list items by size into following buckets by population:

  • 0-10,000,000
  • 10,000,001-20,000,000
  • 20,000,001-30,000,000
  • +30,000,001

So we want to end up with following data:

cities_by_pop = [\n    {\n      \"name\": \"0-10,000,000\",\n      \"items\": [\n          {\"name\": \"Chicago\", \"population\": \"7,000,000\", \"country\": \"USA\"},\n      ]\n    },\n    {\n      \"name\": \"10,000,001-20,000,000\",\n      \"items\": [\n          {\"name\": \"Calcutta\", \"population\": \"15,000,000\", \"country\": \"India\"},\n          {\"name\": \"Mumbai\", \"population\": \"19,000,000\", \"country\": \"India\"},\n          {\"name\": \"New York\", \"population\": \"20,000,000\", \"country\": \"USA\"},\n      ]\n    },\n    {\n      \"name\": \"30,000,001-40,000,000\",\n      \"items\": [\n          {\"name\": \"Tokyo\", \"population\": \"33,000,000\", \"country\": \"Japan\"},\n      ]\n    },\n]\n

Without the get_template_data() method, we'd have to either:

  1. Pre-process the data in Python before passing it to the components.
  2. Define a Django filter or template tag to take the data and process it on the spot.

Instead, with get_template_data(), we can keep this transformation private to this component, and keep the rest of the codebase clean.

def group_by_pop(data):\n    ...\n\n@register(\"population_table\")\nclass PopulationTable(Component):\n    template_file = \"population_table.html\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"data\": group_by_pop(kwargs[\"data\"]),\n        }\n

Similarly we can make use of get_template_data() to pre-process the date that was given to the component:

[project root]/components/calendar/calendar.py
from datetime import date\n\nfrom django_components import Component, register\n\n# If date is Sat or Sun, shift it to next Mon, so the date is always workweek.\ndef to_workweek_date(d: date):\n    ...\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    ...\n    def get_template_data(self, args, kwargs, slots, context):\n        workweek_date = to_workweek_date(kwargs[\"date\"])  # <--- new\n        return {\n            \"date\": workweek_date,  # <--- changed\n            \"extra_class\": kwargs.get(\"extra_class\", \"text-blue\"),\n        }\n
"},{"location":"getting_started/parametrising_components/#4-pass-inputs-to-components","title":"4. Pass inputs to components","text":"

Once we're happy with Calendar.get_template_data(), we can update our templates to use the parametrized version of the component:

<div>\n  {% component \"calendar\" date=\"2024-12-13\" / %}\n  {% component \"calendar\" date=\"1970-01-01\" / %}\n</div>\n
"},{"location":"getting_started/parametrising_components/#5-add-defaults","title":"5. Add defaults","text":"

In our example, we've set the extra_class to default to \"text-blue\" by setting it in the get_template_data() method.

However, you may want to use the same default value in multiple methods, like get_js_data() or get_css_data().

To make things easier, Components can specify their defaults. Defaults are used when no value is provided, or when the value is set to None for a particular input.

To define defaults for a component, you create a nested Defaults class within your Component class. Each attribute in the Defaults class represents a default value for a corresponding input.

from django_components import Component, Default, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n\n    class Defaults:  # <--- new\n        extra_class = \"text-blue\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        workweek_date = to_workweek_date(kwargs[\"date\"])\n        return {\n            \"date\": workweek_date,\n            \"extra_class\": kwargs[\"extra_class\"],  # <--- changed\n        }\n

Next, you will learn how to use slots give your components even more flexibility \u27a1\ufe0f

"},{"location":"getting_started/rendering_components/","title":"Rendering components","text":"

Our calendar component can accept and pre-process data, defines its own CSS and JS, and can be used in templates.

...But how do we actually render the components into HTML?

There's 3 ways to render a component:

  • Render the template that contains the {% component %} tag
  • Render the component directly with Component.render()
  • Render the component directly with Component.render_to_response()

As a reminder, this is what the calendar component looks like:

[project root]/components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    js_file = \"calendar.js\"\n    css_file = \"calendar.css\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": \"1970-01-01\",\n        }\n
"},{"location":"getting_started/rendering_components/#1-render-the-template","title":"1. Render the template","text":"

If you have embedded the component in a Django template using the {% component %} tag:

[project root]/templates/my_template.html
{% load component_tags %}\n<div>\n  {% component \"calendar\" date=\"2024-12-13\" / %}\n</div>\n

You can simply render the template with the Django tooling:

"},{"location":"getting_started/rendering_components/#with-djangoshortcutsrender","title":"With django.shortcuts.render()","text":"
from django.shortcuts import render\n\ncontext = {\"date\": \"2024-12-13\"}\nrendered_template = render(request, \"my_template.html\", context)\n
"},{"location":"getting_started/rendering_components/#with-templaterender","title":"With Template.render()","text":"

Either loading the template with get_template():

from django.template.loader import get_template\n\ntemplate = get_template(\"my_template.html\")\ncontext = {\"date\": \"2024-12-13\"}\nrendered_template = template.render(context)\n

Or creating a new Template instance:

from django.template import Template\n\ntemplate = Template(\"\"\"\n{% load component_tags %}\n<div>\n  {% component \"calendar\" date=\"2024-12-13\" / %}\n</div>\n\"\"\")\nrendered_template = template.render()\n
"},{"location":"getting_started/rendering_components/#2-render-the-component","title":"2. Render the component","text":"

You can also render the component directly with Component.render(), without wrapping the component in a template.

from components.calendar import Calendar\n\ncalendar = Calendar\nrendered_component = calendar.render()\n

You can pass args, kwargs, slots, and more, to the component:

from components.calendar import Calendar\n\ncalendar = Calendar\nrendered_component = calendar.render(\n    args=[\"2024-12-13\"],\n    kwargs={\n        \"extra_class\": \"my-class\"\n    },\n    slots={\n        \"date\": \"<b>2024-12-13</b>\"\n    },\n)\n

Info

Among other, you can pass also the request object to the render method:

from components.calendar import Calendar\n\ncalendar = Calendar\nrendered_component = calendar.render(request=request)\n

The request object is required for some of the component's features, like using Django's context processors.

"},{"location":"getting_started/rendering_components/#3-render-the-component-to-httpresponse","title":"3. Render the component to HttpResponse","text":"

A common pattern in Django is to render the component and then return the resulting HTML as a response to an HTTP request.

For this, you can use the Component.render_to_response() convenience method.

render_to_response() accepts the same args, kwargs, slots, and more, as Component.render(), but wraps the result in an HttpResponse.

from components.calendar import Calendar\n\ndef my_view(request):\n    response = Calendar.render_to_response(\n        args=[\"2024-12-13\"],\n        kwargs={\n            \"extra_class\": \"my-class\"\n        },\n        slots={\n            \"date\": \"<b>2024-12-13</b>\"\n        },\n        request=request,\n    )\n    return response\n

Info

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 MyCustomResponse(HttpResponse):\n    def __init__(self, *args, **kwargs) -> None:\n        super().__init__(*args, **kwargs)\n        # Configure response\n        self.headers = ...\n        self.status = ...\n\nclass SimpleComponent(Component):\n    response_class = MyCustomResponse\n
"},{"location":"getting_started/rendering_components/#4-rendering-slots","title":"4. Rendering slots","text":"

Slots content are automatically escaped by default to prevent XSS attacks.

In other words, it's as if you would be using Django's escape() on the slot contents / result:

from django.utils.html import escape\n\nclass Calendar(Component):\n    template = \"\"\"\n        <div>\n            {% slot \"date\" default date=date / %}\n        </div>\n    \"\"\"\n\nCalendar.render(\n    slots={\n        \"date\": escape(\"<b>Hello</b>\"),\n    }\n)\n

To disable escaping, you can wrap the slot string or slot result in Django's mark_safe():

Calendar.render(\n    slots={\n        # string\n        \"date\": mark_safe(\"<b>Hello</b>\"),\n\n        # function\n        \"date\": lambda ctx: mark_safe(\"<b>Hello</b>\"),\n    }\n)\n

Info

Read more about Django's format_html and mark_safe.

"},{"location":"getting_started/rendering_components/#5-component-views-and-urls","title":"5. Component views and URLs","text":"

For web applications, it's common to define endpoints that serve HTML content (AKA views).

If this is your case, you can define the view request handlers directly on your component by using the nestedComponent.View class.

This is a great place for:

  • Endpoints that render whole pages, if your component is a page component.

  • Endpoints that render the component as HTML fragments, to be used with HTMX or similar libraries.

Read more on Component views and URLs.

[project root]/components/calendar.py
from django_components import Component, ComponentView, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template = \"\"\"\n        <div class=\"calendar-component\">\n            <div class=\"header\">\n                {% slot \"header\" / %}\n            </div>\n            <div class=\"body\">\n                Today's date is <span>{{ date }}</span>\n            </div>\n        </div>\n    \"\"\"\n\n    class View:\n        # Handle GET requests\n        def get(self, request, *args, **kwargs):\n            # Return HttpResponse with the rendered content\n            return Calendar.render_to_response(\n                request=request,\n                kwargs={\n                    \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n                },\n                slots={\n                    \"header\": \"Calendar header\",\n                },\n            )\n

Info

The View class supports all the same HTTP methods as Django's View class. These are:

get(), post(), put(), patch(), delete(), head(), options(), trace()

Each of these receive the HttpRequest object as the first argument.

Next, you need to set the URL for the component.

You can either:

  1. Automatically assign the URL by setting the Component.View.public attribute to True.

    In this case, use get_component_url() to get the URL for the component view.

    from django_components import Component, get_component_url\n\nclass Calendar(Component):\n    class View:\n        public = True\n\nurl = get_component_url(Calendar)\n
  2. Manually assign the URL by setting Component.as_view() to your urlpatterns:

    from django.urls import path\nfrom components.calendar import Calendar\n\nurlpatterns = [\n    path(\"calendar/\", Calendar.as_view()),\n]\n

And with that, you're all set! When you visit the URL, the component will be rendered and the content will be returned.

The get(), post(), etc methods will receive the HttpRequest object as the first argument. So you can parametrize how the component is rendered for example by passing extra query parameters to the URL:

http://localhost:8000/calendar/?date=2024-12-13\n
"},{"location":"getting_started/your_first_component/","title":"Create your first component","text":"

A component in django-components can be as simple as a Django template and Python code to declare the component:

calendar.html
<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n
calendar.py
from django_components import Component\n\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n

Or a combination of Django template, Python, CSS, and Javascript:

calendar.html
<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n
calendar.css
.calendar {\n  width: 200px;\n  background: pink;\n}\n
calendar.js
document.querySelector(\".calendar\").onclick = function () {\n  alert(\"Clicked calendar!\");\n};\n
calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    js_file = \"calendar.js\"\n    css_file = \"calendar.css\"\n

Alternatively, you can \"inline\" HTML, JS, and CSS right into the component class:

from django_components import Component\n\nclass Calendar(Component):\n    template = \"\"\"\n      <div class=\"calendar\">\n        Today's date is <span>{{ date }}</span>\n      </div>\n    \"\"\"\n\n    css = \"\"\"\n      .calendar {\n        width: 200px;\n        background: pink;\n      }\n    \"\"\"\n\n    js = \"\"\"\n      document.querySelector(\".calendar\").onclick = function () {\n        alert(\"Clicked calendar!\");\n      };\n    \"\"\"\n

Note

If you \"inline\" the HTML, JS and CSS code into the Python class, you can set up syntax highlighting for better experience. However, autocompletion / intellisense does not work with syntax highlighting.

We'll start by creating a component that defines only a Django template:

"},{"location":"getting_started/your_first_component/#1-create-project-structure","title":"1. Create project structure","text":"

Start by creating empty calendar.py and calendar.html files:

sampleproject/\n\u251c\u2500\u2500 calendarapp/\n\u251c\u2500\u2500 components/             \ud83c\udd95\n\u2502   \u2514\u2500\u2500 calendar/           \ud83c\udd95\n\u2502       \u251c\u2500\u2500 calendar.py     \ud83c\udd95\n\u2502       \u2514\u2500\u2500 calendar.html   \ud83c\udd95\n\u251c\u2500\u2500 sampleproject/\n\u251c\u2500\u2500 manage.py\n\u2514\u2500\u2500 requirements.txt\n
"},{"location":"getting_started/your_first_component/#2-write-django-template","title":"2. Write Django template","text":"

Inside calendar.html, write:

[project root]/components/calendar/calendar.html
<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n

In this example we've defined one template variable date. You can use any and as many variables as you like. These variables will be defined in the Python file in get_template_data() when creating an instance of this component.

Note

The template will be rendered with whatever template backend you've specified in your Django settings file.

Currently django-components supports only the default \"django.template.backends.django.DjangoTemplates\" template backend!

"},{"location":"getting_started/your_first_component/#3-create-new-component-in-python","title":"3. Create new Component in Python","text":"

In calendar.py, create a subclass of Component to create a new component.

To link the HTML template with our component, set template_file to the name of the HTML file.

[project root]/components/calendar/calendar.py
from django_components import Component\n\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n

Note

The path to the template file can be either:

  1. Relative to the component's python file (as seen above),
  2. Relative to any of the component directories as defined by COMPONENTS.dirs and/or COMPONENTS.app_dirs (e.g. [your apps]/components dir and [project root]/components)
"},{"location":"getting_started/your_first_component/#4-define-the-template-variables","title":"4. Define the template variables","text":"

In calendar.html, we've used the variable date. So we need to define it for the template to work.

This is done using Component.get_template_data(). It's a function that returns a dictionary. The entries in this dictionary will become available within the template as variables, e.g. as {{ date }}.

[project root]/components/calendar/calendar.py
from django_components import Component\n\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": \"1970-01-01\",\n        }\n

Now, when we render the component with Component.render() method:

Calendar.render()\n

It will output

<div class=\"calendar\">\n  Today's date is <span>1970-01-01</span>\n</div>\n

And voil\u00e1!! We've created our first component.

Next, let's add JS and CSS to this component \u27a1\ufe0f.

"},{"location":"guides/devguides/dependency_mgmt/","title":"JS and CSS rendering","text":"

Aim of this doc is to share the intuition on how we manage the JS and CSS (\"dependencies\") associated with components, and how we render them.

"},{"location":"guides/devguides/dependency_mgmt/#starting-conditions","title":"Starting conditions","text":"
  1. First of all, when we consider a component, it has two kind of dependencies - the \"inlined\" JS and CSS, and additional linked JS and CSS via Media.js/css:

    from django_components import Component, types\n\nclass MyTable(Component):\n    # Inlined JS\n    js: types.js = \"\"\"\n      console.log(123);\n    \"\"\"\n\n    # Inlined CSS\n    css: types.css = \"\"\"\n      .my-table {\n        color: red;\n      }\n    \"\"\"\n\n    # Linked JS / CSS\n    class Media:\n        js = [\n            \"script-one.js\",  # STATIC file relative to component file\n            \"/script-two.js\", # URL path\n            \"https://example.com/script-three.js\", # URL\n        ]\n\n        css = [\n            \"style-one.css\",  # STATIC file relative to component file\n            \"/style-two.css\", # URL path\n            \"https://example.com/style-three.css\", # URL\n        ]\n
  2. Second thing to keep in mind is that all component's are eventually rendered into a string. And so, if we want to associate extra info with a rendered component, it has to be serialized to a string.

    This is because a component may be embedded in a Django Template with the {% component %} tag, which, when rendered, is turned into a string:

    template = Template(\"\"\"\n  {% load component_tags %}\n  <div>\n    {% component \"my_table\" / %}\n  </div>\n\"\"\")\n\nhtml_str = template.render(Context({}))\n

    And for this reason, we take the same approach also when we render a component with Component.render() - It returns a string.

  3. Thirdly, we also want to add support for JS / CSS variables. That is, that a variable defined on the component would be somehow accessible from within the JS script / CSS style.

    A simple approach to this would be to modify the inlined JS / CSS directly, and insert them for each component. But if you had extremely large JS / CSS, and e.g. only a single JS / CSS variable that you want to insert, it would be wasteful to create a copy of the JS / CSS scripts for each component instance.

    So instead, a preferred approach here is to defined and insert the inlined JS / CSS only once, and have some kind of mechanism on how we make correct the JS / CSS variables available only to the correct components.

  4. Last important thing is that we want the JS / CSS dependencies to work also with HTML fragments.

    So normally, e.g. when a user hits URL of a web page, the server renders full HTML document, with <!doctype>, <html>, <head>, and <body>. In such case, we know about ALL JS and CSS dependencies at render time, so we can e.g. insert them into <head> and <body> ourselves.

    However this renders only the initial state. HTML fragments is a common pattern where interactivity is added to the web page by fetching and replacing bits of HTML on the main HTML document after some user action.

    In the case of HTML fragments, the HTML is NOT a proper document, but only the HTML that will be inserted somewhere into the DOM.

    The challenge here is that Django template for the HTML fragment MAY contain components, and these components MAY have inlined or linked JS and CSS.

    def fragment_view(request):\n    template = Template(\"\"\"\n      {% load component_tags %}\n      <div>\n        {% component \"my_table\" / %}\n      </div>\n    \"\"\")\n\n    fragment_str = template.render(Context({}))\n    return HttpResponse(fragment_str, status=200)\n

    User may use different libraries to fetch and insert the HTML fragments (e.g. HTMX, AlpineJS, ...). From our perspective, the only thing that we can reliably say is that we expect that the HTML fragment WILL be eventually inserted into the DOM.

    So to include the corresponding JS and CSS, a simple approach could be to append them to the HTML as <style> and <script>, e.g.:

    <!-- Original content -->\n<div>...</div>\n<!-- Associated CSS files -->\n<link href=\"http://...\" />\n<style>\n  .my-class {\n    color: red;\n  }\n</style>\n<!-- Associated JS files -->\n<script src=\"http://...\"></script>\n<script>\n  console.log(123);\n</script>\n

    But this has a number of issues:

    • The JS scripts would run for each instance of the component.
    • Bloating of the HTML file, as each inlined JS or CSS would be included fully for each component.
    • While this sound OK, this could really bloat the HTML files if we used a UI component library for the basic building blocks like buttons, lists, cards, etc.
"},{"location":"guides/devguides/dependency_mgmt/#flow","title":"Flow","text":"

So the solution should address all the points above. To achieve that, we manage the JS / CSS dependencies ourselves in the browser. So when a full HTML document is loaded, we keep track of which JS and CSS have been loaded. And when an HTML fragment is inserted, we check which JS / CSS dependencies it has, and load only those that have NOT been loaded yet.

This is how we achieve that:

  1. When a component is rendered, it inserts an HTML comment containing metadata about the rendered component.

    So a template like this

    {% load component_tags %}\n<div>\n  {% component \"my_table\" / %}\n</div>\n{% component \"button\" %}\n  Click me!\n{% endcomponent %}\n

    May actually render:

    <div>\n  <!-- _RENDERED \"my_table_10bc2c,c020ad\" -->\n  <table>\n    ...\n  </table>\n</div>\n<!-- _RENDERED \"button_309dcf,31c0da\" -->\n<button>Click me!</button>\n

    Each <!-- _RENDERED --> comment includes comma-separated data - a unique hash for the component class, e.g. my_table_10bc2c, and the component ID, e.g. c020ad.

    This way, we or the user can freely pass the rendered around or transform it, treating it as a string to add / remove / replace bits. As long as the <!-- _RENDERED --> comments remain in the rendered string, we will be able to deduce which JS and CSS dependencies the component needs.

  2. Post-process the rendered HTML, extracting the <!-- _RENDERED --> comments, and instead inserting the corresponding JS and CSS dependencies.

    If we dealt only with JS, then we could get away with processing the <!-- _RENDERED --> comments on the client (browser). However, the CSS needs to be processed still on the server, so the browser receives CSS styles already inserted as <style> or <link> HTML tags. Because if we do not do that, we get a flash of unstyled content, as there will be a delay between when the HTML page loaded and when the CSS was fetched and loaded.

    So, assuming that a user has already rendered their template, which still contains <!-- _RENDERED --> comments, we need to extract and process these comments.

    There's multiple ways to achieve this:

    • If users are using Component.render() or Component.render_to_response(), these post-process the <!-- _RENDERED --> comments by default.

    • NOTE: Users are able to opt out of the post-processing by setting deps_strategy=\"ignore\".

    • If one renders a Template directly, the <!-- _RENDERED --> will be processed too. We achieve this by modifying Django's Template.render() method.

    • For advanced use cases, users may use render_dependencies() directly. This is the function that Component.render() calls internally.

    render_dependencies(), whether called directly, or other way, does the following:

    1. Find all <!-- _RENDERED --> comments, and for each comment:

    2. Look up the corresponding component class.

    3. Get the component's inlined JS / CSS from Component.js/css, and linked JS / CSS from Component.Media.js/css.

    4. Generate JS script that loads the JS / CSS dependencies.

    5. Insert the JS scripts either at the end of <body>, or in place of {% component_dependencies %} / {% component_js_dependencies %} tags.

    6. To avoid the flash of unstyled content, we need place the styles into the HTML instead of dynamically loading them from within a JS script. The CSS is placed either at the end of <head>, or in place of {% component_dependencies %} / {% component_css_dependencies %}

    7. We cache the component's inlined JS and CSS, so they can be fetched via an URL, so the inlined JS / CSS an be treated the same way as the JS / CSS dependencies set in Component.Media.js/css.

      • NOTE: While this is currently not entirely necessary, it opens up the doors for allowing plugins to post-process the inlined JS and CSS. Because after it has been post-processed, we need to store it somewhere.
  3. Server returns the post-processed HTML.

  4. In the browser, the generated JS script from step 2.4 is executed. It goes through all JS and CSS dependencies it was given. If some JS / CSS was already loaded, it is NOT fetched again. Otherwise it generates the corresponding <script> or <link> HTML tags to load the JS / CSS dependencies.

    In the browser, the \"dependency manager JS\" may look like this:

    // Load JS or CSS script if not loaded already\nComponents.loadJs('<script src=\"/abc/xyz/script.js\">');\nComponents.loadCss('<link href=\"/abc/xyz/style.css\">');\n\n// Or mark one as already-loaded, so it is ignored when\n// we call `loadJs`\nComponents.markScriptLoaded(\"js\", \"/abc/def\");\n

    Note that loadJs() / loadCss() receive whole <script> / <link> tags, not just the URL. This is because when Django's Media class renders JS and CSS, it formats it as <script> and <link> tags. And we allow users to modify how the JS and CSS should be rendered into the <script> and <link> tags.

    So, if users decided to add an extra attribute to their <script> tags, e.g. <script defer src=\"http://...\"></script>, then this way we make sure that the defer attribute will be present on the <script> tag when it is inserted into the DOM at the time of loading the JS script.

  5. To be able to fetch component's inlined JS and CSS, django-components adds a URL path under:

    /components/cache/<str:comp_cls_id>.<str:script_type>/

    E.g. /components/cache/MyTable_10bc2c.js/

    This endpoint takes the component's unique ID, e.g. MyTable_10bc2c, and looks up the component's inlined JS or CSS.

Thus, with this approach, we ensure that:

  1. All JS / CSS dependencies are loaded / executed only once.
  2. The approach is compatible with HTML fragments
  3. The approach is compatible with JS / CSS variables.
  4. Inlined JS / CSS may be post-processed by plugins
"},{"location":"guides/devguides/slot_rendering/","title":"Slot rendering","text":"

This doc serves as a primer on how component slots and fills are resolved.

"},{"location":"guides/devguides/slot_rendering/#flow","title":"Flow","text":"
  1. Imagine you have a template. Some kind of text, maybe HTML:

    | ------\n| ---------\n| ----\n| -------\n

  2. The template may contain some vars, tags, etc

    | -- {{ my_var }} --\n| ---------\n| ----\n| -------\n

  3. The template also contains some slots, etc

    | -- {{ my_var }} --\n| ---------\n| -- {% slot \"myslot\" %} ---\n| -- {% endslot %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| -- {% endslot %} ---\n| -------\n

  4. Slots may be nested

    | -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %} ---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- JKL {{ my_var }}\n| -- {% endslot %} ---\n| -------\n

  5. Some slots may be inside fills for other components

    | -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %}---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ------\n| -- {% component \"mycomp\" %} ---\n| ---- {% slot \"myslot\" %} ---\n| ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n| ---- {% endslot %} ---\n| -- {% endcomponent %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- PQR {{ my_var }}\n| -- {% endslot %} ---\n| -------\n

  6. The names of the slots and fills may be defined using variables

    | -- {% slot slot_name %} ---\n| ---- STU {{ my_var }}\n| -- {% endslot %} ---\n| -------\n

  7. The slot and fill names may be defined using for loops or other variables defined within the template (e.g. {% with %} tag or {% ... as var %} syntax)

    | -- {% for slot_name in slots %} ---\n| ---- {% slot slot_name %} ---\n| ------ STU {{ slot_name }}\n| ---- {% endslot %} ---\n| -- {% endfor %} ---\n| -------\n

  8. Variables for names and for loops allow us implement \"passthrough slots\" - that is, taking all slots that our component received, and passing them to a child component, dynamically.

    | -- {% component \"mycomp\" %} ---\n| ---- {% for slot_name in slots %} ---\n| ------ {% fill slot_name %} ---\n| -------- {% slot slot_name %} ---\n| ---------- XYZ {{ slot_name }}\n| --------- {% endslot %}\n| ------- {% endfill %}\n| ---- {% endfor %} ---\n| -- {% endcomponent %} ---\n| ----\n

  9. Putting that all together, a document may look like this:

    | -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %}---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ------\n| -- {% component \"mycomp\" %} ---\n| ---- {% slot \"myslot\" %} ---\n| ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n| ---- {% endslot %} ---\n| -- {% endcomponent %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- PQR {{ my_var }}\n| -- {% endslot %} ---\n| -------\n| -- {% for slot_name in slots %} ---\n| ---- {% component \"mycomp\" %} ---\n| ------- {% slot slot_name %}\n| ---------- STU {{ slot_name }}\n| ------- {% endslot %}\n| ---- {% endcomponent %} ---\n| -- {% endfor %} ---\n| ----\n| -- {% component \"mycomp\" %} ---\n| ---- {% for slot_name in slots %} ---\n| ------ {% fill slot_name %} ---\n| -------- {% slot slot_name %} ---\n| ---------- XYZ {{ slot_name }}\n| --------- {% endslot %}\n| ------- {% endfill %}\n| ---- {% endfor %} ---\n| -- {% endcomponent %} ---\n| -------\n

  10. Given the above, we want to render the slots with {% fill %} tag that were defined OUTSIDE of this template. How do I do that?

    NOTE: Before v0.110, slots were resolved statically, by walking down the Django Template and Nodes. However, this did not allow for using for loops or other variables defined in the template.

    Currently, this consists of 2 steps:

    1. If a component is rendered within a template using {% component %} tag, determine the given {% fill %} tags in the component's body (the content in between {% component %} and {% endcomponent %}).

      After this step, we know about all the fills that were passed to the component.

    2. Then we simply render the template as usual. And then we reach the {% slot %} tag, we search the context for the available fills.

      • If there IS a fill with the same name as the slot, we render the fill.
      • If the slot is marked default, and there is a fill named default, then we render that.
      • Otherwise, we render the slot's default content.
  11. Obtaining the fills from {% fill %}.

    When a component is rendered with {% component %} tag, and it has some content in between {% component %} and {% endcomponent %}, we want to figure out if that content is a default slot (no {% fill %} used), or if there is a collection of named {% fill %} tags:

    Default slot:

    | -- {% component \"mycomp\" %} ---\n| ---- STU {{ slot_name }}\n| -- {% endcomponent %} ---\n

    Named slots:

    | -- {% component \"mycomp\" %} ---\n| ---- {% fill \"slot_a\" %}\n| ------ STU\n| ---- {% endslot %}\n| ---- {% fill \"slot_b\" %}\n| ------ XYZ\n| ---- {% endslot %}\n| -- {% endcomponent %} ---\n

    To respect any forloops or other variables defined within the template to which the fills may have access, we:

    1. Render the content between {% component %} and {% endcomponent %} using the context outside of the component.
    2. When we reach a {% fill %} tag, we capture any variables that were created between the {% component %} and {% fill %} tags.
    3. When we reach {% fill %} tag, we do not continue rendering deeper. Instead we make a record that we found the fill tag with given name, kwargs, etc.
    4. After the rendering is done, we check if we've encountered any fills. If yes, we expect only named fills. If no, we assume that the the component's body is a default slot.
    5. Lastly we process the found fills, and make them available to the context, so any slots inside the component may access these fills.
  12. Rendering slots

    Slot rendering works similarly to collecting fills, in a sense that we do not search for the slots ahead of the time, but instead let Django handle the rendering of the template, and we step in only when Django come across as {% slot %} tag.

    When we reach a slot tag, we search the context for the available fills.

    • If there IS a fill with the same name as the slot, we render the fill.
    • If the slot is marked default, and there is a fill named default, then we render that.
    • Otherwise, we render the slot's default content.
"},{"location":"guides/devguides/slot_rendering/#using-the-correct-context-in-slotfill-tags","title":"Using the correct context in {% slot/fill %} tags","text":"

In previous section, we said that the {% fill %} tags should be already rendered by the time they are inserted into the {% slot %} tags.

This is not quite true. To help you understand, consider this complex case:

| -- {% for var in [1, 2, 3] %} ---\n| ---- {% component \"mycomp2\" %} ---\n| ------ {% fill \"first\" %}\n| ------- STU {{ my_var }}\n| -------     {{ var }}\n| ------ {% endfill %}\n| ------ {% fill \"second\" %}\n| -------- {% component var=var my_var=my_var %}\n| ---------- VWX {{ my_var }}\n| -------- {% endcomponent %}\n| ------ {% endfill %}\n| ---- {% endcomponent %} ---\n| -- {% endfor %} ---\n| -------\n

We want the forloop variables to be available inside the {% fill %} tags. Because of that, however, we CANNOT render the fills/slots in advance.

Instead, our solution is closer to how Vue handles slots. In Vue, slots are effectively functions that accept a context variables and render some content.

While we do not wrap the logic in a function, we do PREPARE IN ADVANCE: 1. The content that should be rendered for each slot 2. The context variables from get_template_data()

Thus, once we reach the {% slot %} node, in it's render() method, we access the data above, and, depending on the context_behavior setting, include the current context or not. For more info, see SlotNode.render().

"},{"location":"guides/devguides/slots_and_blocks/","title":"Using slot and block tags","text":"
  1. First let's clarify how include and extends tags work inside components.

    When component template includes include or extends tags, it's as if the \"included\" template was inlined. So if the \"included\" template contains slot tags, then the component uses those slots.

    If you have a template abc.html:

    <div>\n  hello\n  {% slot \"body\" %}{% endslot %}\n</div>\n

    And components that make use of abc.html via include or extends:

    from django_components import Component, register\n\n@register(\"my_comp_extends\")\nclass MyCompWithExtends(Component):\n    template = \"\"\"{% extends \"abc.html\" %}\"\"\"\n\n@register(\"my_comp_include\")\nclass MyCompWithInclude(Component):\n    template = \"\"\"{% include \"abc.html\" %}\"\"\"\n

    Then you can set slot fill for the slot imported via include/extends:

    {% component \"my_comp_extends\" %}\n    {% fill \"body\" %}\n        123\n    {% endfill %}\n{% endcomponent %}\n

    And it will render:

    <div>\n  hello\n  123\n</div>\n

  2. Slot and block

    If you have a template abc.html like so:

    <div>\n  hello\n  {% block inner %}\n    1\n    {% slot \"body\" %}\n      2\n    {% endslot %}\n  {% endblock %}\n</div>\n

    and component my_comp:

    @register(\"my_comp\")\nclass MyComp(Component):\n    template_file = \"abc.html\"\n

    Then:

    1. Since the block wasn't overriden, you can use the body slot:

      {% component \"my_comp\" %}\n    {% fill \"body\" %}\n        XYZ\n    {% endfill %}\n{% endcomponent %}\n

      And we get:

      <div>hello 1 XYZ</div>\n
    2. blocks CANNOT be overriden through the component tag, so something like this:

      {% component \"my_comp\" %}\n    {% fill \"body\" %}\n        XYZ\n    {% endfill %}\n{% endcomponent %}\n{% block \"inner\" %}\n    456\n{% endblock %}\n

      Will still render the component content just the same:

      <div>hello 1 XYZ</div>\n
    3. You CAN override the block tags of abc.html if the component template uses extends. In that case, just as you would expect, the block inner inside abc.html will render OVERRIDEN:

      @register(\"my_comp\")\nclass MyComp(Component):\n    template = \"\"\"\n        {% extends \"abc.html\" %}\n        {% block inner %}\n          OVERRIDEN\n        {% endblock %}\n    \"\"\"\n
    4. This is where it gets interesting (but still intuitive). You can insert even new slots inside these \"overriding\" blocks:

      @register(\"my_comp\")\nclass MyComp(Component):\n    template = \"\"\"\n      {% extends \"abc.html\" %}\n\n      {% load component_tags %}\n      {% block \"inner\" %}\n        OVERRIDEN\n        {% slot \"new_slot\" %}\n          hello\n        {% endslot %}\n      {% endblock %}\n    \"\"\"\n

      And you can then pass fill for this new_slot when rendering the component:

      {% component \"my_comp\" %}\n    {% fill \"new_slot\" %}\n        XYZ\n    {% endfill %}\n{% endcomponent %}\n

      NOTE: Currently you can supply fills for both new_slot and body slots, and you will not get an error for an invalid/unknown slot name. But since body slot is not rendered, it just won't do anything. So this renders the same as above:

      {% component \"my_comp\" %}\n    {% fill \"new_slot\" %}\n        XYZ\n    {% endfill %}\n    {% fill \"body\" %}\n        www\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"guides/other/troubleshooting/","title":"Troubleshooting","text":"

As larger projects get more complex, it can be hard to debug issues. Django Components provides a number of tools and approaches that can help you with that.

"},{"location":"guides/other/troubleshooting/#component-and-slot-highlighting","title":"Component and slot highlighting","text":"

Django Components provides a visual debugging feature that helps you understand the structure and boundaries of your components and slots. When enabled, it adds a colored border and a label around each component and slot on your rendered page.

To enable component and slot highlighting for all components and slots, set highlight_components and highlight_slots to True in extensions defaults in your settings.py file:

from django_components import ComponentsSettings\n\nCOMPONENTS = ComponentsSettings(\n    extensions_defaults={\n        \"debug_highlight\": {\n            \"highlight_slots\": True,\n            \"highlight_components\": True,\n        },\n    },\n)\n

Alternatively, you can enable highlighting for specific components by setting Component.DebugHighlight.highlight_components to True:

class MyComponent(Component):\n    class DebugHighlight:\n        highlight_components = True\n        highlight_slots = True\n

Components will be highlighted with a blue border and label:

While the slots will be highlighted with a red border and label:

Warning

Use this feature ONLY in during development. Do NOT use it in production.

"},{"location":"guides/other/troubleshooting/#component-path-in-errors","title":"Component path in errors","text":"

When an error occurs, the error message will show the path to the component that caused the error. E.g.

KeyError: \"An error occured while rendering components MyPage > MyLayout > MyComponent > Childomponent(slot:content)\n

The error message contains also the slot paths, so if you have a template like this:

{% component \"my_page\" %}\n    {% slot \"content\" %}\n        {% component \"table\" %}\n            {% slot \"header\" %}\n                {% component \"table_header\" %}\n                    ...  {# ERROR HERE #}\n                {% endcomponent %}\n            {% endslot %}\n        {% endcomponent %}\n    {% endslot %}\n{% endcomponent %}\n

Then the error message will show the path to the component that caused the error:

KeyError: \"An error occured while rendering components my_page > layout > layout(slot:content) > my_page(slot:content) > table > table(slot:header) > table_header > table_header(slot:content)\n
"},{"location":"guides/other/troubleshooting/#debug-and-trace-logging","title":"Debug and trace logging","text":"

Django components supports logging with Django.

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\nimport sys\n\nLOGGING = {\n    'version': 1,\n    'disable_existing_loggers': False,\n    \"handlers\": {\n        \"console\": {\n            'class': 'logging.StreamHandler',\n            'stream': sys.stdout,\n        },\n    },\n    \"loggers\": {\n        \"django_components\": {\n            \"level\": logging.DEBUG,\n            \"handlers\": [\"console\"],\n        },\n    },\n}\n

Info

To set TRACE level, set \"level\" to 5:

LOGGING = {\n    \"loggers\": {\n        \"django_components\": {\n            \"level\": 5,\n            \"handlers\": [\"console\"],\n        },\n    },\n}\n
"},{"location":"guides/other/troubleshooting/#logger-levels","title":"Logger levels","text":"

As of v0.126, django-components primarily uses these logger levels:

  • DEBUG: Report on loading associated HTML / JS / CSS files, autodiscovery, etc.
  • TRACE: Detailed interaction of components and slots. Logs when template tags, components, and slots are started / ended rendering, and when a slot is filled.
"},{"location":"guides/other/troubleshooting/#slot-origin","title":"Slot origin","text":"

When you pass a slot fill to a Component, the component and slot names is remebered on the slot object.

Thus, you can check where a slot was filled from by printing it out:

class MyComponent(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]):\n        print(self.slots)\n

might print:

{\n    'content': <Slot component_name='layout' slot_name='content'>,\n    'header': <Slot component_name='my_page' slot_name='header'>,\n    'left_panel': <Slot component_name='layout' slot_name='left_panel'>,\n}\n
"},{"location":"guides/other/troubleshooting/#agentic-debugging","title":"Agentic debugging","text":"

All the features above make django-components to work really well with coding AI agents like Github Copilot or CursorAI.

To debug component rendering with LLMs, you want to provide the LLM with:

  1. The components source code
  2. The rendered output
  3. As much additional context as possible

Your codebase already contains the components source code, but not the latter two.

"},{"location":"guides/other/troubleshooting/#providing-rendered-output","title":"Providing rendered output","text":"

To provide the LLM with the rendered output, you can simply export the rendered output to a file.

rendered = ProjectPage.render(...)\nwith open(\"result.html\", \"w\") as f:\n    f.write(rendered)\n

If you're using render_to_response, access the output from the HttpResponse object:

response = ProjectPage.render_to_response(...)\nwith open(\"result.html\", \"wb\") as f:\n    f.write(response.content)\n
"},{"location":"guides/other/troubleshooting/#providing-contextual-logs","title":"Providing contextual logs","text":"

Next, we provide the agent with info on HOW we got the result that we have. We do so by providing the agent with the trace-level logs.

In your settings.py, configure the trace-level logs to be written to the django_components.log file:

LOGGING = {\n    \"version\": 1,\n    \"disable_existing_loggers\": False,\n    \"handlers\": {\n        \"file\": {\n            \"class\": \"logging.FileHandler\",\n            \"filename\": \"django_components.log\",\n            \"mode\": \"w\",  # Overwrite the file each time\n        },\n    },\n    \"loggers\": {\n        \"django_components\": {\n            \"level\": 5,\n            \"handlers\": [\"file\"],\n        },\n    },\n}\n
"},{"location":"guides/other/troubleshooting/#prompting-the-agent","title":"Prompting the agent","text":"

Now, you can prompt the agent and include the trace log and the rendered output to guide the agent with debugging.

I have a django-components (DJC) project. DJC is like if Vue or React component-based web development but made for Django ecosystem.

In the view project_view, I am rendering the ProjectPage component. However, the output is not as expected. The output is missing the tabs.

You have access to the full log trace in django_components.log.

You can also see the rendered output in result.html.

With this information, help me debug the issue.

First, tell me what kind of info you would be looking for in the logs, and why (how it relates to understanding the cause of the bug).

Then tell me if that info was there, and what the implications are.

Finally, tell me what you would do to fix the issue.

"},{"location":"guides/setup/caching/","title":"Caching","text":"

This page describes the kinds of assets that django-components caches and how to configure the cache backends.

"},{"location":"guides/setup/caching/#component-caching","title":"Component caching","text":"

You can cache the output of your components by setting the Component.Cache options.

Read more about Component caching.

"},{"location":"guides/setup/caching/#components-js-and-css-files","title":"Component's JS and CSS files","text":"

django-components simultaneously supports:

  • Rendering and fetching components as HTML fragments
  • Allowing components (even fragments) to have JS and CSS files associated with them
  • Features like JS/CSS variables or CSS scoping

To achieve all this, django-components defines additional temporary JS and CSS files. These temporary files need to be stored somewhere, so that they can be fetched by the browser when the component is rendered as a fragment. And for that, django-components uses Django's cache framework.

This includes:

  • Inlined JS/CSS defined via Component.js and Component.css
  • JS/CSS variables generated from get_js_data() and get_css_data()

By default, django-components uses Django's local memory cache backend to store these assets. You can configure it to use any of your Django cache backends by setting the COMPONENTS.cache option in your settings:

COMPONENTS = {\n    # Name of the cache backend to use\n    \"cache\": \"my-cache-backend\",\n}\n

The value should be the name of one of your configured cache backends from Django's CACHES setting.

For example, to use Redis for caching component assets:

CACHES = {\n    \"default\": {\n        \"BACKEND\": \"django.core.cache.backends.locmem.LocMemCache\",\n    },\n    \"component-media\": {\n        \"BACKEND\": \"django.core.cache.backends.redis.RedisCache\",\n        \"LOCATION\": \"redis://127.0.0.1:6379/1\",\n    }\n}\n\nCOMPONENTS = {\n    # Use the Redis cache backend\n    \"cache\": \"component-media\",\n}\n

See COMPONENTS.cache for more details about this setting.

"},{"location":"guides/setup/development_server/","title":"Development server","text":""},{"location":"guides/setup/development_server/#reload-dev-server-on-component-file-changes","title":"Reload dev server on component file changes","text":"

This is relevant if you are using the project structure as shown in our examples, where HTML, JS, CSS and Python are in separate files and nested in a directory.

sampleproject/\n\u251c\u2500\u2500 components/\n\u2502   \u2514\u2500\u2500 calendar/\n\u2502       \u251c\u2500\u2500 calendar.py\n\u2502       \u2514\u2500\u2500 calendar.html\n\u2502       \u2514\u2500\u2500 calendar.css\n\u2502       \u2514\u2500\u2500 calendar.js\n\u251c\u2500\u2500 sampleproject/\n\u251c\u2500\u2500 manage.py\n\u2514\u2500\u2500 requirements.txt\n

In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.

From relevant StackOverflow thread:

TL;DR is that the server won't reload if it thinks the changed file is in a templates directory, or in a nested sub directory of a templates directory. This is by design.

To make the dev server reload on all component files, set reload_on_file_change to True. This configures Django to watch for component files too.

Warning

This setting should be enabled only for the dev environment!

"},{"location":"overview/code_of_conduct/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"overview/code_of_conduct/#our-pledge","title":"Our Pledge","text":"

In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.

"},{"location":"overview/code_of_conduct/#our-standards","title":"Our Standards","text":"

Examples of behavior that contributes to creating a positive environment include:

  • Using welcoming and inclusive language
  • Being respectful of differing viewpoints and experiences
  • Gracefully accepting constructive criticism
  • Focusing on what is best for the community
  • Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

  • The use of sexualized language or imagery and unwelcome sexual attention or advances
  • Trolling, insulting/derogatory comments, and personal or political attacks
  • Public or private harassment
  • Publishing others' private information, such as a physical or electronic address, without explicit permission
  • Other conduct which could reasonably be considered inappropriate in a professional setting
"},{"location":"overview/code_of_conduct/#our-responsibilities","title":"Our Responsibilities","text":"

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.

"},{"location":"overview/code_of_conduct/#scope","title":"Scope","text":"

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

"},{"location":"overview/code_of_conduct/#enforcement","title":"Enforcement","text":"

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at emil@emilstenstrom.se. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

"},{"location":"overview/code_of_conduct/#attribution","title":"Attribution","text":"

This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq

"},{"location":"overview/community/","title":"Community","text":""},{"location":"overview/community/#community-questions","title":"Community questions","text":"

The best place to ask questions is in our Github Discussion board.

Please, before opening a new discussion, check if similar discussion wasn't opened already.

"},{"location":"overview/community/#community-examples","title":"Community examples","text":"

One of our goals with django-components is to make it easy to share components between projects (see how to package components). 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.

  • django-htmx-components: A set of components for use with htmx.

  • djc-heroicons: A component that renders icons from Heroicons.com.

"},{"location":"overview/compatibility/","title":"Compatibility","text":"

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.1, 5.2 3.11 4.2, 5.1, 5.2 3.12 4.2, 5.1, 5.2 3.13 5.1, 5.2"},{"location":"overview/compatibility/#operating-systems","title":"Operating systems","text":"

django-components is tested against Ubuntu and Windows, and should work on any operating system that supports Python.

Note

django-components uses Rust-based parsers for better performance.

These sub-packages are built with maturin which supports a wide range of operating systems, architectures, and Python versions (see the full list).

This should cover most of the cases.

However, if your environment is not supported, you will need to install Rust and Cargo to build the sub-packages from source.

"},{"location":"overview/contributing/","title":"Contributing","text":""},{"location":"overview/contributing/#bug-reports","title":"Bug reports","text":"

If you find a bug, please open an issue with detailed description of what happened.

"},{"location":"overview/contributing/#bug-fixes","title":"Bug fixes","text":"

If you found a fix for a bug or typo, go ahead and open a PR with a fix. We'll help you out with the rest!

"},{"location":"overview/contributing/#feature-requests","title":"Feature requests","text":"

For feature requests or suggestions, please open either a discussion or an issue.

"},{"location":"overview/contributing/#getting-involved","title":"Getting involved","text":"

django_components is still under active development, and there's much to build, so come aboard!

"},{"location":"overview/contributing/#sponsoring","title":"Sponsoring","text":"

Another way you can get involved is by donating to the development of django_components.

"},{"location":"overview/development/","title":"Development","text":""},{"location":"overview/development/#install-locally-and-run-the-tests","title":"Install locally and run the tests","text":"

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\ncd django-components\n

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

pip install -r requirements-dev.txt\n

You also have to install this local django-components version. Use -e for editable mode so you don't have to re-install after every change:

pip install -e .\n

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

pytest\n

The library is also tested across many versions of Python and Django. To run tests that way:

pyenv install -s 3.8\npyenv install -s 3.9\npyenv install -s 3.10\npyenv install -s 3.11\npyenv install -s 3.12\npyenv install -s 3.13\npyenv local 3.8 3.9 3.10 3.11 3.12 3.13\ntox -p\n

To run tests for a specific Python version, use:

tox -e py38\n

NOTE: See the available environments in tox.ini.

And to run only linters, use:

tox -e mypy,flake8,isort,black\n
"},{"location":"overview/development/#running-playwright-tests","title":"Running Playwright tests","text":"

We use Playwright for end-to-end tests. You will therefore need to install Playwright to be able to run these tests.

Luckily, Playwright makes it very easy:

pip install -r requirements-dev.txt\nplaywright install chromium --with-deps\n

After Playwright is ready, simply run the tests with tox:

tox\n
"},{"location":"overview/development/#developing-against-live-django-app","title":"Developing against live Django app","text":"

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\n
  2. Install dependencies from the requirements.txt file:

    pip install -r requirements.txt\n
  3. Link to your local version of django-components:

    pip install -e ..\n

    Note

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

  4. Start Django server

    python manage.py runserver\n

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

"},{"location":"overview/development/#building-js-code","title":"Building JS code","text":"

django_components uses a bit of JS code to:

  • Manage the loading of JS and CSS files used by the components
  • Allow to pass data from Python to JS

When you make changes to this JS code, you also need to compile it:

  1. Make sure you are inside src/django_components_js:

    cd src/django_components_js\n
  2. Install the JS dependencies

    npm install\n
  3. Compile the JS/TS code:

    python build.py\n

    The script will combine all JS/TS code into a single .js file, minify it, and copy it to django_components/static/django_components/django_components.min.js.

"},{"location":"overview/development/#packaging-and-publishing","title":"Packaging and publishing","text":"

To package the library into a distribution that can be published to PyPI, run:

# Install pypa/build\npython -m pip install build --user\n# Build a binary wheel and a source tarball\npython -m build --sdist --wheel --outdir dist/ .\n

To publish the package to PyPI, use twine (See Python user guide):

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

See the full workflow here.

"},{"location":"overview/development/#maintenance","title":"Maintenance","text":""},{"location":"overview/development/#updating-supported-versions","title":"Updating supported versions","text":"

The scripts/supported_versions.py script can be used to update the supported versions.

python scripts/supported_versions.py\n

This will check the current versions of Django and Python, and will print to the terminal all the places that need updating and what to set them to.

"},{"location":"overview/development/#updating-link-references","title":"Updating link references","text":"

The scripts/validate_links.py script can be used to update the link references.

python scripts/validate_links.py\n

When new version of Django is released, you can use the script to update the URLs pointing to the Django documentation.

First, you need to update the URL_REWRITE_MAP in the script to point to the new version of Django.

Then, you can run the script to update the URLs in the codebase.

python scripts/validate_links.py --rewrite\n
"},{"location":"overview/development/#development-guides","title":"Development guides","text":"

Head over to Dev guides for a deep dive into how django_components' features are implemented.

"},{"location":"overview/installation/","title":"Installation","text":""},{"location":"overview/installation/#basic-installation","title":"Basic installation","text":"
  1. Install django_components into your environment:

    pip install django_components\n
  2. Load django_components into Django by adding it into INSTALLED_APPS in your settings file:

    # app/settings.py\nINSTALLED_APPS = [\n    ...,\n    'django_components',\n]\n
  3. BASE_DIR setting is required. Ensure that it is defined:

    # app/settings.py\nfrom pathlib import Path\n\nBASE_DIR = Path(__file__).resolve().parent.parent\n
  4. Next, modify TEMPLATES section of settings.py as follows:

    • Remove 'APP_DIRS': True,
      • NOTE: Instead of APP_DIRS: True, we will use django.template.loaders.app_directories.Loader, which has the same effect.
    • Add loaders to OPTIONS list and set it to following value:

    This allows Django to load component HTML files as Django templates.

    TEMPLATES = [\n    {\n        ...,\n        'OPTIONS': {\n            ...,\n            'loaders':[(\n                'django.template.loaders.cached.Loader', [\n                    # Default Django loader\n                    'django.template.loaders.filesystem.Loader',\n                    # Including this is the same as APP_DIRS=True\n                    'django.template.loaders.app_directories.Loader',\n                    # Components loader\n                    'django_components.template_loader.Loader',\n                ]\n            )],\n        },\n    },\n]\n
  5. Add django-component's URL paths to your urlpatterns:

    Django components already prefixes all URLs with components/. So when you are adding the URLs to urlpatterns, you can use an empty string as the first argument:

    from django.urls import include, path\n\nurlpatterns = [\n    ...\n    path(\"\", include(\"django_components.urls\")),\n]\n
"},{"location":"overview/installation/#adding-support-for-js-and-css","title":"Adding support for JS and CSS","text":"

If you want to use JS or CSS with components, you will need to:

  1. Add \"django_components.finders.ComponentsFileSystemFinder\" to STATICFILES_FINDERS in your settings file.

    This allows Django to serve component JS and CSS as static files.

    STATICFILES_FINDERS = [\n    # Default finders\n    \"django.contrib.staticfiles.finders.FileSystemFinder\",\n    \"django.contrib.staticfiles.finders.AppDirectoriesFinder\",\n    # Django components\n    \"django_components.finders.ComponentsFileSystemFinder\",\n]\n
  2. Optional. If you want to change where the JS and CSS is rendered, use {% component_js_dependencies %} and {% component_css_dependencies %}.

    By default, the JS <script> and CSS <link> tags are automatically inserted into the HTML (See Default JS / CSS locations).

    <!doctype html>\n<html>\n  <head>\n    ...\n    {% component_css_dependencies %}\n  </head>\n  <body>\n    ...\n    {% component_js_dependencies %}\n  </body>\n</html>\n
  3. Optional. By default, components' JS and CSS files are cached in memory.

    If you want to change the cache backend, set the COMPONENTS.cache setting.

    Read more in Caching.

"},{"location":"overview/installation/#optional","title":"Optional","text":""},{"location":"overview/installation/#builtin-template-tags","title":"Builtin template tags","text":"

To avoid loading the app in each template using {% load component_tags %}, you can add the tag as a 'builtin' in settings.py:

TEMPLATES = [\n    {\n        ...,\n        'OPTIONS': {\n            ...,\n            'builtins': [\n                'django_components.templatetags.component_tags',\n            ]\n        },\n    },\n]\n
"},{"location":"overview/installation/#component-directories","title":"Component directories","text":"

django-components needs to know where to search for component HTML, JS and CSS files.

There are two ways to configure the component directories:

  • COMPONENTS.dirs sets global component directories.
  • COMPONENTS.app_dirs sets app-level component directories.

By default, django-components will look for a top-level /components directory, {BASE_DIR}/components, equivalent to:

from django_components import ComponentsSettings\n\nCOMPONENTS = ComponentsSettings(\n    dirs=[\n        ...,\n        Path(BASE_DIR) / \"components\",\n    ],\n)\n

For app-level directories, the default is [app]/components, equivalent to:

from django_components import ComponentsSettings\n\nCOMPONENTS = ComponentsSettings(\n    app_dirs=[\n        ...,\n        \"components\",\n    ],\n)\n

Note

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

Now you're all set! Read on to find out how to build your first component.

"},{"location":"overview/license/","title":"License","text":"

MIT License

Copyright (c) 2019 Emil Stenstr\u00f6m

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"},{"location":"overview/migrating/","title":"Migrating","text":"

Django-components is still in active development.

Since django-components is in pre-1.0 development, the public API is not yet frozen. This means that there may be breaking changes between minor versions. We try to minimize the number of breaking changes, but sometimes it's unavoidable.

When upgrading, please read the Release notes.

"},{"location":"overview/migrating/#migrating-in-pre-v10","title":"Migrating in pre-v1.0","text":"

If you're on older pre-v1.0 versions of django-components, we recommend doing step-wise upgrades in the following order:

  • v0.26
  • v0.50
  • v0.70
  • v0.77
  • v0.81
  • v0.85
  • v0.92
  • v0.100
  • v0.110
  • v0.140

These versions introduced breaking changes that are not backwards compatible.

"},{"location":"overview/performance/","title":"Performance","text":"

We track the performance of django-components using ASV.

See the benchmarks dashboard.

"},{"location":"overview/security_notes/","title":"Security notes \ud83d\udea8","text":"

It is strongly recommended to read this section before using django-components in production.

"},{"location":"overview/security_notes/#static-files","title":"Static files","text":"

TL;DR: No action needed from v0.100 onwards. Before v0.100, use safer_staticfiles to avoid exposing backend logic.

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.

"},{"location":"overview/security_notes/#static-files-prior-to-v0100","title":"Static files prior to v0.100","text":"

Prior to v0.100, if your were using django.contrib.staticfiles to collect static files, no distinction was made between the different kinds of files.

As a result, your Python code and templates may inadvertently become available on your static file server. You probably don't want this, as parts of your backend logic will be exposed, posing a potential security vulnerability.

From v0.27 until v0.100, django-components shipped with an additional installable app django_components.safer_staticfiles. It was a drop-in replacement for django.contrib.staticfiles. Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server.

To use it, add it to INSTALLED_APPS and remove django.contrib.staticfiles.

INSTALLED_APPS = [\n    # 'django.contrib.staticfiles',   # <-- REMOVE\n    'django_components',\n    'django_components.safer_staticfiles'  # <-- ADD\n]\n

If you are on an pre-v0.27 version of django-components, your alternatives are:

  • a) passing --ignore <pattern> options to the collecstatic CLI command,
  • b) defining a subclass of StaticFilesConfig.

Both routes are described in the official docs of the staticfiles app.

Note that safer_staticfiles excludes the .py and .html files for collectstatic command:

python manage.py collectstatic\n

but it is ignored on the development server:

python manage.py runserver\n

For a step-by-step guide on deploying production server with static files, see the demo project.

See the older versions of the sampleproject for a setup with pre-v0.100 version.

"},{"location":"overview/welcome/","title":"Welcome to Django Components","text":"

django-components combines Django's templating system with the modularity seen in modern frontend frameworks like Vue or React.

With django-components you can support Django projects small and large without leaving the Django ecosystem.

"},{"location":"overview/welcome/#quickstart","title":"Quickstart","text":"

A component in django-components can be as simple as a Django template and Python code to declare the component:

components/calendar/calendar.html
<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n
components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n

Or a combination of Django template, Python, CSS, and Javascript:

components/calendar/calendar.html
<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n
components/calendar/calendar.css
.calendar {\n  width: 200px;\n  background: pink;\n}\n
components/calendar/calendar.js
document.querySelector(\".calendar\").onclick = () => {\n  alert(\"Clicked calendar!\");\n};\n
components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n    js_file = \"calendar.js\"\n    css_file = \"calendar.css\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\"date\": kwargs[\"date\"]}\n

Use the component like this:

{% component \"calendar\" date=\"2024-11-06\" %}{% endcomponent %}\n

And this is what gets rendered:

<div class=\"calendar-component\">\n  Today's date is <span>2024-11-06</span>\n</div>\n

Read on to learn about all the exciting details and configuration possibilities!

(If you instead prefer to jump right into the code, check out the example project)

"},{"location":"overview/welcome/#features","title":"Features","text":""},{"location":"overview/welcome/#modern-and-modular-ui","title":"Modern and modular UI","text":"
  • Create self-contained, reusable UI elements.
  • Each component can include its own HTML, CSS, and JS, or additional third-party JS and CSS.
  • HTML, CSS, and JS can be defined on the component class, or loaded from files.
from django_components import Component\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template = \"\"\"\n        <div class=\"calendar\">\n            Today's date is\n            <span>{{ date }}</span>\n        </div>\n    \"\"\"\n\n    css = \"\"\"\n        .calendar {\n            width: 200px;\n            background: pink;\n        }\n    \"\"\"\n\n    js = \"\"\"\n        document.querySelector(\".calendar\")\n            .addEventListener(\"click\", () => {\n                alert(\"Clicked calendar!\");\n            });\n    \"\"\"\n\n    # Additional JS and CSS\n    class Media:\n        js = [\"https://cdn.jsdelivr.net/npm/htmx.org@2/dist/htmx.min.js\"]\n        css = [\"bootstrap/dist/css/bootstrap.min.css\"]\n\n    # Variables available in the template\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"date\": kwargs[\"date\"]\n        }\n
"},{"location":"overview/welcome/#composition-with-slots","title":"Composition with slots","text":"
  • Render components inside templates with {% component %} tag.
  • Compose them with {% slot %} and {% fill %} tags.
  • Vue-like slot system, including scoped slots.
{% component \"Layout\"\n    bookmarks=bookmarks\n    breadcrumbs=breadcrumbs\n%}\n    {% fill \"header\" %}\n        <div class=\"flex justify-between gap-x-12\">\n            <div class=\"prose\">\n                <h3>{{ project.name }}</h3>\n            </div>\n            <div class=\"font-semibold text-gray-500\">\n                {{ project.start_date }} - {{ project.end_date }}\n            </div>\n        </div>\n    {% endfill %}\n\n    {# Access data passed to `{% slot %}` with `data` #}\n    {% fill \"tabs\" data=\"tabs_data\" %}\n        {% component \"TabItem\" header=\"Project Info\" %}\n            {% component \"ProjectInfo\"\n                project=project\n                project_tags=project_tags\n                attrs:class=\"py-5\"\n                attrs:width=tabs_data.width\n            / %}\n        {% endcomponent %}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"overview/welcome/#extended-template-tags","title":"Extended template tags","text":"

django-components is designed for flexibility, making working with templates a breeze.

It extends Django's template tags syntax with:

  • Literal lists and dictionaries in the template
  • Self-closing tags {% mytag / %}
  • Multi-line template tags
  • Spread operator ... to dynamically pass args or kwargs into the template tag
  • Template tags inside literal strings like \"{{ first_name }} {{ last_name }}\"
  • Pass dictonaries by their key-value pairs attr:key=val
{% component \"table\"\n    ...default_attrs\n    title=\"Friend list for {{ user.name }}\"\n    headers=[\"Name\", \"Age\", \"Email\"]\n    data=[\n        {\n            \"name\": \"John\"|upper,\n            \"age\": 30|add:1,\n            \"email\": \"john@example.com\",\n            \"hobbies\": [\"reading\"],\n        },\n        {\n            \"name\": \"Jane\"|upper,\n            \"age\": 25|add:1,\n            \"email\": \"jane@example.com\",\n            \"hobbies\": [\"reading\", \"coding\"],\n        },\n    ],\n    attrs:class=\"py-4 ma-2 border-2 border-gray-300 rounded-md\"\n/ %}\n

You too can define template tags with these features by using @template_tag() or BaseNode.

Read more on Custom template tags.

"},{"location":"overview/welcome/#full-programmatic-access","title":"Full programmatic access","text":"

When you render a component, you can access everything about the component:

  • Component input: args, kwargs, slots and context
  • Component's template, CSS and JS
  • Django's context processors
  • Unique render ID
class Table(Component):\n    js_file = \"table.js\"\n    css_file = \"table.css\"\n\n    template = \"\"\"\n        <div class=\"table\">\n            <span>{{ variable }}</span>\n        </div>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        # Access component's ID\n        assert self.id == \"djc1A2b3c\"\n\n        # Access component's inputs and slots\n        assert self.args == [123, \"str\"]\n        assert self.kwargs == {\"variable\": \"test\", \"another\": 1}\n        footer_slot = self.slots[\"footer\"]\n        some_var = self.context[\"some_var\"]\n\n        # Access the request object and Django's context processors, if available\n        assert self.request.GET == {\"query\": \"something\"}\n        assert self.context_processors_data['user'].username == \"admin\"\n\n        return {\n            \"variable\": kwargs[\"variable\"],\n        }\n\n# Access component's HTML / JS / CSS\nTable.template\nTable.js\nTable.css\n\n# Render the component\nrendered = Table.render(\n    kwargs={\"variable\": \"test\", \"another\": 1},\n    args=(123, \"str\"),\n    slots={\"footer\": \"MY_FOOTER\"},\n)\n
"},{"location":"overview/welcome/#granular-html-attributes","title":"Granular HTML attributes","text":"

Use the {% html_attrs %} template tag to render HTML attributes.

It supports:

  • Defining attributes as whole dictionaries or keyword arguments
  • Merging attributes from multiple sources
  • Boolean attributes
  • Appending attributes
  • Removing attributes
  • Defining default attributes
<div\n    {% html_attrs\n        attrs\n        defaults:class=\"default-class\"\n        class=\"extra-class\"\n    %}\n>\n

{% html_attrs %} offers a Vue-like granular control for class and style HTML attributes, where you can use a dictionary to manage each class name or style property separately.

{% html_attrs\n    class=\"foo bar\"\n    class={\n        \"baz\": True,\n        \"foo\": False,\n    }\n    class=\"extra\"\n%}\n
{% html_attrs\n    style=\"text-align: center; background-color: blue;\"\n    style={\n        \"background-color\": \"green\",\n        \"color\": None,\n        \"width\": False,\n    }\n    style=\"position: absolute; height: 12px;\"\n%}\n

Read more about HTML attributes.

"},{"location":"overview/welcome/#html-fragment-support","title":"HTML fragment support","text":"

django-components makes integration with HTMX, AlpineJS or jQuery easy by allowing components to be rendered as HTML fragments:

  • Components's JS and CSS files are loaded automatically when the fragment is inserted into the DOM.

  • Components can be exposed as Django Views with get(), post(), put(), patch(), delete() methods

  • Automatically create an endpoint for a component with Component.View.public

# components/calendar/calendar.py\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar.html\"\n\n    class View:\n        # Register Component with `urlpatterns`\n        public = True\n\n        # Define handlers\n        def get(self, request, *args, **kwargs):\n            page = request.GET.get(\"page\", 1)\n            return self.component.render_to_response(\n                request=request,\n                kwargs={\n                    \"page\": page,\n                },\n            )\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"page\": kwargs[\"page\"],\n        }\n\n# Get auto-generated URL for the component\nurl = get_component_url(Calendar)\n\n# Or define explicit URL in urls.py\npath(\"calendar/\", Calendar.as_view())\n
"},{"location":"overview/welcome/#provide-inject","title":"Provide / Inject","text":"

django-components supports the provide / inject pattern, similarly to React's Context Providers or Vue's provide / inject:

  • Use the {% provide %} tag to provide data to the component tree
  • Use the Component.inject() method to inject data into the component

Read more about Provide / Inject.

<body>\n    {% provide \"theme\" variant=\"light\" %}\n        {% component \"header\" / %}\n    {% endprovide %}\n</body>\n
@register(\"header\")\nclass Header(Component):\n    template = \"...\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        theme = self.inject(\"theme\").variant\n        return {\n            \"theme\": theme,\n        }\n
"},{"location":"overview/welcome/#input-validation-and-static-type-hints","title":"Input validation and static type hints","text":"

Avoid needless errors with type hints and runtime input validation.

To opt-in to input validation, define types for component's args, kwargs, slots:

from typing import NamedTuple, Optional\nfrom django.template import Context\nfrom django_components import Component, Slot, SlotInput\n\nclass Button(Component):\n    class Args(NamedTuple):\n        size: int\n        text: str\n\n    class Kwargs(NamedTuple):\n        variable: str\n        another: int\n        maybe_var: Optional[int] = None  # May be omitted\n\n    class Slots(NamedTuple):\n        my_slot: Optional[SlotInput] = None\n        another_slot: SlotInput\n\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        args.size  # int\n        kwargs.variable  # str\n        slots.my_slot  # Slot[MySlotData]\n

To have type hints when calling Button.render() or Button.render_to_response(), wrap the inputs in their respective Args, Kwargs, and Slots classes:

Button.render(\n    # Error: First arg must be `int`, got `float`\n    args=Button.Args(\n        size=1.25,\n        text=\"abc\",\n    ),\n    # Error: Key \"another\" is missing\n    kwargs=Button.Kwargs(\n        variable=\"text\",\n    ),\n)\n
"},{"location":"overview/welcome/#extensions","title":"Extensions","text":"

Django-components functionality can be extended with Extensions. Extensions allow for powerful customization and integrations. They can:

  • Tap into lifecycle events, such as when a component is created, deleted, or registered
  • Add new attributes and methods to the components
  • Add custom CLI commands
  • Add custom URLs

Some of the extensions include:

  • Component caching
  • Django View integration
  • Component defaults
  • Pydantic integration (input validation)

Some of the planned extensions include:

  • AlpineJS integration
  • Storybook integration
  • Component-level benchmarking with asv
"},{"location":"overview/welcome/#caching","title":"Caching","text":"
  • Components can be cached using Django's cache framework.
  • Caching rules can be configured on a per-component basis.
  • Components are cached based on their input. Or you can write custom caching logic.
from django_components import Component\n\nclass MyComponent(Component):\n    class Cache:\n        enabled = True\n        ttl = 60 * 60 * 24  # 1 day\n\n        def hash(self, *args, **kwargs):\n            return hash(f\"{json.dumps(args)}:{json.dumps(kwargs)}\")\n
"},{"location":"overview/welcome/#simple-testing","title":"Simple testing","text":"
  • Write tests for components with @djc_test decorator.
  • The decorator manages global state, ensuring that tests don't leak.
  • If using pytest, the decorator allows you to parametrize Django or Components settings.
  • The decorator also serves as a stand-in for Django's @override_settings.
from django_components.testing import djc_test\n\nfrom components.my_table import MyTable\n\n@djc_test\ndef test_my_table():\n    rendered = MyTable.render(\n        kwargs={\n            \"title\": \"My table\",\n        },\n    )\n    assert rendered == \"<table>My table</table>\"\n
"},{"location":"overview/welcome/#debugging-features","title":"Debugging features","text":"
  • Visual component inspection: Highlight components and slots directly in your browser.
  • Detailed tracing logs to supply AI-agents with context: The logs include component and slot names and IDs, and their position in the tree.
"},{"location":"overview/welcome/#sharing-components","title":"Sharing components","text":"
  • Install and use third-party components from PyPI
  • Or publish your own \"component registry\"
  • Highly customizable - Choose how the components are called in the template (and more):

    {% component \"calendar\" date=\"2024-11-06\" %}\n{% endcomponent %}\n\n{% calendar date=\"2024-11-06\" %}\n{% endcalendar %}\n
"},{"location":"overview/welcome/#performance","title":"Performance","text":"

Our aim is to be at least as fast as Django templates.

As of 0.130, django-components is ~4x slower than Django templates.

Render time django 68.9\u00b10.6ms django-components 259\u00b14ms

See the full performance breakdown for more information.

"},{"location":"overview/welcome/#release-notes","title":"Release notes","text":"

Read the Release Notes to see the latest features and fixes.

"},{"location":"overview/welcome/#community-examples","title":"Community examples","text":"

One of our goals with django-components is to make it easy to share components between projects. Head over to the Community examples to see some examples.

"},{"location":"overview/welcome/#contributing-and-development","title":"Contributing and development","text":"

Get involved or sponsor this project - See here

Running django-components locally for development - See here

"},{"location":"reference/api/","title":"API","text":""},{"location":"reference/api/#api","title":"API","text":""},{"location":"reference/api/#django_components.BaseNode","title":"BaseNode","text":"
BaseNode(\n    params: List[TagAttr],\n    flags: Optional[Dict[str, bool]] = None,\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    contents: Optional[str] = None,\n    template_name: Optional[str] = None,\n    template_component: Optional[Type[Component]] = None,\n)\n

Bases: django.template.base.Node

See source code

Node class for all django-components custom template tags.

This class has a dual role:

  1. It declares how a particular template tag should be parsed - By setting the tag, end_tag, and allowed_flags attributes:

    class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n    allowed_flags = [\"required\"]\n

    This will allow the template tag {% slot %} to be used like this:

    {% slot required %} ... {% endslot %}\n
  2. The render method is the actual implementation of the template tag.

    This is where the tag's logic is implemented:

    class MyNode(BaseNode):\n    tag = \"mynode\"\n\n    def render(self, context: Context, name: str, **kwargs: Any) -> str:\n        return f\"Hello, {name}!\"\n

    This will allow the template tag {% mynode %} to be used like this:

    {% mynode name=\"John\" %}\n

The template tag accepts parameters as defined on the render method's signature.

For more info, see BaseNode.render().

Methods:

  • parse \u2013
  • register \u2013
  • render \u2013
  • unregister \u2013

Attributes:

  • active_flags (List[str]) \u2013
  • allowed_flags (Optional[List[str]]) \u2013
  • contents (Optional[str]) \u2013
  • end_tag (Optional[str]) \u2013
  • flags (Dict[str, bool]) \u2013
  • node_id (str) \u2013
  • nodelist (NodeList) \u2013
  • params (List[TagAttr]) \u2013
  • tag (str) \u2013
  • template_component (Optional[Type[Component]]) \u2013
  • template_name (Optional[str]) \u2013
"},{"location":"reference/api/#django_components.BaseNode.active_flags","title":"active_flags property","text":"
active_flags: List[str]\n

See source code

Flags that were set for this specific instance as a list of strings.

E.g. the following tag:

{% slot \"content\" default required / %}\n

Will have the following flags:

[\"default\", \"required\"]\n
"},{"location":"reference/api/#django_components.BaseNode.allowed_flags","title":"allowed_flags class-attribute","text":"
allowed_flags: Optional[List[str]] = None\n

See source code

The list of all possible flags for this tag.

E.g. [\"required\"] will allow this tag to be used like {% slot required %}.

class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n    allowed_flags = [\"required\", \"default\"]\n

This will allow the template tag {% slot %} to be used like this:

{% slot required %} ... {% endslot %}\n{% slot default %} ... {% endslot %}\n{% slot required default %} ... {% endslot %}\n
"},{"location":"reference/api/#django_components.BaseNode.contents","title":"contents instance-attribute","text":"
contents: Optional[str] = contents\n

See source code

See source code

The contents of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The contents will be \"<div> ... </div>\".

"},{"location":"reference/api/#django_components.BaseNode.end_tag","title":"end_tag class-attribute","text":"
end_tag: Optional[str] = None\n

See source code

The end tag name.

E.g. \"endcomponent\" or \"endslot\" will make this class match template tags {% endcomponent %} or {% endslot %}.

class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n

This will allow the template tag {% slot %} to be used like this:

{% slot %} ... {% endslot %}\n

If not set, then this template tag has no end tag.

So instead of {% component %} ... {% endcomponent %}, you'd use only {% component %}.

class MyNode(BaseNode):\n    tag = \"mytag\"\n    end_tag = None\n
"},{"location":"reference/api/#django_components.BaseNode.flags","title":"flags instance-attribute","text":"
flags: Dict[str, bool] = flags or {flag: Falsefor flag in (allowed_flags or [])}\n

See source code

See source code

Dictionary of all allowed_flags that were set on the tag.

Flags that were set are True, and the rest are False.

E.g. the following tag:

class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n    allowed_flags = [\"default\", \"required\"]\n
{% slot \"content\" default %}\n

Has 2 flags, default and required, but only default was set.

The flags dictionary will be:

{\n    \"default\": True,\n    \"required\": False,\n}\n

You can check if a flag is set by doing:

if node.flags[\"default\"]:\n    ...\n
"},{"location":"reference/api/#django_components.BaseNode.node_id","title":"node_id instance-attribute","text":"
node_id: str = node_id or gen_id()\n

See source code

See source code

The unique ID of the node.

Extensions can use this ID to store additional information.

"},{"location":"reference/api/#django_components.BaseNode.nodelist","title":"nodelist instance-attribute","text":"
nodelist: NodeList = nodelist or NodeList()\n

See source code

See source code

The nodelist of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The nodelist will contain the <div> ... </div> part.

Unlike contents, the nodelist contains the actual Nodes, not just the text.

"},{"location":"reference/api/#django_components.BaseNode.params","title":"params instance-attribute","text":"
params: List[TagAttr] = params\n

See source code

See source code

The parameters to the tag in the template.

A single param represents an arg or kwarg of the template tag.

E.g. the following tag:

{% component \"my_comp\" key=val key2='val2 two' %}\n

Has 3 params:

  • Posiitonal arg \"my_comp\"
  • Keyword arg key=val
  • Keyword arg key2='val2 two'
"},{"location":"reference/api/#django_components.BaseNode.tag","title":"tag class-attribute","text":"
tag: str\n

See source code

The tag name.

E.g. \"component\" or \"slot\" will make this class match template tags {% component %} or {% slot %}.

class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n

This will allow the template tag {% slot %} to be used like this:

{% slot %} ... {% endslot %}\n
"},{"location":"reference/api/#django_components.BaseNode.template_component","title":"template_component instance-attribute","text":"
template_component: Optional[Type[Component]] = template_component\n

See source code

See source code

If the template that contains this node belongs to a Component, then this will be the Component class.

"},{"location":"reference/api/#django_components.BaseNode.template_name","title":"template_name instance-attribute","text":"
template_name: Optional[str] = template_name\n

See source code

See source code

The name of the Template that contains this node.

The template name is set by Django's template loaders.

For example, the filesystem template loader will set this to the absolute path of the template file.

\"/home/user/project/templates/my_template.html\"\n
"},{"location":"reference/api/#django_components.BaseNode.parse","title":"parse classmethod","text":"
parse(parser: Parser, token: Token, **kwargs: Any) -> BaseNode\n

See source code

This function is what is passed to Django's Library.tag() when registering the tag.

In other words, this method is called by Django's template parser when we encounter a tag that matches this node's tag, e.g. {% component %} or {% slot %}.

To register the tag, you can use BaseNode.register().

"},{"location":"reference/api/#django_components.BaseNode.register","title":"register classmethod","text":"
register(library: Library) -> None\n

See source code

A convenience method for registering the tag with the given library.

class MyNode(BaseNode):\n    tag = \"mynode\"\n\nMyNode.register(library)\n

Allows you to then use the node in templates like so:

{% load mylibrary %}\n{% mynode %}\n
"},{"location":"reference/api/#django_components.BaseNode.render","title":"render","text":"
render(context: Context, *args: Any, **kwargs: Any) -> str\n

See source code

Render the node. This method is meant to be overridden by subclasses.

The signature of this function decides what input the template tag accepts.

The render() method MUST accept a context argument. Any arguments after that will be part of the tag's input parameters.

So if you define a render method like this:

def render(self, context: Context, name: str, **kwargs: Any) -> str:\n

Then the tag will require the name parameter, and accept any extra keyword arguments:

{% component name=\"John\" age=20 %}\n
"},{"location":"reference/api/#django_components.BaseNode.unregister","title":"unregister classmethod","text":"
unregister(library: Library) -> None\n

See source code

Unregisters the node from the given library.

"},{"location":"reference/api/#django_components.CommandLiteralAction","title":"CommandLiteralAction module-attribute","text":"
CommandLiteralAction = Literal['append', 'append_const', 'count', 'extend', 'store', 'store_const', 'store_true', 'store_false', 'version']\n

See source code

The basic type of action to be taken when this argument is encountered at the command line.

This is a subset of the values for action in ArgumentParser.add_argument().

"},{"location":"reference/api/#django_components.Component","title":"Component","text":"
Component(\n    registered_name: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    registry: Optional[ComponentRegistry] = None,\n    context: Optional[Context] = None,\n    args: Optional[Any] = None,\n    kwargs: Optional[Any] = None,\n    slots: Optional[Any] = None,\n    deps_strategy: Optional[DependenciesStrategy] = None,\n    request: Optional[HttpRequest] = None,\n    node: Optional[ComponentNode] = None,\n    id: Optional[str] = None,\n)\n

Methods:

  • as_view \u2013
  • get_context_data \u2013
  • get_css_data \u2013
  • get_js_data \u2013
  • get_template \u2013
  • get_template_data \u2013
  • get_template_name \u2013
  • inject \u2013
  • on_render \u2013
  • on_render_after \u2013
  • on_render_before \u2013
  • render \u2013
  • render_to_response \u2013

Attributes:

  • Args (Optional[Type]) \u2013
  • Cache (Type[ComponentCache]) \u2013
  • CssData (Optional[Type]) \u2013
  • DebugHighlight (Type[ComponentDebugHighlight]) \u2013
  • Defaults (Type[ComponentDefaults]) \u2013
  • JsData (Optional[Type]) \u2013
  • Kwargs (Optional[Type]) \u2013
  • Media (Optional[Type[ComponentMediaInput]]) \u2013
  • Slots (Optional[Type]) \u2013
  • TemplateData (Optional[Type]) \u2013
  • View (Type[ComponentView]) \u2013
  • args (Any) \u2013
  • cache (ComponentCache) \u2013
  • class_id (str) \u2013
  • context (Context) \u2013
  • context_processors_data (Dict) \u2013
  • css (Optional[str]) \u2013
  • css_file (Optional[str]) \u2013
  • debug_highlight (ComponentDebugHighlight) \u2013
  • defaults (ComponentDefaults) \u2013
  • deps_strategy (DependenciesStrategy) \u2013
  • do_not_call_in_templates (bool) \u2013
  • id (str) \u2013
  • input (ComponentInput) \u2013
  • is_filled (SlotIsFilled) \u2013
  • js (Optional[str]) \u2013
  • js_file (Optional[str]) \u2013
  • kwargs (Any) \u2013
  • media (Optional[Media]) \u2013
  • media_class (Type[Media]) \u2013
  • name (str) \u2013
  • node (Optional[ComponentNode]) \u2013
  • outer_context (Optional[Context]) \u2013
  • raw_args (List[Any]) \u2013
  • raw_kwargs (Dict[str, Any]) \u2013
  • raw_slots (Dict[str, Slot]) \u2013
  • registered_name (Optional[str]) \u2013
  • registry (ComponentRegistry) \u2013
  • request (Optional[HttpRequest]) \u2013
  • response_class (Type[HttpResponse]) \u2013
  • slots (Any) \u2013
  • template (Optional[str]) \u2013
  • template_file (Optional[str]) \u2013
  • template_name (Optional[str]) \u2013
  • view (ComponentView) \u2013
"},{"location":"reference/api/#django_components.Component.Args","title":"Args class-attribute","text":"
Args: Optional[Type] = None\n

See source code

Optional typing for positional arguments passed to the component.

If set and not None, then the args parameter of the data methods (get_template_data(), get_js_data(), get_css_data()) will be the instance of this class:

from typing import NamedTuple\nfrom django_components import Component\n\nclass Table(Component):\n    class Args(NamedTuple):\n        color: str\n        size: int\n\n    def get_template_data(self, args: Args, kwargs, slots, context):\n        assert isinstance(args, Table.Args)\n\n        return {\n            \"color\": args.color,\n            \"size\": args.size,\n        }\n

The constructor of this class MUST accept positional arguments:

Args(*args)\n

As such, a good starting point is to set this field to a subclass of NamedTuple.

Use Args to:

  • Validate the input at runtime.
  • Set type hints for the positional arguments for data methods like get_template_data().
  • Document the component inputs.

You can also use Args to validate the positional arguments for Component.render():

Table.render(\n    args=Table.Args(color=\"red\", size=10),\n)\n

Read more on Typing and validation.

"},{"location":"reference/api/#django_components.Component.Cache","title":"Cache class-attribute","text":"
Cache: Type[ComponentCache]\n

See source code

The fields of this class are used to configure the component caching.

Read more about Component caching.

Example:

from django_components import Component\n\nclass MyComponent(Component):\n    class Cache:\n        enabled = True\n        ttl = 60 * 60 * 24  # 1 day\n        cache_name = \"my_cache\"\n
"},{"location":"reference/api/#django_components.Component.CssData","title":"CssData class-attribute","text":"
CssData: Optional[Type] = None\n

See source code

Optional typing for the data to be returned from get_css_data().

If set and not None, then this class will be instantiated with the dictionary returned from get_css_data() to validate the data.

The constructor of this class MUST accept keyword arguments:

CssData(**css_data)\n

You can also return an instance of CssData directly from get_css_data() to get type hints:

from typing import NamedTuple\nfrom django_components import Component\n\nclass Table(Component):\n    class CssData(NamedTuple):\n        color: str\n        size: int\n\n    def get_css_data(self, args, kwargs, slots, context):\n        return Table.CssData(\n            color=kwargs[\"color\"],\n            size=kwargs[\"size\"],\n        )\n

A good starting point is to set this field to a subclass of NamedTuple or a dataclass.

Use CssData to:

  • Validate the data returned from get_css_data() at runtime.
  • Set type hints for this data.
  • Document the component data.

Read more on Typing and validation.

Info

If you use a custom class for CssData, this class needs to be convertable to a dictionary.

You can implement either:

  1. _asdict() method

    class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def _asdict(self):\n        return {'x': self.x, 'y': self.y}\n

  2. Or make the class dict-like with __iter__() and __getitem__()

    class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def __iter__(self):\n        return iter([('x', self.x), ('y', self.y)])\n\n    def __getitem__(self, key):\n        return getattr(self, key)\n

"},{"location":"reference/api/#django_components.Component.DebugHighlight","title":"DebugHighlight class-attribute","text":"
DebugHighlight: Type[ComponentDebugHighlight]\n

See source code

The fields of this class are used to configure the component debug highlighting.

Read more about Component debug highlighting.

"},{"location":"reference/api/#django_components.Component.Defaults","title":"Defaults class-attribute","text":"
Defaults: Type[ComponentDefaults]\n

See source code

The fields of this class are used to set default values for the component's kwargs.

Read more about Component defaults.

Example:

from django_components import Component, Default\n\nclass MyComponent(Component):\n    class Defaults:\n        position = \"left\"\n        selected_items = Default(lambda: [1, 2, 3])\n
"},{"location":"reference/api/#django_components.Component.JsData","title":"JsData class-attribute","text":"
JsData: Optional[Type] = None\n

See source code

Optional typing for the data to be returned from get_js_data().

If set and not None, then this class will be instantiated with the dictionary returned from get_js_data() to validate the data.

The constructor of this class MUST accept keyword arguments:

JsData(**js_data)\n

You can also return an instance of JsData directly from get_js_data() to get type hints:

from typing import NamedTuple\nfrom django_components import Component\n\nclass Table(Component):\n    class JsData(NamedTuple):\n        color: str\n        size: int\n\n    def get_js_data(self, args, kwargs, slots, context):\n        return Table.JsData(\n            color=kwargs[\"color\"],\n            size=kwargs[\"size\"],\n        )\n

A good starting point is to set this field to a subclass of NamedTuple or a dataclass.

Use JsData to:

  • Validate the data returned from get_js_data() at runtime.
  • Set type hints for this data.
  • Document the component data.

Read more on Typing and validation.

Info

If you use a custom class for JsData, this class needs to be convertable to a dictionary.

You can implement either:

  1. _asdict() method

    class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def _asdict(self):\n        return {'x': self.x, 'y': self.y}\n

  2. Or make the class dict-like with __iter__() and __getitem__()

    class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def __iter__(self):\n        return iter([('x', self.x), ('y', self.y)])\n\n    def __getitem__(self, key):\n        return getattr(self, key)\n

"},{"location":"reference/api/#django_components.Component.Kwargs","title":"Kwargs class-attribute","text":"
Kwargs: Optional[Type] = None\n

See source code

Optional typing for keyword arguments passed to the component.

If set and not None, then the kwargs parameter of the data methods (get_template_data(), get_js_data(), get_css_data()) will be the instance of this class:

from typing import NamedTuple\nfrom django_components import Component\n\nclass Table(Component):\n    class Kwargs(NamedTuple):\n        color: str\n        size: int\n\n    def get_template_data(self, args, kwargs: Kwargs, slots, context):\n        assert isinstance(kwargs, Table.Kwargs)\n\n        return {\n            \"color\": kwargs.color,\n            \"size\": kwargs.size,\n        }\n

The constructor of this class MUST accept keyword arguments:

Kwargs(**kwargs)\n

As such, a good starting point is to set this field to a subclass of NamedTuple or a dataclass.

Use Kwargs to:

  • Validate the input at runtime.
  • Set type hints for the keyword arguments for data methods like get_template_data().
  • Document the component inputs.

You can also use Kwargs to validate the keyword arguments for Component.render():

Table.render(\n    kwargs=Table.Kwargs(color=\"red\", size=10),\n)\n

Read more on Typing and validation.

"},{"location":"reference/api/#django_components.Component.Media","title":"Media class-attribute","text":"
Media: Optional[Type[ComponentMediaInput]] = None\n

See source code

Defines JS and CSS media files associated with this component.

This Media class behaves similarly to Django's Media class:

  • Paths are generally handled as static file paths, and resolved URLs are rendered to HTML with media_class.render_js() or media_class.render_css().
  • A path that starts with http, https, or / is considered a URL, skipping the static file resolution. This path is still rendered to HTML with media_class.render_js() or media_class.render_css().
  • A SafeString (with __html__ method) is considered an already-formatted HTML tag, skipping both static file resolution and rendering with media_class.render_js() or media_class.render_css().
  • You can set extend to configure whether to inherit JS / CSS from parent components. See Media inheritance.

However, there's a few differences from Django's Media class:

  1. Our Media class accepts various formats for the JS and CSS files: either a single file, a list, or (CSS-only) a dictionary (See ComponentMediaInput).
  2. Individual JS / CSS files can be any of str, bytes, Path, SafeString, or a function (See ComponentMediaInputPath).

Example:

class MyTable(Component):\n    class Media:\n        js = [\n            \"path/to/script.js\",\n            \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\",  # AlpineJS\n        ]\n        css = {\n            \"all\": [\n                \"path/to/style.css\",\n                \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\",  # TailwindCSS\n            ],\n            \"print\": [\"path/to/style2.css\"],\n        }\n
"},{"location":"reference/api/#django_components.Component.Slots","title":"Slots class-attribute","text":"
Slots: Optional[Type] = None\n

See source code

Optional typing for slots passed to the component.

If set and not None, then the slots parameter of the data methods (get_template_data(), get_js_data(), get_css_data()) will be the instance of this class:

from typing import NamedTuple\nfrom django_components import Component, Slot, SlotInput\n\nclass Table(Component):\n    class Slots(NamedTuple):\n        header: SlotInput\n        footer: Slot\n\n    def get_template_data(self, args, kwargs, slots: Slots, context):\n        assert isinstance(slots, Table.Slots)\n\n        return {\n            \"header\": slots.header,\n            \"footer\": slots.footer,\n        }\n

The constructor of this class MUST accept keyword arguments:

Slots(**slots)\n

As such, a good starting point is to set this field to a subclass of NamedTuple or a dataclass.

Use Slots to:

  • Validate the input at runtime.
  • Set type hints for the slots for data methods like get_template_data().
  • Document the component inputs.

You can also use Slots to validate the slots for Component.render():

Table.render(\n    slots=Table.Slots(\n        header=\"HELLO IM HEADER\",\n        footer=Slot(lambda ctx: ...),\n    ),\n)\n

Read more on Typing and validation.

Info

Components can receive slots as strings, functions, or instances of Slot.

Internally these are all normalized to instances of Slot.

Therefore, the slots dictionary available in data methods (like get_template_data()) will always be a dictionary of Slot instances.

To correctly type this dictionary, you should set the fields of Slots to Slot or SlotInput:

SlotInput is a union of Slot, string, and function types.

"},{"location":"reference/api/#django_components.Component.TemplateData","title":"TemplateData class-attribute","text":"
TemplateData: Optional[Type] = None\n

See source code

Optional typing for the data to be returned from get_template_data().

If set and not None, then this class will be instantiated with the dictionary returned from get_template_data() to validate the data.

The constructor of this class MUST accept keyword arguments:

TemplateData(**template_data)\n

You can also return an instance of TemplateData directly from get_template_data() to get type hints:

from typing import NamedTuple\nfrom django_components import Component\n\nclass Table(Component):\n    class TemplateData(NamedTuple):\n        color: str\n        size: int\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return Table.TemplateData(\n            color=kwargs[\"color\"],\n            size=kwargs[\"size\"],\n        )\n

A good starting point is to set this field to a subclass of NamedTuple or a dataclass.

Use TemplateData to:

  • Validate the data returned from get_template_data() at runtime.
  • Set type hints for this data.
  • Document the component data.

Read more on Typing and validation.

Info

If you use a custom class for TemplateData, this class needs to be convertable to a dictionary.

You can implement either:

  1. _asdict() method

    class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def _asdict(self):\n        return {'x': self.x, 'y': self.y}\n

  2. Or make the class dict-like with __iter__() and __getitem__()

    class MyClass:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n\n    def __iter__(self):\n        return iter([('x', self.x), ('y', self.y)])\n\n    def __getitem__(self, key):\n        return getattr(self, key)\n

"},{"location":"reference/api/#django_components.Component.View","title":"View class-attribute","text":"
View: Type[ComponentView]\n

See source code

The fields of this class are used to configure the component views and URLs.

This class is a subclass of django.views.View. The Component instance is available via self.component.

Override the methods of this class to define the behavior of the component.

Read more about Component views and URLs.

Example:

class MyComponent(Component):\n    class View:\n        def get(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:\n            return HttpResponse(\"Hello, world!\")\n
"},{"location":"reference/api/#django_components.Component.args","title":"args instance-attribute","text":"
args: Any\n

See source code

Positional arguments passed to the component.

This is part of the Render API.

args has the same behavior as the args argument of Component.get_template_data():

  • If you defined the Component.Args class, then the args property will return an instance of that Args class.
  • Otherwise, args will be a plain list.

Example:

With Args class:

from django_components import Component\n\nclass Table(Component):\n    class Args(NamedTuple):\n        page: int\n        per_page: int\n\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.args.page == 123\n        assert self.args.per_page == 10\n\nrendered = Table.render(\n    args=[123, 10],\n)\n

Without Args class:

from django_components import Component\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.args[0] == 123\n        assert self.args[1] == 10\n
"},{"location":"reference/api/#django_components.Component.cache","title":"cache instance-attribute","text":"
cache: ComponentCache\n

See source code

Instance of ComponentCache available at component render time.

"},{"location":"reference/api/#django_components.Component.class_id","title":"class_id class-attribute","text":"
class_id: str\n

See source code

Unique ID of the component class, e.g. MyComponent_ab01f2.

This is derived from the component class' module import path, e.g. path.to.my.MyComponent.

"},{"location":"reference/api/#django_components.Component.context","title":"context instance-attribute","text":"
context: Context\n

See source code

The context argument as passed to Component.get_template_data().

This is Django's Context with which the component template is rendered.

If the root component or template was rendered with RequestContext then this will be an instance of RequestContext.

Whether the context variables defined in context are available to the template depends on the context behavior mode:

  • In \"django\" context behavior mode, the template will have access to the keys of this context.

  • In \"isolated\" context behavior mode, the template will NOT have access to this context, and data MUST be passed via component's args and kwargs.

"},{"location":"reference/api/#django_components.Component.context_processors_data","title":"context_processors_data property","text":"
context_processors_data: Dict\n

See source code

Retrieve data injected by context_processors.

This data is also available from within the component's template, without having to return this data from get_template_data().

In regular Django templates, you need to use RequestContext to apply context processors.

In Components, the context processors are applied to components either when:

  • The component is rendered with RequestContext (Regular Django behavior)
  • The component is rendered with a regular Context (or none), but the request kwarg of Component.render() is set.
  • The component is nested in another component that matches any of these conditions.

See Component.request on how the request (HTTPRequest) object is passed to and within the components.

NOTE: This dictionary is generated dynamically, so any changes to it will not be persisted.

Example:

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        user = self.context_processors_data['user']\n        return {\n            'is_logged_in': user.is_authenticated,\n        }\n
"},{"location":"reference/api/#django_components.Component.css","title":"css class-attribute instance-attribute","text":"
css: Optional[str] = None\n

See source code

Main CSS associated with this component inlined as string.

Warning

Only one of css or css_file must be defined.

Example:

class MyComponent(Component):\n    css = \"\"\"\n        .my-class {\n            color: red;\n        }\n    \"\"\"\n

Syntax highlighting

When using the inlined template, you can enable syntax highlighting with django_components.types.css.

Learn more about syntax highlighting.

from django_components import Component, types\n\nclass MyComponent(Component):\n    css: types.css = '''\n      .my-class {\n        color: red;\n      }\n    '''\n
"},{"location":"reference/api/#django_components.Component.css_file","title":"css_file class-attribute","text":"
css_file: Optional[str] = None\n

See source code

Main CSS associated with this component as file path.

The filepath must be either:

  • Relative to the directory where the Component's Python file is defined.
  • Relative to one of the component directories, as set by COMPONENTS.dirs or COMPONENTS.app_dirs (e.g. <root>/components/).
  • Relative to the staticfiles directories, as set by Django's STATICFILES_DIRS setting (e.g. <root>/static/).

When you create a Component class with css_file, these will happen:

  1. If the file path is relative to the directory where the component's Python file is, the path is resolved.
  2. The file is read and its contents is set to Component.css.

Warning

Only one of css or css_file must be defined.

Example:

path/to/style.css
.my-class {\n    color: red;\n}\n
path/to/component.py
class MyComponent(Component):\n    css_file = \"path/to/style.css\"\n\nprint(MyComponent.css)\n# Output:\n# .my-class {\n#     color: red;\n# };\n
"},{"location":"reference/api/#django_components.Component.debug_highlight","title":"debug_highlight instance-attribute","text":"
debug_highlight: ComponentDebugHighlight\n
"},{"location":"reference/api/#django_components.Component.defaults","title":"defaults instance-attribute","text":"
defaults: ComponentDefaults\n

See source code

Instance of ComponentDefaults available at component render time.

"},{"location":"reference/api/#django_components.Component.deps_strategy","title":"deps_strategy instance-attribute","text":"
deps_strategy: DependenciesStrategy\n

See source code

Dependencies strategy defines how to handle JS and CSS dependencies of this and child components.

Read more about Dependencies rendering.

This is part of the Render API.

There are six strategies:

  • \"document\" (default)
    • Smartly inserts JS / CSS into placeholders or into <head> and <body> tags.
    • Inserts extra script to allow fragment types to work.
    • Assumes the HTML will be rendered in a JS-enabled browser.
  • \"fragment\"
    • A lightweight HTML fragment to be inserted into a document with AJAX.
    • No JS / CSS included.
  • \"simple\"
    • Smartly insert JS / CSS into placeholders or into <head> and <body> tags.
    • No extra script loaded.
  • \"prepend\"
    • Insert JS / CSS before the rendered HTML.
    • No extra script loaded.
  • \"append\"
    • Insert JS / CSS after the rendered HTML.
    • No extra script loaded.
  • \"ignore\"
    • HTML is left as-is. You can still process it with a different strategy later with render_dependencies().
    • Used for inserting rendered HTML into other components.
"},{"location":"reference/api/#django_components.Component.do_not_call_in_templates","title":"do_not_call_in_templates class-attribute","text":"
do_not_call_in_templates: bool = True\n

See source code

Django special property to prevent calling the instance as a function inside Django templates.

Read more about Django's do_not_call_in_templates.

"},{"location":"reference/api/#django_components.Component.id","title":"id instance-attribute","text":"
id: str\n

See source code

This ID is unique for every time a Component.render() (or equivalent) is called (AKA \"render ID\").

This is useful for logging or debugging.

The ID is a 7-letter alphanumeric string in the format cXXXXXX, where XXXXXX is a random string of 6 alphanumeric characters (case-sensitive).

E.g. c1A2b3c.

A single render ID has a chance of collision 1 in 57 billion. However, due to birthday paradox, the chance of collision increases to 1% when approaching ~33K render IDs.

Thus, there is currently a soft-cap of ~30K components rendered on a single page.

If you need to expand this limit, please open an issue on GitHub.

Example:

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        print(f\"Rendering '{self.id}'\")\n\nMyComponent.render()\n# Rendering 'ab3c4d'\n
"},{"location":"reference/api/#django_components.Component.input","title":"input instance-attribute","text":"
input: ComponentInput\n

See source code

Deprecated. Will be removed in v1.

Input holds the data that were passed to the current component at render time.

This includes:

  • args - List of positional arguments
  • kwargs - Dictionary of keyword arguments
  • slots - Dictionary of slots. Values are normalized to Slot instances
  • context - Context object that should be used to render the component
  • And other kwargs passed to Component.render() like deps_strategy

Example:

class Table(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        # Access component's inputs, slots and context\n        assert self.args == [123, \"str\"]\n        assert self.kwargs == {\"variable\": \"test\", \"another\": 1}\n        footer_slot = self.slots[\"footer\"]\n        some_var = self.input.context[\"some_var\"]\n\nrendered = TestComponent.render(\n    kwargs={\"variable\": \"test\", \"another\": 1},\n    args=[123, \"str\"],\n    slots={\"footer\": \"MY_SLOT\"},\n)\n
"},{"location":"reference/api/#django_components.Component.is_filled","title":"is_filled instance-attribute","text":"
is_filled: SlotIsFilled\n

See source code

Deprecated. Will be removed in v1. Use Component.slots instead. Note that Component.slots no longer escapes the slot names.

Dictionary describing which slots have or have not been filled.

This attribute is available for use only within:

You can also access this variable from within the template as

{{ component_vars.is_filled.slot_name }}

"},{"location":"reference/api/#django_components.Component.js","title":"js class-attribute instance-attribute","text":"
js: Optional[str] = None\n

See source code

Main JS associated with this component inlined as string.

Warning

Only one of js or js_file must be defined.

Example:

class MyComponent(Component):\n    js = \"console.log('Hello, World!');\"\n

Syntax highlighting

When using the inlined template, you can enable syntax highlighting with django_components.types.js.

Learn more about syntax highlighting.

from django_components import Component, types\n\nclass MyComponent(Component):\n    js: types.js = '''\n      console.log('Hello, World!');\n    '''\n
"},{"location":"reference/api/#django_components.Component.js_file","title":"js_file class-attribute","text":"
js_file: Optional[str] = None\n

See source code

Main JS associated with this component as file path.

The filepath must be either:

  • Relative to the directory where the Component's Python file is defined.
  • Relative to one of the component directories, as set by COMPONENTS.dirs or COMPONENTS.app_dirs (e.g. <root>/components/).
  • Relative to the staticfiles directories, as set by Django's STATICFILES_DIRS setting (e.g. <root>/static/).

When you create a Component class with js_file, these will happen:

  1. If the file path is relative to the directory where the component's Python file is, the path is resolved.
  2. The file is read and its contents is set to Component.js.

Warning

Only one of js or js_file must be defined.

Example:

path/to/script.js
console.log('Hello, World!');\n
path/to/component.py
class MyComponent(Component):\n    js_file = \"path/to/script.js\"\n\nprint(MyComponent.js)\n# Output: console.log('Hello, World!');\n
"},{"location":"reference/api/#django_components.Component.kwargs","title":"kwargs instance-attribute","text":"
kwargs: Any\n

See source code

Keyword arguments passed to the component.

This is part of the Render API.

kwargs has the same behavior as the kwargs argument of Component.get_template_data():

  • If you defined the Component.Kwargs class, then the kwargs property will return an instance of that Kwargs class.
  • Otherwise, kwargs will be a plain dict.

Example:

With Kwargs class:

from django_components import Component\n\nclass Table(Component):\n    class Kwargs(NamedTuple):\n        page: int\n        per_page: int\n\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.kwargs.page == 123\n        assert self.kwargs.per_page == 10\n\nrendered = Table.render(\n    kwargs={\n        \"page\": 123,\n        \"per_page\": 10,\n    },\n)\n

Without Kwargs class:

from django_components import Component\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.kwargs[\"page\"] == 123\n        assert self.kwargs[\"per_page\"] == 10\n
"},{"location":"reference/api/#django_components.Component.media","title":"media class-attribute instance-attribute","text":"
media: Optional[Media] = None\n

See source code

Normalized definition of JS and CSS media files associated with this component. None if Component.Media is not defined.

This field is generated from Component.media_class.

Read more on Accessing component's Media JS / CSS.

Example:

class MyComponent(Component):\n    class Media:\n        js = \"path/to/script.js\"\n        css = \"path/to/style.css\"\n\nprint(MyComponent.media)\n# Output:\n# <script src=\"/static/path/to/script.js\"></script>\n# <link href=\"/static/path/to/style.css\" media=\"all\" rel=\"stylesheet\">\n
"},{"location":"reference/api/#django_components.Component.media_class","title":"media_class class-attribute","text":"
media_class: Type[Media] = Media\n

See source code

Set the Media class that will be instantiated with the JS and CSS media files from Component.Media.

This is useful when you want to customize the behavior of the media files, like customizing how the JS or CSS files are rendered into <script> or <link> HTML tags.

Read more in Media class.

Example:

class MyTable(Component):\n    class Media:\n        js = \"path/to/script.js\"\n        css = \"path/to/style.css\"\n\n    media_class = MyMediaClass\n
"},{"location":"reference/api/#django_components.Component.name","title":"name instance-attribute","text":"
name: str\n

See source code

The name of the component.

If the component was registered, this will be the name under which the component was registered in the ComponentRegistry.

Otherwise, this will be the name of the class.

Example:

@register(\"my_component\")\nclass RegisteredComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"name\": self.name,  # \"my_component\"\n        }\n\nclass UnregisteredComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"name\": self.name,  # \"UnregisteredComponent\"\n        }\n
"},{"location":"reference/api/#django_components.Component.node","title":"node instance-attribute","text":"
node: Optional[ComponentNode]\n

See source code

The ComponentNode instance that was used to render the component.

This will be set only if the component was rendered with the {% component %} tag.

Accessing the ComponentNode is mostly useful for extensions, which can modify their behaviour based on the source of the Component.

class MyComponent(Component):\n    def get_template_data(self, context, template):\n        if self.node is not None:\n            assert self.node.name == \"my_component\"\n

For example, if MyComponent was used in another component - that is, with a {% component \"my_component\" %} tag in a template that belongs to another component - then you can use self.node.template_component to access the owner Component class.

class Parent(Component):\n    template: types.django_html = '''\n        <div>\n            {% component \"my_component\" / %}\n        </div>\n    '''\n\n@register(\"my_component\")\nclass MyComponent(Component):\n    def get_template_data(self, context, template):\n        if self.node is not None:\n            assert self.node.template_component == Parent\n

Info

Component.node is None if the component is created by Component.render() (but you can pass in the node kwarg yourself).

"},{"location":"reference/api/#django_components.Component.outer_context","title":"outer_context instance-attribute","text":"
outer_context: Optional[Context]\n

See source code

When a component is rendered with the {% component %} tag, this is the Django's Context object that was used just outside of the component.

{% with abc=123 %}\n    {{ abc }} {# <--- This is in outer context #}\n    {% component \"my_component\" / %}\n{% endwith %}\n

This is relevant when your components are isolated, for example when using the \"isolated\" context behavior mode or when using the only flag.

When components are isolated, each component has its own instance of Context, so outer_context is different from the context argument.

"},{"location":"reference/api/#django_components.Component.raw_args","title":"raw_args instance-attribute","text":"
raw_args: List[Any]\n

See source code

Positional arguments passed to the component.

This is part of the Render API.

Unlike Component.args, this attribute is not typed and will remain as plain list even if you define the Component.Args class.

Example:

from django_components import Component\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.raw_args[0] == 123\n        assert self.raw_args[1] == 10\n
"},{"location":"reference/api/#django_components.Component.raw_kwargs","title":"raw_kwargs instance-attribute","text":"
raw_kwargs: Dict[str, Any]\n

See source code

Keyword arguments passed to the component.

This is part of the Render API.

Unlike Component.kwargs, this attribute is not typed and will remain as plain dict even if you define the Component.Kwargs class.

Example:

from django_components import Component\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.raw_kwargs[\"page\"] == 123\n        assert self.raw_kwargs[\"per_page\"] == 10\n
"},{"location":"reference/api/#django_components.Component.raw_slots","title":"raw_slots instance-attribute","text":"
raw_slots: Dict[str, Slot]\n

See source code

Slots passed to the component.

This is part of the Render API.

Unlike Component.slots, this attribute is not typed and will remain as plain dict even if you define the Component.Slots class.

Example:

from django_components import Component\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert self.raw_slots[\"header\"] == \"MY_HEADER\"\n        assert self.raw_slots[\"footer\"] == \"FOOTER: \" + ctx.data[\"user_id\"]\n
"},{"location":"reference/api/#django_components.Component.registered_name","title":"registered_name instance-attribute","text":"
registered_name: Optional[str]\n

See source code

If the component was rendered with the {% component %} template tag, this will be the name under which the component was registered in the ComponentRegistry.

Otherwise, this will be None.

Example:

@register(\"my_component\")\nclass MyComponent(Component):\n    template = \"{{ name }}\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"name\": self.registered_name,\n        }\n

Will print my_component in the template:

{% component \"my_component\" / %}\n

And None when rendered in Python:

MyComponent.render()\n# None\n
"},{"location":"reference/api/#django_components.Component.registry","title":"registry instance-attribute","text":"
registry: ComponentRegistry\n

See source code

The ComponentRegistry instance that was used to render the component.

"},{"location":"reference/api/#django_components.Component.request","title":"request instance-attribute","text":"
request: Optional[HttpRequest]\n

See source code

HTTPRequest object passed to this component.

Example:

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        user_id = self.request.GET['user_id']\n        return {\n            'user_id': user_id,\n        }\n

Passing request to a component:

In regular Django templates, you have to use RequestContext to pass the HttpRequest object to the template.

With Components, you can either use RequestContext, or pass the request object explicitly via Component.render() and Component.render_to_response().

When a component is nested in another, the child component uses parent's request object.

"},{"location":"reference/api/#django_components.Component.response_class","title":"response_class class-attribute","text":"
response_class: Type[HttpResponse] = HttpResponse\n

See source code

This attribute configures what class is used to generate response from Component.render_to_response().

The response class should accept a string as the first argument.

Defaults to django.http.HttpResponse.

Example:

from django.http import HttpResponse\nfrom django_components import Component\n\nclass MyHttpResponse(HttpResponse):\n    ...\n\nclass MyComponent(Component):\n    response_class = MyHttpResponse\n\nresponse = MyComponent.render_to_response()\nassert isinstance(response, MyHttpResponse)\n
"},{"location":"reference/api/#django_components.Component.slots","title":"slots instance-attribute","text":"
slots: Any\n

See source code

Slots passed to the component.

This is part of the Render API.

slots has the same behavior as the slots argument of Component.get_template_data():

  • If you defined the Component.Slots class, then the slots property will return an instance of that class.
  • Otherwise, slots will be a plain dict.

Example:

With Slots class:

from django_components import Component, Slot, SlotInput\n\nclass Table(Component):\n    class Slots(NamedTuple):\n        header: SlotInput\n        footer: SlotInput\n\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert isinstance(self.slots.header, Slot)\n        assert isinstance(self.slots.footer, Slot)\n\nrendered = Table.render(\n    slots={\n        \"header\": \"MY_HEADER\",\n        \"footer\": lambda ctx: \"FOOTER: \" + ctx.data[\"user_id\"],\n    },\n)\n

Without Slots class:

from django_components import Component, Slot, SlotInput\n\nclass Table(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        assert isinstance(self.slots[\"header\"], Slot)\n        assert isinstance(self.slots[\"footer\"], Slot)\n
"},{"location":"reference/api/#django_components.Component.template","title":"template class-attribute instance-attribute","text":"
template: Optional[str] = None\n

See source code

Inlined Django template (as a plain string) associated with this component.

Warning

Only one of template_file, template, get_template_name(), or get_template() must be defined.

Example:

class Table(Component):\n    template = '''\n      <div>\n        {{ my_var }}\n      </div>\n    '''\n

Syntax highlighting

When using the inlined template, you can enable syntax highlighting with django_components.types.django_html.

Learn more about syntax highlighting.

from django_components import Component, types\n\nclass MyComponent(Component):\n    template: types.django_html = '''\n      <div>\n        {{ my_var }}\n      </div>\n    '''\n
"},{"location":"reference/api/#django_components.Component.template_file","title":"template_file class-attribute","text":"
template_file: Optional[str] = None\n

See source code

Filepath to the Django template associated with this component.

The filepath must be either:

  • Relative to the directory where the Component's Python file is defined.
  • Relative to one of the component directories, as set by COMPONENTS.dirs or COMPONENTS.app_dirs (e.g. <root>/components/).
  • Relative to the template directories, as set by Django's TEMPLATES setting (e.g. <root>/templates/).

Warning

Only one of template_file, get_template_name, template or get_template must be defined.

Example:

Assuming this project layout:

|- components/\n  |- table/\n    |- table.html\n    |- table.css\n    |- table.js\n

Template name can be either relative to the python file (components/table/table.py):

class Table(Component):\n    template_file = \"table.html\"\n

Or relative to one of the directories in COMPONENTS.dirs or COMPONENTS.app_dirs (components/):

class Table(Component):\n    template_file = \"table/table.html\"\n
"},{"location":"reference/api/#django_components.Component.template_name","title":"template_name class-attribute","text":"
template_name: Optional[str]\n

See source code

Alias for template_file.

For historical reasons, django-components used template_name to align with Django's TemplateView.

template_file was introduced to align with js/js_file and css/css_file.

Setting and accessing this attribute is proxied to template_file.

"},{"location":"reference/api/#django_components.Component.view","title":"view instance-attribute","text":"
view: ComponentView\n

See source code

Instance of ComponentView available at component render time.

"},{"location":"reference/api/#django_components.Component.as_view","title":"as_view classmethod","text":"
as_view(**initkwargs: Any) -> ViewFn\n

See source code

Shortcut for calling Component.View.as_view and passing component instance to it.

Read more on Component views and URLs.

"},{"location":"reference/api/#django_components.Component.get_context_data","title":"get_context_data","text":"
get_context_data(*args: Any, **kwargs: Any) -> Optional[Mapping]\n

See source code

DEPRECATED: Use get_template_data() instead. Will be removed in v2.

Use this method to define variables that will be available in the template.

Receives the args and kwargs as they were passed to the Component.

This method has access to the Render API.

Read more about Template variables.

Example:

class MyComponent(Component):\n    def get_context_data(self, name, *args, **kwargs):\n        return {\n            \"name\": name,\n            \"id\": self.id,\n        }\n\n    template = \"Hello, {{ name }}!\"\n\nMyComponent.render(name=\"World\")\n

Warning

get_context_data() and get_template_data() are mutually exclusive.

If both methods return non-empty dictionaries, an error will be raised.

"},{"location":"reference/api/#django_components.Component.get_css_data","title":"get_css_data","text":"
get_css_data(args: Any, kwargs: Any, slots: Any, context: Context) -> Optional[Mapping]\n

See source code

Use this method to define variables that will be available from within the component's CSS code.

This method has access to the Render API.

The data returned from this method will be serialized to string.

Read more about CSS variables.

Example:

class MyComponent(Component):\n    def get_css_data(self, args, kwargs, slots, context):\n        return {\n            \"color\": kwargs[\"color\"],\n        }\n\n    css = '''\n        .my-class {\n            color: var(--color);\n        }\n    '''\n\nMyComponent.render(color=\"red\")\n

Args:

  • args: Positional arguments passed to the component.
  • kwargs: Keyword arguments passed to the component.
  • slots: Slots passed to the component.
  • context: Context used for rendering the component template.

Pass-through kwargs:

It's best practice to explicitly define what args and kwargs a component accepts.

However, if you want a looser setup, you can easily write components that accept any number of kwargs, and pass them all to the CSS code.

To do that, simply return the kwargs dictionary itself from get_css_data():

class MyComponent(Component):\n    def get_css_data(self, args, kwargs, slots, context):\n        return kwargs\n

Type hints:

To get type hints for the args, kwargs, and slots parameters, you can define the Args, Kwargs, and Slots classes on the component class, and then directly reference them in the function signature of get_css_data().

When you set these classes, the args, kwargs, and slots parameters will be given as instances of these (args instance of Args, etc).

When you omit these classes, or set them to None, then the args, kwargs, and slots parameters will be given as plain lists / dictionaries, unmodified.

Read more on Typing and validation.

Example:

from typing import NamedTuple\nfrom django.template import Context\nfrom django_components import Component, SlotInput\n\nclass MyComponent(Component):\n    class Args(NamedTuple):\n        color: str\n\n    class Kwargs(NamedTuple):\n        size: int\n\n    class Slots(NamedTuple):\n        footer: SlotInput\n\n    def get_css_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        assert isinstance(args, MyComponent.Args)\n        assert isinstance(kwargs, MyComponent.Kwargs)\n        assert isinstance(slots, MyComponent.Slots)\n\n        return {\n            \"color\": args.color,\n            \"size\": kwargs.size,\n        }\n

You can also add typing to the data returned from get_css_data() by defining the CssData class on the component class.

When you set this class, you can return either the data as a plain dictionary, or an instance of CssData.

If you return plain dictionary, the data will be validated against the CssData class by instantiating it with the dictionary.

Example:

class MyComponent(Component):\n    class CssData(NamedTuple):\n        color: str\n        size: int\n\n    def get_css_data(self, args, kwargs, slots, context):\n        return {\n            \"color\": kwargs[\"color\"],\n            \"size\": kwargs[\"size\"],\n        }\n        # or\n        return MyComponent.CssData(\n            color=kwargs[\"color\"],\n            size=kwargs[\"size\"],\n        )\n
"},{"location":"reference/api/#django_components.Component.get_js_data","title":"get_js_data","text":"
get_js_data(args: Any, kwargs: Any, slots: Any, context: Context) -> Optional[Mapping]\n

See source code

Use this method to define variables that will be available from within the component's JavaScript code.

This method has access to the Render API.

The data returned from this method will be serialized to JSON.

Read more about JavaScript variables.

Example:

class MyComponent(Component):\n    def get_js_data(self, args, kwargs, slots, context):\n        return {\n            \"name\": kwargs[\"name\"],\n            \"id\": self.id,\n        }\n\n    js = '''\n        $onLoad(({ name, id }) => {\n            console.log(name, id);\n        });\n    '''\n\nMyComponent.render(name=\"World\")\n

Args:

  • args: Positional arguments passed to the component.
  • kwargs: Keyword arguments passed to the component.
  • slots: Slots passed to the component.
  • context: Context used for rendering the component template.

Pass-through kwargs:

It's best practice to explicitly define what args and kwargs a component accepts.

However, if you want a looser setup, you can easily write components that accept any number of kwargs, and pass them all to the JavaScript code.

To do that, simply return the kwargs dictionary itself from get_js_data():

class MyComponent(Component):\n    def get_js_data(self, args, kwargs, slots, context):\n        return kwargs\n

Type hints:

To get type hints for the args, kwargs, and slots parameters, you can define the Args, Kwargs, and Slots classes on the component class, and then directly reference them in the function signature of get_js_data().

When you set these classes, the args, kwargs, and slots parameters will be given as instances of these (args instance of Args, etc).

When you omit these classes, or set them to None, then the args, kwargs, and slots parameters will be given as plain lists / dictionaries, unmodified.

Read more on Typing and validation.

Example:

from typing import NamedTuple\nfrom django.template import Context\nfrom django_components import Component, SlotInput\n\nclass MyComponent(Component):\n    class Args(NamedTuple):\n        color: str\n\n    class Kwargs(NamedTuple):\n        size: int\n\n    class Slots(NamedTuple):\n        footer: SlotInput\n\n    def get_js_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        assert isinstance(args, MyComponent.Args)\n        assert isinstance(kwargs, MyComponent.Kwargs)\n        assert isinstance(slots, MyComponent.Slots)\n\n        return {\n            \"color\": args.color,\n            \"size\": kwargs.size,\n            \"id\": self.id,\n        }\n

You can also add typing to the data returned from get_js_data() by defining the JsData class on the component class.

When you set this class, you can return either the data as a plain dictionary, or an instance of JsData.

If you return plain dictionary, the data will be validated against the JsData class by instantiating it with the dictionary.

Example:

class MyComponent(Component):\n    class JsData(NamedTuple):\n        color: str\n        size: int\n\n    def get_js_data(self, args, kwargs, slots, context):\n        return {\n            \"color\": kwargs[\"color\"],\n            \"size\": kwargs[\"size\"],\n        }\n        # or\n        return MyComponent.JsData(\n            color=kwargs[\"color\"],\n            size=kwargs[\"size\"],\n        )\n
"},{"location":"reference/api/#django_components.Component.get_template","title":"get_template","text":"
get_template(context: Context) -> Optional[Union[str, Template]]\n

See source code

DEPRECATED: Use instead Component.template_file, Component.template or Component.on_render(). Will be removed in v1.

Same as Component.template, but allows to dynamically resolve the template at render time.

The template can be either plain string or a Template instance.

See Component.template for more info and examples.

Warning

Only one of template template_file, get_template_name(), or get_template() must be defined.

Warning

The context is not fully populated at the point when this method is called.

If you need to access the context, either use Component.on_render_before() or Component.on_render().

Parameters:

  • context (Context) \u2013

    The Django template Context in which the component is rendered.

Returns:

  • Optional[Union[str, Template]] \u2013

    Optional[Union[str, Template]]: The inlined Django template string or a Template instance.

"},{"location":"reference/api/#django_components.Component.get_template_data","title":"get_template_data","text":"
get_template_data(args: Any, kwargs: Any, slots: Any, context: Context) -> Optional[Mapping]\n

See source code

Use this method to define variables that will be available in the template.

This method has access to the Render API.

Read more about Template variables.

Example:

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"name\": kwargs[\"name\"],\n            \"id\": self.id,\n        }\n\n    template = \"Hello, {{ name }}!\"\n\nMyComponent.render(name=\"World\")\n

Args:

  • args: Positional arguments passed to the component.
  • kwargs: Keyword arguments passed to the component.
  • slots: Slots passed to the component.
  • context: Context used for rendering the component template.

Pass-through kwargs:

It's best practice to explicitly define what args and kwargs a component accepts.

However, if you want a looser setup, you can easily write components that accept any number of kwargs, and pass them all to the template (similar to django-cotton).

To do that, simply return the kwargs dictionary itself from get_template_data():

class MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return kwargs\n

Type hints:

To get type hints for the args, kwargs, and slots parameters, you can define the Args, Kwargs, and Slots classes on the component class, and then directly reference them in the function signature of get_template_data().

When you set these classes, the args, kwargs, and slots parameters will be given as instances of these (args instance of Args, etc).

When you omit these classes, or set them to None, then the args, kwargs, and slots parameters will be given as plain lists / dictionaries, unmodified.

Read more on Typing and validation.

Example:

from typing import NamedTuple\nfrom django.template import Context\nfrom django_components import Component, SlotInput\n\nclass MyComponent(Component):\n    class Args(NamedTuple):\n        color: str\n\n    class Kwargs(NamedTuple):\n        size: int\n\n    class Slots(NamedTuple):\n        footer: SlotInput\n\n    def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n        assert isinstance(args, MyComponent.Args)\n        assert isinstance(kwargs, MyComponent.Kwargs)\n        assert isinstance(slots, MyComponent.Slots)\n\n        return {\n            \"color\": args.color,\n            \"size\": kwargs.size,\n            \"id\": self.id,\n        }\n

You can also add typing to the data returned from get_template_data() by defining the TemplateData class on the component class.

When you set this class, you can return either the data as a plain dictionary, or an instance of TemplateData.

If you return plain dictionary, the data will be validated against the TemplateData class by instantiating it with the dictionary.

Example:

class MyComponent(Component):\n    class TemplateData(NamedTuple):\n        color: str\n        size: int\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"color\": kwargs[\"color\"],\n            \"size\": kwargs[\"size\"],\n        }\n        # or\n        return MyComponent.TemplateData(\n            color=kwargs[\"color\"],\n            size=kwargs[\"size\"],\n        )\n

Warning

get_template_data() and get_context_data() are mutually exclusive.

If both methods return non-empty dictionaries, an error will be raised.

"},{"location":"reference/api/#django_components.Component.get_template_name","title":"get_template_name","text":"
get_template_name(context: Context) -> Optional[str]\n

See source code

DEPRECATED: Use instead Component.template_file, Component.template or Component.on_render(). Will be removed in v1.

Same as Component.template_file, but allows to dynamically resolve the template name at render time.

See Component.template_file for more info and examples.

Warning

The context is not fully populated at the point when this method is called.

If you need to access the context, either use Component.on_render_before() or Component.on_render().

Warning

Only one of template_file, get_template_name(), template or get_template() must be defined.

Parameters:

  • context (Context) \u2013

    The Django template Context in which the component is rendered.

Returns:

  • Optional[str] \u2013

    Optional[str]: The filepath to the template.

"},{"location":"reference/api/#django_components.Component.inject","title":"inject","text":"
inject(key: str, default: Optional[Any] = None) -> Any\n

See source code

Use this method to retrieve the data that was passed to a {% provide %} tag with the corresponding key.

To retrieve the data, inject() must be called inside a component that's inside the {% provide %} tag.

You may also pass a default that will be used if the {% provide %} tag with given key was NOT found.

This method is part of the Render API, and raises an error if called from outside the rendering execution.

Read more about Provide / Inject.

Example:

Given this template:

{% provide \"my_provide\" message=\"hello\" %}\n    {% component \"my_comp\" / %}\n{% endprovide %}\n

And given this definition of \"my_comp\" component:

from django_components import Component, register\n\n@register(\"my_comp\")\nclass MyComp(Component):\n    template = \"hi {{ message }}!\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        data = self.inject(\"my_provide\")\n        message = data.message\n        return {\"message\": message}\n

This renders into:

hi hello!\n

As the {{ message }} is taken from the \"my_provide\" provider.

"},{"location":"reference/api/#django_components.Component.on_render","title":"on_render","text":"
on_render(context: Context, template: Optional[Template]) -> Union[SlotResult, OnRenderGenerator, None]\n

See source code

This method does the actual rendering.

Read more about this hook in Component hooks.

You can override this method to:

  • Change what template gets rendered
  • Modify the context
  • Modify the rendered output after it has been rendered
  • Handle errors

The default implementation renders the component's Template with the given Context.

class MyTable(Component):\n    def on_render(self, context, template):\n        if template is None:\n            return None\n        else:\n            return template.render(context)\n

The template argument is None if the component has no template.

Modifying rendered template

To change what gets rendered, you can:

  • Render a different template
  • Render a component
  • Return a different string or SafeString
class MyTable(Component):\n    def on_render(self, context, template):\n        return \"Hello\"\n

Post-processing rendered template

To access the final output, you can yield the result instead of returning it.

This will return a tuple of (rendered HTML, error). The error is None if the rendering succeeded.

class MyTable(Component):\n    def on_render(self, context, template):\n        html, error = yield template.render(context)\n\n        if error is None:\n            # The rendering succeeded\n            return html\n        else:\n            # The rendering failed\n            print(f\"Error: {error}\")\n

At this point you can do 3 things:

  1. Return a new HTML

    The new HTML will be used as the final output.

    If the original template raised an error, it will be ignored.

    class MyTable(Component):\n    def on_render(self, context, template):\n        html, error = yield template.render(context)\n\n        return \"NEW HTML\"\n
  2. Raise a new exception

    The new exception is what will bubble up from the component.

    The original HTML and original error will be ignored.

    class MyTable(Component):\n    def on_render(self, context, template):\n        html, error = yield template.render(context)\n\n        raise Exception(\"Error message\")\n
  3. Return nothing (or None) to handle the result as usual

    If you don't raise an exception, and neither return a new HTML, then original HTML / error will be used:

    • If rendering succeeded, the original HTML will be used as the final output.
    • If rendering failed, the original error will be propagated.
    class MyTable(Component):\n    def on_render(self, context, template):\n        html, error = yield template.render(context)\n\n        if error is not None:\n            # The rendering failed\n            print(f\"Error: {error}\")\n
"},{"location":"reference/api/#django_components.Component.on_render_after","title":"on_render_after","text":"
on_render_after(context: Context, template: Optional[Template], result: Optional[str], error: Optional[Exception]) -> Optional[SlotResult]\n

See source code

Hook that runs when the component was fully rendered, including all its children.

It receives the same arguments as on_render_before(), plus the outcome of the rendering:

  • result: The rendered output of the component. None if the rendering failed.
  • error: The error that occurred during the rendering, or None if the rendering succeeded.

on_render_after() behaves the same way as the second part of on_render() (after the yield).

class MyTable(Component):\n    def on_render_after(self, context, template, result, error):\n        if error is None:\n            # The rendering succeeded\n            return result\n        else:\n            # The rendering failed\n            print(f\"Error: {error}\")\n

Same as on_render(), you can return a new HTML, raise a new exception, or return nothing:

  1. Return a new HTML

    The new HTML will be used as the final output.

    If the original template raised an error, it will be ignored.

    class MyTable(Component):\n    def on_render_after(self, context, template, result, error):\n        return \"NEW HTML\"\n
  2. Raise a new exception

    The new exception is what will bubble up from the component.

    The original HTML and original error will be ignored.

    class MyTable(Component):\n    def on_render_after(self, context, template, result, error):\n        raise Exception(\"Error message\")\n
  3. Return nothing (or None) to handle the result as usual

    If you don't raise an exception, and neither return a new HTML, then original HTML / error will be used:

    • If rendering succeeded, the original HTML will be used as the final output.
    • If rendering failed, the original error will be propagated.
    class MyTable(Component):\n    def on_render_after(self, context, template, result, error):\n        if error is not None:\n            # The rendering failed\n            print(f\"Error: {error}\")\n
"},{"location":"reference/api/#django_components.Component.on_render_before","title":"on_render_before","text":"
on_render_before(context: Context, template: Optional[Template]) -> None\n

See source code

Runs just before the component's template is rendered.

It is called for every component, including nested ones, as part of the component render lifecycle.

Parameters:

  • context (Context) \u2013

    The Django Context that will be used to render the component's template.

  • template (Optional[Template]) \u2013

    The Django Template instance that will be rendered, or None if no template.

Returns:

  • None \u2013

    None. This hook is for side effects only.

Example:

You can use this hook to access the context or the template:

from django.template import Context, Template\nfrom django_components import Component\n\nclass MyTable(Component):\n    def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n        # Insert value into the Context\n        context[\"from_on_before\"] = \":)\"\n\n        assert isinstance(template, Template)\n

Warning

If you want to pass data to the template, prefer using get_template_data() instead of this hook.

Warning

Do NOT modify the template in this hook. The template is reused across renders.

Since this hook is called for every component, this means that the template would be modified every time a component is rendered.

"},{"location":"reference/api/#django_components.Component.render","title":"render classmethod","text":"
render(\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    args: Optional[Any] = None,\n    kwargs: Optional[Any] = None,\n    slots: Optional[Any] = None,\n    deps_strategy: DependenciesStrategy = \"document\",\n    type: Optional[DependenciesStrategy] = None,\n    render_dependencies: bool = True,\n    request: Optional[HttpRequest] = None,\n    outer_context: Optional[Context] = None,\n    registry: Optional[ComponentRegistry] = None,\n    registered_name: Optional[str] = None,\n    node: Optional[ComponentNode] = None,\n) -> str\n

See source code

Render the component into a string. This is the equivalent of calling the {% component %} tag.

Button.render(\n    args=[\"John\"],\n    kwargs={\n        \"surname\": \"Doe\",\n        \"age\": 30,\n    },\n    slots={\n        \"footer\": \"i AM A SLOT\",\n    },\n)\n

Inputs:

  • args - Optional. A list of positional args for the component. This is the same as calling the component as:

    {% component \"button\" arg1 arg2 ... %}\n
  • kwargs - Optional. A dictionary of keyword arguments for the component. This is the same as calling the component as:

    {% component \"button\" key1=val1 key2=val2 ... %}\n
  • slots - Optional. A dictionary of slot fills. This is the same as passing {% fill %} tags to the component.

    {% component \"button\" %}\n    {% fill \"content\" %}\n        Click me!\n    {% endfill %}\n{% endcomponent %}\n

    Dictionary keys are the slot names. Dictionary values are the slot fills.

    Slot fills can be strings, render functions, or Slot instances:

    Button.render(\n    slots={\n        \"content\": \"Click me!\"\n        \"content2\": lambda ctx: \"Click me!\",\n        \"content3\": Slot(lambda ctx: \"Click me!\"),\n    },\n)\n
  • context - Optional. Plain dictionary or Django's Context. The context within which the component is rendered.

    When a component is rendered within a template with the {% component %} tag, this will be set to the Context instance that is used for rendering the template.

    When you call Component.render() directly from Python, you can ignore this input most of the time. Instead use args, kwargs, and slots to pass data to the component.

    You can pass RequestContext to the context argument, so that the component will gain access to the request object and will use context processors. Read more on Working with HTTP requests.

    Button.render(\n    context=RequestContext(request),\n)\n

    For advanced use cases, you can use context argument to \"pre-render\" the component in Python, and then pass the rendered output as plain string to the template. With this, the inner component is rendered as if it was within the template with {% component %}.

    class Button(Component):\n    def render(self, context, template):\n        # Pass `context` to Icon component so it is rendered\n        # as if nested within Button.\n        icon = Icon.render(\n            context=context,\n            args=[\"icon-name\"],\n            deps_strategy=\"ignore\",\n        )\n        # Update context with icon\n        with context.update({\"icon\": icon}):\n            return template.render(context)\n

    Whether the variables defined in context are available to the template depends on the context behavior mode:

    • In \"django\" context behavior mode, the template will have access to the keys of this context.

    • In \"isolated\" context behavior mode, the template will NOT have access to this context, and data MUST be passed via component's args and kwargs.

  • deps_strategy - Optional. Configure how to handle JS and CSS dependencies. Read more about Dependencies rendering.

    There are six strategies:

    • \"document\" (default)
      • Smartly inserts JS / CSS into placeholders or into <head> and <body> tags.
      • Inserts extra script to allow fragment types to work.
      • Assumes the HTML will be rendered in a JS-enabled browser.
    • \"fragment\"
      • A lightweight HTML fragment to be inserted into a document with AJAX.
      • No JS / CSS included.
    • \"simple\"
      • Smartly insert JS / CSS into placeholders or into <head> and <body> tags.
      • No extra script loaded.
    • \"prepend\"
      • Insert JS / CSS before the rendered HTML.
      • No extra script loaded.
    • \"append\"
      • Insert JS / CSS after the rendered HTML.
      • No extra script loaded.
    • \"ignore\"
      • HTML is left as-is. You can still process it with a different strategy later with render_dependencies().
      • Used for inserting rendered HTML into other components.
  • request - Optional. HTTPRequest object. Pass a request object directly to the component to apply context processors.

    Read more about Working with HTTP requests.

Type hints:

Component.render() is NOT typed. To add type hints, you can wrap the inputs in component's Args, Kwargs, and Slots classes.

Read more on Typing and validation.

from typing import NamedTuple, Optional\nfrom django_components import Component, Slot, SlotInput\n\n# Define the component with the types\nclass Button(Component):\n    class Args(NamedTuple):\n        name: str\n\n    class Kwargs(NamedTuple):\n        surname: str\n        age: int\n\n    class Slots(NamedTuple):\n        my_slot: Optional[SlotInput] = None\n        footer: SlotInput\n\n# Add type hints to the render call\nButton.render(\n    args=Button.Args(\n        name=\"John\",\n    ),\n    kwargs=Button.Kwargs(\n        surname=\"Doe\",\n        age=30,\n    ),\n    slots=Button.Slots(\n        footer=Slot(lambda ctx: \"Click me!\"),\n    ),\n)\n
"},{"location":"reference/api/#django_components.Component.render_to_response","title":"render_to_response classmethod","text":"
render_to_response(\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    args: Optional[Any] = None,\n    kwargs: Optional[Any] = None,\n    slots: Optional[Any] = None,\n    deps_strategy: DependenciesStrategy = \"document\",\n    type: Optional[DependenciesStrategy] = None,\n    render_dependencies: bool = True,\n    request: Optional[HttpRequest] = None,\n    outer_context: Optional[Context] = None,\n    registry: Optional[ComponentRegistry] = None,\n    registered_name: Optional[str] = None,\n    node: Optional[ComponentNode] = None,\n    **response_kwargs: Any\n) -> HttpResponse\n

See source code

Render the component and wrap the content in an HTTP response class.

render_to_response() takes the same inputs as Component.render(). See that method for more information.

After the component is rendered, the HTTP response class is instantiated with the rendered content.

Any additional kwargs are passed to the response class.

Example:

Button.render_to_response(\n    args=[\"John\"],\n    kwargs={\n        \"surname\": \"Doe\",\n        \"age\": 30,\n    },\n    slots={\n        \"footer\": \"i AM A SLOT\",\n    },\n    # HttpResponse kwargs\n    status=201,\n    headers={...},\n)\n# HttpResponse(content=..., status=201, headers=...)\n

Custom response class:

You can set a custom response class on the component via Component.response_class. Defaults to django.http.HttpResponse.

from django.http import HttpResponse\nfrom django_components import Component\n\nclass MyHttpResponse(HttpResponse):\n    ...\n\nclass MyComponent(Component):\n    response_class = MyHttpResponse\n\nresponse = MyComponent.render_to_response()\nassert isinstance(response, MyHttpResponse)\n
"},{"location":"reference/api/#django_components.ComponentCache","title":"ComponentCache","text":"
ComponentCache(component: Component)\n

Bases: django_components.extension.ExtensionComponentConfig

See source code

The interface for Component.Cache.

The fields of this class are used to configure the component caching.

Read more about Component caching.

Example:

from django_components import Component\n\nclass MyComponent(Component):\n    class Cache:\n        enabled = True\n        ttl = 60 * 60 * 24  # 1 day\n        cache_name = \"my_cache\"\n

Methods:

  • get_cache \u2013
  • get_cache_key \u2013
  • get_entry \u2013
  • hash \u2013
  • hash_slots \u2013
  • set_entry \u2013

Attributes:

  • cache_name (Optional[str]) \u2013
  • component (Component) \u2013
  • component_class (Type[Component]) \u2013
  • component_cls (Type[Component]) \u2013
  • enabled (bool) \u2013
  • include_slots (bool) \u2013
  • ttl (Optional[int]) \u2013
"},{"location":"reference/api/#django_components.ComponentCache.cache_name","title":"cache_name class-attribute instance-attribute","text":"
cache_name: Optional[str] = None\n

See source code

The name of the cache to use. If None, the default cache will be used.

"},{"location":"reference/api/#django_components.ComponentCache.component","title":"component instance-attribute","text":"
component: Component = component\n

See source code

See source code

When a Component is instantiated, also the nested extension classes (such as Component.View) are instantiated, receiving the component instance as an argument.

This attribute holds the owner Component instance that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentCache.component_class","title":"component_class instance-attribute","text":"
component_class: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentCache.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentCache.enabled","title":"enabled class-attribute instance-attribute","text":"
enabled: bool = False\n

See source code

Whether this Component should be cached. Defaults to False.

"},{"location":"reference/api/#django_components.ComponentCache.include_slots","title":"include_slots class-attribute instance-attribute","text":"
include_slots: bool = False\n

See source code

Whether the slots should be hashed into the cache key.

If enabled, the following two cases will be treated as different entries:

{% component \"mycomponent\" name=\"foo\" %}\n    FILL ONE\n{% endcomponent %}\n\n{% component \"mycomponent\" name=\"foo\" %}\n    FILL TWO\n{% endcomponent %}\n

Warning

Passing slots as functions to cached components with include_slots=True will raise an error.

Warning

Slot caching DOES NOT account for context variables within the {% fill %} tag.

For example, the following two cases will be treated as the same entry:

{% with my_var=\"foo\" %}\n    {% component \"mycomponent\" name=\"foo\" %}\n        {{ my_var }}\n    {% endcomponent %}\n{% endwith %}\n\n{% with my_var=\"bar\" %}\n    {% component \"mycomponent\" name=\"bar\" %}\n        {{ my_var }}\n    {% endcomponent %}\n{% endwith %}\n

Currently it's impossible to capture used variables. This will be addressed in v2. Read more about it in https://github.com/django-components/django-components/issues/1164.

"},{"location":"reference/api/#django_components.ComponentCache.ttl","title":"ttl class-attribute instance-attribute","text":"
ttl: Optional[int] = None\n

See source code

The time-to-live (TTL) in seconds, i.e. for how long should an entry be valid in the cache.

  • If > 0, the entries will be cached for the given number of seconds.
  • If -1, the entries will be cached indefinitely.
  • If 0, the entries won't be cached.
  • If None, the default TTL will be used.
"},{"location":"reference/api/#django_components.ComponentCache.get_cache","title":"get_cache","text":"
get_cache() -> BaseCache\n
"},{"location":"reference/api/#django_components.ComponentCache.get_cache_key","title":"get_cache_key","text":"
get_cache_key(args: List, kwargs: Dict, slots: Dict) -> str\n
"},{"location":"reference/api/#django_components.ComponentCache.get_entry","title":"get_entry","text":"
get_entry(cache_key: str) -> Any\n
"},{"location":"reference/api/#django_components.ComponentCache.hash","title":"hash","text":"
hash(args: List, kwargs: Dict) -> str\n

See source code

Defines how the input (both args and kwargs) is hashed into a cache key.

By default, hash() serializes the input into a string. As such, the default implementation might NOT be suitable if you need to hash complex objects.

"},{"location":"reference/api/#django_components.ComponentCache.hash_slots","title":"hash_slots","text":"
hash_slots(slots: Dict[str, Slot]) -> str\n
"},{"location":"reference/api/#django_components.ComponentCache.set_entry","title":"set_entry","text":"
set_entry(cache_key: str, value: Any) -> None\n
"},{"location":"reference/api/#django_components.ComponentDebugHighlight","title":"ComponentDebugHighlight","text":"
ComponentDebugHighlight(component: Component)\n

Bases: django_components.extension.ExtensionComponentConfig

See source code

The interface for Component.DebugHighlight.

The fields of this class are used to configure the component debug highlighting for this component and its direct slots.

Read more about Component debug highlighting.

Example:

from django_components import Component\n\nclass MyComponent(Component):\n    class DebugHighlight:\n        highlight_components = True\n        highlight_slots = True\n

To highlight ALL components and slots, set extension defaults in your settings:

from django_components import ComponentsSettings\n\nCOMPONENTS = ComponentsSettings(\n    extensions_defaults={\n        \"debug_highlight\": {\n            \"highlight_components\": True,\n            \"highlight_slots\": True,\n        },\n    },\n)\n

Attributes:

  • component (Component) \u2013
  • component_class (Type[Component]) \u2013
  • component_cls (Type[Component]) \u2013
  • highlight_components \u2013
  • highlight_slots \u2013
"},{"location":"reference/api/#django_components.ComponentDebugHighlight.component","title":"component instance-attribute","text":"
component: Component = component\n

See source code

See source code

When a Component is instantiated, also the nested extension classes (such as Component.View) are instantiated, receiving the component instance as an argument.

This attribute holds the owner Component instance that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentDebugHighlight.component_class","title":"component_class instance-attribute","text":"
component_class: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentDebugHighlight.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentDebugHighlight.highlight_components","title":"highlight_components class-attribute instance-attribute","text":"
highlight_components = HighlightComponentsDescriptor()\n

See source code

Whether to highlight this component in the rendered output.

"},{"location":"reference/api/#django_components.ComponentDebugHighlight.highlight_slots","title":"highlight_slots class-attribute instance-attribute","text":"
highlight_slots = HighlightSlotsDescriptor()\n

See source code

Whether to highlight slots of this component in the rendered output.

"},{"location":"reference/api/#django_components.ComponentDefaults","title":"ComponentDefaults","text":"
ComponentDefaults(component: Component)\n

Bases: django_components.extension.ExtensionComponentConfig

See source code

The interface for Component.Defaults.

The fields of this class are used to set default values for the component's kwargs.

Read more about Component defaults.

Example:

from django_components import Component, Default\n\nclass MyComponent(Component):\n    class Defaults:\n        position = \"left\"\n        selected_items = Default(lambda: [1, 2, 3])\n

Attributes:

  • component (Component) \u2013
  • component_class (Type[Component]) \u2013
  • component_cls (Type[Component]) \u2013
"},{"location":"reference/api/#django_components.ComponentDefaults.component","title":"component instance-attribute","text":"
component: Component = component\n

See source code

See source code

When a Component is instantiated, also the nested extension classes (such as Component.View) are instantiated, receiving the component instance as an argument.

This attribute holds the owner Component instance that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentDefaults.component_class","title":"component_class instance-attribute","text":"
component_class: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentDefaults.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentExtension","title":"ComponentExtension","text":"

Bases: object

See source code

Base class for all extensions.

Read more on Extensions.

Example:

class ExampleExtension(ComponentExtension):\n    name = \"example\"\n\n    # Component-level behavior and settings. User will be able to override\n    # the attributes and methods defined here on the component classes.\n    class ComponentConfig(ComponentExtension.ComponentConfig):\n        foo = \"1\"\n        bar = \"2\"\n\n        def baz(cls):\n            return \"3\"\n\n    # URLs\n    urls = [\n        URLRoute(path=\"dummy-view/\", handler=dummy_view, name=\"dummy\"),\n        URLRoute(path=\"dummy-view-2/<int:id>/<str:name>/\", handler=dummy_view_2, name=\"dummy-2\"),\n    ]\n\n    # Commands\n    commands = [\n        HelloWorldCommand,\n    ]\n\n    # Hooks\n    def on_component_class_created(self, ctx: OnComponentClassCreatedContext) -> None:\n        print(ctx.component_cls.__name__)\n\n    def on_component_class_deleted(self, ctx: OnComponentClassDeletedContext) -> None:\n        print(ctx.component_cls.__name__)\n

Which users then can override on a per-component basis. E.g.:

class MyComp(Component):\n    class Example:\n        foo = \"overridden\"\n\n        def baz(self):\n            return \"overridden baz\"\n

Methods:

  • on_component_class_created \u2013
  • on_component_class_deleted \u2013
  • on_component_data \u2013
  • on_component_input \u2013
  • on_component_registered \u2013
  • on_component_rendered \u2013
  • on_component_unregistered \u2013
  • on_css_loaded \u2013
  • on_js_loaded \u2013
  • on_registry_created \u2013
  • on_registry_deleted \u2013
  • on_slot_rendered \u2013
  • on_template_compiled \u2013
  • on_template_loaded \u2013

Attributes:

  • ComponentConfig (Type[ExtensionComponentConfig]) \u2013
  • class_name (str) \u2013
  • commands (List[Type[ComponentCommand]]) \u2013
  • name (str) \u2013
  • urls (List[URLRoute]) \u2013
"},{"location":"reference/api/#django_components.ComponentExtension.ComponentConfig","title":"ComponentConfig class-attribute","text":"
ComponentConfig: Type[ExtensionComponentConfig] = ExtensionComponentConfig\n

See source code

Base class that the \"component-level\" extension config nested within a Component class will inherit from.

This is where you can define new methods and attributes that will be available to the component instance.

Background:

The extension may add new features to the Component class by allowing users to define and access a nested class in the Component class. E.g.:

class MyComp(Component):\n    class MyExtension:\n        ...\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"my_extension\": self.my_extension.do_something(),\n        }\n

When rendering a component, the nested extension class will be set as a subclass of ComponentConfig. So it will be same as if the user had directly inherited from extension's ComponentConfig. E.g.:

class MyComp(Component):\n    class MyExtension(ComponentExtension.ComponentConfig):\n        ...\n

This setting decides what the extension class will inherit from.

"},{"location":"reference/api/#django_components.ComponentExtension.class_name","title":"class_name class-attribute","text":"
class_name: str\n

See source code

Name of the extension class.

By default, this is set automatically at class creation. The class name is the same as the name attribute, but with snake_case converted to PascalCase.

So if the extension name is \"my_extension\", then the extension class name will be \"MyExtension\".

class MyComp(Component):\n    class MyExtension:  # <--- This is the extension class\n        ...\n

To customize the class name, you can manually set the class_name attribute.

The class name must be a valid Python identifier.

Example:

class MyExt(ComponentExtension):\n    name = \"my_extension\"\n    class_name = \"MyCustomExtension\"\n

This will make the extension class name \"MyCustomExtension\".

class MyComp(Component):\n    class MyCustomExtension:  # <--- This is the extension class\n        ...\n
"},{"location":"reference/api/#django_components.ComponentExtension.commands","title":"commands class-attribute","text":"
commands: List[Type[ComponentCommand]] = []\n

See source code

List of commands that can be run by the extension.

These commands will be available to the user as components ext run <extension> <command>.

Commands are defined as subclasses of ComponentCommand.

Example:

This example defines an extension with a command that prints \"Hello world\". To run the command, the user would run components ext run hello_world hello.

from django_components import ComponentCommand, ComponentExtension, CommandArg, CommandArgGroup\n\nclass HelloWorldCommand(ComponentCommand):\n    name = \"hello\"\n    help = \"Hello world command.\"\n\n    # Allow to pass flags `--foo`, `--bar` and `--baz`.\n    # Argument parsing is managed by `argparse`.\n    arguments = [\n        CommandArg(\n            name_or_flags=\"--foo\",\n            help=\"Foo description.\",\n        ),\n        # When printing the command help message, `bar` and `baz`\n        # will be grouped under \"group bar\".\n        CommandArgGroup(\n            title=\"group bar\",\n            description=\"Group description.\",\n            arguments=[\n                CommandArg(\n                    name_or_flags=\"--bar\",\n                    help=\"Bar description.\",\n                ),\n                CommandArg(\n                    name_or_flags=\"--baz\",\n                    help=\"Baz description.\",\n                ),\n            ],\n        ),\n    ]\n\n    # Callback that receives the parsed arguments and options.\n    def handle(self, *args, **kwargs):\n        print(f\"HelloWorldCommand.handle: args={args}, kwargs={kwargs}\")\n\n# Associate the command with the extension\nclass HelloWorldExtension(ComponentExtension):\n    name = \"hello_world\"\n\n    commands = [\n        HelloWorldCommand,\n    ]\n
"},{"location":"reference/api/#django_components.ComponentExtension.name","title":"name class-attribute","text":"
name: str\n

See source code

Name of the extension.

Name must be lowercase, and must be a valid Python identifier (e.g. \"my_extension\").

The extension may add new features to the Component class by allowing users to define and access a nested class in the Component class.

The extension name determines the name of the nested class in the Component class, and the attribute under which the extension will be accessible.

E.g. if the extension name is \"my_extension\", then the nested class in the Component class will be MyExtension, and the extension will be accessible as MyComp.my_extension.

class MyComp(Component):\n    class MyExtension:\n        ...\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"my_extension\": self.my_extension.do_something(),\n        }\n

Info

The extension class name can be customized by setting the class_name attribute.

"},{"location":"reference/api/#django_components.ComponentExtension.urls","title":"urls class-attribute","text":"
urls: List[URLRoute] = []\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_component_class_created","title":"on_component_class_created","text":"
on_component_class_created(ctx: OnComponentClassCreatedContext) -> None\n

See source code

Called when a new Component class is created.

This hook is called after the Component class is fully defined but before it's registered.

Use this hook to perform any initialization or validation of the Component class.

Example:

from django_components import ComponentExtension, OnComponentClassCreatedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_class_created(self, ctx: OnComponentClassCreatedContext) -> None:\n        # Add a new attribute to the Component class\n        ctx.component_cls.my_attr = \"my_value\"\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_component_class_deleted","title":"on_component_class_deleted","text":"
on_component_class_deleted(ctx: OnComponentClassDeletedContext) -> None\n

See source code

Called when a Component class is being deleted.

This hook is called before the Component class is deleted from memory.

Use this hook to perform any cleanup related to the Component class.

Example:

from django_components import ComponentExtension, OnComponentClassDeletedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_class_deleted(self, ctx: OnComponentClassDeletedContext) -> None:\n        # Remove Component class from the extension's cache on deletion\n        self.cache.pop(ctx.component_cls, None)\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_component_data","title":"on_component_data","text":"
on_component_data(ctx: OnComponentDataContext) -> None\n

See source code

Called when a Component was triggered to render, after a component's context and data methods have been processed.

This hook is called after Component.get_template_data(), Component.get_js_data() and Component.get_css_data().

This hook runs after on_component_input.

Use this hook to modify or validate the component's data before rendering.

Example:

from django_components import ComponentExtension, OnComponentDataContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_data(self, ctx: OnComponentDataContext) -> None:\n        # Add extra template variable to all components when they are rendered\n        ctx.template_data[\"my_template_var\"] = \"my_value\"\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_component_input","title":"on_component_input","text":"
on_component_input(ctx: OnComponentInputContext) -> Optional[str]\n

See source code

Called when a Component was triggered to render, but before a component's context and data methods are invoked.

Use this hook to modify or validate component inputs before they're processed.

This is the first hook that is called when rendering a component. As such this hook is called before Component.get_template_data(), Component.get_js_data(), and Component.get_css_data() methods, and the on_component_data hook.

This hook also allows to skip the rendering of a component altogether. If the hook returns a non-null value, this value will be used instead of rendering the component.

You can use this to implement a caching mechanism for components, or define components that will be rendered conditionally.

Example:

from django_components import ComponentExtension, OnComponentInputContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_input(self, ctx: OnComponentInputContext) -> None:\n        # Add extra kwarg to all components when they are rendered\n        ctx.kwargs[\"my_input\"] = \"my_value\"\n

Warning

In this hook, the components' inputs are still mutable.

As such, if a component defines Args, Kwargs, Slots types, these types are NOT yet instantiated.

Instead, component fields like Component.args, Component.kwargs, Component.slots are plain list / dict objects.

"},{"location":"reference/api/#django_components.ComponentExtension.on_component_registered","title":"on_component_registered","text":"
on_component_registered(ctx: OnComponentRegisteredContext) -> None\n

See source code

Called when a Component class is registered with a ComponentRegistry.

This hook is called after a Component class is successfully registered.

Example:

from django_components import ComponentExtension, OnComponentRegisteredContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_registered(self, ctx: OnComponentRegisteredContext) -> None:\n        print(f\"Component {ctx.component_cls} registered to {ctx.registry} as '{ctx.name}'\")\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_component_rendered","title":"on_component_rendered","text":"
on_component_rendered(ctx: OnComponentRenderedContext) -> Optional[str]\n

See source code

Called when a Component was rendered, including all its child components.

Use this hook to access or post-process the component's rendered output.

This hook works similarly to Component.on_render_after():

  1. To modify the output, return a new string from this hook. The original output or error will be ignored.

  2. To cause this component to return a new error, raise that error. The original output and error will be ignored.

  3. If you neither raise nor return string, the original output or error will be used.

Examples:

Change the final output of a component:

from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n        # Append a comment to the component's rendered output\n        return ctx.result + \"<!-- MyExtension comment -->\"\n

Cause the component to raise a new exception:

from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n        # Raise a new exception\n        raise Exception(\"Error message\")\n

Return nothing (or None) to handle the result as usual:

from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n        if ctx.error is not None:\n            # The component raised an exception\n            print(f\"Error: {ctx.error}\")\n        else:\n            # The component rendered successfully\n            print(f\"Result: {ctx.result}\")\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_component_unregistered","title":"on_component_unregistered","text":"
on_component_unregistered(ctx: OnComponentUnregisteredContext) -> None\n

See source code

Called when a Component class is unregistered from a ComponentRegistry.

This hook is called after a Component class is removed from the registry.

Example:

from django_components import ComponentExtension, OnComponentUnregisteredContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_unregistered(self, ctx: OnComponentUnregisteredContext) -> None:\n        print(f\"Component {ctx.component_cls} unregistered from {ctx.registry} as '{ctx.name}'\")\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_css_loaded","title":"on_css_loaded","text":"
on_css_loaded(ctx: OnCssLoadedContext) -> Optional[str]\n

See source code

Called when a Component's CSS is loaded as a string.

This hook runs only once per Component class and works for both Component.css and Component.css_file.

Use this hook to read or modify the CSS.

To modify the CSS, return a new string from this hook.

Example:

from django_components import ComponentExtension, OnCssLoadedContext\n\nclass MyExtension(ComponentExtension):\n    def on_css_loaded(self, ctx: OnCssLoadedContext) -> Optional[str]:\n        # Modify the CSS\n        return ctx.content.replace(\"Hello\", \"Hi\")\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_js_loaded","title":"on_js_loaded","text":"
on_js_loaded(ctx: OnJsLoadedContext) -> Optional[str]\n

See source code

Called when a Component's JS is loaded as a string.

This hook runs only once per Component class and works for both Component.js and Component.js_file.

Use this hook to read or modify the JS.

To modify the JS, return a new string from this hook.

Example:

from django_components import ComponentExtension, OnCssLoadedContext\n\nclass MyExtension(ComponentExtension):\n    def on_js_loaded(self, ctx: OnJsLoadedContext) -> Optional[str]:\n        # Modify the JS\n        return ctx.content.replace(\"Hello\", \"Hi\")\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_registry_created","title":"on_registry_created","text":"
on_registry_created(ctx: OnRegistryCreatedContext) -> None\n

See source code

Called when a new ComponentRegistry is created.

This hook is called after a new ComponentRegistry instance is initialized.

Use this hook to perform any initialization needed for the registry.

Example:

from django_components import ComponentExtension, OnRegistryCreatedContext\n\nclass MyExtension(ComponentExtension):\n    def on_registry_created(self, ctx: OnRegistryCreatedContext) -> None:\n        # Add a new attribute to the registry\n        ctx.registry.my_attr = \"my_value\"\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_registry_deleted","title":"on_registry_deleted","text":"
on_registry_deleted(ctx: OnRegistryDeletedContext) -> None\n

See source code

Called when a ComponentRegistry is being deleted.

This hook is called before a ComponentRegistry instance is deleted.

Use this hook to perform any cleanup related to the registry.

Example:

from django_components import ComponentExtension, OnRegistryDeletedContext\n\nclass MyExtension(ComponentExtension):\n    def on_registry_deleted(self, ctx: OnRegistryDeletedContext) -> None:\n        # Remove registry from the extension's cache on deletion\n        self.cache.pop(ctx.registry, None)\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_slot_rendered","title":"on_slot_rendered","text":"
on_slot_rendered(ctx: OnSlotRenderedContext) -> Optional[str]\n

See source code

Called when a {% slot %} tag was rendered.

Use this hook to access or post-process the slot's rendered output.

To modify the output, return a new string from this hook.

Example:

from django_components import ComponentExtension, OnSlotRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_slot_rendered(self, ctx: OnSlotRenderedContext) -> Optional[str]:\n        # Append a comment to the slot's rendered output\n        return ctx.result + \"<!-- MyExtension comment -->\"\n

Access slot metadata:

You can access the {% slot %} tag node (SlotNode) and its metadata using ctx.slot_node.

For example, to find the Component class to which belongs the template where the {% slot %} tag is defined, you can use ctx.slot_node.template_component:

from django_components import ComponentExtension, OnSlotRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_slot_rendered(self, ctx: OnSlotRenderedContext) -> Optional[str]:\n        # Access slot metadata\n        slot_node = ctx.slot_node\n        slot_owner = slot_node.template_component\n        print(f\"Slot owner: {slot_owner}\")\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_template_compiled","title":"on_template_compiled","text":"
on_template_compiled(ctx: OnTemplateCompiledContext) -> None\n

See source code

Called when a Component's template is compiled into a Template object.

This hook runs only once per Component class and works for both Component.template and Component.template_file.

Use this hook to read or modify the template (in-place) after it's compiled.

Example:

from django_components import ComponentExtension, OnTemplateCompiledContext\n\nclass MyExtension(ComponentExtension):\n    def on_template_compiled(self, ctx: OnTemplateCompiledContext) -> None:\n        print(f\"Template origin: {ctx.template.origin.name}\")\n
"},{"location":"reference/api/#django_components.ComponentExtension.on_template_loaded","title":"on_template_loaded","text":"
on_template_loaded(ctx: OnTemplateLoadedContext) -> Optional[str]\n

See source code

Called when a Component's template is loaded as a string.

This hook runs only once per Component class and works for both Component.template and Component.template_file.

Use this hook to read or modify the template before it's compiled.

To modify the template, return a new string from this hook.

Example:

from django_components import ComponentExtension, OnTemplateLoadedContext\n\nclass MyExtension(ComponentExtension):\n    def on_template_loaded(self, ctx: OnTemplateLoadedContext) -> Optional[str]:\n        # Modify the template\n        return ctx.content.replace(\"Hello\", \"Hi\")\n
"},{"location":"reference/api/#django_components.ComponentFileEntry","title":"ComponentFileEntry","text":"

Bases: tuple

See source code

Result returned by get_component_files().

Attributes:

  • dot_path (str) \u2013
  • filepath (Path) \u2013
"},{"location":"reference/api/#django_components.ComponentFileEntry.dot_path","title":"dot_path instance-attribute","text":"
dot_path: str\n

See source code

The python import path for the module. E.g. app.components.mycomp

"},{"location":"reference/api/#django_components.ComponentFileEntry.filepath","title":"filepath instance-attribute","text":"
filepath: Path\n

See source code

The filesystem path to the module. E.g. /path/to/project/app/components/mycomp.py

"},{"location":"reference/api/#django_components.ComponentInput","title":"ComponentInput dataclass","text":"
ComponentInput(\n    context: Context,\n    args: List,\n    kwargs: Dict,\n    slots: Dict[SlotName, Slot],\n    deps_strategy: DependenciesStrategy,\n    type: DependenciesStrategy,\n    render_dependencies: bool,\n)\n

Bases: object

See source code

Deprecated. Will be removed in v1.

Object holding the inputs that were passed to Component.render() or the {% component %} template tag.

This object is available only during render under Component.input.

Read more about the Render API.

Attributes:

  • args (List) \u2013
  • context (Context) \u2013
  • deps_strategy (DependenciesStrategy) \u2013
  • kwargs (Dict) \u2013
  • render_dependencies (bool) \u2013
  • slots (Dict[SlotName, Slot]) \u2013
  • type (DependenciesStrategy) \u2013
"},{"location":"reference/api/#django_components.ComponentInput.args","title":"args instance-attribute","text":"
args: List\n

See source code

Positional arguments (as list) passed to Component.render()

"},{"location":"reference/api/#django_components.ComponentInput.context","title":"context instance-attribute","text":"
context: Context\n

See source code

Django's Context passed to Component.render()

"},{"location":"reference/api/#django_components.ComponentInput.deps_strategy","title":"deps_strategy instance-attribute","text":"
deps_strategy: DependenciesStrategy\n

See source code

Dependencies strategy passed to Component.render()

"},{"location":"reference/api/#django_components.ComponentInput.kwargs","title":"kwargs instance-attribute","text":"
kwargs: Dict\n

See source code

Keyword arguments (as dict) passed to Component.render()

"},{"location":"reference/api/#django_components.ComponentInput.render_dependencies","title":"render_dependencies instance-attribute","text":"
render_dependencies: bool\n

See source code

Deprecated. Will be removed in v1. Use deps_strategy=\"ignore\" instead.

"},{"location":"reference/api/#django_components.ComponentInput.slots","title":"slots instance-attribute","text":"
slots: Dict[SlotName, Slot]\n

See source code

Slots (as dict) passed to Component.render()

"},{"location":"reference/api/#django_components.ComponentInput.type","title":"type instance-attribute","text":"
type: DependenciesStrategy\n

See source code

Deprecated. Will be removed in v1. Use deps_strategy instead.

"},{"location":"reference/api/#django_components.ComponentMediaInput","title":"ComponentMediaInput","text":"

Bases: typing.Protocol

See source code

Defines JS and CSS media files associated with a Component.

class MyTable(Component):\n    class Media:\n        js = [\n            \"path/to/script.js\",\n            \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\",  # AlpineJS\n        ]\n        css = {\n            \"all\": [\n                \"path/to/style.css\",\n                \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\",  # TailwindCSS\n            ],\n            \"print\": [\"path/to/style2.css\"],\n        }\n

Attributes:

  • css (Optional[Union[ComponentMediaInputPath, List[ComponentMediaInputPath], Dict[str, ComponentMediaInputPath], Dict[str, List[ComponentMediaInputPath]]]]) \u2013
  • extend (Union[bool, List[Type[Component]]]) \u2013
  • js (Optional[Union[ComponentMediaInputPath, List[ComponentMediaInputPath]]]) \u2013
"},{"location":"reference/api/#django_components.ComponentMediaInput.css","title":"css class-attribute instance-attribute","text":"
css: Optional[\n    Union[\n        ComponentMediaInputPath, List[ComponentMediaInputPath], Dict[str, ComponentMediaInputPath], Dict[str, List[ComponentMediaInputPath]]\n    ]\n] = None\n

See source code

CSS files associated with a Component.

  • If a string, it's assumed to be a path to a CSS file.

  • If a list, each entry is assumed to be a path to a CSS file.

  • If a dict, the keys are media types (e.g. \"all\", \"print\", \"screen\", etc.), and the values are either:

    • A string, assumed to be a path to a CSS file.
    • A list, each entry is assumed to be a path to a CSS file.

Each entry can be a string, bytes, SafeString, PathLike, or a callable that returns one of the former (see ComponentMediaInputPath).

Examples:

class MyComponent(Component):\n    class Media:\n        css = \"path/to/style.css\"\n

class MyComponent(Component):\n    class Media:\n        css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n
class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": \"path/to/style.css\",\n            \"print\": \"path/to/print.css\",\n        }\n
class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": [\"path/to/style1.css\", \"path/to/style2.css\"],\n            \"print\": \"path/to/print.css\",\n        }\n
"},{"location":"reference/api/#django_components.ComponentMediaInput.extend","title":"extend class-attribute instance-attribute","text":"
extend: Union[bool, List[Type[Component]]] = True\n

See source code

Configures whether the component should inherit the media files from the parent component.

  • If True, the component inherits the media files from the parent component.
  • If False, the component does not inherit the media files from the parent component.
  • If a list of components classes, the component inherits the media files ONLY from these specified components.

Read more in Media inheritance section.

Example:

Disable media inheritance:

class ParentComponent(Component):\n    class Media:\n        js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n    class Media:\n        extend = False  # Don't inherit parent media\n        js = [\"script.js\"]\n\nprint(MyComponent.media._js)  # [\"script.js\"]\n

Specify which components to inherit from. In this case, the media files are inherited ONLY from the specified components, and NOT from the original parent components:

class ParentComponent(Component):\n    class Media:\n        js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n    class Media:\n        # Only inherit from these, ignoring the files from the parent\n        extend = [OtherComponent1, OtherComponent2]\n\n        js = [\"script.js\"]\n\nprint(MyComponent.media._js)  # [\"script.js\", \"other1.js\", \"other2.js\"]\n
"},{"location":"reference/api/#django_components.ComponentMediaInput.js","title":"js class-attribute instance-attribute","text":"
js: Optional[Union[ComponentMediaInputPath, List[ComponentMediaInputPath]]] = None\n

See source code

JS files associated with a Component.

  • If a string, it's assumed to be a path to a JS file.

  • If a list, each entry is assumed to be a path to a JS file.

Each entry can be a string, bytes, SafeString, PathLike, or a callable that returns one of the former (see ComponentMediaInputPath).

Examples:

class MyComponent(Component):\n    class Media:\n        js = \"path/to/script.js\"\n

class MyComponent(Component):\n    class Media:\n        js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n
class MyComponent(Component):\n    class Media:\n        js = lambda: [\"path/to/script1.js\", \"path/to/script2.js\"]\n
"},{"location":"reference/api/#django_components.ComponentMediaInputPath","title":"ComponentMediaInputPath module-attribute","text":"
ComponentMediaInputPath = Union[str, bytes, SafeData, Path, PathLike, Callable[[], Union[str, bytes, SafeData, Path, PathLike]]]\n

See source code

A type representing an entry in Media.js or Media.css.

If an entry is a SafeString (or has __html__ method), then entry is assumed to be a formatted HTML tag. Otherwise, it's assumed to be a path to a file.

Example:

class MyComponent\n    class Media:\n        js = [\n            \"path/to/script.js\",\n            b\"script.js\",\n            SafeString(\"<script src='path/to/script.js'></script>\"),\n        ]\n        css = [\n            Path(\"path/to/style.css\"),\n            lambda: \"path/to/style.css\",\n            lambda: Path(\"path/to/style.css\"),\n        ]\n
"},{"location":"reference/api/#django_components.ComponentNode","title":"ComponentNode","text":"
ComponentNode(\n    name: str,\n    registry: ComponentRegistry,\n    params: List[TagAttr],\n    flags: Optional[Dict[str, bool]] = None,\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    contents: Optional[str] = None,\n    template_name: Optional[str] = None,\n    template_component: Optional[Type[Component]] = None,\n)\n

Bases: django_components.node.BaseNode

See source code

Renders one of the components that was previously registered with @register() decorator.

The {% component %} tag takes:

  • Component's registered name as the first positional argument,
  • Followed by any number of positional and keyword arguments.
{% load component_tags %}\n<div>\n    {% component \"button\" name=\"John\" job=\"Developer\" / %}\n</div>\n

The component name must be a string literal.

"},{"location":"reference/api/#django_components.ComponentNode--inserting-slot-fills","title":"Inserting slot fills","text":"

If the component defined any slots, you can \"fill\" these slots by placing the {% fill %} tags within the {% component %} tag:

{% component \"my_table\" rows=rows headers=headers %}\n  {% fill \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endfill %}\n{% endcomponent %}\n

You can even nest {% fill %} tags within {% if %}, {% for %} and other tags:

{% component \"my_table\" rows=rows headers=headers %}\n    {% if rows %}\n        {% fill \"pagination\" %}\n            < 1 | 2 | 3 >\n        {% endfill %}\n    {% endif %}\n{% endcomponent %}\n
"},{"location":"reference/api/#django_components.ComponentNode--isolating-components","title":"Isolating components","text":"

By default, components behave similarly to Django's {% include %}, and the template inside the component has access to the variables defined in the outer template.

You can selectively isolate a component, using the only flag, so that the inner template can access only the data that was explicitly passed to it:

{% component \"name\" positional_arg keyword_arg=value ... only %}\n

Alternatively, you can set all components to be isolated by default, by setting context_behavior to \"isolated\" in your settings:

# settings.py\nCOMPONENTS = {\n    \"context_behavior\": \"isolated\",\n}\n
"},{"location":"reference/api/#django_components.ComponentNode--omitting-the-component-keyword","title":"Omitting the component keyword","text":"

If you would like to omit the component keyword, and simply refer to your components by their registered names:

{% button name=\"John\" job=\"Developer\" / %}\n

You can do so by setting the \"shorthand\" Tag formatter in the settings:

# settings.py\nCOMPONENTS = {\n    \"tag_formatter\": \"django_components.component_shorthand_formatter\",\n}\n

Methods:

  • parse \u2013
  • register \u2013
  • render \u2013
  • unregister \u2013

Attributes:

  • active_flags (List[str]) \u2013
  • allowed_flags \u2013
  • contents (Optional[str]) \u2013
  • end_tag \u2013
  • flags (Dict[str, bool]) \u2013
  • name \u2013
  • node_id (str) \u2013
  • nodelist (NodeList) \u2013
  • params (List[TagAttr]) \u2013
  • registry \u2013
  • tag \u2013
  • template_component (Optional[Type[Component]]) \u2013
  • template_name (Optional[str]) \u2013
"},{"location":"reference/api/#django_components.ComponentNode.active_flags","title":"active_flags property","text":"
active_flags: List[str]\n

See source code

Flags that were set for this specific instance as a list of strings.

E.g. the following tag:

{% slot \"content\" default required / %}\n

Will have the following flags:

[\"default\", \"required\"]\n
"},{"location":"reference/api/#django_components.ComponentNode.allowed_flags","title":"allowed_flags class-attribute instance-attribute","text":"
allowed_flags = [COMP_ONLY_FLAG]\n
"},{"location":"reference/api/#django_components.ComponentNode.contents","title":"contents instance-attribute","text":"
contents: Optional[str] = contents\n

See source code

See source code

The contents of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The contents will be \"<div> ... </div>\".

"},{"location":"reference/api/#django_components.ComponentNode.end_tag","title":"end_tag class-attribute instance-attribute","text":"
end_tag = 'endcomponent'\n
"},{"location":"reference/api/#django_components.ComponentNode.flags","title":"flags instance-attribute","text":"
flags: Dict[str, bool] = flags or {flag: Falsefor flag in (allowed_flags or [])}\n

See source code

See source code

Dictionary of all allowed_flags that were set on the tag.

Flags that were set are True, and the rest are False.

E.g. the following tag:

class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n    allowed_flags = [\"default\", \"required\"]\n
{% slot \"content\" default %}\n

Has 2 flags, default and required, but only default was set.

The flags dictionary will be:

{\n    \"default\": True,\n    \"required\": False,\n}\n

You can check if a flag is set by doing:

if node.flags[\"default\"]:\n    ...\n
"},{"location":"reference/api/#django_components.ComponentNode.name","title":"name instance-attribute","text":"
name = name\n
"},{"location":"reference/api/#django_components.ComponentNode.node_id","title":"node_id instance-attribute","text":"
node_id: str = node_id or gen_id()\n

See source code

See source code

The unique ID of the node.

Extensions can use this ID to store additional information.

"},{"location":"reference/api/#django_components.ComponentNode.nodelist","title":"nodelist instance-attribute","text":"
nodelist: NodeList = nodelist or NodeList()\n

See source code

See source code

The nodelist of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The nodelist will contain the <div> ... </div> part.

Unlike contents, the nodelist contains the actual Nodes, not just the text.

"},{"location":"reference/api/#django_components.ComponentNode.params","title":"params instance-attribute","text":"
params: List[TagAttr] = params\n

See source code

See source code

The parameters to the tag in the template.

A single param represents an arg or kwarg of the template tag.

E.g. the following tag:

{% component \"my_comp\" key=val key2='val2 two' %}\n

Has 3 params:

  • Posiitonal arg \"my_comp\"
  • Keyword arg key=val
  • Keyword arg key2='val2 two'
"},{"location":"reference/api/#django_components.ComponentNode.registry","title":"registry instance-attribute","text":"
registry = registry\n
"},{"location":"reference/api/#django_components.ComponentNode.tag","title":"tag class-attribute instance-attribute","text":"
tag = 'component'\n
"},{"location":"reference/api/#django_components.ComponentNode.template_component","title":"template_component instance-attribute","text":"
template_component: Optional[Type[Component]] = template_component\n

See source code

See source code

If the template that contains this node belongs to a Component, then this will be the Component class.

"},{"location":"reference/api/#django_components.ComponentNode.template_name","title":"template_name instance-attribute","text":"
template_name: Optional[str] = template_name\n

See source code

See source code

The name of the Template that contains this node.

The template name is set by Django's template loaders.

For example, the filesystem template loader will set this to the absolute path of the template file.

\"/home/user/project/templates/my_template.html\"\n
"},{"location":"reference/api/#django_components.ComponentNode.parse","title":"parse classmethod","text":"
parse(parser: Parser, token: Token, registry: ComponentRegistry, name: str, start_tag: str, end_tag: str) -> ComponentNode\n
"},{"location":"reference/api/#django_components.ComponentNode.register","title":"register classmethod","text":"
register(library: Library) -> None\n

See source code

A convenience method for registering the tag with the given library.

class MyNode(BaseNode):\n    tag = \"mynode\"\n\nMyNode.register(library)\n

Allows you to then use the node in templates like so:

{% load mylibrary %}\n{% mynode %}\n
"},{"location":"reference/api/#django_components.ComponentNode.render","title":"render","text":"
render(context: Context, *args: Any, **kwargs: Any) -> str\n
"},{"location":"reference/api/#django_components.ComponentNode.unregister","title":"unregister classmethod","text":"
unregister(library: Library) -> None\n

See source code

Unregisters the node from the given library.

"},{"location":"reference/api/#django_components.ComponentRegistry","title":"ComponentRegistry","text":"
ComponentRegistry(\n    library: Optional[Library] = None, settings: Optional[Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]] = None\n)\n

Bases: object

See source code

Manages components and makes them available in the template, by default as {% component %} tags.

{% component \"my_comp\" key=value %}\n{% endcomponent %}\n

To enable a component to be used in a template, the component must be registered with a component registry.

When you register a component to a registry, behind the scenes the registry automatically adds the component's template tag (e.g. {% component %} to the Library. And the opposite happens when you unregister a component - the tag is removed.

See Registering components.

Parameters:

  • library (Library, default: None ) \u2013

    Django Library associated with this registry. If omitted, the default Library instance from django_components is used.

  • settings (Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]], default: None ) \u2013

    Configure how the components registered with this registry will behave when rendered. See RegistrySettings. Can be either a static value or a callable that returns the settings. If omitted, the settings from COMPONENTS are used.

Notes:

  • The default registry is available as django_components.registry.
  • The default registry is used when registering components with @register decorator.

Example:

# Use with default Library\nregistry = ComponentRegistry()\n\n# Or a custom one\nmy_lib = Library()\nregistry = ComponentRegistry(library=my_lib)\n\n# Usage\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\nregistry.all()\nregistry.clear()\nregistry.get(\"button\")\nregistry.has(\"button\")\n
"},{"location":"reference/api/#django_components.ComponentRegistry--using-registry-to-share-components","title":"Using registry to share components","text":"

You can use component registry for isolating or \"packaging\" components:

  1. Create new instance of ComponentRegistry and Library:

    my_comps = Library()\nmy_comps_reg = ComponentRegistry(library=my_comps)\n

  2. Register components to the registry:

    my_comps_reg.register(\"my_button\", ButtonComponent)\nmy_comps_reg.register(\"my_card\", CardComponent)\n

  3. In your target project, load the Library associated with the registry:

    {% load my_comps %}\n

  4. Use the registered components in your templates:

    {% component \"button\" %}\n{% endcomponent %}\n

Methods:

  • all \u2013
  • clear \u2013
  • get \u2013
  • has \u2013
  • register \u2013
  • unregister \u2013

Attributes:

  • library (Library) \u2013
  • settings (InternalRegistrySettings) \u2013
"},{"location":"reference/api/#django_components.ComponentRegistry.library","title":"library property","text":"
library: Library\n

See source code

The template tag Library that is associated with the registry.

"},{"location":"reference/api/#django_components.ComponentRegistry.settings","title":"settings property","text":"
settings: InternalRegistrySettings\n

See source code

Registry settings configured for this registry.

"},{"location":"reference/api/#django_components.ComponentRegistry.all","title":"all","text":"
all() -> Dict[str, Type[Component]]\n

See source code

Retrieve all registered Component classes.

Returns:

  • Dict[str, Type[Component]] \u2013

    Dict[str, Type[Component]]: A dictionary of component names to component classes

Example:

# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then get all\nregistry.all()\n# > {\n# >   \"button\": ButtonComponent,\n# >   \"card\": CardComponent,\n# > }\n
"},{"location":"reference/api/#django_components.ComponentRegistry.clear","title":"clear","text":"
clear() -> None\n

See source code

Clears the registry, unregistering all components.

Example:

# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then clear\nregistry.clear()\n# Then get all\nregistry.all()\n# > {}\n
"},{"location":"reference/api/#django_components.ComponentRegistry.get","title":"get","text":"
get(name: str) -> Type[Component]\n

See source code

Retrieve a Component class registered under the given name.

Parameters:

  • name (str) \u2013

    The name under which the component was registered. Required.

Returns:

  • Type[Component] \u2013

    Type[Component]: The component class registered under the given name.

Raises:

  • NotRegistered if the given name is not registered.

Example:

# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then get\nregistry.get(\"button\")\n# > ButtonComponent\n
"},{"location":"reference/api/#django_components.ComponentRegistry.has","title":"has","text":"
has(name: str) -> bool\n

See source code

Check if a Component class is registered under the given name.

Parameters:

  • name (str) \u2013

    The name under which the component was registered. Required.

Returns:

  • bool ( bool ) \u2013

    True if the component is registered, False otherwise.

Example:

# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then check\nregistry.has(\"button\")\n# > True\n
"},{"location":"reference/api/#django_components.ComponentRegistry.register","title":"register","text":"
register(name: str, component: Type[Component]) -> None\n

See source code

Register a Component class with this registry under the given name.

A component MUST be registered before it can be used in a template such as:

{% component \"my_comp\" %}\n{% endcomponent %}\n

Parameters:

  • name (str) \u2013

    The name under which the component will be registered. Required.

  • component (Type[Component]) \u2013

    The component class to register. Required.

Raises:

  • AlreadyRegistered if a different component was already registered under the same name.

Example:

registry.register(\"button\", ButtonComponent)\n
"},{"location":"reference/api/#django_components.ComponentRegistry.unregister","title":"unregister","text":"
unregister(name: str) -> None\n

See source code

Unregister the Component class that was registered under the given name.

Once a component is unregistered, it is no longer available in the templates.

Parameters:

  • name (str) \u2013

    The name under which the component is registered. Required.

Raises:

  • NotRegistered if the given name is not registered.

Example:

# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
"},{"location":"reference/api/#django_components.ComponentVars","title":"ComponentVars","text":"

Bases: tuple

See source code

Type for the variables available inside the component templates.

All variables here are scoped under component_vars., so e.g. attribute kwargs on this class is accessible inside the template as:

{{ component_vars.kwargs }}\n

Attributes:

  • args (Any) \u2013
  • is_filled (Dict[str, bool]) \u2013
  • kwargs (Any) \u2013
  • slots (Any) \u2013
"},{"location":"reference/api/#django_components.ComponentVars.args","title":"args instance-attribute","text":"
args: Any\n

See source code

The args argument as passed to Component.get_template_data().

This is the same Component.args that's available on the component instance.

If you defined the Component.Args class, then the args property will return an instance of that class.

Otherwise, args will be a plain list.

Example:

With Args class:

from django_components import Component, register\n\n@register(\"table\")\nclass Table(Component):\n    class Args(NamedTuple):\n        page: int\n        per_page: int\n\n    template = '''\n        <div>\n            <h1>Table</h1>\n            <p>Page: {{ component_vars.args.page }}</p>\n            <p>Per page: {{ component_vars.args.per_page }}</p>\n        </div>\n    '''\n

Without Args class:

from django_components import Component, register\n\n@register(\"table\")\nclass Table(Component):\n    template = '''\n        <div>\n            <h1>Table</h1>\n            <p>Page: {{ component_vars.args.0 }}</p>\n            <p>Per page: {{ component_vars.args.1 }}</p>\n        </div>\n    '''\n
"},{"location":"reference/api/#django_components.ComponentVars.is_filled","title":"is_filled instance-attribute","text":"
is_filled: Dict[str, bool]\n

See source code

Deprecated. Will be removed in v1. Use component_vars.slots instead. Note that component_vars.slots no longer escapes the slot names.

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

New in version 0.70

Use as {{ component_vars.is_filled }}

Example:

{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n    <div class=\"slot-wrapper\">\n        {% slot \"my_slot\" / %}\n    </div>\n{% endif %}\n

This is equivalent to checking if a given key is among the slot fills:

class MyTable(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"my_slot_filled\": \"my_slot\" in slots\n        }\n
"},{"location":"reference/api/#django_components.ComponentVars.kwargs","title":"kwargs instance-attribute","text":"
kwargs: Any\n

See source code

The kwargs argument as passed to Component.get_template_data().

This is the same Component.kwargs that's available on the component instance.

If you defined the Component.Kwargs class, then the kwargs property will return an instance of that class.

Otherwise, kwargs will be a plain dict.

Example:

With Kwargs class:

from django_components import Component, register\n\n@register(\"table\")\nclass Table(Component):\n    class Kwargs(NamedTuple):\n        page: int\n        per_page: int\n\n    template = '''\n        <div>\n            <h1>Table</h1>\n            <p>Page: {{ component_vars.kwargs.page }}</p>\n            <p>Per page: {{ component_vars.kwargs.per_page }}</p>\n        </div>\n    '''\n

Without Kwargs class:

from django_components import Component, register\n\n@register(\"table\")\nclass Table(Component):\n    template = '''\n        <div>\n            <h1>Table</h1>\n            <p>Page: {{ component_vars.kwargs.page }}</p>\n            <p>Per page: {{ component_vars.kwargs.per_page }}</p>\n        </div>\n    '''\n
"},{"location":"reference/api/#django_components.ComponentVars.slots","title":"slots instance-attribute","text":"
slots: Any\n

See source code

The slots argument as passed to Component.get_template_data().

This is the same Component.slots that's available on the component instance.

If you defined the Component.Slots class, then the slots property will return an instance of that class.

Otherwise, slots will be a plain dict.

Example:

With Slots class:

from django_components import Component, SlotInput, register\n\n@register(\"table\")\nclass Table(Component):\n    class Slots(NamedTuple):\n        footer: SlotInput\n\n    template = '''\n        <div>\n            {% component \"pagination\" %}\n                {% fill \"footer\" body=component_vars.slots.footer / %}\n            {% endcomponent %}\n        </div>\n    '''\n

Without Slots class:

from django_components import Component, SlotInput, register\n\n@register(\"table\")\nclass Table(Component):\n    template = '''\n        <div>\n            {% component \"pagination\" %}\n                {% fill \"footer\" body=component_vars.slots.footer / %}\n            {% endcomponent %}\n        </div>\n    '''\n
"},{"location":"reference/api/#django_components.ComponentView","title":"ComponentView","text":"
ComponentView(component: Component, **kwargs: Any)\n

Bases: django_components.extension.ExtensionComponentConfig, django.views.generic.base.View

See source code

The interface for Component.View.

The fields of this class are used to configure the component views and URLs.

This class is a subclass of django.views.View. The Component class is available via self.component_cls.

Override the methods of this class to define the behavior of the component.

Read more about Component views and URLs.

Example:

class MyComponent(Component):\n    class View:\n        def get(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:\n            return HttpResponse(\"Hello, world!\")\n

Component URL:

If the public attribute is set to True, the component will have its own URL that will point to the Component's View.

from django_components import Component\n\nclass MyComponent(Component):\n    class View:\n        public = True\n\n        def get(self, request, *args, **kwargs):\n            return HttpResponse(\"Hello, world!\")\n

Will create a URL route like /components/ext/view/components/a1b2c3/.

To get the URL for the component, use get_component_url():

url = get_component_url(MyComponent)\n

Methods:

  • delete \u2013
  • get \u2013
  • head \u2013
  • options \u2013
  • patch \u2013
  • post \u2013
  • put \u2013
  • trace \u2013

Attributes:

  • component \u2013
  • component_class (Type[Component]) \u2013
  • component_cls \u2013
  • public (bool) \u2013
  • url (str) \u2013
"},{"location":"reference/api/#django_components.ComponentView.component","title":"component class-attribute instance-attribute","text":"
component = cast('Component', None)\n

See source code

DEPRECATED: Will be removed in v1.0. Use component_cls instead.

This is a dummy instance created solely for the View methods.

It is the same as if you instantiated the component class directly:

component = Calendar()\ncomponent.render_to_response(request=request)\n
"},{"location":"reference/api/#django_components.ComponentView.component_class","title":"component_class instance-attribute","text":"
component_class: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.ComponentView.component_cls","title":"component_cls class-attribute instance-attribute","text":"
component_cls = cast(Type['Component'], None)\n

See source code

The parent component class.

Example:

class MyComponent(Component):\n    class View:\n        def get(self, request):\n            return self.component_cls.render_to_response(request=request)\n
"},{"location":"reference/api/#django_components.ComponentView.public","title":"public class-attribute","text":"
public: bool = False\n

See source code

Whether the component should be available via a URL.

Example:

from django_components import Component\n\nclass MyComponent(Component):\n    class View:\n        public = True\n

Will create a URL route like /components/ext/view/components/a1b2c3/.

To get the URL for the component, use get_component_url():

url = get_component_url(MyComponent)\n
"},{"location":"reference/api/#django_components.ComponentView.url","title":"url property","text":"
url: str\n

See source code

The URL for the component.

Raises RuntimeError if the component is not public.

This is the same as calling get_component_url() with the parent Component class:

class MyComponent(Component):\n    class View:\n        def get(self, request):\n            assert self.url == get_component_url(self.component_cls)\n
"},{"location":"reference/api/#django_components.ComponentView.delete","title":"delete","text":"
delete(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse\n
"},{"location":"reference/api/#django_components.ComponentView.get","title":"get","text":"
get(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse\n
"},{"location":"reference/api/#django_components.ComponentView.head","title":"head","text":"
head(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse\n
"},{"location":"reference/api/#django_components.ComponentView.options","title":"options","text":"
options(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse\n
"},{"location":"reference/api/#django_components.ComponentView.patch","title":"patch","text":"
patch(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse\n
"},{"location":"reference/api/#django_components.ComponentView.post","title":"post","text":"
post(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse\n
"},{"location":"reference/api/#django_components.ComponentView.put","title":"put","text":"
put(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse\n
"},{"location":"reference/api/#django_components.ComponentView.trace","title":"trace","text":"
trace(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse\n
"},{"location":"reference/api/#django_components.ComponentsSettings","title":"ComponentsSettings","text":"

Bases: tuple

See source code

Settings available for django_components.

Example:

COMPONENTS = ComponentsSettings(\n    autodiscover=False,\n    dirs = [BASE_DIR / \"components\"],\n)\n

Attributes:

  • app_dirs (Optional[Sequence[str]]) \u2013
  • autodiscover (Optional[bool]) \u2013
  • cache (Optional[str]) \u2013
  • context_behavior (Optional[ContextBehaviorType]) \u2013
  • debug_highlight_components (Optional[bool]) \u2013
  • debug_highlight_slots (Optional[bool]) \u2013
  • dirs (Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]]) \u2013
  • dynamic_component_name (Optional[str]) \u2013
  • extensions (Optional[Sequence[Union[Type[ComponentExtension], str]]]) \u2013
  • extensions_defaults (Optional[Dict[str, Any]]) \u2013
  • forbidden_static_files (Optional[List[Union[str, Pattern]]]) \u2013
  • libraries (Optional[List[str]]) \u2013
  • multiline_tags (Optional[bool]) \u2013
  • reload_on_file_change (Optional[bool]) \u2013
  • reload_on_template_change (Optional[bool]) \u2013
  • static_files_allowed (Optional[List[Union[str, Pattern]]]) \u2013
  • static_files_forbidden (Optional[List[Union[str, Pattern]]]) \u2013
  • tag_formatter (Optional[Union[TagFormatterABC, str]]) \u2013
  • template_cache_size (Optional[int]) \u2013
"},{"location":"reference/api/#django_components.ComponentsSettings.app_dirs","title":"app_dirs class-attribute instance-attribute","text":"
app_dirs: Optional[Sequence[str]] = None\n

See source code

Specify the app-level directories that contain your components.

Defaults to [\"components\"]. That is, for each Django app, we search <app>/components/ for components.

The paths must be relative to app, e.g.:

COMPONENTS = ComponentsSettings(\n    app_dirs=[\"my_comps\"],\n)\n

To search for <app>/my_comps/.

These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.

Set to empty list to disable app-level components:

COMPONENTS = ComponentsSettings(\n    app_dirs=[],\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.autodiscover","title":"autodiscover class-attribute instance-attribute","text":"
autodiscover: Optional[bool] = None\n

See source code

Toggle whether to run autodiscovery at the Django server startup.

Defaults to True

COMPONENTS = ComponentsSettings(\n    autodiscover=False,\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.cache","title":"cache class-attribute instance-attribute","text":"
cache: Optional[str] = None\n

See source code

Name of the Django cache to be used for storing component's JS and CSS files.

If None, a LocMemCache is used with default settings.

Defaults to None.

Read more about caching.

COMPONENTS = ComponentsSettings(\n    cache=\"my_cache\",\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.context_behavior","title":"context_behavior class-attribute instance-attribute","text":"
context_behavior: Optional[ContextBehaviorType] = None\n

See source code

Configure whether, inside a component template, you can use variables from the outside (\"django\") or not (\"isolated\"). This also affects what variables are available inside the {% fill %} tags.

Also see Component context and scope.

Defaults to \"django\".

COMPONENTS = ComponentsSettings(\n    context_behavior=\"isolated\",\n)\n

NOTE: context_behavior and slot_context_behavior options were merged in v0.70.

If you are migrating from BEFORE v0.67, set context_behavior to \"django\". From v0.67 to v0.78 (incl) the default value was \"isolated\".

For v0.79 and later, the default is again \"django\". See the rationale for change here.

"},{"location":"reference/api/#django_components.ComponentsSettings.debug_highlight_components","title":"debug_highlight_components class-attribute instance-attribute","text":"
debug_highlight_components: Optional[bool] = None\n

See source code

DEPRECATED. Use extensions_defaults instead. Will be removed in v1.

Enable / disable component highlighting. See Troubleshooting for more details.

Defaults to False.

COMPONENTS = ComponentsSettings(\n    debug_highlight_components=True,\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.debug_highlight_slots","title":"debug_highlight_slots class-attribute instance-attribute","text":"
debug_highlight_slots: Optional[bool] = None\n

See source code

DEPRECATED. Use extensions_defaults instead. Will be removed in v1.

Enable / disable slot highlighting. See Troubleshooting for more details.

Defaults to False.

COMPONENTS = ComponentsSettings(\n    debug_highlight_slots=True,\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.dirs","title":"dirs class-attribute instance-attribute","text":"
dirs: Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]] = None\n

See source code

Specify the directories that contain your components.

Defaults to [Path(settings.BASE_DIR) / \"components\"]. That is, the root components/ app.

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

COMPONENTS = ComponentsSettings(\n    dirs=[BASE_DIR / \"components\"],\n)\n

Set to empty list to disable global components directories:

COMPONENTS = ComponentsSettings(\n    dirs=[],\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.dynamic_component_name","title":"dynamic_component_name class-attribute instance-attribute","text":"
dynamic_component_name: Optional[str] = None\n

See source code

By default, the dynamic component is registered under the name \"dynamic\".

In case of a conflict, you can use this setting to change the component name used for the dynamic components.

# settings.py\nCOMPONENTS = ComponentsSettings(\n    dynamic_component_name=\"my_dynamic\",\n)\n

After which you will be able to use the dynamic component with the new name:

{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/api/#django_components.ComponentsSettings.extensions","title":"extensions class-attribute instance-attribute","text":"
extensions: Optional[Sequence[Union[Type[ComponentExtension], str]]] = None\n

See source code

List of extensions to be loaded.

The extensions can be specified as:

  • Python import path, e.g. \"path.to.my_extension.MyExtension\".
  • Extension class, e.g. my_extension.MyExtension.

Read more about extensions.

Example:

COMPONENTS = ComponentsSettings(\n    extensions=[\n        \"path.to.my_extension.MyExtension\",\n        StorybookExtension,\n    ],\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.extensions_defaults","title":"extensions_defaults class-attribute instance-attribute","text":"
extensions_defaults: Optional[Dict[str, Any]] = None\n

See source code

Global defaults for the extension classes.

Read more about Extension defaults.

Example:

COMPONENTS = ComponentsSettings(\n    extensions_defaults={\n        \"my_extension\": {\n            \"my_setting\": \"my_value\",\n        },\n        \"cache\": {\n            \"enabled\": True,\n            \"ttl\": 60,\n        },\n    },\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.forbidden_static_files","title":"forbidden_static_files class-attribute instance-attribute","text":"
forbidden_static_files: Optional[List[Union[str, Pattern]]] = None\n

See source code

Deprecated. Use COMPONENTS.static_files_forbidden instead.

"},{"location":"reference/api/#django_components.ComponentsSettings.libraries","title":"libraries class-attribute instance-attribute","text":"
libraries: Optional[List[str]] = None\n

See source code

Configure extra python modules that should be loaded.

This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.

Expects a list of python module paths. Defaults to empty list.

Example:

COMPONENTS = ComponentsSettings(\n    libraries=[\n        \"mysite.components.forms\",\n        \"mysite.components.buttons\",\n        \"mysite.components.cards\",\n    ],\n)\n

This would be the equivalent of importing these modules from within Django's AppConfig.ready():

class MyAppConfig(AppConfig):\n    def ready(self):\n        import \"mysite.components.forms\"\n        import \"mysite.components.buttons\"\n        import \"mysite.components.cards\"\n
"},{"location":"reference/api/#django_components.ComponentsSettings.libraries--manually-loading-libraries","title":"Manually loading libraries","text":"

In the rare case that you need to manually trigger the import of libraries, you can use the import_libraries() function:

from django_components import import_libraries\n\nimport_libraries()\n
"},{"location":"reference/api/#django_components.ComponentsSettings.multiline_tags","title":"multiline_tags class-attribute instance-attribute","text":"
multiline_tags: Optional[bool] = None\n

See source code

Enable / disable multiline support for template tags. If True, template tags like {% component %} or {{ my_var }} can span multiple lines.

Defaults to True.

Disable this setting if you are making custom modifications to Django's regular expression for parsing templates at django.template.base.tag_re.

COMPONENTS = ComponentsSettings(\n    multiline_tags=False,\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.reload_on_file_change","title":"reload_on_file_change class-attribute instance-attribute","text":"
reload_on_file_change: Optional[bool] = None\n

See source code

This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.

In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.

Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.

The setting reload_on_file_change fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.

If True, django_components configures Django to reload when files inside COMPONENTS.dirs or COMPONENTS.app_dirs change.

See Reload dev server on component file changes.

Defaults to False.

Warning

This setting should be enabled only for the dev environment!

"},{"location":"reference/api/#django_components.ComponentsSettings.reload_on_template_change","title":"reload_on_template_change class-attribute instance-attribute","text":"
reload_on_template_change: Optional[bool] = None\n

See source code

Deprecated. Use COMPONENTS.reload_on_file_change instead.

"},{"location":"reference/api/#django_components.ComponentsSettings.static_files_allowed","title":"static_files_allowed class-attribute instance-attribute","text":"
static_files_allowed: Optional[List[Union[str, Pattern]]] = None\n

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or 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 = ComponentsSettings(\n    static_files_allowed=[\n        \".css\",\n        \".js\", \".jsx\", \".ts\", \".tsx\",\n        # Images\n        \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n        \".jpeg\",  \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n        \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n        # Fonts\n        \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n    ],\n)\n

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

"},{"location":"reference/api/#django_components.ComponentsSettings.static_files_forbidden","title":"static_files_forbidden class-attribute instance-attribute","text":"
static_files_forbidden: Optional[List[Union[str, Pattern]]] = None\n

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs will NEVER be treated as static files.

If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in static_files_allowed.

Use this setting together with static_files_allowed for a fine control over what file types will be exposed.

You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

By default, any HTML and Python are considered NOT static files:

COMPONENTS = ComponentsSettings(\n    static_files_forbidden=[\n        \".html\", \".django\", \".dj\", \".tpl\",\n        # Python files\n        \".py\", \".pyc\",\n    ],\n)\n

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

"},{"location":"reference/api/#django_components.ComponentsSettings.tag_formatter","title":"tag_formatter class-attribute instance-attribute","text":"
tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n

See source code

Configure what syntax is used inside Django templates to render components. See the available tag formatters.

Defaults to \"django_components.component_formatter\".

Learn more about Customizing component tags with TagFormatter.

Can be set either as direct reference:

from django_components import component_formatter\n\nCOMPONENTS = ComponentsSettings(\n    \"tag_formatter\": component_formatter\n)\n

Or as an import string;

COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_formatter\"\n)\n

Examples:

  • \"django_components.component_formatter\"

    Set

    COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_formatter\"\n)\n

    To write components like this:

    {% component \"button\" href=\"...\" %}\n    Click me!\n{% endcomponent %}\n
  • django_components.component_shorthand_formatter

    Set

    COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_shorthand_formatter\"\n)\n

    To write components like this:

    {% button href=\"...\" %}\n    Click me!\n{% endbutton %}\n
"},{"location":"reference/api/#django_components.ComponentsSettings.template_cache_size","title":"template_cache_size class-attribute instance-attribute","text":"
template_cache_size: Optional[int] = None\n

See source code

DEPRECATED. Template caching will be removed in v1.

Configure the maximum amount of Django templates to be cached.

Defaults to 128.

Each time a Django 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 overriding Component.get_template() to render many dynamic templates, you can increase this number.

COMPONENTS = ComponentsSettings(\n    template_cache_size=256,\n)\n

To remove the cache limit altogether and cache everything, set template_cache_size to None.

COMPONENTS = ComponentsSettings(\n    template_cache_size=None,\n)\n

If you want to add templates to the cache yourself, you can use cached_template():

from django_components import cached_template\n\ncached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n    pass\n\ncached_template(\n    \"Variable: {{ variable }}\",\n    template_cls=MyTemplate,\n    name=...\n    origin=...\n    engine=...\n)\n
"},{"location":"reference/api/#django_components.ContextBehavior","title":"ContextBehavior","text":"

Bases: str, enum.Enum

See source code

Configure how (and whether) the context is passed to the component fills and what variables are available inside the {% fill %} tags.

Also see Component context and scope.

Options:

  • django: With this setting, component fills behave as usual Django tags.
  • isolated: This setting makes the component fills behave similar to Vue or React.

Attributes:

  • DJANGO \u2013
  • ISOLATED \u2013
"},{"location":"reference/api/#django_components.ContextBehavior.DJANGO","title":"DJANGO class-attribute instance-attribute","text":"
DJANGO = 'django'\n

See source code

With this setting, component fills behave as usual Django tags. That is, they enrich the context, and pass it along.

  1. Component fills use the context of the component they are within.
  2. Variables from Component.get_template_data() are available to the component fill.

Example:

Given this template

{% with cheese=\"feta\" %}\n  {% component 'my_comp' %}\n    {{ my_var }}  # my_var\n    {{ cheese }}  # cheese\n  {% endcomponent %}\n{% endwith %}\n

and this context returned from the Component.get_template_data() method

{ \"my_var\": 123 }\n

Then if component \"my_comp\" defines context

{ \"my_var\": 456 }\n

Then this will render:

456   # my_var\nfeta  # cheese\n

Because \"my_comp\" overrides the variable \"my_var\", so {{ my_var }} equals 456.

And variable \"cheese\" will equal feta, because the fill CAN access the current context.

"},{"location":"reference/api/#django_components.ContextBehavior.ISOLATED","title":"ISOLATED class-attribute instance-attribute","text":"
ISOLATED = 'isolated'\n

See source code

This setting makes the component fills behave similar to Vue or React, where the fills use EXCLUSIVELY the context variables defined in Component.get_template_data().

Example:

Given this template

{% with cheese=\"feta\" %}\n  {% component 'my_comp' %}\n    {{ my_var }}  # my_var\n    {{ cheese }}  # cheese\n  {% endcomponent %}\n{% endwith %}\n

and this context returned from the get_template_data() method

{ \"my_var\": 123 }\n

Then if component \"my_comp\" defines context

{ \"my_var\": 456 }\n

Then this will render:

123   # my_var\n      # cheese\n

Because both variables \"my_var\" and \"cheese\" are taken from the root context. Since \"cheese\" is not defined in root context, it's empty.

"},{"location":"reference/api/#django_components.Default","title":"Default dataclass","text":"
Default(value: Callable[[], Any])\n

Bases: object

See source code

Use this class to mark a field on the Component.Defaults class as a factory.

Read more about Component defaults.

Example:

from django_components import Default\n\nclass MyComponent(Component):\n    class Defaults:\n        # Plain value doesn't need a factory\n        position = \"left\"\n        # Lists and dicts need to be wrapped in `Default`\n        # Otherwise all instances will share the same value\n        selected_items = Default(lambda: [1, 2, 3])\n

Attributes:

  • value (Callable[[], Any]) \u2013
"},{"location":"reference/api/#django_components.Default.value","title":"value instance-attribute","text":"
value: Callable[[], Any]\n
"},{"location":"reference/api/#django_components.DependenciesStrategy","title":"DependenciesStrategy module-attribute","text":"
DependenciesStrategy = Literal['document', 'fragment', 'simple', 'prepend', 'append', 'ignore']\n

See source code

Type for the available strategies for rendering JS and CSS dependencies.

Read more about the dependencies strategies.

"},{"location":"reference/api/#django_components.Empty","title":"Empty","text":"

Bases: tuple

See source code

Type for an object with no members.

You can use this to define Component types that accept NO args, kwargs, slots, etc:

from django_components import Component, Empty\n\nclass Table(Component):\n    Args = Empty\n    Kwargs = Empty\n    ...\n

This class is a shorthand for:

class Empty(NamedTuple):\n    pass\n

Read more about Typing and validation.

"},{"location":"reference/api/#django_components.ExtensionComponentConfig","title":"ExtensionComponentConfig","text":"
ExtensionComponentConfig(component: Component)\n

Bases: object

See source code

ExtensionComponentConfig is the base class for all extension component configs.

Extensions can define nested classes on the component class, such as Component.View or Component.Cache:

class MyComp(Component):\n    class View:\n        def get(self, request):\n            ...\n\n    class Cache:\n        ttl = 60\n

This allows users to configure extension behavior per component.

Behind the scenes, the nested classes that users define on their components are merged with the extension's \"base\" class.

So the example above is the same as:

class MyComp(Component):\n    class View(ViewExtension.ComponentConfig):\n        def get(self, request):\n            ...\n\n    class Cache(CacheExtension.ComponentConfig):\n        ttl = 60\n

Where both ViewExtension.ComponentConfig and CacheExtension.ComponentConfig are subclasses of ExtensionComponentConfig.

Attributes:

  • component (Component) \u2013
  • component_class (Type[Component]) \u2013
  • component_cls (Type[Component]) \u2013
"},{"location":"reference/api/#django_components.ExtensionComponentConfig.component","title":"component instance-attribute","text":"
component: Component = component\n

See source code

See source code

When a Component is instantiated, also the nested extension classes (such as Component.View) are instantiated, receiving the component instance as an argument.

This attribute holds the owner Component instance that this extension is defined on.

"},{"location":"reference/api/#django_components.ExtensionComponentConfig.component_class","title":"component_class instance-attribute","text":"
component_class: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.ExtensionComponentConfig.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The Component class that this extension is defined on.

"},{"location":"reference/api/#django_components.FillNode","title":"FillNode","text":"
FillNode(\n    params: List[TagAttr],\n    flags: Optional[Dict[str, bool]] = None,\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    contents: Optional[str] = None,\n    template_name: Optional[str] = None,\n    template_component: Optional[Type[Component]] = None,\n)\n

Bases: django_components.node.BaseNode

See source code

Use {% fill %} tag to insert content into component's slots.

{% fill %} tag may be used only within a {% component %}..{% endcomponent %} block, and raises a TemplateSyntaxError if used outside of a component.

Args:

  • name (str, required): Name of the slot to insert this content into. Use \"default\" for the default slot.
  • data (str, optional): This argument allows you to access the data passed to the slot under the specified variable name. See Slot data.
  • fallback (str, optional): This argument allows you to access the original content of the slot under the specified variable name. See Slot fallback.

Example:

{% component \"my_table\" %}\n  {% fill \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/api/#django_components.FillNode--access-slot-fallback","title":"Access slot fallback","text":"

Use the fallback kwarg to access the original content of the slot.

The fallback kwarg defines the name of the variable that will contain the slot's fallback content.

Read more about Slot fallback.

Component template:

{# my_table.html #}\n<table>\n  ...\n  {% slot \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endslot %}\n</table>\n

Fill:

{% component \"my_table\" %}\n  {% fill \"pagination\" fallback=\"fallback\" %}\n    <div class=\"my-class\">\n      {{ fallback }}\n    </div>\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/api/#django_components.FillNode--access-slot-data","title":"Access slot data","text":"

Use the data kwarg to access the data passed to the slot.

The data kwarg defines the name of the variable that will contain the slot's data.

Read more about Slot data.

Component template:

{# my_table.html #}\n<table>\n  ...\n  {% slot \"pagination\" pages=pages %}\n    < 1 | 2 | 3 >\n  {% endslot %}\n</table>\n

Fill:

{% component \"my_table\" %}\n  {% fill \"pagination\" data=\"slot_data\" %}\n    {% for page in slot_data.pages %}\n        <a href=\"{{ page.link }}\">\n          {{ page.index }}\n        </a>\n    {% endfor %}\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/api/#django_components.FillNode--using-default-slot","title":"Using default slot","text":"

To access slot data and the fallback slot content on the default slot, use {% fill %} with name set to \"default\":

{% component \"button\" %}\n  {% fill name=\"default\" data=\"slot_data\" fallback=\"slot_fallback\" %}\n    You clicked me {{ slot_data.count }} times!\n    {{ slot_fallback }}\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/api/#django_components.FillNode--slot-fills-from-python","title":"Slot fills from Python","text":"

You can pass a slot fill from Python to a component by setting the body kwarg on the {% fill %} tag.

First pass a Slot instance to the template with the get_template_data() method:

from django_components import component, Slot\n\nclass Table(Component):\n  def get_template_data(self, args, kwargs, slots, context):\n    return {\n        \"my_slot\": Slot(lambda ctx: \"Hello, world!\"),\n    }\n

Then pass the slot to the {% fill %} tag:

{% component \"table\" %}\n  {% fill \"pagination\" body=my_slot / %}\n{% endcomponent %}\n

Warning

If you define both the body kwarg and the {% fill %} tag's body, an error will be raised.

{% component \"table\" %}\n  {% fill \"pagination\" body=my_slot %}\n    ...\n  {% endfill %}\n{% endcomponent %}\n

Methods:

  • parse \u2013
  • register \u2013
  • render \u2013
  • unregister \u2013

Attributes:

  • active_flags (List[str]) \u2013
  • allowed_flags \u2013
  • contents (Optional[str]) \u2013
  • end_tag \u2013
  • flags (Dict[str, bool]) \u2013
  • node_id (str) \u2013
  • nodelist (NodeList) \u2013
  • params (List[TagAttr]) \u2013
  • tag \u2013
  • template_component (Optional[Type[Component]]) \u2013
  • template_name (Optional[str]) \u2013
"},{"location":"reference/api/#django_components.FillNode.active_flags","title":"active_flags property","text":"
active_flags: List[str]\n

See source code

Flags that were set for this specific instance as a list of strings.

E.g. the following tag:

{% slot \"content\" default required / %}\n

Will have the following flags:

[\"default\", \"required\"]\n
"},{"location":"reference/api/#django_components.FillNode.allowed_flags","title":"allowed_flags class-attribute instance-attribute","text":"
allowed_flags = []\n
"},{"location":"reference/api/#django_components.FillNode.contents","title":"contents instance-attribute","text":"
contents: Optional[str] = contents\n

See source code

See source code

The contents of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The contents will be \"<div> ... </div>\".

"},{"location":"reference/api/#django_components.FillNode.end_tag","title":"end_tag class-attribute instance-attribute","text":"
end_tag = 'endfill'\n
"},{"location":"reference/api/#django_components.FillNode.flags","title":"flags instance-attribute","text":"
flags: Dict[str, bool] = flags or {flag: Falsefor flag in (allowed_flags or [])}\n

See source code

See source code

Dictionary of all allowed_flags that were set on the tag.

Flags that were set are True, and the rest are False.

E.g. the following tag:

class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n    allowed_flags = [\"default\", \"required\"]\n
{% slot \"content\" default %}\n

Has 2 flags, default and required, but only default was set.

The flags dictionary will be:

{\n    \"default\": True,\n    \"required\": False,\n}\n

You can check if a flag is set by doing:

if node.flags[\"default\"]:\n    ...\n
"},{"location":"reference/api/#django_components.FillNode.node_id","title":"node_id instance-attribute","text":"
node_id: str = node_id or gen_id()\n

See source code

See source code

The unique ID of the node.

Extensions can use this ID to store additional information.

"},{"location":"reference/api/#django_components.FillNode.nodelist","title":"nodelist instance-attribute","text":"
nodelist: NodeList = nodelist or NodeList()\n

See source code

See source code

The nodelist of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The nodelist will contain the <div> ... </div> part.

Unlike contents, the nodelist contains the actual Nodes, not just the text.

"},{"location":"reference/api/#django_components.FillNode.params","title":"params instance-attribute","text":"
params: List[TagAttr] = params\n

See source code

See source code

The parameters to the tag in the template.

A single param represents an arg or kwarg of the template tag.

E.g. the following tag:

{% component \"my_comp\" key=val key2='val2 two' %}\n

Has 3 params:

  • Posiitonal arg \"my_comp\"
  • Keyword arg key=val
  • Keyword arg key2='val2 two'
"},{"location":"reference/api/#django_components.FillNode.tag","title":"tag class-attribute instance-attribute","text":"
tag = 'fill'\n
"},{"location":"reference/api/#django_components.FillNode.template_component","title":"template_component instance-attribute","text":"
template_component: Optional[Type[Component]] = template_component\n

See source code

See source code

If the template that contains this node belongs to a Component, then this will be the Component class.

"},{"location":"reference/api/#django_components.FillNode.template_name","title":"template_name instance-attribute","text":"
template_name: Optional[str] = template_name\n

See source code

See source code

The name of the Template that contains this node.

The template name is set by Django's template loaders.

For example, the filesystem template loader will set this to the absolute path of the template file.

\"/home/user/project/templates/my_template.html\"\n
"},{"location":"reference/api/#django_components.FillNode.parse","title":"parse classmethod","text":"
parse(parser: Parser, token: Token, **kwargs: Any) -> BaseNode\n

See source code

This function is what is passed to Django's Library.tag() when registering the tag.

In other words, this method is called by Django's template parser when we encounter a tag that matches this node's tag, e.g. {% component %} or {% slot %}.

To register the tag, you can use BaseNode.register().

"},{"location":"reference/api/#django_components.FillNode.register","title":"register classmethod","text":"
register(library: Library) -> None\n

See source code

A convenience method for registering the tag with the given library.

class MyNode(BaseNode):\n    tag = \"mynode\"\n\nMyNode.register(library)\n

Allows you to then use the node in templates like so:

{% load mylibrary %}\n{% mynode %}\n
"},{"location":"reference/api/#django_components.FillNode.render","title":"render","text":"
render(\n    context: Context,\n    name: str,\n    *,\n    data: Optional[str] = None,\n    fallback: Optional[str] = None,\n    body: Optional[SlotInput] = None,\n    default: Optional[str] = None\n) -> str\n
"},{"location":"reference/api/#django_components.FillNode.unregister","title":"unregister classmethod","text":"
unregister(library: Library) -> None\n

See source code

Unregisters the node from the given library.

"},{"location":"reference/api/#django_components.OnRenderGenerator","title":"OnRenderGenerator module-attribute","text":"
OnRenderGenerator = Generator[Optional[SlotResult], Tuple[Optional[SlotResult], Optional[Exception]], Optional[SlotResult]]\n

See source code

This is the signature of the Component.on_render() method if it yields (and thus returns a generator).

When on_render() is a generator then it:

  • Yields a rendered template (string or None)

  • Receives back a tuple of (final_output, error).

    The final output is the rendered template that now has all its children rendered too. May be None if you yielded None earlier.

    The error is None if the rendering was successful. Otherwise the error is set and the output is None.

  • At the end it may return a new string to override the final rendered output.

Example:

from django_components import Component, OnRenderGenerator\n\nclass MyTable(Component):\n    def on_render(\n        self,\n        context: Context,\n        template: Optional[Template],\n    ) -> OnRenderGenerator:\n        # Do something BEFORE rendering template\n        # Same as `Component.on_render_before()`\n        context[\"hello\"] = \"world\"\n\n        # Yield rendered template to receive fully-rendered template or error\n        html, error = yield template.render(context)\n\n        # Do something AFTER rendering template, or post-process\n        # the rendered template.\n        # Same as `Component.on_render_after()`\n        return html + \"<p>Hello</p>\"\n
"},{"location":"reference/api/#django_components.ProvideNode","title":"ProvideNode","text":"
ProvideNode(\n    params: List[TagAttr],\n    flags: Optional[Dict[str, bool]] = None,\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    contents: Optional[str] = None,\n    template_name: Optional[str] = None,\n    template_component: Optional[Type[Component]] = None,\n)\n

Bases: django_components.node.BaseNode

See source code

The {% provide %} tag is part of the \"provider\" part of the provide / inject feature.

Pass kwargs to this tag to define the provider's data.

Any components defined within the {% provide %}..{% endprovide %} tags will be able to access this data with Component.inject().

This is similar to React's ContextProvider, or Vue's provide().

Args:

  • name (str, required): Provider name. This is the name you will then use in Component.inject().
  • **kwargs: Any extra kwargs will be passed as the provided data.

Example:

Provide the \"user_data\" in parent component:

@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      <div>\n        {% provide \"user_data\" user=user %}\n          {% component \"child\" / %}\n        {% endprovide %}\n      </div>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"user\": kwargs[\"user\"],\n        }\n

Since the \"child\" component is used within the {% provide %} / {% endprovide %} tags, we can request the \"user_data\" using Component.inject(\"user_data\"):

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        User is: {{ user }}\n      </div>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        user = self.inject(\"user_data\").user\n        return {\n            \"user\": user,\n        }\n

Notice that the keys defined on the {% provide %} tag are then accessed as attributes when accessing them with Component.inject().

\u2705 Do this

user = self.inject(\"user_data\").user\n

\u274c Don't do this

user = self.inject(\"user_data\")[\"user\"]\n

Methods:

  • parse \u2013
  • register \u2013
  • render \u2013
  • unregister \u2013

Attributes:

  • active_flags (List[str]) \u2013
  • allowed_flags \u2013
  • contents (Optional[str]) \u2013
  • end_tag \u2013
  • flags (Dict[str, bool]) \u2013
  • node_id (str) \u2013
  • nodelist (NodeList) \u2013
  • params (List[TagAttr]) \u2013
  • tag \u2013
  • template_component (Optional[Type[Component]]) \u2013
  • template_name (Optional[str]) \u2013
"},{"location":"reference/api/#django_components.ProvideNode.active_flags","title":"active_flags property","text":"
active_flags: List[str]\n

See source code

Flags that were set for this specific instance as a list of strings.

E.g. the following tag:

{% slot \"content\" default required / %}\n

Will have the following flags:

[\"default\", \"required\"]\n
"},{"location":"reference/api/#django_components.ProvideNode.allowed_flags","title":"allowed_flags class-attribute instance-attribute","text":"
allowed_flags = []\n
"},{"location":"reference/api/#django_components.ProvideNode.contents","title":"contents instance-attribute","text":"
contents: Optional[str] = contents\n

See source code

See source code

The contents of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The contents will be \"<div> ... </div>\".

"},{"location":"reference/api/#django_components.ProvideNode.end_tag","title":"end_tag class-attribute instance-attribute","text":"
end_tag = 'endprovide'\n
"},{"location":"reference/api/#django_components.ProvideNode.flags","title":"flags instance-attribute","text":"
flags: Dict[str, bool] = flags or {flag: Falsefor flag in (allowed_flags or [])}\n

See source code

See source code

Dictionary of all allowed_flags that were set on the tag.

Flags that were set are True, and the rest are False.

E.g. the following tag:

class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n    allowed_flags = [\"default\", \"required\"]\n
{% slot \"content\" default %}\n

Has 2 flags, default and required, but only default was set.

The flags dictionary will be:

{\n    \"default\": True,\n    \"required\": False,\n}\n

You can check if a flag is set by doing:

if node.flags[\"default\"]:\n    ...\n
"},{"location":"reference/api/#django_components.ProvideNode.node_id","title":"node_id instance-attribute","text":"
node_id: str = node_id or gen_id()\n

See source code

See source code

The unique ID of the node.

Extensions can use this ID to store additional information.

"},{"location":"reference/api/#django_components.ProvideNode.nodelist","title":"nodelist instance-attribute","text":"
nodelist: NodeList = nodelist or NodeList()\n

See source code

See source code

The nodelist of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The nodelist will contain the <div> ... </div> part.

Unlike contents, the nodelist contains the actual Nodes, not just the text.

"},{"location":"reference/api/#django_components.ProvideNode.params","title":"params instance-attribute","text":"
params: List[TagAttr] = params\n

See source code

See source code

The parameters to the tag in the template.

A single param represents an arg or kwarg of the template tag.

E.g. the following tag:

{% component \"my_comp\" key=val key2='val2 two' %}\n

Has 3 params:

  • Posiitonal arg \"my_comp\"
  • Keyword arg key=val
  • Keyword arg key2='val2 two'
"},{"location":"reference/api/#django_components.ProvideNode.tag","title":"tag class-attribute instance-attribute","text":"
tag = 'provide'\n
"},{"location":"reference/api/#django_components.ProvideNode.template_component","title":"template_component instance-attribute","text":"
template_component: Optional[Type[Component]] = template_component\n

See source code

See source code

If the template that contains this node belongs to a Component, then this will be the Component class.

"},{"location":"reference/api/#django_components.ProvideNode.template_name","title":"template_name instance-attribute","text":"
template_name: Optional[str] = template_name\n

See source code

See source code

The name of the Template that contains this node.

The template name is set by Django's template loaders.

For example, the filesystem template loader will set this to the absolute path of the template file.

\"/home/user/project/templates/my_template.html\"\n
"},{"location":"reference/api/#django_components.ProvideNode.parse","title":"parse classmethod","text":"
parse(parser: Parser, token: Token, **kwargs: Any) -> BaseNode\n

See source code

This function is what is passed to Django's Library.tag() when registering the tag.

In other words, this method is called by Django's template parser when we encounter a tag that matches this node's tag, e.g. {% component %} or {% slot %}.

To register the tag, you can use BaseNode.register().

"},{"location":"reference/api/#django_components.ProvideNode.register","title":"register classmethod","text":"
register(library: Library) -> None\n

See source code

A convenience method for registering the tag with the given library.

class MyNode(BaseNode):\n    tag = \"mynode\"\n\nMyNode.register(library)\n

Allows you to then use the node in templates like so:

{% load mylibrary %}\n{% mynode %}\n
"},{"location":"reference/api/#django_components.ProvideNode.render","title":"render","text":"
render(context: Context, name: str, **kwargs: Any) -> SafeString\n
"},{"location":"reference/api/#django_components.ProvideNode.unregister","title":"unregister classmethod","text":"
unregister(library: Library) -> None\n

See source code

Unregisters the node from the given library.

"},{"location":"reference/api/#django_components.RegistrySettings","title":"RegistrySettings","text":"

Bases: tuple

See source code

Configuration for a ComponentRegistry.

These settings define how the components registered with this registry will behave when rendered.

from django_components import ComponentRegistry, RegistrySettings\n\nregistry_settings = RegistrySettings(\n    context_behavior=\"django\",\n    tag_formatter=\"django_components.component_shorthand_formatter\",\n)\n\nregistry = ComponentRegistry(settings=registry_settings)\n

Attributes:

  • CONTEXT_BEHAVIOR (Optional[ContextBehaviorType]) \u2013
  • TAG_FORMATTER (Optional[Union[TagFormatterABC, str]]) \u2013
  • context_behavior (Optional[ContextBehaviorType]) \u2013
  • tag_formatter (Optional[Union[TagFormatterABC, str]]) \u2013
"},{"location":"reference/api/#django_components.RegistrySettings.CONTEXT_BEHAVIOR","title":"CONTEXT_BEHAVIOR class-attribute instance-attribute","text":"
CONTEXT_BEHAVIOR: Optional[ContextBehaviorType] = None\n

See source code

Deprecated. Use context_behavior instead. Will be removed in v1.

Same as the global COMPONENTS.context_behavior setting, but for this registry.

If omitted, defaults to the global COMPONENTS.context_behavior setting.

"},{"location":"reference/api/#django_components.RegistrySettings.TAG_FORMATTER","title":"TAG_FORMATTER class-attribute instance-attribute","text":"
TAG_FORMATTER: Optional[Union[TagFormatterABC, str]] = None\n

See source code

Deprecated. Use tag_formatter instead. Will be removed in v1.

Same as the global COMPONENTS.tag_formatter setting, but for this registry.

If omitted, defaults to the global COMPONENTS.tag_formatter setting.

"},{"location":"reference/api/#django_components.RegistrySettings.context_behavior","title":"context_behavior class-attribute instance-attribute","text":"
context_behavior: Optional[ContextBehaviorType] = None\n

See source code

Same as the global COMPONENTS.context_behavior setting, but for this registry.

If omitted, defaults to the global COMPONENTS.context_behavior setting.

"},{"location":"reference/api/#django_components.RegistrySettings.tag_formatter","title":"tag_formatter class-attribute instance-attribute","text":"
tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n

See source code

Same as the global COMPONENTS.tag_formatter setting, but for this registry.

If omitted, defaults to the global COMPONENTS.tag_formatter setting.

"},{"location":"reference/api/#django_components.Slot","title":"Slot dataclass","text":"
Slot(\n    contents: Any,\n    content_func: SlotFunc[TSlotData] = cast(SlotFunc[TSlotData], None),\n    component_name: Optional[str] = None,\n    slot_name: Optional[str] = None,\n    nodelist: Optional[NodeList] = None,\n    fill_node: Optional[Union[FillNode, ComponentNode]] = None,\n    extra: Dict[str, Any] = dict(),\n)\n

Bases: typing.Generic

See source code

This class is the main way for defining and handling slots.

It holds the slot content function along with related metadata.

Read more about Slot class.

Example:

Passing slots to components:

from django_components import Slot\n\nslot = Slot(lambda ctx: f\"Hello, {ctx.data['name']}!\")\n\nMyComponent.render(\n    slots={\n        \"my_slot\": slot,\n    },\n)\n

Accessing slots inside the components:

from django_components import Component\n\nclass MyComponent(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        my_slot = slots[\"my_slot\"]\n        return {\n            \"my_slot\": my_slot,\n        }\n

Rendering slots:

from django_components import Slot\n\nslot = Slot(lambda ctx: f\"Hello, {ctx.data['name']}!\")\nhtml = slot({\"name\": \"John\"})  # Output: Hello, John!\n

Attributes:

  • component_name (Optional[str]) \u2013
  • content_func (SlotFunc[TSlotData]) \u2013
  • contents (Any) \u2013
  • do_not_call_in_templates (bool) \u2013
  • extra (Dict[str, Any]) \u2013
  • fill_node (Optional[Union[FillNode, ComponentNode]]) \u2013
  • nodelist (Optional[NodeList]) \u2013
  • slot_name (Optional[str]) \u2013
"},{"location":"reference/api/#django_components.Slot.component_name","title":"component_name class-attribute instance-attribute","text":"
component_name: Optional[str] = None\n

See source code

Name of the component that originally received this slot fill.

See Slot metadata.

"},{"location":"reference/api/#django_components.Slot.content_func","title":"content_func class-attribute instance-attribute","text":"
content_func: SlotFunc[TSlotData] = cast(SlotFunc[TSlotData], None)\n

See source code

The actual slot function.

Do NOT call this function directly, instead call the Slot instance as a function.

Read more about Rendering slot functions.

"},{"location":"reference/api/#django_components.Slot.contents","title":"contents instance-attribute","text":"
contents: Any\n

See source code

The original value that was passed to the Slot constructor.

  • If Slot was created from {% fill %} tag, Slot.contents will contain the body (string) of that {% fill %} tag.
  • If Slot was created from string as Slot(\"...\"), Slot.contents will contain that string.
  • If Slot was created from a function, Slot.contents will contain that function.

Read more about Slot contents.

"},{"location":"reference/api/#django_components.Slot.do_not_call_in_templates","title":"do_not_call_in_templates property","text":"
do_not_call_in_templates: bool\n

See source code

Django special property to prevent calling the instance as a function inside Django templates.

"},{"location":"reference/api/#django_components.Slot.extra","title":"extra class-attribute instance-attribute","text":"
extra: Dict[str, Any] = field(default_factory=dict)\n

See source code

Dictionary that can be used to store arbitrary metadata about the slot.

See Slot metadata.

See Pass slot metadata for usage for extensions.

Example:

# Either at slot creation\nslot = Slot(lambda ctx: \"Hello, world!\", extra={\"foo\": \"bar\"})\n\n# Or later\nslot.extra[\"baz\"] = \"qux\"\n
"},{"location":"reference/api/#django_components.Slot.fill_node","title":"fill_node class-attribute instance-attribute","text":"
fill_node: Optional[Union[FillNode, ComponentNode]] = None\n

See source code

If the slot was created from a {% fill %} tag, this will be the FillNode instance.

If the slot was a default slot created from a {% component %} tag, this will be the ComponentNode instance.

Otherwise, this will be None.

Extensions can use this info to handle slots differently based on their source.

See Slot metadata.

Example:

You can use this to find the Component in whose template the {% fill %} tag was defined:

class MyTable(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        footer_slot = slots.get(\"footer\")\n        if footer_slot is not None and footer_slot.fill_node is not None:\n            owner_component = footer_slot.fill_node.template_component\n            # ...\n
"},{"location":"reference/api/#django_components.Slot.nodelist","title":"nodelist class-attribute instance-attribute","text":"
nodelist: Optional[NodeList] = None\n

See source code

If the slot was defined with {% fill %} tag, this will be the Nodelist of the fill's content.

See Slot metadata.

"},{"location":"reference/api/#django_components.Slot.slot_name","title":"slot_name class-attribute instance-attribute","text":"
slot_name: Optional[str] = None\n

See source code

Slot name to which this Slot was initially assigned.

See Slot metadata.

"},{"location":"reference/api/#django_components.SlotContent","title":"SlotContent module-attribute","text":"
SlotContent = SlotInput[TSlotData]\n

See source code

DEPRECATED: Use SlotInput instead. Will be removed in v1.

"},{"location":"reference/api/#django_components.SlotContext","title":"SlotContext dataclass","text":"
SlotContext(data: TSlotData, fallback: Optional[Union[str, SlotFallback]] = None, context: Optional[Context] = None)\n

Bases: typing.Generic

See source code

Metadata available inside slot functions.

Read more about Slot functions.

Example:

from django_components import SlotContext, SlotResult\n\ndef my_slot(ctx: SlotContext) -> SlotResult:\n    return f\"Hello, {ctx.data['name']}!\"\n

You can pass a type parameter to the SlotContext to specify the type of the data passed to the slot:

class MySlotData(TypedDict):\n    name: str\n\ndef my_slot(ctx: SlotContext[MySlotData]):\n    return f\"Hello, {ctx.data['name']}!\"\n

Attributes:

  • context (Optional[Context]) \u2013
  • data (TSlotData) \u2013
  • fallback (Optional[Union[str, SlotFallback]]) \u2013
"},{"location":"reference/api/#django_components.SlotContext.context","title":"context class-attribute instance-attribute","text":"
context: Optional[Context] = None\n

See source code

Django template Context available inside the {% fill %} tag.

May be None if you call the slot fill directly, without using {% slot %} tags.

"},{"location":"reference/api/#django_components.SlotContext.data","title":"data instance-attribute","text":"
data: TSlotData\n

See source code

Data passed to the slot.

Read more about Slot data.

Example:

def my_slot(ctx: SlotContext):\n    return f\"Hello, {ctx.data['name']}!\"\n
"},{"location":"reference/api/#django_components.SlotContext.fallback","title":"fallback class-attribute instance-attribute","text":"
fallback: Optional[Union[str, SlotFallback]] = None\n

See source code

Slot's fallback content. Lazily-rendered - coerce this value to string to force it to render.

Read more about Slot fallback.

Example:

def my_slot(ctx: SlotContext):\n    return f\"Hello, {ctx.fallback}!\"\n

May be None if you call the slot fill directly, without using {% slot %} tags.

"},{"location":"reference/api/#django_components.SlotFallback","title":"SlotFallback","text":"
SlotFallback(slot: SlotNode, context: Context)\n

Bases: object

See source code

The content between the {% slot %}..{% endslot %} tags is the fallback content that will be rendered if no fill is given for the slot.

{% slot \"name\" %}\n    Hello, my name is {{ name }}  <!-- Fallback content -->\n{% endslot %}\n

Because the fallback is defined as a piece of the template (NodeList), we want to lazily render it only when needed.

SlotFallback type allows to pass around the slot fallback as a variable.

To force the fallback to render, coerce it to string to trigger the __str__() method.

Example:

def slot_function(self, ctx: SlotContext):\n    return f\"Hello, {ctx.fallback}!\"\n
"},{"location":"reference/api/#django_components.SlotFunc","title":"SlotFunc","text":"

Bases: typing.Protocol

See source code

When rendering components with Component.render() or Component.render_to_response(), the slots can be given either as strings or as functions.

If a slot is given as a function, it will have the signature of SlotFunc.

Read more about Slot functions.

Parameters:

  • ctx (SlotContext) \u2013

    Single named tuple that holds the slot data and metadata.

Returns:

  • str | SafeString \u2013

    The rendered slot content.

Example:

from django_components import SlotContext, SlotResult\n\ndef header(ctx: SlotContext) -> SlotResult:\n    if ctx.data.get(\"name\"):\n        return f\"Hello, {ctx.data['name']}!\"\n    else:\n        return ctx.fallback\n\nhtml = MyTable.render(\n    slots={\n        \"header\": header,\n    },\n)\n
"},{"location":"reference/api/#django_components.SlotInput","title":"SlotInput module-attribute","text":"
SlotInput = Union[SlotResult, SlotFunc[TSlotData], Slot[TSlotData]]\n

See source code

Type representing all forms in which slot content can be passed to a component.

When rendering a component with Component.render() or Component.render_to_response(), the slots may be given a strings, functions, or Slot instances. This type describes that union.

Use this type when typing the slots in your component.

SlotInput accepts an optional type parameter to specify the data dictionary that will be passed to the slot content function.

Example:

from typing import NamedTuple\nfrom typing_extensions import TypedDict\nfrom django_components import Component, SlotInput\n\nclass TableFooterSlotData(TypedDict):\n    page_number: int\n\nclass Table(Component):\n    class Slots(NamedTuple):\n        header: SlotInput\n        footer: SlotInput[TableFooterSlotData]\n\n    template = \"<div>{% slot 'footer' %}</div>\"\n\nhtml = Table.render(\n    slots={\n        # As a string\n        \"header\": \"Hello, World!\",\n\n        # Safe string\n        \"header\": mark_safe(\"<i><am><safe>\"),\n\n        # Function\n        \"footer\": lambda ctx: f\"Page: {ctx.data['page_number']}!\",\n\n        # Slot instance\n        \"footer\": Slot(lambda ctx: f\"Page: {ctx.data['page_number']}!\"),\n\n        # None (Same as no slot)\n        \"header\": None,\n    },\n)\n
"},{"location":"reference/api/#django_components.SlotNode","title":"SlotNode","text":"
SlotNode(\n    params: List[TagAttr],\n    flags: Optional[Dict[str, bool]] = None,\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    contents: Optional[str] = None,\n    template_name: Optional[str] = None,\n    template_component: Optional[Type[Component]] = None,\n)\n

Bases: django_components.node.BaseNode

See source code

{% slot %} tag marks a place inside a component where content can be inserted from outside.

Learn more about using slots.

This is similar to slots as seen in Web components, Vue or React's children.

Args:

  • name (str, required): Registered name of the component to render
  • default: Optional flag. If there is a default slot, you can pass the component slot content without using the {% fill %} tag. See Default slot
  • required: Optional flag. Will raise an error if a slot is required but not given.
  • **kwargs: Any extra kwargs will be passed as the slot data.

Example:

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        {% slot \"content\" default %}\n          This is shown if not overriden!\n        {% endslot %}\n      </div>\n      <aside>\n        {% slot \"sidebar\" required / %}\n      </aside>\n    \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      <div>\n        {% component \"child\" %}\n          {% fill \"content\" %}\n            \ud83d\uddde\ufe0f\ud83d\udcf0\n          {% endfill %}\n\n          {% fill \"sidebar\" %}\n            \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n          {% endfill %}\n        {% endcomponent %}\n      </div>\n    \"\"\"\n
"},{"location":"reference/api/#django_components.SlotNode--slot-data","title":"Slot data","text":"

Any extra kwargs will be considered as slot data, and will be accessible in the {% fill %} tag via fill's data kwarg:

Read more about Slot data.

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        {# Passing data to the slot #}\n        {% slot \"content\" user=user %}\n          This is shown if not overriden!\n        {% endslot %}\n      </div>\n    \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      {# Parent can access the slot data #}\n      {% component \"child\" %}\n        {% fill \"content\" data=\"data\" %}\n          <div class=\"wrapper-class\">\n            {{ data.user }}\n          </div>\n        {% endfill %}\n      {% endcomponent %}\n    \"\"\"\n
"},{"location":"reference/api/#django_components.SlotNode--slot-fallback","title":"Slot fallback","text":"

The content between the {% slot %}..{% endslot %} tags is the fallback content that will be rendered if no fill is given for the slot.

This fallback content can then be accessed from within the {% fill %} tag using the fill's fallback kwarg. This is useful if you need to wrap / prepend / append the original slot's content.

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        {% slot \"content\" %}\n          This is fallback content!\n        {% endslot %}\n      </div>\n    \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      {# Parent can access the slot's fallback content #}\n      {% component \"child\" %}\n        {% fill \"content\" fallback=\"fallback\" %}\n          {{ fallback }}\n        {% endfill %}\n      {% endcomponent %}\n    \"\"\"\n

Methods:

  • parse \u2013
  • register \u2013
  • render \u2013
  • unregister \u2013

Attributes:

  • active_flags (List[str]) \u2013
  • allowed_flags \u2013
  • contents (Optional[str]) \u2013
  • end_tag \u2013
  • flags (Dict[str, bool]) \u2013
  • node_id (str) \u2013
  • nodelist (NodeList) \u2013
  • params (List[TagAttr]) \u2013
  • tag \u2013
  • template_component (Optional[Type[Component]]) \u2013
  • template_name (Optional[str]) \u2013
"},{"location":"reference/api/#django_components.SlotNode.active_flags","title":"active_flags property","text":"
active_flags: List[str]\n

See source code

Flags that were set for this specific instance as a list of strings.

E.g. the following tag:

{% slot \"content\" default required / %}\n

Will have the following flags:

[\"default\", \"required\"]\n
"},{"location":"reference/api/#django_components.SlotNode.allowed_flags","title":"allowed_flags class-attribute instance-attribute","text":"
allowed_flags = [SLOT_DEFAULT_FLAG, SLOT_REQUIRED_FLAG]\n
"},{"location":"reference/api/#django_components.SlotNode.contents","title":"contents instance-attribute","text":"
contents: Optional[str] = contents\n

See source code

See source code

The contents of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The contents will be \"<div> ... </div>\".

"},{"location":"reference/api/#django_components.SlotNode.end_tag","title":"end_tag class-attribute instance-attribute","text":"
end_tag = 'endslot'\n
"},{"location":"reference/api/#django_components.SlotNode.flags","title":"flags instance-attribute","text":"
flags: Dict[str, bool] = flags or {flag: Falsefor flag in (allowed_flags or [])}\n

See source code

See source code

Dictionary of all allowed_flags that were set on the tag.

Flags that were set are True, and the rest are False.

E.g. the following tag:

class SlotNode(BaseNode):\n    tag = \"slot\"\n    end_tag = \"endslot\"\n    allowed_flags = [\"default\", \"required\"]\n
{% slot \"content\" default %}\n

Has 2 flags, default and required, but only default was set.

The flags dictionary will be:

{\n    \"default\": True,\n    \"required\": False,\n}\n

You can check if a flag is set by doing:

if node.flags[\"default\"]:\n    ...\n
"},{"location":"reference/api/#django_components.SlotNode.node_id","title":"node_id instance-attribute","text":"
node_id: str = node_id or gen_id()\n

See source code

See source code

The unique ID of the node.

Extensions can use this ID to store additional information.

"},{"location":"reference/api/#django_components.SlotNode.nodelist","title":"nodelist instance-attribute","text":"
nodelist: NodeList = nodelist or NodeList()\n

See source code

See source code

The nodelist of the tag.

This is the text between the opening and closing tags, e.g.

{% slot \"content\" default required %}\n  <div>\n    ...\n  </div>\n{% endslot %}\n

The nodelist will contain the <div> ... </div> part.

Unlike contents, the nodelist contains the actual Nodes, not just the text.

"},{"location":"reference/api/#django_components.SlotNode.params","title":"params instance-attribute","text":"
params: List[TagAttr] = params\n

See source code

See source code

The parameters to the tag in the template.

A single param represents an arg or kwarg of the template tag.

E.g. the following tag:

{% component \"my_comp\" key=val key2='val2 two' %}\n

Has 3 params:

  • Posiitonal arg \"my_comp\"
  • Keyword arg key=val
  • Keyword arg key2='val2 two'
"},{"location":"reference/api/#django_components.SlotNode.tag","title":"tag class-attribute instance-attribute","text":"
tag = 'slot'\n
"},{"location":"reference/api/#django_components.SlotNode.template_component","title":"template_component instance-attribute","text":"
template_component: Optional[Type[Component]] = template_component\n

See source code

See source code

If the template that contains this node belongs to a Component, then this will be the Component class.

"},{"location":"reference/api/#django_components.SlotNode.template_name","title":"template_name instance-attribute","text":"
template_name: Optional[str] = template_name\n

See source code

See source code

The name of the Template that contains this node.

The template name is set by Django's template loaders.

For example, the filesystem template loader will set this to the absolute path of the template file.

\"/home/user/project/templates/my_template.html\"\n
"},{"location":"reference/api/#django_components.SlotNode.parse","title":"parse classmethod","text":"
parse(parser: Parser, token: Token, **kwargs: Any) -> BaseNode\n

See source code

This function is what is passed to Django's Library.tag() when registering the tag.

In other words, this method is called by Django's template parser when we encounter a tag that matches this node's tag, e.g. {% component %} or {% slot %}.

To register the tag, you can use BaseNode.register().

"},{"location":"reference/api/#django_components.SlotNode.register","title":"register classmethod","text":"
register(library: Library) -> None\n

See source code

A convenience method for registering the tag with the given library.

class MyNode(BaseNode):\n    tag = \"mynode\"\n\nMyNode.register(library)\n

Allows you to then use the node in templates like so:

{% load mylibrary %}\n{% mynode %}\n
"},{"location":"reference/api/#django_components.SlotNode.render","title":"render","text":"
render(context: Context, name: str, **kwargs: Any) -> SafeString\n
"},{"location":"reference/api/#django_components.SlotNode.unregister","title":"unregister classmethod","text":"
unregister(library: Library) -> None\n

See source code

Unregisters the node from the given library.

"},{"location":"reference/api/#django_components.SlotRef","title":"SlotRef module-attribute","text":"
SlotRef = SlotFallback\n

See source code

DEPRECATED: Use SlotFallback instead. Will be removed in v1.

"},{"location":"reference/api/#django_components.SlotResult","title":"SlotResult module-attribute","text":"
SlotResult = Union[str, SafeString]\n

See source code

Type representing the result of a slot render function.

Example:

from django_components import SlotContext, SlotResult\n\ndef my_slot_fn(ctx: SlotContext) -> SlotResult:\n    return \"Hello, world!\"\n\nmy_slot = Slot(my_slot_fn)\nhtml = my_slot()  # Output: Hello, world!\n

Read more about Slot functions.

"},{"location":"reference/api/#django_components.TagFormatterABC","title":"TagFormatterABC","text":"

Bases: abc.ABC

See source code

Abstract base class for defining custom tag formatters.

Tag formatters define how the component tags are used in the template.

Read more about Tag formatter.

For example, with the default tag formatter (ComponentFormatter), components are written as:

{% component \"comp_name\" %}\n{% endcomponent %}\n

While with the shorthand tag formatter (ShorthandComponentFormatter), components are written as:

{% comp_name %}\n{% endcomp_name %}\n

Example:

Implementation for ShorthandComponentFormatter:

from djagno_components import TagFormatterABC, TagResult\n\nclass ShorthandComponentFormatter(TagFormatterABC):\n    def start_tag(self, name: str) -> str:\n        return name\n\n    def end_tag(self, name: str) -> str:\n        return f\"end{name}\"\n\n    def parse(self, tokens: List[str]) -> TagResult:\n        tokens = [*tokens]\n        name = tokens.pop(0)\n        return TagResult(name, tokens)\n

Methods:

  • end_tag \u2013
  • parse \u2013
  • start_tag \u2013
"},{"location":"reference/api/#django_components.TagFormatterABC.end_tag","title":"end_tag abstractmethod","text":"
end_tag(name: str) -> str\n

See source code

Formats the end tag of a block component.

Parameters:

  • name (str) \u2013

    Component's registered name. Required.

Returns:

  • str ( str ) \u2013

    The formatted end tag.

"},{"location":"reference/api/#django_components.TagFormatterABC.parse","title":"parse abstractmethod","text":"
parse(tokens: List[str]) -> TagResult\n

See source code

Given the tokens (words) passed to a component start tag, this function extracts the component name from the tokens list, and returns TagResult, which is a tuple of (component_name, remaining_tokens).

Parameters:

  • tokens ([List(str]) \u2013

    List of tokens passed to the component tag.

Returns:

  • TagResult ( TagResult ) \u2013

    Parsed component name and remaining tokens.

Example:

Assuming we used a component in a template like this:

{% component \"my_comp\" key=val key2=val2 %}\n{% endcomponent %}\n

This function receives a list of tokens:

['component', '\"my_comp\"', 'key=val', 'key2=val2']\n
  • component is the tag name, which we drop.
  • \"my_comp\" is the component name, but we must remove the extra quotes.
  • The remaining tokens we pass unmodified, as that's the input to the component.

So in the end, we return:

TagResult('my_comp', ['key=val', 'key2=val2'])\n
"},{"location":"reference/api/#django_components.TagFormatterABC.start_tag","title":"start_tag abstractmethod","text":"
start_tag(name: str) -> str\n

See source code

Formats the start tag of a component.

Parameters:

  • name (str) \u2013

    Component's registered name. Required.

Returns:

  • str ( str ) \u2013

    The formatted start tag.

"},{"location":"reference/api/#django_components.TagResult","title":"TagResult","text":"

Bases: tuple

See source code

The return value from TagFormatter.parse().

Read more about Tag formatter.

Attributes:

  • component_name (str) \u2013
  • tokens (List[str]) \u2013
"},{"location":"reference/api/#django_components.TagResult.component_name","title":"component_name instance-attribute","text":"
component_name: str\n

See source code

Component name extracted from the template tag

For example, if we had tag

{% component \"my_comp\" key=val key2=val2 %}\n

Then component_name would be my_comp.

"},{"location":"reference/api/#django_components.TagResult.tokens","title":"tokens instance-attribute","text":"
tokens: List[str]\n

See source code

Remaining tokens (words) that were passed to the tag, with component name removed

For example, if we had tag

{% component \"my_comp\" key=val key2=val2 %}\n

Then tokens would be ['key=val', 'key2=val2'].

"},{"location":"reference/api/#django_components.all_components","title":"all_components","text":"
all_components() -> List[Type[Component]]\n

See source code

Get a list of all created Component classes.

"},{"location":"reference/api/#django_components.all_registries","title":"all_registries","text":"
all_registries() -> List[ComponentRegistry]\n

See source code

Get a list of all created ComponentRegistry instances.

"},{"location":"reference/api/#django_components.autodiscover","title":"autodiscover","text":"
autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n

See source code

Search for all python files in COMPONENTS.dirs and COMPONENTS.app_dirs and import them.

See Autodiscovery.

NOTE: Subdirectories and files starting with an underscore _ (except for __init__.py are ignored.

Parameters:

  • map_module (Callable[[str], str], default: None ) \u2013

    Map the module paths with map_module function. This serves as an escape hatch for when you need to use this function in tests.

Returns:

  • List[str] \u2013

    List[str]: A list of module paths of imported files.

To get the same list of modules that autodiscover() would return, but without importing them, use get_component_files():

from django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
"},{"location":"reference/api/#django_components.cached_template","title":"cached_template","text":"
cached_template(\n    template_string: str,\n    template_cls: Optional[Type[Template]] = None,\n    origin: Optional[Origin] = None,\n    name: Optional[str] = None,\n    engine: Optional[Any] = None,\n) -> Template\n

See source code

DEPRECATED. Template caching will be removed in v1.

Create a Template instance that will be cached as per the COMPONENTS.template_cache_size setting.

Parameters:

  • template_string (str) \u2013

    Template as a string, same as the first argument to Django's Template. Required.

  • template_cls (Type[Template], default: None ) \u2013

    Specify the Template class that should be instantiated. Defaults to Django's Template class.

  • origin (Type[Origin], default: None ) \u2013

    Sets Template.Origin.

  • name (Type[str], default: None ) \u2013

    Sets Template.name

  • engine (Type[Any], default: None ) \u2013

    Sets Template.engine

from django_components import cached_template\n\ntemplate = cached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n    pass\n\ntemplate = cached_template(\n    \"Variable: {{ variable }}\",\n    template_cls=MyTemplate,\n    name=...\n    origin=...\n    engine=...\n)\n
"},{"location":"reference/api/#django_components.format_attributes","title":"format_attributes","text":"
format_attributes(attributes: Mapping[str, Any]) -> str\n

See source code

Format a dict of attributes into an HTML attributes string.

Read more about HTML attributes.

Example:

format_attributes({\"class\": \"my-class\", \"data-id\": \"123\"})\n

will return

'class=\"my-class\" data-id=\"123\"'\n
"},{"location":"reference/api/#django_components.get_component_by_class_id","title":"get_component_by_class_id","text":"
get_component_by_class_id(comp_cls_id: str) -> Type[Component]\n

See source code

Get a component class by its unique ID.

Each component class is associated with a unique hash that's derived from its module import path.

E.g. path.to.my.secret.MyComponent -> MyComponent_ab01f32

This hash is available under class_id on the component class.

Raises KeyError if the component class is not found.

NOTE: This is mainly intended for extensions.

"},{"location":"reference/api/#django_components.get_component_dirs","title":"get_component_dirs","text":"
get_component_dirs(include_apps: bool = True) -> List[Path]\n

See source code

Get directories that may contain component files.

This is the heart of all features that deal with filesystem and file lookup. Autodiscovery, Django template resolution, static file resolution - They all use this.

Parameters:

  • include_apps (bool, default: True ) \u2013

    Include directories from installed Django apps. Defaults to True.

Returns:

  • List[Path] \u2013

    List[Path]: A list of directories that may contain component files.

get_component_dirs() searches for dirs set in COMPONENTS.dirs settings. If none set, defaults to searching for a \"components\" app.

In addition to that, also all installed Django apps are checked whether they contain directories as set in COMPONENTS.app_dirs (e.g. [app]/components).

Notes:

  • Paths that do not point to directories are ignored.

  • BASE_DIR setting is required.

  • The paths in COMPONENTS.dirs must be absolute paths.

"},{"location":"reference/api/#django_components.get_component_files","title":"get_component_files","text":"
get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]\n

See source code

Search for files within the component directories (as defined in get_component_dirs()).

Requires BASE_DIR setting to be set.

Subdirectories and files starting with an underscore _ (except __init__.py) are ignored.

Parameters:

  • suffix (Optional[str], default: None ) \u2013

    The suffix to search for. E.g. .py, .js, .css. Defaults to None, which will search for all files.

Returns:

  • List[ComponentFileEntry] \u2013

    List[ComponentFileEntry] A list of entries that contain both the filesystem path and the python import path (dot path).

Example:

from django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
"},{"location":"reference/api/#django_components.get_component_url","title":"get_component_url","text":"
get_component_url(component: Union[Type[Component], Component], query: Optional[Dict] = None, fragment: Optional[str] = None) -> str\n

See source code

Get the URL for a Component.

Raises RuntimeError if the component is not public.

Read more about Component views and URLs.

get_component_url() optionally accepts query and fragment arguments.

Example:

from django_components import Component, get_component_url\n\nclass MyComponent(Component):\n    class View:\n        public = True\n\n# Get the URL for the component\nurl = get_component_url(\n    MyComponent,\n    query={\"foo\": \"bar\"},\n    fragment=\"baz\",\n)\n# /components/ext/view/components/c1ab2c3?foo=bar#baz\n
"},{"location":"reference/api/#django_components.import_libraries","title":"import_libraries","text":"
import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n

See source code

Import modules set in COMPONENTS.libraries setting.

See Autodiscovery.

Parameters:

  • map_module (Callable[[str], str], default: None ) \u2013

    Map the module paths with map_module function. This serves as an escape hatch for when you need to use this function in tests.

Returns:

  • List[str] \u2013

    List[str]: A list of module paths of imported files.

Examples:

Normal usage - load libraries after Django has loaded

from django_components import import_libraries\n\nclass MyAppConfig(AppConfig):\n    def ready(self):\n        import_libraries()\n

Potential usage in tests

from django_components import import_libraries\n\nimport_libraries(lambda path: path.replace(\"tests.\", \"myapp.\"))\n

"},{"location":"reference/api/#django_components.merge_attributes","title":"merge_attributes","text":"
merge_attributes(*attrs: Dict) -> Dict\n

See source code

Merge a list of dictionaries into a single dictionary.

The dictionaries are treated as HTML attributes and are merged accordingly:

  • If a same key is present in multiple dictionaries, the values are joined with a space character.
  • The class and style keys are handled specially, similar to how Vue does it.

Read more about HTML attributes.

Example:

merge_attributes(\n    {\"my-attr\": \"my-value\", \"class\": \"my-class\"},\n    {\"my-attr\": \"extra-value\", \"data-id\": \"123\"},\n)\n

will result in

{\n    \"my-attr\": \"my-value extra-value\",\n    \"class\": \"my-class\",\n    \"data-id\": \"123\",\n}\n

The class attribute

The class attribute can be given as a string, or a dictionary.

  • If given as a string, it is used as is.
  • If given as a dictionary, only the keys with a truthy value are used.

Example:

merge_attributes(\n    {\"class\": \"my-class extra-class\"},\n    {\"class\": {\"truthy\": True, \"falsy\": False}},\n)\n

will result in

{\n    \"class\": \"my-class extra-class truthy\",\n}\n

The style attribute

The style attribute can be given as a string, a list, or a dictionary.

  • If given as a string, it is used as is.
  • If given as a dictionary, it is converted to a style attribute string.

Example:

merge_attributes(\n    {\"style\": \"color: red; background-color: blue;\"},\n    {\"style\": {\"background-color\": \"green\", \"color\": False}},\n)\n

will result in

{\n    \"style\": \"color: red; background-color: blue; background-color: green;\",\n}\n
"},{"location":"reference/api/#django_components.register","title":"register","text":"
register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[Type[TComponent]], Type[TComponent]]\n

See source code

Class decorator for registering a component to a component registry.

See Registering components.

Parameters:

  • name (str) \u2013

    Registered name. This is the name by which the component will be accessed from within a template when using the {% component %} tag. Required.

  • registry (ComponentRegistry, default: None ) \u2013

    Specify the registry to which to register this component. If omitted, component is registered to the default registry.

Raises:

  • AlreadyRegistered \u2013

    If there is already a component registered under the same name.

Examples:

from django_components import Component, register\n\n@register(\"my_component\")\nclass MyComponent(Component):\n    ...\n

Specifing ComponentRegistry the component should be registered to by setting the registry kwarg:

from django.template import Library\nfrom django_components import Component, ComponentRegistry, register\n\nmy_lib = Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n    ...\n
"},{"location":"reference/api/#django_components.registry","title":"registry module-attribute","text":"
registry: ComponentRegistry = ComponentRegistry()\n

See source code

The default and global component registry. Use this instance to directly register or remove components:

See Registering components.

# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get single\nregistry.get(\"button\")\n\n# Get all\nregistry.all()\n\n# Check if component is registered\nregistry.has(\"button\")\n\n# Unregister single\nregistry.unregister(\"button\")\n\n# Unregister all\nregistry.clear()\n
"},{"location":"reference/api/#django_components.render_dependencies","title":"render_dependencies","text":"
render_dependencies(content: TContent, strategy: DependenciesStrategy = 'document') -> TContent\n

See source code

Given a string that contains parts that were rendered by components, this function inserts all used JS and CSS.

By default, the string is parsed as an HTML and: - CSS is inserted at the end of <head> (if present) - JS is inserted at the end of <body> (if present)

If you used {% component_js_dependencies %} or {% component_css_dependencies %}, then the JS and CSS will be inserted only at these locations.

Example:

def my_view(request):\n    template = Template('''\n        {% load components %}\n        <!doctype html>\n        <html>\n            <head></head>\n            <body>\n                <h1>{{ table_name }}</h1>\n                {% component \"table\" name=table_name / %}\n            </body>\n        </html>\n    ''')\n\n    html = template.render(\n        Context({\n            \"table_name\": request.GET[\"name\"],\n        })\n    )\n\n    # This inserts components' JS and CSS\n    processed_html = render_dependencies(html)\n\n    return HttpResponse(processed_html)\n

"},{"location":"reference/api/#django_components.template_tag","title":"template_tag","text":"
template_tag(\n    library: Library, tag: str, end_tag: Optional[str] = None, allowed_flags: Optional[List[str]] = None\n) -> Callable[[Callable], Callable]\n

See source code

A simplified version of creating a template tag based on BaseNode.

Instead of defining the whole class, you can just define the render() method.

from django.template import Context, Library\nfrom django_components import BaseNode, template_tag\n\nlibrary = Library()\n\n@template_tag(\n    library,\n    tag=\"mytag\",\n    end_tag=\"endmytag\",\n    allowed_flags=[\"required\"],\n)\ndef mytag(node: BaseNode, context: Context, name: str, **kwargs: Any) -> str:\n    return f\"Hello, {name}!\"\n

This will allow the template tag {% mytag %} to be used like this:

{% mytag name=\"John\" %}\n{% mytag name=\"John\" required %} ... {% endmytag %}\n

The given function will be wrapped in a class that inherits from BaseNode.

And this class will be registered with the given library.

The function MUST accept at least two positional arguments: node and context

  • node is the BaseNode instance.
  • context is the Context of the template.

Any extra parameters defined on this function will be part of the tag's input parameters.

For more info, see BaseNode.render().

"},{"location":"reference/commands/","title":"CLI commands","text":""},{"location":"reference/commands/#commands","title":"Commands","text":"

These are all the Django management commands that will be added by installing django_components:

"},{"location":"reference/commands/#components","title":"components","text":"
usage: python manage.py  components [-h] {create,upgrade,ext,list} ...\n

See source code

The entrypoint for the 'components' commands.

Options:

  • -h, --help
    • show this help message and exit

Subcommands:

  • create
    • Create a new django component.
  • upgrade
    • Upgrade django components syntax from '{% component_block ... %}' to '{% component ... %}'.
  • ext
    • Run extension commands.
  • list
    • List all components created in this project.

The entrypoint for the \"components\" commands.

python manage.py components list\npython manage.py components create <name>\npython manage.py components upgrade\npython manage.py components ext list\npython manage.py components ext run <extension> <command>\n
"},{"location":"reference/commands/#components-create","title":"components create","text":"
usage: python manage.py components create [-h] [--path PATH] [--js JS] [--css CSS] [--template TEMPLATE]\n              [--force] [--verbose] [--dry-run]\n              name\n

See source code

Create a new django component.

Positional Arguments:

  • name
    • The name of the component to create. This is a required argument.

Options:

  • -h, --help
    • show this help message and exit
  • --path PATH
    • The path to the component's directory. This is an optional argument. If not provided, the command will use the COMPONENTS.dirs setting from your Django settings.
  • --js JS
    • The name of the JavaScript file. This is an optional argument. The default value is script.js.
  • --css CSS
    • The name of the CSS file. This is an optional argument. The default value is style.css.
  • --template TEMPLATE
    • The name of the template file. This is an optional argument. The default value is template.html.
  • --force
    • This option allows you to overwrite existing files if they exist. This is an optional argument.
  • --verbose
    • This option allows the command to print additional information during component creation. This is an optional argument.
  • --dry-run
    • This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False.
"},{"location":"reference/commands/#usage","title":"Usage","text":"

To use the command, run the following command in your terminal:

python manage.py components create <name> --path <path> --js <js_filename> --css <css_filename> --template <template_filename> --force --verbose --dry-run\n

Replace <name>, <path>, <js_filename>, <css_filename>, and <template_filename> with your desired values.

"},{"location":"reference/commands/#examples","title":"Examples","text":"

Here are some examples of how you can use the command:

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 components create my_component\n

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.

Creating a Component with Custom Settings

You can also create a component with custom settings by providing additional arguments:

python manage.py components create new_component --path my_components --js my_script.js --css my_style.css --template my_template.html\n

This will create a new component named new_component in the my_components directory. The JavaScript, CSS, and template files will be named my_script.js, my_style.css, and my_template.html, respectively.

Overwriting an Existing Component

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

python manage.py components create my_component --force\n

This will overwrite the existing my_component if it exists.

Simulating Component Creation

If you want to simulate the creation of a component without actually creating any files, you can use the --dry-run option:

python manage.py components create my_component --dry-run\n

This will simulate the creation of my_component without creating any files.

"},{"location":"reference/commands/#components-upgrade","title":"components upgrade","text":"
usage: python manage.py components upgrade [-h] [--path PATH]\n

See source code

Upgrade django components syntax from '{% component_block ... %}' to '{% component ... %}'.

Options:

  • -h, --help
    • show this help message and exit
  • --path PATH
    • Path to search for components
"},{"location":"reference/commands/#components-ext","title":"components ext","text":"
usage: python manage.py components ext [-h] {list,run} ...\n

See source code

Run extension commands.

Options:

  • -h, --help
    • show this help message and exit

Subcommands:

  • list
    • List all extensions.
  • run
    • Run a command added by an extension.

Run extension commands.

python manage.py components ext list\npython manage.py components ext run <extension> <command>\n
"},{"location":"reference/commands/#components-ext-list","title":"components ext list","text":"
usage: python manage.py components ext list [-h] [--all] [--columns COLUMNS] [-s]\n

See source code

List all extensions.

Options:

  • -h, --help
    • show this help message and exit
  • --all
    • Show all columns. Same as --columns name.
  • --columns COLUMNS
    • Comma-separated list of columns to show. Available columns: name. Defaults to --columns name.
  • -s, --simple
    • Only show table data, without headers. Use this option for generating machine-readable output.

List all extensions.

python manage.py components ext list\n

Prints the list of installed extensions:

name\n==============\nview\nmy_extension\n

To specify which columns to show, use the --columns flag:

python manage.py components ext list --columns name\n

Which prints:

name\n==============\nview\nmy_extension\n

To print out all columns, use the --all flag:

python manage.py components ext list --all\n

If you need to omit the title in order to programmatically post-process the output, you can use the --simple (or -s) flag:

python manage.py components ext list --simple\n

Which prints just:

view\nmy_extension\n
"},{"location":"reference/commands/#components-ext-run","title":"components ext run","text":"
usage: python manage.py components ext run [-h]\n

See source code

Run a command added by an extension.

Options:

  • -h, --help
    • show this help message and exit

Run a command added by an extension.

Each extension can add its own commands, which will be available to run with this command.

For example, if you define and install the following extension:

from django_components import ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n    name = \"hello\"\n    help = \"Say hello\"\n    def handle(self, *args, **kwargs):\n        print(\"Hello, world!\")\n\nclass MyExt(ComponentExtension):\n    name = \"my_ext\"\n    commands = [HelloCommand]\n

You can run the hello command with:

python manage.py components ext run my_ext hello\n

You can also define arguments for the command, which will be passed to the command's handle method.

from django_components import CommandArg, ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n    name = \"hello\"\n    help = \"Say hello\"\n    arguments = [\n        CommandArg(name=\"name\", help=\"The name to say hello to\"),\n        CommandArg(name=[\"--shout\", \"-s\"], action=\"store_true\"),\n    ]\n\n    def handle(self, name: str, *args, **kwargs):\n        shout = kwargs.get(\"shout\", False)\n        msg = f\"Hello, {name}!\"\n        if shout:\n            msg = msg.upper()\n        print(msg)\n

You can run the command with:

python manage.py components ext run my_ext hello --name John --shout\n

Note

Command arguments and options are based on Python's argparse module.

For more information, see the argparse documentation.

"},{"location":"reference/commands/#components-list","title":"components list","text":"
usage: python manage.py components list [-h] [--all] [--columns COLUMNS] [-s]\n

See source code

List all components created in this project.

Options:

  • -h, --help
    • show this help message and exit
  • --all
    • Show all columns. Same as --columns name,full_name,path.
  • --columns COLUMNS
    • Comma-separated list of columns to show. Available columns: name, full_name, path. Defaults to --columns full_name,path.
  • -s, --simple
    • Only show table data, without headers. Use this option for generating machine-readable output.

List all components.

python manage.py components list\n

Prints the list of available components:

full_name                                                     path\n==================================================================================================\nproject.pages.project.ProjectPage                             ./project/pages/project\nproject.components.dashboard.ProjectDashboard                 ./project/components/dashboard\nproject.components.dashboard_action.ProjectDashboardAction    ./project/components/dashboard_action\n

To specify which columns to show, use the --columns flag:

python manage.py components list --columns name,full_name,path\n

Which prints:

name                      full_name                                                     path\n==================================================================================================\nProjectPage               project.pages.project.ProjectPage                             ./project/pages/project\nProjectDashboard          project.components.dashboard.ProjectDashboard                 ./project/components/dashboard\nProjectDashboardAction    project.components.dashboard_action.ProjectDashboardAction    ./project/components/dashboard_action\n

To print out all columns, use the --all flag:

python manage.py components list --all\n

If you need to omit the title in order to programmatically post-process the output, you can use the --simple (or -s) flag:

python manage.py components list --simple\n

Which prints just:

ProjectPage               project.pages.project.ProjectPage                             ./project/pages/project\nProjectDashboard          project.components.dashboard.ProjectDashboard                 ./project/components/dashboard\nProjectDashboardAction    project.components.dashboard_action.ProjectDashboardAction    ./project/components/dashboard_action\n
"},{"location":"reference/commands/#startcomponent","title":"startcomponent","text":"
usage: startcomponent [-h] [--path PATH] [--js JS] [--css CSS]\n                      [--template TEMPLATE] [--force] [--verbose] [--dry-run]\n                      [--version] [-v {0,1,2,3}] [--settings SETTINGS]\n                      [--pythonpath PYTHONPATH] [--traceback] [--no-color]\n                      [--force-color] [--skip-checks]\n                      name\n

See source code

Deprecated. Use components create instead.

Positional Arguments:

  • name
    • The name of the component to create. This is a required argument.

Options:

  • -h, --help
    • show this help message and exit
  • --path PATH
    • The path to the component's directory. This is an optional argument. If not provided, the command will use the COMPONENTS.dirs setting from your Django settings.
  • --js JS
    • The name of the JavaScript file. This is an optional argument. The default value is script.js.
  • --css CSS
    • The name of the CSS file. This is an optional argument. The default value is style.css.
  • --template TEMPLATE
    • The name of the template file. This is an optional argument. The default value is template.html.
  • --force
    • This option allows you to overwrite existing files if they exist. This is an optional argument.
  • --verbose
    • This option allows the command to print additional information during component creation. This is an optional argument.
  • --dry-run
    • This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False.
  • --version
    • Show program's version number and exit.
  • -v, --verbosity {0,1,2,3}
    • Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output
  • --settings SETTINGS
    • The Python path to a settings module, e.g. \"myproject.settings.main\". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used.
  • --pythonpath PYTHONPATH
    • A directory to add to the Python path, e.g. \"/home/djangoprojects/myproject\".
  • --traceback
    • Raise on CommandError exceptions.
  • --no-color
    • Don't colorize the command output.
  • --force-color
    • Force colorization of the command output.
  • --skip-checks
    • Skip system checks.

Deprecated. Use components create instead.

"},{"location":"reference/commands/#upgradecomponent","title":"upgradecomponent","text":"
usage: upgradecomponent [-h] [--path PATH] [--version] [-v {0,1,2,3}]\n                        [--settings SETTINGS] [--pythonpath PYTHONPATH]\n                        [--traceback] [--no-color] [--force-color]\n                        [--skip-checks]\n

See source code

Deprecated. Use components upgrade instead.

Options:

  • -h, --help
    • show this help message and exit
  • --path PATH
    • Path to search for components
  • --version
    • Show program's version number and exit.
  • -v, --verbosity {0,1,2,3}
    • Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output
  • --settings SETTINGS
    • The Python path to a settings module, e.g. \"myproject.settings.main\". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used.
  • --pythonpath PYTHONPATH
    • A directory to add to the Python path, e.g. \"/home/djangoprojects/myproject\".
  • --traceback
    • Raise on CommandError exceptions.
  • --no-color
    • Don't colorize the command output.
  • --force-color
    • Force colorization of the command output.
  • --skip-checks
    • Skip system checks.

Deprecated. Use components upgrade instead.

"},{"location":"reference/components/","title":"Components","text":""},{"location":"reference/components/#components","title":"Components","text":"

These are the components provided by django_components.

"},{"location":"reference/components/#django_components.components.dynamic.DynamicComponent","title":"DynamicComponent","text":"

Bases: django_components.component.Component

See source code

This component is given a registered name or a reference to another component, and behaves as if the other component was in its place.

The args, kwargs, and slot fills are all passed down to the underlying component.

Parameters:

  • is (str | Type[Component]) \u2013

    Component that should be rendered. Either a registered name of a component, or a Component class directly. Required.

  • registry (ComponentRegistry, default: None ) \u2013

    Specify the registry to search for the registered name. If omitted, all registries are searched until the first match.

  • *args (Optional[Any], default: None ) \u2013

    Additional data passed to the component.

  • **kwargs (Optional[Any], default: None ) \u2013

    Additional data passed to the component.

Slots:

  • Any slots, depending on the actual component.

Examples:

Django

{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% endcomponent %}\n

Or in case you use the django_components.component_shorthand_formatter tag formatter:

{% dynamic is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% enddynamic %}\n

Python

from django_components import DynamicComponent\n\nDynamicComponent.render(\n    kwargs={\n        \"is\": table_comp,\n        \"data\": table_data,\n        \"headers\": table_headers,\n    },\n    slots={\n        \"pagination\": PaginationComponent.render(\n            deps_strategy=\"ignore\",\n        ),\n    },\n)\n

"},{"location":"reference/components/#django_components.components.dynamic.DynamicComponent--use-cases","title":"Use cases","text":"

Dynamic components are suitable if you are writing something like a form component. You may design it such that users give you a list of input types, and you render components depending on the input types.

While you could handle this with a series of if / else statements, that's not an extensible approach. Instead, you can use the dynamic component in place of normal components.

"},{"location":"reference/components/#django_components.components.dynamic.DynamicComponent--component-name","title":"Component name","text":"

By default, the dynamic component is registered under the name \"dynamic\". In case of a conflict, you can set the COMPONENTS.dynamic_component_name setting to change the name used for the dynamic components.

# settings.py\nCOMPONENTS = ComponentsSettings(\n    dynamic_component_name=\"my_dynamic\",\n)\n

After which you will be able to use the dynamic component with the new name:

{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% endcomponent %}\n

"},{"location":"reference/exceptions/","title":"Exceptions","text":""},{"location":"reference/exceptions/#exceptions","title":"Exceptions","text":""},{"location":"reference/exceptions/#django_components.AlreadyRegistered","title":"AlreadyRegistered","text":"

Bases: Exception

See source code

Raised when you try to register a Component, but it's already registered with given ComponentRegistry.

"},{"location":"reference/exceptions/#django_components.NotRegistered","title":"NotRegistered","text":"

Bases: Exception

See source code

Raised when you try to access a Component, but it's NOT registered with given ComponentRegistry.

"},{"location":"reference/exceptions/#django_components.TagProtectedError","title":"TagProtectedError","text":"

Bases: Exception

See source code

The way the TagFormatter works is that, based on which start and end tags are used for rendering components, the ComponentRegistry behind the scenes un-/registers the template tags with the associated instance of Django's Library.

In other words, if I have registered a component \"table\", and I use the shorthand syntax:

{% table ... %}\n{% endtable %}\n

Then ComponentRegistry registers the tag table onto the Django's Library instance.

However, that means that if we registered a component \"slot\", then we would overwrite the {% slot %} tag from django_components.

Thus, this exception is raised when a component is attempted to be registered under a forbidden name, such that it would overwrite one of django_component's own template tags.

"},{"location":"reference/extension_commands/","title":"Extension commands API","text":""},{"location":"reference/extension_commands/#extension-commands-api","title":"Extension commands API","text":"

Overview of all classes, functions, and other objects related to defining extension commands.

Read more on Extensions.

"},{"location":"reference/extension_commands/#django_components.CommandArg","title":"CommandArg dataclass","text":"
CommandArg(\n    name_or_flags: Union[str, Sequence[str]],\n    action: Optional[Union[CommandLiteralAction, Action]] = None,\n    nargs: Optional[Union[int, Literal[\"*\", \"+\", \"?\"]]] = None,\n    const: Any = None,\n    default: Any = None,\n    type: Optional[Union[Type, Callable[[str], Any]]] = None,\n    choices: Optional[Sequence[Any]] = None,\n    required: Optional[bool] = None,\n    help: Optional[str] = None,\n    metavar: Optional[str] = None,\n    dest: Optional[str] = None,\n    version: Optional[str] = None,\n    deprecated: Optional[bool] = None,\n)\n

Bases: object

See source code

Define a single positional argument or an option for a command.

Fields on this class correspond to the arguments for ArgumentParser.add_argument()

Methods:

  • asdict \u2013

Attributes:

  • action (Optional[Union[CommandLiteralAction, Action]]) \u2013
  • choices (Optional[Sequence[Any]]) \u2013
  • const (Any) \u2013
  • default (Any) \u2013
  • deprecated (Optional[bool]) \u2013
  • dest (Optional[str]) \u2013
  • help (Optional[str]) \u2013
  • metavar (Optional[str]) \u2013
  • name_or_flags (Union[str, Sequence[str]]) \u2013
  • nargs (Optional[Union[int, Literal['*', '+', '?']]]) \u2013
  • required (Optional[bool]) \u2013
  • type (Optional[Union[Type, Callable[[str], Any]]]) \u2013
  • version (Optional[str]) \u2013
"},{"location":"reference/extension_commands/#django_components.CommandArg.action","title":"action class-attribute instance-attribute","text":"
action: Optional[Union[CommandLiteralAction, Action]] = None\n

See source code

The basic type of action to be taken when this argument is encountered at the command line.

"},{"location":"reference/extension_commands/#django_components.CommandArg.choices","title":"choices class-attribute instance-attribute","text":"
choices: Optional[Sequence[Any]] = None\n

See source code

A sequence of the allowable values for the argument.

"},{"location":"reference/extension_commands/#django_components.CommandArg.const","title":"const class-attribute instance-attribute","text":"
const: Any = None\n

See source code

A constant value required by some action and nargs selections.

"},{"location":"reference/extension_commands/#django_components.CommandArg.default","title":"default class-attribute instance-attribute","text":"
default: Any = None\n

See source code

The value produced if the argument is absent from the command line and if it is absent from the namespace object.

"},{"location":"reference/extension_commands/#django_components.CommandArg.deprecated","title":"deprecated class-attribute instance-attribute","text":"
deprecated: Optional[bool] = None\n

See source code

Whether or not use of the argument is deprecated.

NOTE: This is supported only in Python 3.13+

"},{"location":"reference/extension_commands/#django_components.CommandArg.dest","title":"dest class-attribute instance-attribute","text":"
dest: Optional[str] = None\n

See source code

The name of the attribute to be added to the object returned by parse_args().

"},{"location":"reference/extension_commands/#django_components.CommandArg.help","title":"help class-attribute instance-attribute","text":"
help: Optional[str] = None\n

See source code

A brief description of what the argument does.

"},{"location":"reference/extension_commands/#django_components.CommandArg.metavar","title":"metavar class-attribute instance-attribute","text":"
metavar: Optional[str] = None\n

See source code

A name for the argument in usage messages.

"},{"location":"reference/extension_commands/#django_components.CommandArg.name_or_flags","title":"name_or_flags instance-attribute","text":"
name_or_flags: Union[str, Sequence[str]]\n

See source code

Either a name or a list of option strings, e.g. 'foo' or '-f', '--foo'.

"},{"location":"reference/extension_commands/#django_components.CommandArg.nargs","title":"nargs class-attribute instance-attribute","text":"
nargs: Optional[Union[int, Literal['*', '+', '?']]] = None\n

See source code

The number of command-line arguments that should be consumed.

"},{"location":"reference/extension_commands/#django_components.CommandArg.required","title":"required class-attribute instance-attribute","text":"
required: Optional[bool] = None\n

See source code

Whether or not the command-line option may be omitted (optionals only).

"},{"location":"reference/extension_commands/#django_components.CommandArg.type","title":"type class-attribute instance-attribute","text":"
type: Optional[Union[Type, Callable[[str], Any]]] = None\n

See source code

The type to which the command-line argument should be converted.

"},{"location":"reference/extension_commands/#django_components.CommandArg.version","title":"version class-attribute instance-attribute","text":"
version: Optional[str] = None\n

See source code

The version string to be added to the object returned by parse_args().

MUST be used with action='version'.

See https://docs.python.org/3/library/argparse.html#action

"},{"location":"reference/extension_commands/#django_components.CommandArg.asdict","title":"asdict","text":"
asdict() -> dict\n

See source code

Convert the dataclass to a dictionary, stripping out fields with None values

"},{"location":"reference/extension_commands/#django_components.CommandArgGroup","title":"CommandArgGroup dataclass","text":"
CommandArgGroup(title: Optional[str] = None, description: Optional[str] = None, arguments: Sequence[CommandArg] = ())\n

Bases: object

See source code

Define a group of arguments for a command.

Fields on this class correspond to the arguments for ArgumentParser.add_argument_group()

Methods:

  • asdict \u2013

Attributes:

  • arguments (Sequence[CommandArg]) \u2013
  • description (Optional[str]) \u2013
  • title (Optional[str]) \u2013
"},{"location":"reference/extension_commands/#django_components.CommandArgGroup.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Sequence[CommandArg] = ()\n
"},{"location":"reference/extension_commands/#django_components.CommandArgGroup.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n

See source code

Description for the argument group in help output, by default None

"},{"location":"reference/extension_commands/#django_components.CommandArgGroup.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = None\n

See source code

Title for the argument group in help output; by default \u201cpositional arguments\u201d if description is provided, otherwise uses title for positional arguments.

"},{"location":"reference/extension_commands/#django_components.CommandArgGroup.asdict","title":"asdict","text":"
asdict() -> dict\n

See source code

Convert the dataclass to a dictionary, stripping out fields with None values

"},{"location":"reference/extension_commands/#django_components.CommandHandler","title":"CommandHandler","text":""},{"location":"reference/extension_commands/#django_components.CommandParserInput","title":"CommandParserInput dataclass","text":"
CommandParserInput(\n    prog: Optional[str] = None,\n    usage: Optional[str] = None,\n    description: Optional[str] = None,\n    epilog: Optional[str] = None,\n    parents: Optional[Sequence[ArgumentParser]] = None,\n    formatter_class: Optional[Type[_FormatterClass]] = None,\n    prefix_chars: Optional[str] = None,\n    fromfile_prefix_chars: Optional[str] = None,\n    argument_default: Optional[Any] = None,\n    conflict_handler: Optional[str] = None,\n    add_help: Optional[bool] = None,\n    allow_abbrev: Optional[bool] = None,\n    exit_on_error: Optional[bool] = None,\n)\n

Bases: object

See source code

Typing for the input to the ArgumentParser constructor.

Methods:

  • asdict \u2013

Attributes:

  • add_help (Optional[bool]) \u2013
  • allow_abbrev (Optional[bool]) \u2013
  • argument_default (Optional[Any]) \u2013
  • conflict_handler (Optional[str]) \u2013
  • description (Optional[str]) \u2013
  • epilog (Optional[str]) \u2013
  • exit_on_error (Optional[bool]) \u2013
  • formatter_class (Optional[Type[_FormatterClass]]) \u2013
  • fromfile_prefix_chars (Optional[str]) \u2013
  • parents (Optional[Sequence[ArgumentParser]]) \u2013
  • prefix_chars (Optional[str]) \u2013
  • prog (Optional[str]) \u2013
  • usage (Optional[str]) \u2013
"},{"location":"reference/extension_commands/#django_components.CommandParserInput.add_help","title":"add_help class-attribute instance-attribute","text":"
add_help: Optional[bool] = None\n

See source code

Add a -h/--help option to the parser (default: True)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.allow_abbrev","title":"allow_abbrev class-attribute instance-attribute","text":"
allow_abbrev: Optional[bool] = None\n

See source code

Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.argument_default","title":"argument_default class-attribute instance-attribute","text":"
argument_default: Optional[Any] = None\n

See source code

The global default value for arguments (default: None)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.conflict_handler","title":"conflict_handler class-attribute instance-attribute","text":"
conflict_handler: Optional[str] = None\n

See source code

The strategy for resolving conflicting optionals (usually unnecessary)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n

See source code

Text to display before the argument help (by default, no text)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.epilog","title":"epilog class-attribute instance-attribute","text":"
epilog: Optional[str] = None\n

See source code

Text to display after the argument help (by default, no text)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.exit_on_error","title":"exit_on_error class-attribute instance-attribute","text":"
exit_on_error: Optional[bool] = None\n

See source code

Determines whether or not ArgumentParser exits with error info when an error occurs. (default: True)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.formatter_class","title":"formatter_class class-attribute instance-attribute","text":"
formatter_class: Optional[Type[_FormatterClass]] = None\n

See source code

A class for customizing the help output

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.fromfile_prefix_chars","title":"fromfile_prefix_chars class-attribute instance-attribute","text":"
fromfile_prefix_chars: Optional[str] = None\n

See source code

The set of characters that prefix files from which additional arguments should be read (default: None)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.parents","title":"parents class-attribute instance-attribute","text":"
parents: Optional[Sequence[ArgumentParser]] = None\n

See source code

A list of ArgumentParser objects whose arguments should also be included

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.prefix_chars","title":"prefix_chars class-attribute instance-attribute","text":"
prefix_chars: Optional[str] = None\n

See source code

The set of characters that prefix optional arguments (default: \u2018-\u2018)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.prog","title":"prog class-attribute instance-attribute","text":"
prog: Optional[str] = None\n

See source code

The name of the program (default: os.path.basename(sys.argv[0]))

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.usage","title":"usage class-attribute instance-attribute","text":"
usage: Optional[str] = None\n

See source code

The string describing the program usage (default: generated from arguments added to parser)

"},{"location":"reference/extension_commands/#django_components.CommandParserInput.asdict","title":"asdict","text":"
asdict() -> dict\n

See source code

Convert the dataclass to a dictionary, stripping out fields with None values

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand","title":"CommandSubcommand dataclass","text":"
CommandSubcommand(\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    prog: Optional[str] = None,\n    parser_class: Optional[Type[ArgumentParser]] = None,\n    action: Optional[Union[CommandLiteralAction, Action]] = None,\n    dest: Optional[str] = None,\n    required: Optional[bool] = None,\n    help: Optional[str] = None,\n    metavar: Optional[str] = None,\n)\n

Bases: object

See source code

Define a subcommand for a command.

Fields on this class correspond to the arguments for ArgumentParser.add_subparsers.add_parser()

Methods:

  • asdict \u2013

Attributes:

  • action (Optional[Union[CommandLiteralAction, Action]]) \u2013
  • description (Optional[str]) \u2013
  • dest (Optional[str]) \u2013
  • help (Optional[str]) \u2013
  • metavar (Optional[str]) \u2013
  • parser_class (Optional[Type[ArgumentParser]]) \u2013
  • prog (Optional[str]) \u2013
  • required (Optional[bool]) \u2013
  • title (Optional[str]) \u2013
"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.action","title":"action class-attribute instance-attribute","text":"
action: Optional[Union[CommandLiteralAction, Action]] = None\n

See source code

The basic type of action to be taken when this argument is encountered at the command line.

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n

See source code

Description for the sub-parser group in help output, by default None.

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.dest","title":"dest class-attribute instance-attribute","text":"
dest: Optional[str] = None\n

See source code

Name of the attribute under which sub-command name will be stored; by default None and no value is stored.

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.help","title":"help class-attribute instance-attribute","text":"
help: Optional[str] = None\n

See source code

Help for sub-parser group in help output, by default None.

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.metavar","title":"metavar class-attribute instance-attribute","text":"
metavar: Optional[str] = None\n

See source code

String presenting available subcommands in help; by default it is None and presents subcommands in form {cmd1, cmd2, ..}.

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.parser_class","title":"parser_class class-attribute instance-attribute","text":"
parser_class: Optional[Type[ArgumentParser]] = None\n

See source code

Class which will be used to create sub-parser instances, by default the class of the current parser (e.g. ArgumentParser).

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.prog","title":"prog class-attribute instance-attribute","text":"
prog: Optional[str] = None\n

See source code

Usage information that will be displayed with sub-command help, by default the name of the program and any positional arguments before the subparser argument.

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.required","title":"required class-attribute instance-attribute","text":"
required: Optional[bool] = None\n

See source code

Whether or not a subcommand must be provided, by default False (added in 3.7)

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = None\n

See source code

Title for the sub-parser group in help output; by default \u201csubcommands\u201d if description is provided, otherwise uses title for positional arguments.

"},{"location":"reference/extension_commands/#django_components.CommandSubcommand.asdict","title":"asdict","text":"
asdict() -> dict\n

See source code

Convert the dataclass to a dictionary, stripping out fields with None values

"},{"location":"reference/extension_commands/#django_components.ComponentCommand","title":"ComponentCommand","text":"

Bases: object

See source code

Definition of a CLI command.

This class is based on Python's argparse module and Django's BaseCommand class. ComponentCommand allows you to define:

  • Command name, description, and help text
  • Arguments and options (e.g. --name John)
  • Group arguments (see argparse groups)
  • Subcommands (e.g. components ext run my_ext hello)
  • Handler behavior

Each extension can add its own commands, which will be available to run with components ext run.

Extensions use the ComponentCommand class to define their commands.

For example, if you define and install the following extension:

from django_components ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n    name = \"hello\"\n    help = \"Say hello\"\n    def handle(self, *args, **kwargs):\n        print(\"Hello, world!\")\n\nclass MyExt(ComponentExtension):\n    name = \"my_ext\"\n    commands = [HelloCommand]\n

You can run the hello command with:

python manage.py components ext run my_ext hello\n

You can also define arguments for the command, which will be passed to the command's handle method.

from django_components import CommandArg, ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n    name = \"hello\"\n    help = \"Say hello\"\n    arguments = [\n        CommandArg(name=\"name\", help=\"The name to say hello to\"),\n        CommandArg(name=[\"--shout\", \"-s\"], action=\"store_true\"),\n    ]\n\n    def handle(self, name: str, *args, **kwargs):\n        shout = kwargs.get(\"shout\", False)\n        msg = f\"Hello, {name}!\"\n        if shout:\n            msg = msg.upper()\n        print(msg)\n

You can run the command with:

python manage.py components ext run my_ext hello --name John --shout\n

Note

Command arguments and options are based on Python's argparse module.

For more information, see the argparse documentation.

Attributes:

  • arguments (Sequence[Union[CommandArg, CommandArgGroup]]) \u2013
  • handle (Optional[CommandHandler]) \u2013
  • help (Optional[str]) \u2013
  • name (str) \u2013
  • parser_input (Optional[CommandParserInput]) \u2013
  • subcommands (Sequence[Type[ComponentCommand]]) \u2013
  • subparser_input (Optional[CommandSubcommand]) \u2013
"},{"location":"reference/extension_commands/#django_components.ComponentCommand.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Sequence[Union[CommandArg, CommandArgGroup]] = ()\n

See source code

argparse arguments for the command

"},{"location":"reference/extension_commands/#django_components.ComponentCommand.handle","title":"handle class-attribute instance-attribute","text":"
handle: Optional[CommandHandler] = None\n

See source code

The function that is called when the command is run. If None, the command will print the help message.

"},{"location":"reference/extension_commands/#django_components.ComponentCommand.help","title":"help class-attribute instance-attribute","text":"
help: Optional[str] = None\n

See source code

The help text for the command

"},{"location":"reference/extension_commands/#django_components.ComponentCommand.name","title":"name instance-attribute","text":"
name: str\n

See source code

The name of the command - this is what is used to call the command

"},{"location":"reference/extension_commands/#django_components.ComponentCommand.parser_input","title":"parser_input class-attribute instance-attribute","text":"
parser_input: Optional[CommandParserInput] = None\n

See source code

The input to use when creating the ArgumentParser for this command. If None, the default values will be used.

"},{"location":"reference/extension_commands/#django_components.ComponentCommand.subcommands","title":"subcommands class-attribute instance-attribute","text":"
subcommands: Sequence[Type[ComponentCommand]] = ()\n

See source code

Subcommands for the command

"},{"location":"reference/extension_commands/#django_components.ComponentCommand.subparser_input","title":"subparser_input class-attribute instance-attribute","text":"
subparser_input: Optional[CommandSubcommand] = None\n

See source code

The input to use when this command is a subcommand installed with add_subparser(). If None, the default values will be used.

"},{"location":"reference/extension_hooks/","title":"Extension hooks","text":""},{"location":"reference/extension_hooks/#extension-hooks","title":"Extension hooks","text":"

Overview of all the extension hooks available in Django Components.

Read more on Extensions.

"},{"location":"reference/extension_hooks/#hooks","title":"Hooks","text":"

Available data:

name type description component_cls Type[Component] The created Component class

Available data:

name type description component_cls Type[Component] The to-be-deleted Component class

Available data:

name type description component Component The Component instance that is being rendered component_cls Type[Component] The Component class component_id str The unique identifier for this component instance context_data Dict Deprecated. Use template_data instead. Will be removed in v1.0. css_data Dict Dictionary of CSS data from Component.get_css_data() js_data Dict Dictionary of JavaScript data from Component.get_js_data() template_data Dict Dictionary of template data from Component.get_template_data()

Available data:

name type description args List List of positional arguments passed to the component component Component The Component instance that received the input and is being rendered component_cls Type[Component] The Component class component_id str The unique identifier for this component instance context Context The Django template Context object kwargs Dict Dictionary of keyword arguments passed to the component slots Dict[str, Slot] Dictionary of slot definitions

Available data:

name type description component_cls Type[Component] The registered Component class name str The name the component was registered under registry ComponentRegistry The registry the component was registered to

Available data:

name type description component Component The Component instance that is being rendered component_cls Type[Component] The Component class component_id str The unique identifier for this component instance error Optional[Exception] The error that occurred during rendering, or None if rendering was successful result Optional[str] The rendered component, or None if rendering failed

Available data:

name type description component_cls Type[Component] The unregistered Component class name str The name the component was registered under registry ComponentRegistry The registry the component was unregistered from

Available data:

name type description component_cls Type[Component] The Component class whose CSS was loaded content str The CSS content (string)

Available data:

name type description component_cls Type[Component] The Component class whose JS was loaded content str The JS content (string)

Available data:

name type description registry ComponentRegistry The created ComponentRegistry instance

Available data:

name type description registry ComponentRegistry The to-be-deleted ComponentRegistry instance

Available data:

name type description component Component The Component instance that contains the {% slot %} tag component_cls Type[Component] The Component class that contains the {% slot %} tag component_id str The unique identifier for this component instance result SlotResult The rendered result of the slot slot Slot The Slot instance that was rendered slot_is_default bool Whether the slot is default slot_is_required bool Whether the slot is required slot_name str The name of the {% slot %} tag slot_node SlotNode The node instance of the {% slot %} tag

Available data:

name type description component_cls Type[Component] The Component class whose template was loaded template django.template.base.Template The compiled template object

Available data:

name type description component_cls Type[Component] The Component class whose template was loaded content str The template string name Optional[str] The name of the template origin Optional[django.template.base.Origin] The origin of the template"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_component_class_created","title":"on_component_class_created","text":"
on_component_class_created(ctx: OnComponentClassCreatedContext) -> None\n

See source code

Called when a new Component class is created.

This hook is called after the Component class is fully defined but before it's registered.

Use this hook to perform any initialization or validation of the Component class.

Example:

from django_components import ComponentExtension, OnComponentClassCreatedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_class_created(self, ctx: OnComponentClassCreatedContext) -> None:\n        # Add a new attribute to the Component class\n        ctx.component_cls.my_attr = \"my_value\"\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_component_class_deleted","title":"on_component_class_deleted","text":"
on_component_class_deleted(ctx: OnComponentClassDeletedContext) -> None\n

See source code

Called when a Component class is being deleted.

This hook is called before the Component class is deleted from memory.

Use this hook to perform any cleanup related to the Component class.

Example:

from django_components import ComponentExtension, OnComponentClassDeletedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_class_deleted(self, ctx: OnComponentClassDeletedContext) -> None:\n        # Remove Component class from the extension's cache on deletion\n        self.cache.pop(ctx.component_cls, None)\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_component_data","title":"on_component_data","text":"
on_component_data(ctx: OnComponentDataContext) -> None\n

See source code

Called when a Component was triggered to render, after a component's context and data methods have been processed.

This hook is called after Component.get_template_data(), Component.get_js_data() and Component.get_css_data().

This hook runs after on_component_input.

Use this hook to modify or validate the component's data before rendering.

Example:

from django_components import ComponentExtension, OnComponentDataContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_data(self, ctx: OnComponentDataContext) -> None:\n        # Add extra template variable to all components when they are rendered\n        ctx.template_data[\"my_template_var\"] = \"my_value\"\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_component_input","title":"on_component_input","text":"
on_component_input(ctx: OnComponentInputContext) -> Optional[str]\n

See source code

Called when a Component was triggered to render, but before a component's context and data methods are invoked.

Use this hook to modify or validate component inputs before they're processed.

This is the first hook that is called when rendering a component. As such this hook is called before Component.get_template_data(), Component.get_js_data(), and Component.get_css_data() methods, and the on_component_data hook.

This hook also allows to skip the rendering of a component altogether. If the hook returns a non-null value, this value will be used instead of rendering the component.

You can use this to implement a caching mechanism for components, or define components that will be rendered conditionally.

Example:

from django_components import ComponentExtension, OnComponentInputContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_input(self, ctx: OnComponentInputContext) -> None:\n        # Add extra kwarg to all components when they are rendered\n        ctx.kwargs[\"my_input\"] = \"my_value\"\n

Warning

In this hook, the components' inputs are still mutable.

As such, if a component defines Args, Kwargs, Slots types, these types are NOT yet instantiated.

Instead, component fields like Component.args, Component.kwargs, Component.slots are plain list / dict objects.

"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_component_registered","title":"on_component_registered","text":"
on_component_registered(ctx: OnComponentRegisteredContext) -> None\n

See source code

Called when a Component class is registered with a ComponentRegistry.

This hook is called after a Component class is successfully registered.

Example:

from django_components import ComponentExtension, OnComponentRegisteredContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_registered(self, ctx: OnComponentRegisteredContext) -> None:\n        print(f\"Component {ctx.component_cls} registered to {ctx.registry} as '{ctx.name}'\")\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_component_rendered","title":"on_component_rendered","text":"
on_component_rendered(ctx: OnComponentRenderedContext) -> Optional[str]\n

See source code

Called when a Component was rendered, including all its child components.

Use this hook to access or post-process the component's rendered output.

This hook works similarly to Component.on_render_after():

  1. To modify the output, return a new string from this hook. The original output or error will be ignored.

  2. To cause this component to return a new error, raise that error. The original output and error will be ignored.

  3. If you neither raise nor return string, the original output or error will be used.

Examples:

Change the final output of a component:

from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n        # Append a comment to the component's rendered output\n        return ctx.result + \"<!-- MyExtension comment -->\"\n

Cause the component to raise a new exception:

from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n        # Raise a new exception\n        raise Exception(\"Error message\")\n

Return nothing (or None) to handle the result as usual:

from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n        if ctx.error is not None:\n            # The component raised an exception\n            print(f\"Error: {ctx.error}\")\n        else:\n            # The component rendered successfully\n            print(f\"Result: {ctx.result}\")\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_component_unregistered","title":"on_component_unregistered","text":"
on_component_unregistered(ctx: OnComponentUnregisteredContext) -> None\n

See source code

Called when a Component class is unregistered from a ComponentRegistry.

This hook is called after a Component class is removed from the registry.

Example:

from django_components import ComponentExtension, OnComponentUnregisteredContext\n\nclass MyExtension(ComponentExtension):\n    def on_component_unregistered(self, ctx: OnComponentUnregisteredContext) -> None:\n        print(f\"Component {ctx.component_cls} unregistered from {ctx.registry} as '{ctx.name}'\")\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_css_loaded","title":"on_css_loaded","text":"
on_css_loaded(ctx: OnCssLoadedContext) -> Optional[str]\n

See source code

Called when a Component's CSS is loaded as a string.

This hook runs only once per Component class and works for both Component.css and Component.css_file.

Use this hook to read or modify the CSS.

To modify the CSS, return a new string from this hook.

Example:

from django_components import ComponentExtension, OnCssLoadedContext\n\nclass MyExtension(ComponentExtension):\n    def on_css_loaded(self, ctx: OnCssLoadedContext) -> Optional[str]:\n        # Modify the CSS\n        return ctx.content.replace(\"Hello\", \"Hi\")\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_js_loaded","title":"on_js_loaded","text":"
on_js_loaded(ctx: OnJsLoadedContext) -> Optional[str]\n

See source code

Called when a Component's JS is loaded as a string.

This hook runs only once per Component class and works for both Component.js and Component.js_file.

Use this hook to read or modify the JS.

To modify the JS, return a new string from this hook.

Example:

from django_components import ComponentExtension, OnCssLoadedContext\n\nclass MyExtension(ComponentExtension):\n    def on_js_loaded(self, ctx: OnJsLoadedContext) -> Optional[str]:\n        # Modify the JS\n        return ctx.content.replace(\"Hello\", \"Hi\")\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_registry_created","title":"on_registry_created","text":"
on_registry_created(ctx: OnRegistryCreatedContext) -> None\n

See source code

Called when a new ComponentRegistry is created.

This hook is called after a new ComponentRegistry instance is initialized.

Use this hook to perform any initialization needed for the registry.

Example:

from django_components import ComponentExtension, OnRegistryCreatedContext\n\nclass MyExtension(ComponentExtension):\n    def on_registry_created(self, ctx: OnRegistryCreatedContext) -> None:\n        # Add a new attribute to the registry\n        ctx.registry.my_attr = \"my_value\"\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_registry_deleted","title":"on_registry_deleted","text":"
on_registry_deleted(ctx: OnRegistryDeletedContext) -> None\n

See source code

Called when a ComponentRegistry is being deleted.

This hook is called before a ComponentRegistry instance is deleted.

Use this hook to perform any cleanup related to the registry.

Example:

from django_components import ComponentExtension, OnRegistryDeletedContext\n\nclass MyExtension(ComponentExtension):\n    def on_registry_deleted(self, ctx: OnRegistryDeletedContext) -> None:\n        # Remove registry from the extension's cache on deletion\n        self.cache.pop(ctx.registry, None)\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_slot_rendered","title":"on_slot_rendered","text":"
on_slot_rendered(ctx: OnSlotRenderedContext) -> Optional[str]\n

See source code

Called when a {% slot %} tag was rendered.

Use this hook to access or post-process the slot's rendered output.

To modify the output, return a new string from this hook.

Example:

from django_components import ComponentExtension, OnSlotRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_slot_rendered(self, ctx: OnSlotRenderedContext) -> Optional[str]:\n        # Append a comment to the slot's rendered output\n        return ctx.result + \"<!-- MyExtension comment -->\"\n

Access slot metadata:

You can access the {% slot %} tag node (SlotNode) and its metadata using ctx.slot_node.

For example, to find the Component class to which belongs the template where the {% slot %} tag is defined, you can use ctx.slot_node.template_component:

from django_components import ComponentExtension, OnSlotRenderedContext\n\nclass MyExtension(ComponentExtension):\n    def on_slot_rendered(self, ctx: OnSlotRenderedContext) -> Optional[str]:\n        # Access slot metadata\n        slot_node = ctx.slot_node\n        slot_owner = slot_node.template_component\n        print(f\"Slot owner: {slot_owner}\")\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_template_compiled","title":"on_template_compiled","text":"
on_template_compiled(ctx: OnTemplateCompiledContext) -> None\n

See source code

Called when a Component's template is compiled into a Template object.

This hook runs only once per Component class and works for both Component.template and Component.template_file.

Use this hook to read or modify the template (in-place) after it's compiled.

Example:

from django_components import ComponentExtension, OnTemplateCompiledContext\n\nclass MyExtension(ComponentExtension):\n    def on_template_compiled(self, ctx: OnTemplateCompiledContext) -> None:\n        print(f\"Template origin: {ctx.template.origin.name}\")\n
"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_template_loaded","title":"on_template_loaded","text":"
on_template_loaded(ctx: OnTemplateLoadedContext) -> Optional[str]\n

See source code

Called when a Component's template is loaded as a string.

This hook runs only once per Component class and works for both Component.template and Component.template_file.

Use this hook to read or modify the template before it's compiled.

To modify the template, return a new string from this hook.

Example:

from django_components import ComponentExtension, OnTemplateLoadedContext\n\nclass MyExtension(ComponentExtension):\n    def on_template_loaded(self, ctx: OnTemplateLoadedContext) -> Optional[str]:\n        # Modify the template\n        return ctx.content.replace(\"Hello\", \"Hi\")\n
"},{"location":"reference/extension_hooks/#objects","title":"Objects","text":""},{"location":"reference/extension_hooks/#django_components.extension.OnComponentClassCreatedContext","title":"OnComponentClassCreatedContext","text":"

Attributes:

  • component_cls (Type[Component]) \u2013
"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentClassCreatedContext.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The created Component class

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentClassDeletedContext","title":"OnComponentClassDeletedContext","text":"

Attributes:

  • component_cls (Type[Component]) \u2013
"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentClassDeletedContext.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The to-be-deleted Component class

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentDataContext","title":"OnComponentDataContext","text":"

Attributes:

  • component (Component) \u2013
  • component_cls (Type[Component]) \u2013
  • component_id (str) \u2013
  • context_data (Dict) \u2013
  • css_data (Dict) \u2013
  • js_data (Dict) \u2013
  • template_data (Dict) \u2013
"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentDataContext.component","title":"component instance-attribute","text":"
component: Component\n

See source code

The Component instance that is being rendered

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentDataContext.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The Component class

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentDataContext.component_id","title":"component_id instance-attribute","text":"
component_id: str\n

See source code

The unique identifier for this component instance

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentDataContext.context_data","title":"context_data instance-attribute","text":"
context_data: Dict\n

See source code

Deprecated. Use template_data instead. Will be removed in v1.0.

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentDataContext.css_data","title":"css_data instance-attribute","text":"
css_data: Dict\n

See source code

Dictionary of CSS data from Component.get_css_data()

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentDataContext.js_data","title":"js_data instance-attribute","text":"
js_data: Dict\n

See source code

Dictionary of JavaScript data from Component.get_js_data()

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentDataContext.template_data","title":"template_data instance-attribute","text":"
template_data: Dict\n

See source code

Dictionary of template data from Component.get_template_data()

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentInputContext","title":"OnComponentInputContext","text":"

Attributes:

  • args (List) \u2013
  • component (Component) \u2013
  • component_cls (Type[Component]) \u2013
  • component_id (str) \u2013
  • context (Context) \u2013
  • kwargs (Dict) \u2013
  • slots (Dict[str, Slot]) \u2013
"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentInputContext.args","title":"args instance-attribute","text":"
args: List\n

See source code

List of positional arguments passed to the component

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentInputContext.component","title":"component instance-attribute","text":"
component: Component\n

See source code

The Component instance that received the input and is being rendered

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentInputContext.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The Component class

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentInputContext.component_id","title":"component_id instance-attribute","text":"
component_id: str\n

See source code

The unique identifier for this component instance

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentInputContext.context","title":"context instance-attribute","text":"
context: Context\n

See source code

The Django template Context object

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentInputContext.kwargs","title":"kwargs instance-attribute","text":"
kwargs: Dict\n

See source code

Dictionary of keyword arguments passed to the component

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentInputContext.slots","title":"slots instance-attribute","text":"
slots: Dict[str, Slot]\n

See source code

Dictionary of slot definitions

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentRegisteredContext","title":"OnComponentRegisteredContext","text":"

Attributes:

  • component_cls (Type[Component]) \u2013
  • name (str) \u2013
  • registry (ComponentRegistry) \u2013
"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentRegisteredContext.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The registered Component class

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentRegisteredContext.name","title":"name instance-attribute","text":"
name: str\n

See source code

The name the component was registered under

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentRegisteredContext.registry","title":"registry instance-attribute","text":"
registry: ComponentRegistry\n

See source code

The registry the component was registered to

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentUnregisteredContext","title":"OnComponentUnregisteredContext","text":"

Attributes:

  • component_cls (Type[Component]) \u2013
  • name (str) \u2013
  • registry (ComponentRegistry) \u2013
"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentUnregisteredContext.component_cls","title":"component_cls instance-attribute","text":"
component_cls: Type[Component]\n

See source code

The unregistered Component class

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentUnregisteredContext.name","title":"name instance-attribute","text":"
name: str\n

See source code

The name the component was registered under

"},{"location":"reference/extension_hooks/#django_components.extension.OnComponentUnregisteredContext.registry","title":"registry instance-attribute","text":"
registry: ComponentRegistry\n

See source code

The registry the component was unregistered from

"},{"location":"reference/extension_hooks/#django_components.extension.OnRegistryCreatedContext","title":"OnRegistryCreatedContext","text":"

Attributes:

  • registry (ComponentRegistry) \u2013
"},{"location":"reference/extension_hooks/#django_components.extension.OnRegistryCreatedContext.registry","title":"registry instance-attribute","text":"
registry: ComponentRegistry\n

See source code

The created ComponentRegistry instance

"},{"location":"reference/extension_hooks/#django_components.extension.OnRegistryDeletedContext","title":"OnRegistryDeletedContext","text":"

Attributes:

  • registry (ComponentRegistry) \u2013
"},{"location":"reference/extension_hooks/#django_components.extension.OnRegistryDeletedContext.registry","title":"registry instance-attribute","text":"
registry: ComponentRegistry\n

See source code

The to-be-deleted ComponentRegistry instance

"},{"location":"reference/extension_urls/","title":"Extension URLs API","text":""},{"location":"reference/extension_urls/#extension-urls-api","title":"Extension URLs API","text":"

Overview of all classes, functions, and other objects related to defining extension URLs.

Read more on Extensions.

"},{"location":"reference/extension_urls/#django_components.URLRoute","title":"URLRoute dataclass","text":"
URLRoute(\n    path: str,\n    handler: Optional[URLRouteHandler] = None,\n    children: Iterable[URLRoute] = list(),\n    name: Optional[str] = None,\n    extra: Dict[str, Any] = dict(),\n)\n

Bases: object

See source code

Framework-agnostic route definition.

This is similar to Django's URLPattern object created with django.urls.path().

The URLRoute must either define a handler function or have a list of child routes children. If both are defined, an error will be raised.

Example:

URLRoute(\"/my/path\", handler=my_handler, name=\"my_name\", extra={\"kwargs\": {\"my_extra\": \"my_value\"}})\n

Is equivalent to:

django.urls.path(\"/my/path\", my_handler, name=\"my_name\", kwargs={\"my_extra\": \"my_value\"})\n

With children:

URLRoute(\n    \"/my/path\",\n    name=\"my_name\",\n    extra={\"kwargs\": {\"my_extra\": \"my_value\"}},\n    children=[\n        URLRoute(\n            \"/child/<str:name>/\",\n            handler=my_handler,\n            name=\"my_name\",\n            extra={\"kwargs\": {\"my_extra\": \"my_value\"}},\n        ),\n        URLRoute(\"/other/<int:id>/\", handler=other_handler),\n    ],\n)\n

Attributes:

  • children (Iterable[URLRoute]) \u2013
  • extra (Dict[str, Any]) \u2013
  • handler (Optional[URLRouteHandler]) \u2013
  • name (Optional[str]) \u2013
  • path (str) \u2013
"},{"location":"reference/extension_urls/#django_components.URLRoute.children","title":"children class-attribute instance-attribute","text":"
children: Iterable[URLRoute] = field(default_factory=list)\n
"},{"location":"reference/extension_urls/#django_components.URLRoute.extra","title":"extra class-attribute instance-attribute","text":"
extra: Dict[str, Any] = field(default_factory=dict)\n
"},{"location":"reference/extension_urls/#django_components.URLRoute.handler","title":"handler class-attribute instance-attribute","text":"
handler: Optional[URLRouteHandler] = None\n
"},{"location":"reference/extension_urls/#django_components.URLRoute.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
"},{"location":"reference/extension_urls/#django_components.URLRoute.path","title":"path instance-attribute","text":"
path: str\n
"},{"location":"reference/extension_urls/#django_components.URLRouteHandler","title":"URLRouteHandler","text":"

Bases: typing.Protocol

See source code

Framework-agnostic 'view' function for routes

"},{"location":"reference/settings/","title":"Settings","text":""},{"location":"reference/settings/#settings","title":"Settings","text":"

You can configure django_components with a global COMPONENTS variable in your Django settings file, e.g. settings.py. By default you don't need it set, there are resonable defaults.

To configure the settings you can instantiate ComponentsSettings for validation and type hints. Or, for backwards compatibility, you can also use plain dictionary:

# settings.py\nfrom django_components import ComponentsSettings\n\nCOMPONENTS = ComponentsSettings(\n    autodiscover=True,\n    ...\n)\n\n# or\n\nCOMPONENTS = {\n    \"autodiscover\": True,\n    ...\n}\n
"},{"location":"reference/settings/#settings-defaults","title":"Settings defaults","text":"

Here's overview of all available settings and their defaults:

defaults = ComponentsSettings(\n    autodiscover=True,\n    cache=None,\n    context_behavior=ContextBehavior.DJANGO.value,  # \"django\" | \"isolated\"\n    # Root-level \"components\" dirs, e.g. `/path/to/proj/components/`\n    dirs=[Path(settings.BASE_DIR) / \"components\"],\n    # App-level \"components\" dirs, e.g. `[app]/components/`\n    app_dirs=[\"components\"],\n    debug_highlight_components=False,\n    debug_highlight_slots=False,\n    dynamic_component_name=\"dynamic\",\n    extensions=[],\n    extensions_defaults={},\n    libraries=[],  # E.g. [\"mysite.components.forms\", ...]\n    multiline_tags=True,\n    reload_on_file_change=False,\n    static_files_allowed=[\n        \".css\",\n        \".js\", \".jsx\", \".ts\", \".tsx\",\n        # Images\n        \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n        \".jpeg\", \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n        \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n        # Fonts\n        \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n    ],\n    static_files_forbidden=[\n        # See https://marketplace.visualstudio.com/items?itemName=junstyle.vscode-django-support\n        \".html\", \".django\", \".dj\", \".tpl\",\n        # Python files\n        \".py\", \".pyc\",\n    ],\n    tag_formatter=\"django_components.component_formatter\",\n    template_cache_size=128,\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.app_dirs","title":"app_dirs","text":"
app_dirs: Optional[Sequence[str]] = None\n

See source code

Specify the app-level directories that contain your components.

Defaults to [\"components\"]. That is, for each Django app, we search <app>/components/ for components.

The paths must be relative to app, e.g.:

COMPONENTS = ComponentsSettings(\n    app_dirs=[\"my_comps\"],\n)\n

To search for <app>/my_comps/.

These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.

Set to empty list to disable app-level components:

COMPONENTS = ComponentsSettings(\n    app_dirs=[],\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.autodiscover","title":"autodiscover","text":"
autodiscover: Optional[bool] = None\n

See source code

Toggle whether to run autodiscovery at the Django server startup.

Defaults to True

COMPONENTS = ComponentsSettings(\n    autodiscover=False,\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.cache","title":"cache","text":"
cache: Optional[str] = None\n

See source code

Name of the Django cache to be used for storing component's JS and CSS files.

If None, a LocMemCache is used with default settings.

Defaults to None.

Read more about caching.

COMPONENTS = ComponentsSettings(\n    cache=\"my_cache\",\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.context_behavior","title":"context_behavior","text":"
context_behavior: Optional[ContextBehaviorType] = None\n

See source code

Configure whether, inside a component template, you can use variables from the outside (\"django\") or not (\"isolated\"). This also affects what variables are available inside the {% fill %} tags.

Also see Component context and scope.

Defaults to \"django\".

COMPONENTS = ComponentsSettings(\n    context_behavior=\"isolated\",\n)\n

NOTE: context_behavior and slot_context_behavior options were merged in v0.70.

If you are migrating from BEFORE v0.67, set context_behavior to \"django\". From v0.67 to v0.78 (incl) the default value was \"isolated\".

For v0.79 and later, the default is again \"django\". See the rationale for change here.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.debug_highlight_components","title":"debug_highlight_components","text":"
debug_highlight_components: Optional[bool] = None\n

See source code

DEPRECATED. Use extensions_defaults instead. Will be removed in v1.

Enable / disable component highlighting. See Troubleshooting for more details.

Defaults to False.

COMPONENTS = ComponentsSettings(\n    debug_highlight_components=True,\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.debug_highlight_slots","title":"debug_highlight_slots","text":"
debug_highlight_slots: Optional[bool] = None\n

See source code

DEPRECATED. Use extensions_defaults instead. Will be removed in v1.

Enable / disable slot highlighting. See Troubleshooting for more details.

Defaults to False.

COMPONENTS = ComponentsSettings(\n    debug_highlight_slots=True,\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.dirs","title":"dirs","text":"
dirs: Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]] = None\n

See source code

Specify the directories that contain your components.

Defaults to [Path(settings.BASE_DIR) / \"components\"]. That is, the root components/ app.

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

COMPONENTS = ComponentsSettings(\n    dirs=[BASE_DIR / \"components\"],\n)\n

Set to empty list to disable global components directories:

COMPONENTS = ComponentsSettings(\n    dirs=[],\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.dynamic_component_name","title":"dynamic_component_name","text":"
dynamic_component_name: Optional[str] = None\n

See source code

By default, the dynamic component is registered under the name \"dynamic\".

In case of a conflict, you can use this setting to change the component name used for the dynamic components.

# settings.py\nCOMPONENTS = ComponentsSettings(\n    dynamic_component_name=\"my_dynamic\",\n)\n

After which you will be able to use the dynamic component with the new name:

{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.extensions","title":"extensions","text":"
extensions: Optional[Sequence[Union[Type[ComponentExtension], str]]] = None\n

See source code

List of extensions to be loaded.

The extensions can be specified as:

  • Python import path, e.g. \"path.to.my_extension.MyExtension\".
  • Extension class, e.g. my_extension.MyExtension.

Read more about extensions.

Example:

COMPONENTS = ComponentsSettings(\n    extensions=[\n        \"path.to.my_extension.MyExtension\",\n        StorybookExtension,\n    ],\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.extensions_defaults","title":"extensions_defaults","text":"
extensions_defaults: Optional[Dict[str, Any]] = None\n

See source code

Global defaults for the extension classes.

Read more about Extension defaults.

Example:

COMPONENTS = ComponentsSettings(\n    extensions_defaults={\n        \"my_extension\": {\n            \"my_setting\": \"my_value\",\n        },\n        \"cache\": {\n            \"enabled\": True,\n            \"ttl\": 60,\n        },\n    },\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.forbidden_static_files","title":"forbidden_static_files","text":"
forbidden_static_files: Optional[List[Union[str, Pattern]]] = None\n

See source code

Deprecated. Use COMPONENTS.static_files_forbidden instead.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.libraries","title":"libraries","text":"
libraries: Optional[List[str]] = None\n

See source code

Configure extra python modules that should be loaded.

This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.

Expects a list of python module paths. Defaults to empty list.

Example:

COMPONENTS = ComponentsSettings(\n    libraries=[\n        \"mysite.components.forms\",\n        \"mysite.components.buttons\",\n        \"mysite.components.cards\",\n    ],\n)\n

This would be the equivalent of importing these modules from within Django's AppConfig.ready():

class MyAppConfig(AppConfig):\n    def ready(self):\n        import \"mysite.components.forms\"\n        import \"mysite.components.buttons\"\n        import \"mysite.components.cards\"\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.libraries--manually-loading-libraries","title":"Manually loading libraries","text":"

In the rare case that you need to manually trigger the import of libraries, you can use the import_libraries() function:

from django_components import import_libraries\n\nimport_libraries()\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.multiline_tags","title":"multiline_tags","text":"
multiline_tags: Optional[bool] = None\n

See source code

Enable / disable multiline support for template tags. If True, template tags like {% component %} or {{ my_var }} can span multiple lines.

Defaults to True.

Disable this setting if you are making custom modifications to Django's regular expression for parsing templates at django.template.base.tag_re.

COMPONENTS = ComponentsSettings(\n    multiline_tags=False,\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.reload_on_file_change","title":"reload_on_file_change","text":"
reload_on_file_change: Optional[bool] = None\n

See source code

This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.

In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.

Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.

The setting reload_on_file_change fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.

If True, django_components configures Django to reload when files inside COMPONENTS.dirs or COMPONENTS.app_dirs change.

See Reload dev server on component file changes.

Defaults to False.

Warning

This setting should be enabled only for the dev environment!

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.reload_on_template_change","title":"reload_on_template_change","text":"
reload_on_template_change: Optional[bool] = None\n

See source code

Deprecated. Use COMPONENTS.reload_on_file_change instead.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.static_files_allowed","title":"static_files_allowed","text":"
static_files_allowed: Optional[List[Union[str, Pattern]]] = None\n

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or 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 = ComponentsSettings(\n    static_files_allowed=[\n        \".css\",\n        \".js\", \".jsx\", \".ts\", \".tsx\",\n        # Images\n        \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n        \".jpeg\",  \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n        \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n        # Fonts\n        \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n    ],\n)\n

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.static_files_forbidden","title":"static_files_forbidden","text":"
static_files_forbidden: Optional[List[Union[str, Pattern]]] = None\n

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs will NEVER be treated as static files.

If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in static_files_allowed.

Use this setting together with static_files_allowed for a fine control over what file types will be exposed.

You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

By default, any HTML and Python are considered NOT static files:

COMPONENTS = ComponentsSettings(\n    static_files_forbidden=[\n        \".html\", \".django\", \".dj\", \".tpl\",\n        # Python files\n        \".py\", \".pyc\",\n    ],\n)\n

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.tag_formatter","title":"tag_formatter","text":"
tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n

See source code

Configure what syntax is used inside Django templates to render components. See the available tag formatters.

Defaults to \"django_components.component_formatter\".

Learn more about Customizing component tags with TagFormatter.

Can be set either as direct reference:

from django_components import component_formatter\n\nCOMPONENTS = ComponentsSettings(\n    \"tag_formatter\": component_formatter\n)\n

Or as an import string;

COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_formatter\"\n)\n

Examples:

  • \"django_components.component_formatter\"

    Set

    COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_formatter\"\n)\n

    To write components like this:

    {% component \"button\" href=\"...\" %}\n    Click me!\n{% endcomponent %}\n
  • django_components.component_shorthand_formatter

    Set

    COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_shorthand_formatter\"\n)\n

    To write components like this:

    {% button href=\"...\" %}\n    Click me!\n{% endbutton %}\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.template_cache_size","title":"template_cache_size","text":"
template_cache_size: Optional[int] = None\n

See source code

DEPRECATED. Template caching will be removed in v1.

Configure the maximum amount of Django templates to be cached.

Defaults to 128.

Each time a Django 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 overriding Component.get_template() to render many dynamic templates, you can increase this number.

COMPONENTS = ComponentsSettings(\n    template_cache_size=256,\n)\n

To remove the cache limit altogether and cache everything, set template_cache_size to None.

COMPONENTS = ComponentsSettings(\n    template_cache_size=None,\n)\n

If you want to add templates to the cache yourself, you can use cached_template():

from django_components import cached_template\n\ncached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n    pass\n\ncached_template(\n    \"Variable: {{ variable }}\",\n    template_cls=MyTemplate,\n    name=...\n    origin=...\n    engine=...\n)\n
"},{"location":"reference/signals/","title":"Signals","text":""},{"location":"reference/signals/#signals","title":"Signals","text":"

Below are the signals that are sent by or during the use of django-components.

"},{"location":"reference/signals/#template_rendered","title":"template_rendered","text":"

Django's template_rendered signal. This signal is sent when a template is rendered.

Django-components triggers this signal when a component is rendered. If there are nested components, the signal is triggered for each component.

Import from django as django.test.signals.template_rendered.

from django.test.signals import template_rendered\n\n# Setup a callback function\ndef my_callback(sender, **kwargs):\n    ...\n\ntemplate_rendered.connect(my_callback)\n\nclass MyTable(Component):\n    template = \"\"\"\n    <table>\n        <tr>\n            <th>Header</th>\n        </tr>\n        <tr>\n            <td>Cell</td>\n        </tr>\n    \"\"\"\n\n# This will trigger the signal\nMyTable().render()\n
"},{"location":"reference/tag_formatters/","title":"Tag formatters","text":""},{"location":"reference/tag_formatters/#tag-formatters","title":"Tag Formatters","text":"

Tag formatters allow you to change the syntax for calling components from within the Django templates.

Tag formatter are set via the tag_formatter setting.

"},{"location":"reference/tag_formatters/#available-tag-formatters","title":"Available tag formatters","text":"
  • django_components.component_formatter for ComponentFormatter

  • django_components.component_shorthand_formatter for ShorthandComponentFormatter

"},{"location":"reference/tag_formatters/#django_components.tag_formatter.ComponentFormatter","title":"ComponentFormatter","text":"

Bases: django_components.tag_formatter.TagFormatterABC

See source code

The original django_component's component tag formatter, it uses the {% component %} and {% endcomponent %} tags, and the component name is given as the first positional arg.

Example as block:

{% component \"mycomp\" abc=123 %}\n    {% fill \"myfill\" %}\n        ...\n    {% endfill %}\n{% endcomponent %}\n

Example as inlined tag:

{% component \"mycomp\" abc=123 / %}\n

"},{"location":"reference/tag_formatters/#django_components.tag_formatter.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":"

Bases: django_components.tag_formatter.TagFormatterABC

See source code

The component tag formatter that uses {% <name> %} / {% end<name> %} tags.

This is similar to django-web-components and django-slippers syntax.

Example as block:

{% mycomp abc=123 %}\n    {% fill \"myfill\" %}\n        ...\n    {% endfill %}\n{% endmycomp %}\n

Example as inlined tag:

{% mycomp abc=123 / %}\n

"},{"location":"reference/template_tags/","title":"Template tags","text":""},{"location":"reference/template_tags/#template-tags","title":"Template tags","text":"

All following template tags are defined in

django_components.templatetags.component_tags

Import as

{% load component_tags %}\n

"},{"location":"reference/template_tags/#component_css_dependencies","title":"component_css_dependencies","text":"
{% component_css_dependencies  %}\n

See source code

Marks location where CSS link tags should be rendered after the whole HTML has been generated.

Generally, this should be inserted into the <head> tag of the HTML.

If the generated HTML does NOT contain any {% component_css_dependencies %} tags, CSS links are by default inserted into the <head> tag of the HTML. (See Default JS / CSS locations)

Note that there should be only one {% component_css_dependencies %} for the whole HTML document. If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.

"},{"location":"reference/template_tags/#component_js_dependencies","title":"component_js_dependencies","text":"
{% component_js_dependencies  %}\n

See source code

Marks location where JS link tags should be rendered after the whole HTML has been generated.

Generally, this should be inserted at the end of the <body> tag of the HTML.

If the generated HTML does NOT contain any {% component_js_dependencies %} tags, JS scripts are by default inserted at the end of the <body> tag of the HTML. (See Default JS / CSS locations)

Note that there should be only one {% component_js_dependencies %} for the whole HTML document. If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.

"},{"location":"reference/template_tags/#component","title":"component","text":"
{% component *args: Any, **kwargs: Any [only] %}\n{% endcomponent %}\n

See source code

Renders one of the components that was previously registered with @register() decorator.

The {% component %} tag takes:

  • Component's registered name as the first positional argument,
  • Followed by any number of positional and keyword arguments.
{% load component_tags %}\n<div>\n    {% component \"button\" name=\"John\" job=\"Developer\" / %}\n</div>\n

The component name must be a string literal.

"},{"location":"reference/template_tags/#inserting-slot-fills","title":"Inserting slot fills","text":"

If the component defined any slots, you can \"fill\" these slots by placing the {% fill %} tags within the {% component %} tag:

{% component \"my_table\" rows=rows headers=headers %}\n  {% fill \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endfill %}\n{% endcomponent %}\n

You can even nest {% fill %} tags within {% if %}, {% for %} and other tags:

{% component \"my_table\" rows=rows headers=headers %}\n    {% if rows %}\n        {% fill \"pagination\" %}\n            < 1 | 2 | 3 >\n        {% endfill %}\n    {% endif %}\n{% endcomponent %}\n
"},{"location":"reference/template_tags/#isolating-components","title":"Isolating components","text":"

By default, components behave similarly to Django's {% include %}, and the template inside the component has access to the variables defined in the outer template.

You can selectively isolate a component, using the only flag, so that the inner template can access only the data that was explicitly passed to it:

{% component \"name\" positional_arg keyword_arg=value ... only %}\n

Alternatively, you can set all components to be isolated by default, by setting context_behavior to \"isolated\" in your settings:

# settings.py\nCOMPONENTS = {\n    \"context_behavior\": \"isolated\",\n}\n
"},{"location":"reference/template_tags/#omitting-the-component-keyword","title":"Omitting the component keyword","text":"

If you would like to omit the component keyword, and simply refer to your components by their registered names:

{% button name=\"John\" job=\"Developer\" / %}\n

You can do so by setting the \"shorthand\" Tag formatter in the settings:

# settings.py\nCOMPONENTS = {\n    \"tag_formatter\": \"django_components.component_shorthand_formatter\",\n}\n
"},{"location":"reference/template_tags/#fill","title":"fill","text":"
{% fill name: str, *, data: Optional[str] = None, fallback: Optional[str] = None, body: Union[str, django.utils.safestring.SafeString, django_components.slots.SlotFunc[~TSlotData], django_components.slots.Slot[~TSlotData], NoneType] = None, default: Optional[str] = None %}\n{% endfill %}\n

See source code

Use {% fill %} tag to insert content into component's slots.

{% fill %} tag may be used only within a {% component %}..{% endcomponent %} block, and raises a TemplateSyntaxError if used outside of a component.

Args:

  • name (str, required): Name of the slot to insert this content into. Use \"default\" for the default slot.
  • data (str, optional): This argument allows you to access the data passed to the slot under the specified variable name. See Slot data.
  • fallback (str, optional): This argument allows you to access the original content of the slot under the specified variable name. See Slot fallback.

Example:

{% component \"my_table\" %}\n  {% fill \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/template_tags/#access-slot-fallback","title":"Access slot fallback","text":"

Use the fallback kwarg to access the original content of the slot.

The fallback kwarg defines the name of the variable that will contain the slot's fallback content.

Read more about Slot fallback.

Component template:

{# my_table.html #}\n<table>\n  ...\n  {% slot \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endslot %}\n</table>\n

Fill:

{% component \"my_table\" %}\n  {% fill \"pagination\" fallback=\"fallback\" %}\n    <div class=\"my-class\">\n      {{ fallback }}\n    </div>\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/template_tags/#access-slot-data","title":"Access slot data","text":"

Use the data kwarg to access the data passed to the slot.

The data kwarg defines the name of the variable that will contain the slot's data.

Read more about Slot data.

Component template:

{# my_table.html #}\n<table>\n  ...\n  {% slot \"pagination\" pages=pages %}\n    < 1 | 2 | 3 >\n  {% endslot %}\n</table>\n

Fill:

{% component \"my_table\" %}\n  {% fill \"pagination\" data=\"slot_data\" %}\n    {% for page in slot_data.pages %}\n        <a href=\"{{ page.link }}\">\n          {{ page.index }}\n        </a>\n    {% endfor %}\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/template_tags/#using-default-slot","title":"Using default slot","text":"

To access slot data and the fallback slot content on the default slot, use {% fill %} with name set to \"default\":

{% component \"button\" %}\n  {% fill name=\"default\" data=\"slot_data\" fallback=\"slot_fallback\" %}\n    You clicked me {{ slot_data.count }} times!\n    {{ slot_fallback }}\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/template_tags/#slot-fills-from-python","title":"Slot fills from Python","text":"

You can pass a slot fill from Python to a component by setting the body kwarg on the {% fill %} tag.

First pass a Slot instance to the template with the get_template_data() method:

from django_components import component, Slot\n\nclass Table(Component):\n  def get_template_data(self, args, kwargs, slots, context):\n    return {\n        \"my_slot\": Slot(lambda ctx: \"Hello, world!\"),\n    }\n

Then pass the slot to the {% fill %} tag:

{% component \"table\" %}\n  {% fill \"pagination\" body=my_slot / %}\n{% endcomponent %}\n

Warning

If you define both the body kwarg and the {% fill %} tag's body, an error will be raised.

{% component \"table\" %}\n  {% fill \"pagination\" body=my_slot %}\n    ...\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/template_tags/#html_attrs","title":"html_attrs","text":"
{% html_attrs attrs: Optional[Dict] = None, defaults: Optional[Dict] = None, **kwargs: Any %}\n

See source code

Generate HTML attributes (key=\"value\"), combining data from multiple sources, whether its template variables or static text.

It is designed to easily merge HTML attributes passed from outside as well as inside the component.

Args:

  • attrs (dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides values in the default dictionary.
  • default (str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden with values in the attrs dictionary.
  • Any extra kwargs will be appended to the corresponding keys

The attributes in attrs and defaults are merged and resulting dict is rendered as HTML attributes (key=\"value\").

Extra kwargs (key=value) are concatenated to existing keys. So if we have

attrs = {\"class\": \"my-class\"}\n

Then

{% html_attrs attrs class=\"extra-class\" %}\n

will result in class=\"my-class extra-class\".

Example:

<div {% html_attrs\n    attrs\n    defaults:class=\"default-class\"\n    class=\"extra-class\"\n    data-id=\"123\"\n%}>\n

renders

<div class=\"my-class extra-class\" data-id=\"123\">\n

See more usage examples in HTML attributes.

"},{"location":"reference/template_tags/#provide","title":"provide","text":"
{% provide name: str, **kwargs: Any %}\n{% endprovide %}\n

See source code

The {% provide %} tag is part of the \"provider\" part of the provide / inject feature.

Pass kwargs to this tag to define the provider's data.

Any components defined within the {% provide %}..{% endprovide %} tags will be able to access this data with Component.inject().

This is similar to React's ContextProvider, or Vue's provide().

Args:

  • name (str, required): Provider name. This is the name you will then use in Component.inject().
  • **kwargs: Any extra kwargs will be passed as the provided data.

Example:

Provide the \"user_data\" in parent component:

@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      <div>\n        {% provide \"user_data\" user=user %}\n          {% component \"child\" / %}\n        {% endprovide %}\n      </div>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"user\": kwargs[\"user\"],\n        }\n

Since the \"child\" component is used within the {% provide %} / {% endprovide %} tags, we can request the \"user_data\" using Component.inject(\"user_data\"):

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        User is: {{ user }}\n      </div>\n    \"\"\"\n\n    def get_template_data(self, args, kwargs, slots, context):\n        user = self.inject(\"user_data\").user\n        return {\n            \"user\": user,\n        }\n

Notice that the keys defined on the {% provide %} tag are then accessed as attributes when accessing them with Component.inject().

\u2705 Do this

user = self.inject(\"user_data\").user\n

\u274c Don't do this

user = self.inject(\"user_data\")[\"user\"]\n

"},{"location":"reference/template_tags/#slot","title":"slot","text":"
{% slot name: str, **kwargs: Any [default] [required] %}\n{% endslot %}\n

See source code

{% slot %} tag marks a place inside a component where content can be inserted from outside.

Learn more about using slots.

This is similar to slots as seen in Web components, Vue or React's children.

Args:

  • name (str, required): Registered name of the component to render
  • default: Optional flag. If there is a default slot, you can pass the component slot content without using the {% fill %} tag. See Default slot
  • required: Optional flag. Will raise an error if a slot is required but not given.
  • **kwargs: Any extra kwargs will be passed as the slot data.

Example:

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        {% slot \"content\" default %}\n          This is shown if not overriden!\n        {% endslot %}\n      </div>\n      <aside>\n        {% slot \"sidebar\" required / %}\n      </aside>\n    \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      <div>\n        {% component \"child\" %}\n          {% fill \"content\" %}\n            \ud83d\uddde\ufe0f\ud83d\udcf0\n          {% endfill %}\n\n          {% fill \"sidebar\" %}\n            \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n          {% endfill %}\n        {% endcomponent %}\n      </div>\n    \"\"\"\n
"},{"location":"reference/template_tags/#slot-data","title":"Slot data","text":"

Any extra kwargs will be considered as slot data, and will be accessible in the {% fill %} tag via fill's data kwarg:

Read more about Slot data.

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        {# Passing data to the slot #}\n        {% slot \"content\" user=user %}\n          This is shown if not overriden!\n        {% endslot %}\n      </div>\n    \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      {# Parent can access the slot data #}\n      {% component \"child\" %}\n        {% fill \"content\" data=\"data\" %}\n          <div class=\"wrapper-class\">\n            {{ data.user }}\n          </div>\n        {% endfill %}\n      {% endcomponent %}\n    \"\"\"\n
"},{"location":"reference/template_tags/#slot-fallback","title":"Slot fallback","text":"

The content between the {% slot %}..{% endslot %} tags is the fallback content that will be rendered if no fill is given for the slot.

This fallback content can then be accessed from within the {% fill %} tag using the fill's fallback kwarg. This is useful if you need to wrap / prepend / append the original slot's content.

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        {% slot \"content\" %}\n          This is fallback content!\n        {% endslot %}\n      </div>\n    \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      {# Parent can access the slot's fallback content #}\n      {% component \"child\" %}\n        {% fill \"content\" fallback=\"fallback\" %}\n          {{ fallback }}\n        {% endfill %}\n      {% endcomponent %}\n    \"\"\"\n
"},{"location":"reference/template_variables/","title":"Template variables","text":""},{"location":"reference/template_variables/#template-variables","title":"Template variables","text":"

Here is a list of all variables that are automatically available from inside the component's template:

"},{"location":"reference/template_variables/#django_components.component.ComponentVars.args","title":"args instance-attribute","text":"
args: Any\n

See source code

The args argument as passed to Component.get_template_data().

This is the same Component.args that's available on the component instance.

If you defined the Component.Args class, then the args property will return an instance of that class.

Otherwise, args will be a plain list.

Example:

With Args class:

from django_components import Component, register\n\n@register(\"table\")\nclass Table(Component):\n    class Args(NamedTuple):\n        page: int\n        per_page: int\n\n    template = '''\n        <div>\n            <h1>Table</h1>\n            <p>Page: {{ component_vars.args.page }}</p>\n            <p>Per page: {{ component_vars.args.per_page }}</p>\n        </div>\n    '''\n

Without Args class:

from django_components import Component, register\n\n@register(\"table\")\nclass Table(Component):\n    template = '''\n        <div>\n            <h1>Table</h1>\n            <p>Page: {{ component_vars.args.0 }}</p>\n            <p>Per page: {{ component_vars.args.1 }}</p>\n        </div>\n    '''\n
"},{"location":"reference/template_variables/#django_components.component.ComponentVars.kwargs","title":"kwargs instance-attribute","text":"
kwargs: Any\n

See source code

The kwargs argument as passed to Component.get_template_data().

This is the same Component.kwargs that's available on the component instance.

If you defined the Component.Kwargs class, then the kwargs property will return an instance of that class.

Otherwise, kwargs will be a plain dict.

Example:

With Kwargs class:

from django_components import Component, register\n\n@register(\"table\")\nclass Table(Component):\n    class Kwargs(NamedTuple):\n        page: int\n        per_page: int\n\n    template = '''\n        <div>\n            <h1>Table</h1>\n            <p>Page: {{ component_vars.kwargs.page }}</p>\n            <p>Per page: {{ component_vars.kwargs.per_page }}</p>\n        </div>\n    '''\n

Without Kwargs class:

from django_components import Component, register\n\n@register(\"table\")\nclass Table(Component):\n    template = '''\n        <div>\n            <h1>Table</h1>\n            <p>Page: {{ component_vars.kwargs.page }}</p>\n            <p>Per page: {{ component_vars.kwargs.per_page }}</p>\n        </div>\n    '''\n
"},{"location":"reference/template_variables/#django_components.component.ComponentVars.slots","title":"slots instance-attribute","text":"
slots: Any\n

See source code

The slots argument as passed to Component.get_template_data().

This is the same Component.slots that's available on the component instance.

If you defined the Component.Slots class, then the slots property will return an instance of that class.

Otherwise, slots will be a plain dict.

Example:

With Slots class:

from django_components import Component, SlotInput, register\n\n@register(\"table\")\nclass Table(Component):\n    class Slots(NamedTuple):\n        footer: SlotInput\n\n    template = '''\n        <div>\n            {% component \"pagination\" %}\n                {% fill \"footer\" body=component_vars.slots.footer / %}\n            {% endcomponent %}\n        </div>\n    '''\n

Without Slots class:

from django_components import Component, SlotInput, register\n\n@register(\"table\")\nclass Table(Component):\n    template = '''\n        <div>\n            {% component \"pagination\" %}\n                {% fill \"footer\" body=component_vars.slots.footer / %}\n            {% endcomponent %}\n        </div>\n    '''\n
"},{"location":"reference/template_variables/#django_components.component.ComponentVars.is_filled","title":"is_filled instance-attribute","text":"
is_filled: Dict[str, bool]\n

See source code

Deprecated. Will be removed in v1. Use component_vars.slots instead. Note that component_vars.slots no longer escapes the slot names.

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

New in version 0.70

Use as {{ component_vars.is_filled }}

Example:

{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n    <div class=\"slot-wrapper\">\n        {% slot \"my_slot\" / %}\n    </div>\n{% endif %}\n

This is equivalent to checking if a given key is among the slot fills:

class MyTable(Component):\n    def get_template_data(self, args, kwargs, slots, context):\n        return {\n            \"my_slot_filled\": \"my_slot\" in slots\n        }\n
"},{"location":"reference/testing_api/","title":"Testing API","text":""},{"location":"reference/testing_api/#testing-api","title":"Testing API","text":""},{"location":"reference/testing_api/#django_components.testing.djc_test","title":"djc_test","text":"
djc_test(\n    django_settings: Union[Optional[Dict], Callable, Type] = None,\n    components_settings: Optional[Dict] = None,\n    parametrize: Optional[\n        Union[\n            Tuple[Sequence[str], Sequence[Sequence[Any]]],\n            Tuple[\n                Sequence[str],\n                Sequence[Sequence[Any]],\n                Optional[Union[Iterable[Union[None, str, float, int, bool]], Callable[[Any], Optional[object]]]],\n            ],\n        ]\n    ] = None,\n    gc_collect: bool = True,\n) -> Callable\n

See source code

Decorator for testing components from django-components.

@djc_test manages the global state of django-components, ensuring that each test is properly isolated and that components registered in one test do not affect other tests.

This decorator can be applied to a function, method, or a class. If applied to a class, it will search for all methods that start with test_, and apply the decorator to them. This is applied recursively to nested classes as well.

Examples:

Applying to a function:

from django_components.testing import djc_test\n\n@djc_test\ndef test_my_component():\n    @register(\"my_component\")\n    class MyComponent(Component):\n        template = \"...\"\n    ...\n

Applying to a class:

from django_components.testing import djc_test\n\n@djc_test\nclass TestMyComponent:\n    def test_something(self):\n        ...\n\n    class Nested:\n        def test_something_else(self):\n            ...\n

Applying to a class is the same as applying the decorator to each test_ method individually:

from django_components.testing import djc_test\n\nclass TestMyComponent:\n    @djc_test\n    def test_something(self):\n        ...\n\n    class Nested:\n        @djc_test\n        def test_something_else(self):\n            ...\n

To use @djc_test, Django must be set up first:

import django\nfrom django_components.testing import djc_test\n\ndjango.setup()\n\n@djc_test\ndef test_my_component():\n    ...\n

Arguments:

  • django_settings: Django settings, a dictionary passed to Django's @override_settings. The test runs within the context of these overridden settings.

    If django_settings contains django-components settings (COMPONENTS field), these are merged. Other Django settings are simply overridden.

  • components_settings: Instead of defining django-components settings under django_settings[\"COMPONENTS\"], you can simply set the Components settings here.

    These settings are merged with the django-components settings from django_settings[\"COMPONENTS\"].

    Fields in components_settings override fields in django_settings[\"COMPONENTS\"].

  • parametrize: Parametrize the test function with pytest.mark.parametrize. This requires pytest to be installed.

    The input is a tuple of:

    • (param_names, param_values) or
    • (param_names, param_values, ids)

    Example:

    from django_components.testing import djc_test\n\n@djc_test(\n    parametrize=(\n         [\"input\", \"expected\"],\n         [[1, \"<div>1</div>\"], [2, \"<div>2</div>\"]],\n         ids=[\"1\", \"2\"]\n     )\n)\ndef test_component(input, expected):\n    rendered = MyComponent(input=input).render()\n    assert rendered == expected\n

    You can parametrize the Django or Components settings by setting up parameters called django_settings and components_settings. These will be merged with the respetive settings from the decorator.

    Example of parametrizing context_behavior:

    from django_components.testing import djc_test\n\n@djc_test(\n    components_settings={\n        # Settings shared by all tests\n        \"app_dirs\": [\"custom_dir\"],\n    },\n    parametrize=(\n        # Parametrized settings\n        [\"components_settings\"],\n        [\n            [{\"context_behavior\": \"django\"}],\n            [{\"context_behavior\": \"isolated\"}],\n        ],\n        [\"django\", \"isolated\"],\n    )\n)\ndef test_context_behavior(components_settings):\n    rendered = MyComponent.render()\n    ...\n

  • gc_collect: By default djc_test runs garbage collection after each test to force the state cleanup. Set this to False to skip this.

Settings resolution:

@djc_test accepts settings from different sources. The settings are resolved in the following order:

  • Django settings:

    1. The defaults are the Django settings that Django was set up with.
    2. Those are then overriden with fields in the django_settings kwarg.
    3. The parametrized django_settings override the fields on the django_settings kwarg.

    Priority: django_settings (parametrized) > django_settings > django.conf.settings

  • Components settings:

    1. Same as above, except that the django_settings[\"COMPONENTS\"] field is merged instead of overridden.
    2. The components_settings kwarg is then merged with the django_settings[\"COMPONENTS\"] field.
    3. The parametrized components_settings override the fields on the components_settings kwarg.

    Priority: components_settings (parametrized) > components_settings > django_settings[\"COMPONENTS\"] > django.conf.settings.COMPONENTS

"},{"location":"reference/urls/","title":"URLs","text":""},{"location":"reference/urls/#urls","title":"URLs","text":"

Below are all the URL patterns that will be added by adding django_components.urls.

See Installation on how to add these URLs to your Django project.

Django components already prefixes all URLs with components/. So when you are adding the URLs to urlpatterns, you can use an empty string as the first argument:

from django.urls import include, path\n\nurlpatterns = [\n    ...\n    path(\"\", include(\"django_components.urls\")),\n]\n
"},{"location":"reference/urls/#list-of-urls","title":"List of URLs","text":"
  • components/cache/<str:comp_cls_id>.<str:input_hash>.<str:script_type>

  • components/cache/<str:comp_cls_id>.<str:script_type>

"}]} \ No newline at end of file diff --git a/dev/sitemap.xml b/dev/sitemap.xml index e8ea4638..ff52df38 100644 --- a/dev/sitemap.xml +++ b/dev/sitemap.xml @@ -2,270 +2,270 @@ https://django-components.github.io/django-components/latest/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/migrating_from_safer_staticfiles/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/release_notes/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/advanced/component_caching/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/advanced/component_context_scope/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/advanced/component_libraries/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/advanced/component_registry/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/advanced/extensions/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/advanced/hooks/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/advanced/html_fragments/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/advanced/provide_inject/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/advanced/rendering_js_css/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/advanced/tag_formatters/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/advanced/template_tags/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/advanced/testing/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/fundamentals/autodiscovery/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/fundamentals/component_defaults/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/fundamentals/component_views_urls/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/fundamentals/html_attributes/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/fundamentals/html_js_css_files/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/fundamentals/html_js_css_variables/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/fundamentals/http_request/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/fundamentals/render_api/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/fundamentals/rendering_components/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/fundamentals/secondary_js_css_files/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/fundamentals/single_file_components/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/fundamentals/slots/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/fundamentals/subclassing_components/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/fundamentals/template_tag_syntax/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/concepts/fundamentals/typing_and_validation/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/getting_started/adding_js_and_css/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/getting_started/adding_slots/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/getting_started/components_in_templates/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/getting_started/parametrising_components/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/getting_started/rendering_components/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/getting_started/your_first_component/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/guides/devguides/dependency_mgmt/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/guides/devguides/slot_rendering/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/guides/devguides/slots_and_blocks/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/guides/other/troubleshooting/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/guides/setup/caching/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/guides/setup/development_server/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/overview/code_of_conduct/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/overview/community/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/overview/compatibility/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/overview/contributing/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/overview/development/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/overview/installation/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/overview/license/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/overview/migrating/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/overview/performance/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/overview/security_notes/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/overview/welcome/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/reference/api/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/reference/commands/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/reference/components/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/reference/exceptions/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/reference/extension_commands/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/reference/extension_hooks/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/reference/extension_urls/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/reference/settings/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/reference/signals/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/reference/tag_formatters/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/reference/template_tags/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/reference/template_variables/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/reference/testing_api/ - 2025-08-05 + 2025-08-13 https://django-components.github.io/django-components/latest/reference/urls/ - 2025-08-05 + 2025-08-13 \ No newline at end of file diff --git a/dev/sitemap.xml.gz b/dev/sitemap.xml.gz index 6d0cec64..b71be9d7 100644 Binary files a/dev/sitemap.xml.gz and b/dev/sitemap.xml.gz differ diff --git a/versions.json b/versions.json index 93efbc09..7f286ccc 100644 --- a/versions.json +++ b/versions.json @@ -1,7 +1,7 @@ [ { "version": "dev", - "title": "dev (0df269a)", + "title": "dev (93cea3d)", "aliases": [] }, {