diff --git a/dev/getting_started/adding_slots/index.html b/dev/getting_started/adding_slots/index.html index f6683448..d5d2aece 100644 --- a/dev/getting_started/adding_slots/index.html +++ b/dev/getting_started/adding_slots/index.html @@ -117,4 +117,4 @@ <div class="calendar"> Today's date is <i>2024-12-16</i> </div> -

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.

\ No newline at end of file +

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’s explore other ways to render components ➡️] (./rendering_components.md)

\ No newline at end of file diff --git a/dev/search/search_index.json b/dev/search/search_index.json index 4e594654..a8addd14 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":"
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":"
{% 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:

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

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:

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

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:

Some of the extensions include:

Some of the planned extensions include:

"},{"location":"#caching","title":"Caching","text":"
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":"
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":""},{"location":"#sharing-components","title":"Sharing components","text":""},{"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/#v01411","title":"v0.141.1","text":""},{"location":"release_notes/#fix","title":"Fix","text":""},{"location":"release_notes/#v01410","title":"v0.141.0","text":""},{"location":"release_notes/#feat","title":"Feat","text":""},{"location":"release_notes/#fix_1","title":"Fix","text":""},{"location":"release_notes/#refactor","title":"Refactor","text":""},{"location":"release_notes/#v01401","title":"v0.140.1","text":""},{"location":"release_notes/#fix_2","title":"Fix","text":""},{"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:

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

Middleware

Typing

Component API

Template tags

Slots

Miscellaneous

"},{"location":"release_notes/#deprecation","title":"\ud83d\udea8\ud83d\udce2 Deprecation","text":"

Component API

Extensions

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

Miscellaneous

"},{"location":"release_notes/#feat_1","title":"Feat","text":""},{"location":"release_notes/#refactor_1","title":"Refactor","text":""},{"location":"release_notes/#fix_3","title":"Fix","text":""},{"location":"release_notes/#v01391","title":"v0.139.1","text":""},{"location":"release_notes/#fix_4","title":"Fix","text":""},{"location":"release_notes/#refactor_2","title":"Refactor","text":""},{"location":"release_notes/#v01390","title":"v0.139.0","text":""},{"location":"release_notes/#fix_5","title":"Fix","text":""},{"location":"release_notes/#v0138","title":"v0.138","text":""},{"location":"release_notes/#fix_6","title":"Fix","text":""},{"location":"release_notes/#v0137","title":"v0.137","text":""},{"location":"release_notes/#feat_2","title":"Feat","text":""},{"location":"release_notes/#deprecation_1","title":"Deprecation","text":""},{"location":"release_notes/#refactor_3","title":"Refactor","text":""},{"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":""},{"location":"release_notes/#fix_7","title":"Fix","text":""},{"location":"release_notes/#v0135","title":"v0.135","text":""},{"location":"release_notes/#feat_3","title":"Feat","text":"

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
"},{"location":"release_notes/#fix_8","title":"Fix","text":""},{"location":"release_notes/#v0134","title":"v0.134","text":""},{"location":"release_notes/#fix_9","title":"Fix","text":""},{"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_10","title":"Fix","text":""},{"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":""},{"location":"release_notes/#fix_11","title":"Fix","text":""},{"location":"release_notes/#v0131","title":"v0.131","text":""},{"location":"release_notes/#feat_5","title":"Feat","text":""},{"location":"release_notes/#refactor_4","title":"Refactor","text":""},{"location":"release_notes/#internal","title":"Internal","text":""},{"location":"release_notes/#v0130","title":"v0.130","text":""},{"location":"release_notes/#feat_6","title":"Feat","text":""},{"location":"release_notes/#v0129","title":"v0.129","text":""},{"location":"release_notes/#fix_12","title":"Fix","text":""},{"location":"release_notes/#v0128","title":"v0.128","text":""},{"location":"release_notes/#feat_7","title":"Feat","text":""},{"location":"release_notes/#refactor_5","title":"Refactor","text":""},{"location":"release_notes/#perf","title":"Perf","text":""},{"location":"release_notes/#v0127","title":"v0.127","text":""},{"location":"release_notes/#fix_13","title":"Fix","text":""},{"location":"release_notes/#v0126","title":"v0.126","text":""},{"location":"release_notes/#refactor_6","title":"Refactor","text":""},{"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":"

Read more on Template tags.

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

"},{"location":"release_notes/#refactor_7","title":"Refactor","text":""},{"location":"release_notes/#v0124","title":"v0.124","text":""},{"location":"release_notes/#feat_9","title":"Feat","text":""},{"location":"release_notes/#refactor_8","title":"Refactor","text":""},{"location":"release_notes/#v0123","title":"v0.123","text":""},{"location":"release_notes/#fix_14","title":"Fix","text":""},{"location":"release_notes/#v0122","title":"v0.122","text":""},{"location":"release_notes/#feat_10","title":"Feat","text":""},{"location":"release_notes/#v0121","title":"v0.121","text":""},{"location":"release_notes/#fix_15","title":"Fix","text":""},{"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_16","title":"Fix","text":""},{"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_17","title":"Fix","text":""},{"location":"release_notes/#refactor_9","title":"Refactor","text":""},{"location":"release_notes/#v0118","title":"v0.118","text":""},{"location":"release_notes/#feat_11","title":"Feat","text":"

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
"},{"location":"release_notes/#v0117","title":"v0.117","text":""},{"location":"release_notes/#fix_18","title":"Fix","text":""},{"location":"release_notes/#refactor_10","title":"Refactor","text":""},{"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_19","title":"Fix","text":"

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_20","title":"Fix","text":""},{"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_21","title":"Fix","text":""},{"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_22","title":"Fix","text":""},{"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_23","title":"Fix","text":""},{"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_24","title":"Fix","text":""},{"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":""},{"location":"release_notes/#feat_12","title":"Feat","text":"

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
"},{"location":"release_notes/#refactor_11","title":"Refactor","text":"

The old uppercase settings CONTEXT_BEHAVIOR and TAG_FORMATTER are 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":""},{"location":"release_notes/#fix_25","title":"Fix","text":""},{"location":"release_notes/#refactor_12","title":"Refactor","text":""},{"location":"release_notes/#slots","title":"Slots","text":""},{"location":"release_notes/#feat_13","title":"Feat","text":"

Following is now possible

{% component \"table\" %}\n  {% for slot_name in slots %}\n    {% fill name=slot_name %}\n    {% endfill %}\n  {% endfor %}\n{% endcomponent %}\n

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
class MyTable(Component):\n    def get_context_data(self, *args, **kwargs):\n        default_slot = self.input.slots[\"default\"]\n        ...\n
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_26","title":"Fix","text":"

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

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.

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

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":""},{"location":"release_notes/#feat_14","title":"Feat","text":""},{"location":"release_notes/#refactor_14","title":"Refactor","text":""},{"location":"release_notes/#v097","title":"v0.97","text":""},{"location":"release_notes/#fix_27","title":"Fix","text":""},{"location":"release_notes/#refactor_15","title":"Refactor","text":""},{"location":"release_notes/#v096","title":"v0.96","text":""},{"location":"release_notes/#feat_15","title":"Feat","text":""},{"location":"release_notes/#095","title":"0.95","text":""},{"location":"release_notes/#feat_16","title":"Feat","text":""},{"location":"release_notes/#refactor_16","title":"Refactor","text":""},{"location":"release_notes/#v094","title":"v0.94","text":""},{"location":"release_notes/#feat_17","title":"Feat","text":""},{"location":"release_notes/#v093","title":"v0.93","text":""},{"location":"release_notes/#feat_18","title":"Feat","text":""},{"location":"release_notes/#v092","title":"\ud83d\udea8\ud83d\udce2 v0.92","text":""},{"location":"release_notes/#breaking-changes_5","title":"BREAKING CHANGES","text":""},{"location":"release_notes/#feat_19","title":"Feat","text":""},{"location":"release_notes/#v090","title":"v0.90","text":""},{"location":"release_notes/#feat_20","title":"Feat","text":""},{"location":"release_notes/#v085","title":"\ud83d\udea8\ud83d\udce2 v0.85","text":""},{"location":"release_notes/#breaking-changes_6","title":"BREAKING CHANGES","text":""},{"location":"release_notes/#v081","title":"\ud83d\udea8\ud83d\udce2 v0.81","text":""},{"location":"release_notes/#breaking-changes_7","title":"BREAKING CHANGES","text":""},{"location":"release_notes/#feat_21","title":"Feat","text":""},{"location":"release_notes/#v080","title":"v0.80","text":""},{"location":"release_notes/#feat_22","title":"Feat","text":""},{"location":"release_notes/#v079","title":"\ud83d\udea8\ud83d\udce2 v0.79","text":""},{"location":"release_notes/#breaking-changes_8","title":"BREAKING CHANGES","text":""},{"location":"release_notes/#v077","title":"\ud83d\udea8\ud83d\udce2 v0.77","text":""},{"location":"release_notes/#breaking","title":"BREAKING","text":""},{"location":"release_notes/#v074","title":"v0.74","text":""},{"location":"release_notes/#feat_23","title":"Feat","text":""},{"location":"release_notes/#v070","title":"\ud83d\udea8\ud83d\udce2 v0.70","text":""},{"location":"release_notes/#breaking-changes_9","title":"BREAKING CHANGES","text":""},{"location":"release_notes/#v067","title":"v0.67","text":""},{"location":"release_notes/#refactor_17","title":"Refactor","text":""},{"location":"release_notes/#v050","title":"\ud83d\udea8\ud83d\udce2 v0.50","text":""},{"location":"release_notes/#breaking-changes_10","title":"BREAKING CHANGES","text":""},{"location":"release_notes/#v034","title":"v0.34","text":""},{"location":"release_notes/#feat_24","title":"Feat","text":""},{"location":"release_notes/#v028","title":"v0.28","text":""},{"location":"release_notes/#feat_25","title":"Feat","text":""},{"location":"release_notes/#v027","title":"v0.27","text":""},{"location":"release_notes/#feat_26","title":"Feat","text":""},{"location":"release_notes/#v026","title":"\ud83d\udea8\ud83d\udce2 v0.26","text":""},{"location":"release_notes/#breaking-changes_11","title":"BREAKING CHANGES","text":""},{"location":"release_notes/#v022","title":"v0.22","text":""},{"location":"release_notes/#feat_27","title":"Feat","text":""},{"location":"release_notes/#v017","title":"v0.17","text":""},{"location":"release_notes/#breaking-changes_12","title":"BREAKING CHANGES","text":""},{"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
"},{"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:

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:

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

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

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:

"},{"location":"concepts/advanced/extensions/#live-examples","title":"Live examples","text":""},{"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:

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

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.

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:

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:

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

"},{"location":"concepts/advanced/extensions/#define-commands","title":"Define commands","text":"

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

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:

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:

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:

    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:

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:

    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:

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:

A component is rendered as a \"document\" when:

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:

A component is rendered as \"fragment\" when:

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:

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

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

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

If you want to place the dependencies elsewhere in the HTML, you can override the locations by inserting following Django template tags:

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:

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:

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

Location:

JS and CSS is 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:

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:

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

Included scripts:

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

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:

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:

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

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:

To do so, subclass from TagFormatterABC and implement following method:

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:

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:

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

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:

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:

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:

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:

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:

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

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:

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:

  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.

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.

If a style property is specified multiple times, the last value is used.

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:

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

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

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:

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:

  2. Render the component.

Once the component's media files have been loaded once, they will remain in-memory on the Component class:

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:

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:

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:

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:

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:

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:

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:

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

# \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:

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:

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

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

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:

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:

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

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

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

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:

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:

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\":

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:

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

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:

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

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:

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:

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

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:

inheritance follows these rules:

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:

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.

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:

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:

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:

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:

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:

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

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

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

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

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:

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:

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:

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

    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.

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

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

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:

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:

Examples of unacceptable behavior by participants include:

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

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

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:

    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:

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:

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:

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

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

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:

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

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:

Some of the extensions include:

Some of the planned extensions include:

"},{"location":"overview/welcome/#caching","title":"Caching","text":"
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":"
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":""},{"location":"overview/welcome/#sharing-components","title":"Sharing components","text":""},{"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:

Attributes:

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

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

Attributes:

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

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:

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:

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:

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:

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:

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:

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

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:

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

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:

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:

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

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:

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

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

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:

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:

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:

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:

Returns:

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

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:

Returns:

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

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:

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:

    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:

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:

    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:

Returns:

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:

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:

Attributes:

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

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

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

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

Attributes:

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

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

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

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

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.

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.

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:

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

Attributes:

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

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

Notes:

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:

Attributes:

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

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:

Returns:

Raises:

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:

Returns:

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:

Raises:

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:

Raises:

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:

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

Attributes:

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

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

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:

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

Attributes:

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

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

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

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:

Attributes:

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

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

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:

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:

Attributes:

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

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

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

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

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:

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

Returns:

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:

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:

Attributes:

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

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

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

Returns:

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

Returns:

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

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:

Returns:

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

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

Returns:

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:

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:

Returns:

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:

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

Returns:

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:

Returns:

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:

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.

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.

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:

Raises:

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

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:

Subcommands:

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:

Options:

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

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

Subcommands:

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:

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:

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:

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:

Options:

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:

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:

Slots:

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:

Attributes:

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

Attributes:

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

Attributes:

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

Attributes:

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

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:

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

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

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

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

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

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

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

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

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

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

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:

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

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

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:

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:

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:

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:

Settings resolution:

@djc_test accepts settings from different sources. The settings are resolved in the following order:

"},{"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":""}]} \ 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":"
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":"
{% 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:

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

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:

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

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:

Some of the extensions include:

Some of the planned extensions include:

"},{"location":"#caching","title":"Caching","text":"
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":"
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":""},{"location":"#sharing-components","title":"Sharing components","text":""},{"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/#v01411","title":"v0.141.1","text":""},{"location":"release_notes/#fix","title":"Fix","text":""},{"location":"release_notes/#v01410","title":"v0.141.0","text":""},{"location":"release_notes/#feat","title":"Feat","text":""},{"location":"release_notes/#fix_1","title":"Fix","text":""},{"location":"release_notes/#refactor","title":"Refactor","text":""},{"location":"release_notes/#v01401","title":"v0.140.1","text":""},{"location":"release_notes/#fix_2","title":"Fix","text":""},{"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:

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

Middleware

Typing

Component API

Template tags

Slots

Miscellaneous

"},{"location":"release_notes/#deprecation","title":"\ud83d\udea8\ud83d\udce2 Deprecation","text":"

Component API

Extensions

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

Miscellaneous

"},{"location":"release_notes/#feat_1","title":"Feat","text":""},{"location":"release_notes/#refactor_1","title":"Refactor","text":""},{"location":"release_notes/#fix_3","title":"Fix","text":""},{"location":"release_notes/#v01391","title":"v0.139.1","text":""},{"location":"release_notes/#fix_4","title":"Fix","text":""},{"location":"release_notes/#refactor_2","title":"Refactor","text":""},{"location":"release_notes/#v01390","title":"v0.139.0","text":""},{"location":"release_notes/#fix_5","title":"Fix","text":""},{"location":"release_notes/#v0138","title":"v0.138","text":""},{"location":"release_notes/#fix_6","title":"Fix","text":""},{"location":"release_notes/#v0137","title":"v0.137","text":""},{"location":"release_notes/#feat_2","title":"Feat","text":""},{"location":"release_notes/#deprecation_1","title":"Deprecation","text":""},{"location":"release_notes/#refactor_3","title":"Refactor","text":""},{"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":""},{"location":"release_notes/#fix_7","title":"Fix","text":""},{"location":"release_notes/#v0135","title":"v0.135","text":""},{"location":"release_notes/#feat_3","title":"Feat","text":"

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
"},{"location":"release_notes/#fix_8","title":"Fix","text":""},{"location":"release_notes/#v0134","title":"v0.134","text":""},{"location":"release_notes/#fix_9","title":"Fix","text":""},{"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_10","title":"Fix","text":""},{"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":""},{"location":"release_notes/#fix_11","title":"Fix","text":""},{"location":"release_notes/#v0131","title":"v0.131","text":""},{"location":"release_notes/#feat_5","title":"Feat","text":""},{"location":"release_notes/#refactor_4","title":"Refactor","text":""},{"location":"release_notes/#internal","title":"Internal","text":""},{"location":"release_notes/#v0130","title":"v0.130","text":""},{"location":"release_notes/#feat_6","title":"Feat","text":""},{"location":"release_notes/#v0129","title":"v0.129","text":""},{"location":"release_notes/#fix_12","title":"Fix","text":""},{"location":"release_notes/#v0128","title":"v0.128","text":""},{"location":"release_notes/#feat_7","title":"Feat","text":""},{"location":"release_notes/#refactor_5","title":"Refactor","text":""},{"location":"release_notes/#perf","title":"Perf","text":""},{"location":"release_notes/#v0127","title":"v0.127","text":""},{"location":"release_notes/#fix_13","title":"Fix","text":""},{"location":"release_notes/#v0126","title":"v0.126","text":""},{"location":"release_notes/#refactor_6","title":"Refactor","text":""},{"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":"

Read more on Template tags.

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

"},{"location":"release_notes/#refactor_7","title":"Refactor","text":""},{"location":"release_notes/#v0124","title":"v0.124","text":""},{"location":"release_notes/#feat_9","title":"Feat","text":""},{"location":"release_notes/#refactor_8","title":"Refactor","text":""},{"location":"release_notes/#v0123","title":"v0.123","text":""},{"location":"release_notes/#fix_14","title":"Fix","text":""},{"location":"release_notes/#v0122","title":"v0.122","text":""},{"location":"release_notes/#feat_10","title":"Feat","text":""},{"location":"release_notes/#v0121","title":"v0.121","text":""},{"location":"release_notes/#fix_15","title":"Fix","text":""},{"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_16","title":"Fix","text":""},{"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_17","title":"Fix","text":""},{"location":"release_notes/#refactor_9","title":"Refactor","text":""},{"location":"release_notes/#v0118","title":"v0.118","text":""},{"location":"release_notes/#feat_11","title":"Feat","text":"

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
"},{"location":"release_notes/#v0117","title":"v0.117","text":""},{"location":"release_notes/#fix_18","title":"Fix","text":""},{"location":"release_notes/#refactor_10","title":"Refactor","text":""},{"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_19","title":"Fix","text":"

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_20","title":"Fix","text":""},{"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_21","title":"Fix","text":""},{"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_22","title":"Fix","text":""},{"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_23","title":"Fix","text":""},{"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_24","title":"Fix","text":""},{"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":""},{"location":"release_notes/#feat_12","title":"Feat","text":"

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
"},{"location":"release_notes/#refactor_11","title":"Refactor","text":"

The old uppercase settings CONTEXT_BEHAVIOR and TAG_FORMATTER are 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":""},{"location":"release_notes/#fix_25","title":"Fix","text":""},{"location":"release_notes/#refactor_12","title":"Refactor","text":""},{"location":"release_notes/#slots","title":"Slots","text":""},{"location":"release_notes/#feat_13","title":"Feat","text":"

Following is now possible

{% component \"table\" %}\n  {% for slot_name in slots %}\n    {% fill name=slot_name %}\n    {% endfill %}\n  {% endfor %}\n{% endcomponent %}\n

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
class MyTable(Component):\n    def get_context_data(self, *args, **kwargs):\n        default_slot = self.input.slots[\"default\"]\n        ...\n
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_26","title":"Fix","text":"

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

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.

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

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":""},{"location":"release_notes/#feat_14","title":"Feat","text":""},{"location":"release_notes/#refactor_14","title":"Refactor","text":""},{"location":"release_notes/#v097","title":"v0.97","text":""},{"location":"release_notes/#fix_27","title":"Fix","text":""},{"location":"release_notes/#refactor_15","title":"Refactor","text":""},{"location":"release_notes/#v096","title":"v0.96","text":""},{"location":"release_notes/#feat_15","title":"Feat","text":""},{"location":"release_notes/#095","title":"0.95","text":""},{"location":"release_notes/#feat_16","title":"Feat","text":""},{"location":"release_notes/#refactor_16","title":"Refactor","text":""},{"location":"release_notes/#v094","title":"v0.94","text":""},{"location":"release_notes/#feat_17","title":"Feat","text":""},{"location":"release_notes/#v093","title":"v0.93","text":""},{"location":"release_notes/#feat_18","title":"Feat","text":""},{"location":"release_notes/#v092","title":"\ud83d\udea8\ud83d\udce2 v0.92","text":""},{"location":"release_notes/#breaking-changes_5","title":"BREAKING CHANGES","text":""},{"location":"release_notes/#feat_19","title":"Feat","text":""},{"location":"release_notes/#v090","title":"v0.90","text":""},{"location":"release_notes/#feat_20","title":"Feat","text":""},{"location":"release_notes/#v085","title":"\ud83d\udea8\ud83d\udce2 v0.85","text":""},{"location":"release_notes/#breaking-changes_6","title":"BREAKING CHANGES","text":""},{"location":"release_notes/#v081","title":"\ud83d\udea8\ud83d\udce2 v0.81","text":""},{"location":"release_notes/#breaking-changes_7","title":"BREAKING CHANGES","text":""},{"location":"release_notes/#feat_21","title":"Feat","text":""},{"location":"release_notes/#v080","title":"v0.80","text":""},{"location":"release_notes/#feat_22","title":"Feat","text":""},{"location":"release_notes/#v079","title":"\ud83d\udea8\ud83d\udce2 v0.79","text":""},{"location":"release_notes/#breaking-changes_8","title":"BREAKING CHANGES","text":""},{"location":"release_notes/#v077","title":"\ud83d\udea8\ud83d\udce2 v0.77","text":""},{"location":"release_notes/#breaking","title":"BREAKING","text":""},{"location":"release_notes/#v074","title":"v0.74","text":""},{"location":"release_notes/#feat_23","title":"Feat","text":""},{"location":"release_notes/#v070","title":"\ud83d\udea8\ud83d\udce2 v0.70","text":""},{"location":"release_notes/#breaking-changes_9","title":"BREAKING CHANGES","text":""},{"location":"release_notes/#v067","title":"v0.67","text":""},{"location":"release_notes/#refactor_17","title":"Refactor","text":""},{"location":"release_notes/#v050","title":"\ud83d\udea8\ud83d\udce2 v0.50","text":""},{"location":"release_notes/#breaking-changes_10","title":"BREAKING CHANGES","text":""},{"location":"release_notes/#v034","title":"v0.34","text":""},{"location":"release_notes/#feat_24","title":"Feat","text":""},{"location":"release_notes/#v028","title":"v0.28","text":""},{"location":"release_notes/#feat_25","title":"Feat","text":""},{"location":"release_notes/#v027","title":"v0.27","text":""},{"location":"release_notes/#feat_26","title":"Feat","text":""},{"location":"release_notes/#v026","title":"\ud83d\udea8\ud83d\udce2 v0.26","text":""},{"location":"release_notes/#breaking-changes_11","title":"BREAKING CHANGES","text":""},{"location":"release_notes/#v022","title":"v0.22","text":""},{"location":"release_notes/#feat_27","title":"Feat","text":""},{"location":"release_notes/#v017","title":"v0.17","text":""},{"location":"release_notes/#breaking-changes_12","title":"BREAKING CHANGES","text":""},{"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
"},{"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:

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:

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

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

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:

"},{"location":"concepts/advanced/extensions/#live-examples","title":"Live examples","text":""},{"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:

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

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.

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:

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:

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

"},{"location":"concepts/advanced/extensions/#define-commands","title":"Define commands","text":"

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

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:

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:

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:

    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:

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:

    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:

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:

A component is rendered as a \"document\" when:

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:

A component is rendered as \"fragment\" when:

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:

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

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

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

If you want to place the dependencies elsewhere in the HTML, you can override the locations by inserting following Django template tags:

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:

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:

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

Location:

JS and CSS is 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:

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:

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

Included scripts:

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

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:

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:

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

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:

To do so, subclass from TagFormatterABC and implement following method:

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:

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:

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

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:

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:

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:

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:

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:

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

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:

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:

  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.

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.

If a style property is specified multiple times, the last value is used.

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:

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

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

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:

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:

  2. Render the component.

Once the component's media files have been loaded once, they will remain in-memory on the Component class:

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:

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:

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:

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:

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:

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:

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:

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

# \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:

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:

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

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

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:

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:

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

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

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

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:

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:

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\":

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:

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

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:

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

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:

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:

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

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:

inheritance follows these rules:

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:

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.

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:

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:

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:

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:

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:

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

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

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

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:

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:

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:

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

    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.

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

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

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:

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:

Examples of unacceptable behavior by participants include:

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

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

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:

    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:

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:

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:

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

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

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:

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

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:

Some of the extensions include:

Some of the planned extensions include:

"},{"location":"overview/welcome/#caching","title":"Caching","text":"
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":"
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":""},{"location":"overview/welcome/#sharing-components","title":"Sharing components","text":""},{"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:

Attributes:

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

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

Attributes:

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

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:

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:

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:

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:

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:

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:

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

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:

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

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:

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:

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

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:

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

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

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:

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:

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:

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:

Returns:

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

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:

Returns:

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

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:

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:

    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:

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:

    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:

Returns:

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:

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:

Attributes:

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

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

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

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

Attributes:

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

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

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

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

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.

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.

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:

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

Attributes:

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

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

Notes:

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:

Attributes:

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

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:

Returns:

Raises:

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:

Returns:

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:

Raises:

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:

Raises:

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:

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

Attributes:

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

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

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:

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

Attributes:

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

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

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

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:

Attributes:

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

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

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:

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:

Attributes:

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

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

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

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

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:

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

Returns:

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:

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:

Attributes:

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

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

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

Returns:

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

Returns:

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

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:

Returns:

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

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

Returns:

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:

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:

Returns:

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:

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

Returns:

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:

Returns:

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:

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.

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.

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:

Raises:

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

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:

Subcommands:

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:

Options:

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

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

Subcommands:

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:

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:

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:

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:

Options:

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:

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:

Slots:

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:

Attributes:

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

Attributes:

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

Attributes:

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

Attributes:

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

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:

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

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

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

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

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

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

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

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

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

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

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:

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

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

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:

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:

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:

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:

Settings resolution:

@djc_test accepts settings from different sources. The settings are resolved in the following order:

"},{"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":""}]} \ No newline at end of file diff --git a/versions.json b/versions.json index 9878d4ce..7a3e9caa 100644 --- a/versions.json +++ b/versions.json @@ -1,7 +1,7 @@ [ { "version": "dev", - "title": "dev (0c7e17d)", + "title": "dev (b7b0d25)", "aliases": [] }, {