From fb1a2d71777da7484e2404024eaf9e1470612545 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 7 Jan 2025 18:49:36 +0000 Subject: [PATCH] Deployed 203d29f to dev with MkDocs 1.6.1 and mike 2.1.3 --- dev/concepts/fundamentals/autodiscovery/index.html | 6 +++--- dev/reference/api/index.html | 6 +++--- dev/search/search_index.json | 2 +- versions.json | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/dev/concepts/fundamentals/autodiscovery/index.html b/dev/concepts/fundamentals/autodiscovery/index.html index b5339ebf..a0c728cc 100644 --- a/dev/concepts/fundamentals/autodiscovery/index.html +++ b/dev/concepts/fundamentals/autodiscovery/index.html @@ -3,7 +3,7 @@ @register("calendar") class Calendar(Component): ... -

But for the component to be registered, the code needs to be executed - the file needs to be imported as a module.

One way to do that is by importing all your components in apps.py:

from django.apps import AppConfig
+

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.

One way to do that is by importing all your components in apps.py:

from django.apps import AppConfig
 
 class MyAppConfig(AppConfig):
     name = "my_app"
@@ -14,10 +14,10 @@
         from components.menu.menu import Menu
         from components.button.button import Button
         ...
-

However, there's a simpler way!

By default, the Python files in the COMPONENTS.dirs directories (and app-level [app]/components/) are auto-imported in order to auto-register 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.

Manually trigger autodiscovery¤

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
+

However, there's a simpler way!

By default, the Python files in the COMPONENTS.dirs directories (and app-level [app]/components/) are auto-imported in order to auto-register 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.

Manually trigger autodiscovery¤

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

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
 
 modules = get_component_files(".py")
-
\ No newline at end of file +
\ No newline at end of file diff --git a/dev/reference/api/index.html b/dev/reference/api/index.html index 00a3e448..3d7e593e 100644 --- a/dev/reference/api/index.html +++ b/dev/reference/api/index.html @@ -518,7 +518,7 @@

Then component_name would be my_comp.

tokens instance-attribute ¤

tokens: List[str]
 

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

Then tokens would be ['key=val', 'key2=val2'].

autodiscover ¤

autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]
-

See source code

Search for all python files in COMPONENTS.dirs and COMPONENTS.app_dirs and import them.

See Autodiscovery.

Parameters:

  • map_module (Callable[[str], str], default: None ) –

    Map the module paths with map_module function. This serves as an escape hatch for when you need to use this function in tests.

Returns:

  • List[str]

    List[str]: A list of module paths of imported files.

To get the same list of modules that autodiscover() would return, but without importing them, use get_component_files():

from django_components import get_component_files
+

See source code

Search for all python files in COMPONENTS.dirs and COMPONENTS.app_dirs and import them.

See Autodiscovery.

NOTE: Subdirectories and files starting with an underscore _ (except for __init__.py are ignored.

Parameters:

  • map_module (Callable[[str], str], default: None ) –

    Map the module paths with map_module function. This serves as an escape hatch for when you need to use this function in tests.

Returns:

  • List[str]

    List[str]: A list of module paths of imported files.

To get the same list of modules that autodiscover() would return, but without importing them, use get_component_files():

from django_components import get_component_files
 
 modules = get_component_files(".py")
 

cached_template ¤

cached_template(
@@ -545,11 +545,11 @@
 )
 

get_component_dirs ¤

get_component_dirs(include_apps: bool = True) -> List[Path]
 

See source code

Get directories that may contain component files.

This is the heart of all features that deal with filesystem and file lookup. Autodiscovery, Django template resolution, static file resolution - They all use this.

Parameters:

  • include_apps (bool, default: True ) –

    Include directories from installed Django apps. Defaults to True.

Returns:

  • List[Path]

    List[Path]: A list of directories that may contain component files.

get_component_dirs() searches for dirs set in COMPONENTS.dirs settings. If none set, defaults to searching for a "components" app.

In addition to that, also all installed Django apps are checked whether they contain directories as set in COMPONENTS.app_dirs (e.g. [app]/components).

Notes:

  • Paths that do not point to directories are ignored.

  • BASE_DIR setting is required.

  • The paths in COMPONENTS.dirs must be absolute paths.

get_component_files ¤

get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]
-

See source code

Search for files within the component directories (as defined in get_component_dirs()).

Requires BASE_DIR setting to be set.

Parameters:

  • suffix (Optional[str], default: None ) –

    The suffix to search for. E.g. .py, .js, .css. Defaults to None, which will search for all files.

Returns:

  • List[ComponentFileEntry]

    List[ComponentFileEntry] A list of entries that contain both the filesystem path and the python import path (dot path).

Example:

from django_components import get_component_files
+

See source code

Search for files within the component directories (as defined in get_component_dirs()).

Requires BASE_DIR setting to be set.

Subdirectories and files starting with an underscore _ (except __init__.py) are ignored.

Parameters:

  • suffix (Optional[str], default: None ) –

    The suffix to search for. E.g. .py, .js, .css. Defaults to None, which will search for all files.

Returns:

  • List[ComponentFileEntry]

    List[ComponentFileEntry] A list of entries that contain both the filesystem path and the python import path (dot path).

Example:

from django_components import get_component_files
 
 modules = get_component_files(".py")
 

import_libraries ¤

import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]
-

See source code

Import modules set in COMPONENTS.libraries setting.

See Autodiscovery.

Parameters:

  • map_module (Callable[[str], str], default: None ) –

    Map the module paths with map_module function. This serves as an escape hatch for when you need to use this function in tests.

Returns:

  • List[str]

    List[str]: A list of module paths of imported files.

Examples:

Normal usage - load libraries after Django has loaded

from django_components import import_libraries
+

See source code

Import modules set in COMPONENTS.libraries setting.

See Autodiscovery.

Parameters:

  • map_module (Callable[[str], str], default: None ) –

    Map the module paths with map_module function. This serves as an escape hatch for when you need to use this function in tests.

Returns:

  • List[str]

    List[str]: A list of module paths of imported files.

Examples:

Normal usage - load libraries after Django has loaded

from django_components import import_libraries
 
 class MyAppConfig(AppConfig):
     def ready(self):
diff --git a/dev/search/search_index.json b/dev/search/search_index.json
index 7024e921..c1357165 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 introduces component-based architecture to Django's server-side rendering. It combines Django's templating system with the modularity seen in modern frontend frameworks like Vue or React.

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\n\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
"},{"location":"#features","title":"Features","text":"
  1. \ud83e\udde9 Reusability: Allows creation of self-contained, reusable UI elements.
  2. \ud83d\udce6 Encapsulation: Each component can include its own HTML, CSS, and JavaScript.
  3. \ud83d\ude80 Server-side rendering: Components render on the server, improving initial load times and SEO.
  4. \ud83d\udc0d Django integration: Works within the Django ecosystem, using familiar concepts like template tags.
  5. \u26a1 Asynchronous loading: Components can render independently opening up for integration with JS frameworks like HTMX or AlpineJS.

Potential benefits:

  • \ud83d\udd04 Reduced code duplication
  • \ud83d\udee0\ufe0f Improved maintainability through modular design
  • \ud83e\udde0 Easier management of complex UIs
  • \ud83e\udd1d Enhanced collaboration between frontend and backend developers

Django-components can be particularly useful for larger Django projects that require a more structured approach to UI development, without necessitating a shift to a separate frontend framework.

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

django-components lets you create reusable blocks of code needed to generate the front end code you need for a modern app.

Define a component in components/calendar/calendar.py like this:

@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"template.html\"\n\n    def get_context_data(self, date):\n        return {\"date\": date}\n

With this template.html file:

<div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n

Use the component like this:

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

And this is what gets rendered:

<div class=\"calendar-component\">Today's date is <span>2024-11-06</span></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":"#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. If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.

  • django-htmx-components: A set of components for use with htmx. Try out the live demo.
"},{"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":"SUMMARY/","title":"SUMMARY","text":"
  • Get Started
  • Concepts
  • Getting started
  • Fundamentals
  • Advanced
  • Guides
  • Setup
  • Dev guides
  • API Documentation
  • Release notes
"},{"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/#v0124","title":"v0.124","text":""},{"location":"release_notes/#feat","title":"Feat","text":"
  • Instead of inlining the JS and CSS under Component.js and Component.css, you can move them to their own files, and link the JS/CSS files with Component.js_file and Component.css_file.

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

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

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

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

    See the updated \"Getting Started\" tutorial

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  • Fix compatibility with AlpineJS

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

AlpineJS can be configured like so:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    to

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Following is now possible

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Internally, django-components handles slot fills as functions.

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

Now, something like this is possible:

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

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

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

Before:

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

After:

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

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

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

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

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

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

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

{% component \"child\" %}\n  {% fill slot=\"default\" %}\n    Hello from default slot\n  {% endfill %}\n  {% fill slot=\"content\" data=\"data\" %}\n    Hello from content slot\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"release_notes/#v0100","title":"\ud83d\udea8\ud83d\udce2 v0.100","text":""},{"location":"release_notes/#breaking-changes_2","title":"BREAKING CHANGES","text":"
  • django_components.safer_staticfiles app was removed. It is no longer needed.

  • Installation changes:

    • Instead of defining component directories in STATICFILES_DIRS, set them to COMPONENTS.dirs.
    • You now must define STATICFILES_FINDERS

    • See here how to migrate your settings.py

"},{"location":"release_notes/#feat_5","title":"Feat","text":"
  • Beside the top-level /components directory, you can now define also app-level components dirs, e.g. [app]/components (See COMPONENTS.app_dirs).
"},{"location":"release_notes/#refactor_6","title":"Refactor","text":"
  • When you call as_view() on a component instance, that instance will be passed to View.as_view()
"},{"location":"release_notes/#v097","title":"v0.97","text":""},{"location":"release_notes/#fix_13","title":"Fix","text":"
  • Fixed template caching. You can now also manually create cached templates with cached_template()
"},{"location":"release_notes/#refactor_7","title":"Refactor","text":"
  • The previously undocumented get_template was made private.

  • In it's place, there's a new get_template, which supersedes get_template_string (will be removed in v1). The new get_template is the same as get_template_string, except it allows to return either a string or a Template instance.

  • You now must use only one of template, get_template, template_name, or get_template_name.

"},{"location":"release_notes/#v096","title":"v0.96","text":""},{"location":"release_notes/#feat_6","title":"Feat","text":"
  • Run-time type validation for Python 3.11+ - If the Component class is typed, e.g. Component[Args, Kwargs, ...], the args, kwargs, slots, and data are validated against the given types. (See Runtime input validation with types)

  • Render hooks - Set on_render_before and on_render_after methods on Component to intercept or modify the template or context before rendering, or the rendered result afterwards. (See Component hooks)

  • component_vars.is_filled context variable can be accessed from within on_render_before and on_render_after hooks as self.is_filled.my_slot

"},{"location":"release_notes/#095","title":"0.95","text":""},{"location":"release_notes/#feat_7","title":"Feat","text":"
  • Added support for dynamic components, where the component name is passed as a variable. (See Dynamic components)
"},{"location":"release_notes/#refactor_8","title":"Refactor","text":"
  • Changed Component.input to raise RuntimeError if accessed outside of render context. Previously it returned None if unset.
"},{"location":"release_notes/#v094","title":"v0.94","text":""},{"location":"release_notes/#feat_8","title":"Feat","text":"
  • django_components now automatically configures Django to support multi-line tags. (See Multi-line tags)

  • New setting reload_on_template_change. Set this to True to reload the dev server on changes to component template files. (See Reload dev server on component file changes)

"},{"location":"release_notes/#v093","title":"v0.93","text":""},{"location":"release_notes/#feat_9","title":"Feat","text":"
  • Spread operator ...dict inside template tags. (See Spread operator)

  • Use template tags inside string literals in component inputs. (See Use template tags inside component inputs)

  • Dynamic slots, fills and provides - The name argument for these can now be a variable, a template expression, or via spread operator

  • Component library authors can now configure CONTEXT_BEHAVIOR and TAG_FORMATTER settings independently from user settings.

"},{"location":"release_notes/#v092","title":"\ud83d\udea8\ud83d\udce2 v0.92","text":""},{"location":"release_notes/#breaking-changes_3","title":"BREAKING CHANGES","text":"
  • Component class is no longer a subclass of View. To configure the View class, set the Component.View nested class. HTTP methods like get or post can still be defined directly on Component class, and Component.as_view() internally calls Component.View.as_view(). (See Modifying the View class)
"},{"location":"release_notes/#feat_10","title":"Feat","text":"
  • The inputs (args, kwargs, slots, context, ...) that you pass to Component.render() can be accessed from within get_context_data, get_template and get_template_name via self.input. (See Accessing data passed to the component)

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

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

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

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

    The default is django_components.component_formatter:

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

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

    {% button href=\"...\" disabled %}\n    Click me!\n{% endbutton %}\n
"},{"location":"release_notes/#v085","title":"\ud83d\udea8\ud83d\udce2 v0.85","text":""},{"location":"release_notes/#breaking-changes_4","title":"BREAKING CHANGES","text":"
  • Autodiscovery module resolution changed. Following undocumented behavior was removed:

    • Previously, autodiscovery also imported any [app]/components.py files, and used SETTINGS_MODULE to search for component dirs.

      To migrate from:

      • [app]/components.py - Define each module in COMPONENTS.libraries setting, or import each module inside the AppConfig.ready() hook in respective apps.py files.

      • SETTINGS_MODULE - Define component dirs using STATICFILES_DIRS

    • Previously, autodiscovery handled relative files in STATICFILES_DIRS. To align with Django, STATICFILES_DIRS now must be full paths (Django docs).

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

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

"},{"location":"release_notes/#v080","title":"v0.80","text":""},{"location":"release_notes/#feat_13","title":"Feat","text":"
  • Vue-like provide/inject with the {% provide %} tag and inject() method.
"},{"location":"release_notes/#v079","title":"\ud83d\udea8\ud83d\udce2 v0.79","text":""},{"location":"release_notes/#breaking-changes_6","title":"BREAKING CHANGES","text":"
  • Default value for the COMPONENTS.context_behavior setting was changes from \"isolated\" to \"django\". If you did not set this value explicitly before, this may be a breaking change. See the rationale for change here.
"},{"location":"release_notes/#v077","title":"\ud83d\udea8\ud83d\udce2 v0.77","text":""},{"location":"release_notes/#breaking","title":"BREAKING","text":"
  • The syntax for accessing default slot content has changed from

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

    to

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

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

"},{"location":"release_notes/#v070","title":"\ud83d\udea8\ud83d\udce2 v0.70","text":""},{"location":"release_notes/#breaking-changes_7","title":"BREAKING CHANGES","text":"
  • {% if_filled \"my_slot\" %} tags were replaced with {{ component_vars.is_filled.my_slot }} variables.

  • Simplified settings - slot_context_behavior and context_behavior were merged. See the documentation for more details.

"},{"location":"release_notes/#v067","title":"v0.67","text":""},{"location":"release_notes/#refactor_9","title":"Refactor","text":"
  • Changed the default way how context variables are resolved in slots. See the documentation for more details.
"},{"location":"release_notes/#v050","title":"\ud83d\udea8\ud83d\udce2 v0.50","text":""},{"location":"release_notes/#breaking-changes_8","title":"BREAKING CHANGES","text":"
  • {% component_block %} is now {% component %}, and {% component %} blocks need an ending {% endcomponent %} tag.

    The new python manage.py upgradecomponent command can be used to upgrade a directory (use --path argument to point to each dir) of templates that use components to the new syntax automatically.

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

"},{"location":"release_notes/#v034","title":"v0.34","text":""},{"location":"release_notes/#feat_15","title":"Feat","text":"
  • Components as views, which allows you to handle requests and render responses from within a component. See the documentation for more details.
"},{"location":"release_notes/#v028","title":"v0.28","text":""},{"location":"release_notes/#feat_16","title":"Feat","text":"
  • 'implicit' slot filling and the default option for slot tags.
"},{"location":"release_notes/#v027","title":"v0.27","text":""},{"location":"release_notes/#feat_17","title":"Feat","text":"
  • A second installable app django_components.safer_staticfiles. It provides the same behavior as django.contrib.staticfiles but with extra security guarantees (more info below in Security Notes).
"},{"location":"release_notes/#v026","title":"\ud83d\udea8\ud83d\udce2 v0.26","text":""},{"location":"release_notes/#breaking-changes_9","title":"BREAKING CHANGES","text":"
  • Changed the syntax for {% slot %} tags. From now on, we separate defining a slot ({% slot %}) from filling a slot with content ({% fill %}). This means you will likely need to change a lot of slot tags to fill.

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

"},{"location":"release_notes/#v022","title":"v0.22","text":""},{"location":"release_notes/#feat_18","title":"Feat","text":"
  • All files inside components subdirectores are autoimported to simplify setup.

    An existing project might start to get AlreadyRegistered errors because of this. To solve this, either remove your custom loading of components, or set \"autodiscover\": False in settings.COMPONENTS.

"},{"location":"release_notes/#v017","title":"v0.17","text":""},{"location":"release_notes/#breaking-changes_10","title":"BREAKING CHANGES","text":"
  • Renamed Component.context and Component.template to get_context_data and get_template_name. The old methods still work, but emit a deprecation warning.

    This change was done to sync naming with Django's class based views, and make using django-components more familiar to Django users. Component.context and Component.template will be removed when version 1.0 is released.

"},{"location":"concepts/advanced/authoring_component_libraries/","title":"Authoring component libraries","text":"

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

"},{"location":"concepts/advanced/authoring_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 Dict, NotRequired, Optional, Tuple, TypedDict\n\nfrom django_components import Component, SlotFunc, register, types\n\nfrom myapp.templatetags.mytags import comp_registry\n\n# Define the types\nclass EmptyDict(TypedDict):\n    pass\n\ntype MyMenuArgs = Tuple[int, str]\n\nclass MyMenuSlots(TypedDict):\n    default: NotRequired[Optional[SlotFunc[EmptyDict]]]\n\nclass MyMenuProps(TypedDict):\n    vertical: NotRequired[bool]\n    klass: NotRequired[str]\n    style: NotRequired[str]\n\n# Define the component\n# NOTE: Don't forget to set the `registry`!\n@register(\"my_menu\", registry=comp_registry)\nclass MyMenu(Component[MyMenuArgs, MyMenuProps, MyMenuSlots, Any, Any, Any]):\n    def get_context_data(\n        self,\n        *args,\n        attrs: Optional[Dict] = None,\n    ):\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/authoring_component_libraries/#publishing-component-libraries","title":"Publishing component libraries","text":"

Once you are ready to share your library, you need to build a distribution and then publish it to PyPI.

django_components uses the build utility to build a distribution:

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

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

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

Notes on publishing:

  • If you use components where the HTML / CSS / JS files are separate, you may need to define MANIFEST.in to include those files with the distribution (see user guide).
"},{"location":"concepts/advanced/authoring_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_context_data(self, date):\n        return {\n            \"date\": 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# Unregister single component\nregistry.unregister(\"card\")\n\n# Unregister all components\nregistry.clear()\n
"},{"location":"concepts/advanced/component_registry/#registering-components-to-custom-componentregistry","title":"Registering components to custom ComponentRegistry","text":"

If you are writing a component library to be shared with others, you may want to manage your own instance of ComponentRegistry and register components onto a different Library instance than the default one.

The Library instance can be set at instantiation of ComponentRegistry. If omitted, then the default Library instance from django_components is used.

from django.template import Library\nfrom django_components import ComponentRegistry\n\nmy_library = Library(...)\nmy_registry = ComponentRegistry(library=my_library)\n

When you have defined your own ComponentRegistry, you can either register the components with my_registry.register(), or pass the registry to the @component.register() decorator via the registry kwarg:

from path.to.my.registry import my_registry\n\n@register(\"my_component\", registry=my_registry)\nclass MyComponent(Component):\n    ...\n

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

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

When you are creating an instance of ComponentRegistry, you can define the components' behavior within the template.

The registry accepts these settings:

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

These settings are the same as the ones you can set for django_components.

In fact, when you set COMPONENT.tag_formatter or COMPONENT.context_behavior, these are forwarded to the default ComponentRegistry.

This makes it possible to have multiple registries with different settings in one projects, and makes sharing of component libraries possible.

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

New in version 0.96

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

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

Hook that runs just before the component's template is rendered.

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

def on_render_before(self, context, template) -> None:\n    # Insert value into the Context\n    context[\"from_on_before\"] = \":)\"\n\n    # Append text into the Template\n    template.nodelist.append(TextNode(\"FROM_ON_BEFORE\"))\n
  • on_render_after
def on_render_after(\n    self: Component,\n    context: Context,\n    template: Template,\n    content: str\n) -> None | str | SafeString:\n

Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.

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

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

def on_render_after(self, context, template, content):\n    # Prepend text to the rendered content\n    return \"Chocolate cookie recipe: \" + content\n
"},{"location":"concepts/advanced/hooks/#component-hooks-example","title":"Component hooks 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_tragments/","title":"HTML fragments","text":"

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

When you define a component that has extra JS or CSS, and you use django-components to render the fragment, django-components will:

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

Info

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

It is one of the methods for updating the state in the browser UI upon user interaction.

How it works is that:

  1. User makes an action - clicks a button or submits a form
  2. The action causes a request to be made from the client to the server.
  3. Server processes the request (e.g. form submission), and responds with HTML of some part of the UI (e.g. a new entry in a table).
  4. A library like HTMX, AlpineJS, or custom function inserts the new HTML into the correct place.
"},{"location":"concepts/advanced/html_tragments/#document-and-fragment-types","title":"Document and fragment types","text":"

Components support two modes of rendering - As a \"document\" or as a \"fragment\".

What's the difference?

"},{"location":"concepts/advanced/html_tragments/#document-mode","title":"Document mode","text":"

Document mode assumes that the rendered components will be embedded into the HTML of the initial page load. This means that:

  • The JS and CSS is embedded into the HTML as <script> and <style> tags (see JS and CSS output locations)
  • Django-components injects a JS script for managing JS and CSS assets

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

  • It is embedded inside a template as {% component %}
  • It is rendered with Component.render() or Component.render_to_response() with the type kwarg set to \"document\" (default)

Example:

MyTable.render(\n    kwargs={...},\n)\n\n# or\n\nMyTable.render(\n    kwargs={...},\n    type=\"document\",\n)\n
"},{"location":"concepts/advanced/html_tragments/#fragment-mode","title":"Fragment mode","text":"

Fragment mode assumes that the main HTML has already been rendered and loaded on the page. The component renders HTML that will be inserted into the page as a fragment, at a LATER time:

  • JS and CSS is not directly embedded to avoid duplicately executing the same JS scripts. So template tags like {% component_js_dependencies %} inside of fragments are ignored.
  • Instead, django-components appends the fragment's content with a JSON <script> to trigger a call to its asset manager JS script, which will load the JS and CSS smartly.
  • The asset manager JS script is assumed to be already loaded on the page.

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

  • It is rendered with Component.render() or Component.render_to_response() with the type kwarg set to \"fragment\"

Example:

MyTable.render(\n    kwargs={...},\n    type=\"fragment\",\n)\n
"},{"location":"concepts/advanced/html_tragments/#live-examples","title":"Live examples","text":"

For live interactive examples, start our demo project (sampleproject).

Then navigate to these URLs:

  • /fragment/base/alpine
  • /fragment/base/htmx
  • /fragment/base/js
"},{"location":"concepts/advanced/html_tragments/#example-htmx","title":"Example - HTMX","text":""},{"location":"concepts/advanced/html_tragments/#1-define-document-html","title":"1. Define document HTML","text":"[root]/components/demo.py
from django_components import Component, types\n\n# HTML into which a fragment will be loaded using HTMX\nclass MyPage(Component):\n    def get(self, request):\n        return self.render_to_response()\n\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
"},{"location":"concepts/advanced/html_tragments/#2-define-fragment-html","title":"2. Define fragment HTML","text":"[root]/components/demo.py
class Frag(Component):\n    def get(self, request):\n        return self.render_to_response(\n            # IMPORTANT: Don't forget `type=\"fragment\"`\n            type=\"fragment\",\n        )\n\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
"},{"location":"concepts/advanced/html_tragments/#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_tragments/#example-alpinejs","title":"Example - AlpineJS","text":""},{"location":"concepts/advanced/html_tragments/#1-define-document-html_1","title":"1. Define document HTML","text":"[root]/components/demo.py
from django_components import Component, types\n\n# HTML into which a fragment will be loaded using AlpineJS\nclass MyPage(Component):\n    def get(self, request):\n        return self.render_to_response()\n\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
"},{"location":"concepts/advanced/html_tragments/#2-define-fragment-html_1","title":"2. Define fragment HTML","text":"[root]/components/demo.py
class Frag(Component):\n    def get(self, request):\n        # IMPORTANT: Don't forget `type=\"fragment\"`\n        return self.render_to_response(\n            type=\"fragment\",\n        )\n\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
"},{"location":"concepts/advanced/html_tragments/#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_tragments/#example-vanilla-js","title":"Example - Vanilla JS","text":""},{"location":"concepts/advanced/html_tragments/#1-define-document-html_2","title":"1. Define document HTML","text":"[root]/components/demo.py
from django_components import Component, types\n\n# HTML into which a fragment will be loaded using JS\nclass MyPage(Component):\n    def get(self, request):\n        return self.render_to_response()\n\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
"},{"location":"concepts/advanced/html_tragments/#2-define-fragment-html_2","title":"2. Define fragment HTML","text":"[root]/components/demo.py
class Frag(Component):\n    def get(self, request):\n        return self.render_to_response(\n            # IMPORTANT: Don't forget `type=\"fragment\"`\n            type=\"fragment\",\n        )\n\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
"},{"location":"concepts/advanced/html_tragments/#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 or ContextProvider pattern with the combination of:

  1. {% provide %} tag
  2. inject() method of the Component class
"},{"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.

"},{"location":"concepts/advanced/provide_inject/#how-to-use-provide-inject","title":"How to use provide / inject","text":"

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/#using-provide-tag","title":"Using {% provide %} tag","text":"

First we use the {% provide %} tag to define the data we want to \"provide\" (make available).

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

Notice that the provide tag REQUIRES a name as a first argument. This is the key by which we can then access the data passed to this tag.

provide tag name must resolve to a valid identifier (AKA a valid Python variable name).

Once you've set the name, you define the data you want to \"provide\" by passing it as keyword arguments. This is similar to how you pass data to the {% with %} tag.

NOTE: Kwargs passed to {% provide %} are NOT added to the context. In the example below, the {{ key }} won't render anything:

{% provide \"my_data\" key=\"hi\" another=123 %}\n    {{ key }}\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:

{% provide name=name ... %}\n    ...\n{% provide %}\n</table>\n
"},{"location":"concepts/advanced/provide_inject/#using-inject-method","title":"Using inject() method","text":"

To \"inject\" (access) the data defined on the provide tag, you can use the inject() method inside of get_context_data().

For a component to be able to \"inject\" some data, the component ({% component %} tag) must be nested inside the {% provide %} tag.

In the example from previous section, we've defined two kwargs: key=\"hi\" another=123. That means that if we now inject \"my_data\", we get an object with 2 attributes - key and another.

class ChildComponent(Component):\n    def get_context_data(self):\n        my_data = self.inject(\"my_data\")\n        print(my_data.key)     # hi\n        print(my_data.another) # 123\n        return {}\n

First argument to inject is the key (or name) of the provided data. This must match the string that you used in the provide tag. If no provider with given key is found, inject raises a KeyError.

To avoid the error, you can pass a second argument to inject to which will act as a default value, similar to dict.get(key, default):

class ChildComponent(Component):\n    def get_context_data(self):\n        my_data = self.inject(\"invalid_key\", DEFAULT_DATA)\n        assert my_data == DEFAUKT_DATA\n        return {}\n

The instance returned from inject() is a subclass of NamedTuple, so the instance is immutable. This ensures that the data returned from inject will always have all the keys that were passed to the provide tag.

NOTE: inject() works strictly only in get_context_data. If you try to call it from elsewhere, it will raise an error.

"},{"location":"concepts/advanced/provide_inject/#full-example","title":"Full example","text":"
@register(\"child\")\nclass ChildComponent(Component):\n    template = \"\"\"\n        <div> {{ my_data.key }} </div>\n        <div> {{ my_data.another }} </div>\n    \"\"\"\n\n    def get_context_data(self):\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\" key=\"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/#js-and-css-output-locations","title":"JS and CSS output locations","text":"

If:

  1. Your components use JS and CSS via any of:
    • Component.css
    • Component.js
    • Component.Media.css
    • Component.Media.js
  2. And you use the ComponentDependencyMiddleware middleware

Then, by default, the components' JS and CSS will be automatically inserted into the HTML:

  • CSS styles will be inserted at the end of the <head>
  • JS scripts will be inserted at the end of the <body>

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

  • {% component_js_dependencies %} - Set new location(s) for JS scripts
  • {% component_css_dependencies %} - Set new location(s) for CSS styles

So if you have a component with JS and CSS:

from django_components import Component, types\n\nclass MyButton(Component):\n    template: types.django_html = \"\"\"\n        <button class=\"my-button\">\n            Click me!\n        </button>\n    \"\"\"\n    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    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 the JS from MyButton.js and MyButton.Media.js will be rendered at the default place, or in {% component_js_dependencies %}.

And the CSS from MyButton.css and MyButton.Media.css will be rendered at the default place, or in {% component_css_dependencies %}.

And if you don't specify {% component_dependencies %} tags, it is the equivalent of:

<!doctype html>\n<html>\n  <head>\n    <title>MyPage</title>\n    ...\n    {% component_css_dependencies %}\n  </head>\n  <body>\n    <main>\n      ...\n    </main>\n    {% component_js_dependencies %}\n  </body>\n</html>\n
"},{"location":"concepts/advanced/rendering_js_css/#setting-up-the-middleware","title":"Setting up the middleware","text":"

ComponentDependencyMiddleware is a Django middleware designed to manage and inject CSS / JS dependencies of rendered components dynamically. It ensures that only the necessary stylesheets and scripts are loaded in your HTML responses, based on the components used in your Django templates.

To set it up, add the middleware to your MIDDLEWARE in settings.py:

MIDDLEWARE = [\n    # ... other middleware classes ...\n    'django_components.middleware.ComponentDependencyMiddleware'\n    # ... other middleware classes ...\n]\n
"},{"location":"concepts/advanced/rendering_js_css/#render_dependencies-and-rendering-js-css-without-the-middleware","title":"render_dependencies and rendering JS / CSS without the middleware","text":"

For most scenarios, using the ComponentDependencyMiddleware middleware will be just fine.

However, this section is for you if you want to:

  • Render HTML that will NOT be sent as a server response
  • Insert pre-rendered HTML into another component
  • Render HTML fragments (partials)

Every time there is an HTML string that has parts which were rendered using components, and any of those components has JS / CSS, then this HTML string MUST be processed with render_dependencies().

It is actually render_dependencies() that finds all used components in the HTML string, and inserts the component's JS and CSS into {% component_dependencies %} tags, or at the default locations.

"},{"location":"concepts/advanced/rendering_js_css/#render-js-css-without-the-middleware","title":"Render JS / CSS without the middleware","text":"

The truth is that the ComponentDependencyMiddleware middleware just calls render_dependencies(), passing in the HTML content. So if you render a template that contained {% component %} tags, you MUST pass the result through render_dependencies(). And the middleware is just one of the options.

Here is how you can achieve the same, without the middleware, using render_dependencies():

from django.template.base import Template\nfrom django.template.context import Context\nfrom django_component 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())\nrendered = render_dependencies(rendered)\n

Same applies if you render a template using Django's django.shortcuts.render:

from django.shortcuts import render\n\ndef my_view(request):\n    rendered = render(request, \"pages/home.html\")\n    rendered = render_dependencies(rendered)\n    return rendered\n

Alternatively, when you render HTML with Component.render() or Component.render_to_response(), these, by default, call render_dependencies() for you, so you don't have to:

from django_components import Component\n\nclass MyButton(Component):\n    ...\n\n# No need to call `render_dependencies()`\nrendered = MyButton.render()\n
"},{"location":"concepts/advanced/rendering_js_css/#inserting-pre-rendered-html-into-another-component","title":"Inserting pre-rendered HTML into another component","text":"

In previous section we've shown that render_dependencies() does NOT need to be called when you render a component via Component.render().

API of django_components makes it possible to compose components in a \"React-like\" way, where we pre-render a piece of HTML and then insert it into a larger structure.

To do this, you must add render_dependencies=False to the nested components:

card_actions = CardActions.render(\n    kwargs={\"editable\": editable},\n    render_dependencies=False,\n)\n\ncard = Card.render(\n    slots={\"actions\": card_actions},\n    render_dependencies=False,\n)\n\npage = MyPage.render(\n    slots={\"card\": card},\n)\n

Why is render_dependencies=False required?

This is a technical limitation of the current implementation.

As mentioned earlier, each time we call Component.render(), we also call render_dependencies().

However, there is a problem here - When we call render_dependencies() inside CardActions.render(), we extract and REMOVE the info on components' JS and CSS from the HTML. But the template of CardActions contains no {% component_depedencies %} tags, and nor <head> nor <body> HTML tags. So the component's JS and CSS will NOT be inserted, and will be lost.

To work around this, you must set render_dependencies=False when rendering pieces of HTML with Component.render() and inserting them into larger structures.

"},{"location":"concepts/advanced/rendering_js_css/#summary","title":"Summary","text":"
  1. Every time you render HTML that contained components, you have to call render_dependencies() on the rendered output.
  2. There are several ways to call render_dependencies():
    • Using the ComponentDependencyMiddleware middleware
    • Rendering the HTML by calling Component.render() with render_dependencies=True (default)
    • Rendering the HTML by calling Component.render_to_response() (always renders dependencies)
    • Directly passing rendered HTML to render_dependencies()
  3. If you pre-render one component to pass it into another, the pre-rendered component must be rendered with render_dependencies=False.
"},{"location":"concepts/advanced/tag_formatter/","title":"Tag formatters","text":""},{"location":"concepts/advanced/tag_formatter/#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_formatter/#available-tagformatters","title":"Available TagFormatters","text":"

django_components provides following predefined TagFormatters:

  • ComponentFormatter (django_components.component_formatter)

Default

Uses the component and endcomponent tags, and the component name is gives as the first positional argument.

Example as block:

{% component \"button\" href=\"...\" %}\n    {% fill \"content\" %}\n        ...\n    {% endfill %}\n{% endcomponent %}\n

Example as inlined tag:

{% component \"button\" href=\"...\" / %}\n
  • ShorthandComponentFormatter (django_components.component_shorthand_formatter)

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

Example as block:

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

Example as inlined tag:

{% button href=\"...\" / %}\n
"},{"location":"concepts/advanced/tag_formatter/#writing-your-own-tagformatter","title":"Writing your own TagFormatter","text":""},{"location":"concepts/advanced/tag_formatter/#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_formatter/#tagformatter","title":"TagFormatter","text":"

TagFormatter handles following parts of the process above:

  • Generates start/end tags, given a component. This is what you then call from within your template as {% component %}.

  • When you {% component %}, tag formatter pre-processes the tag contents, so it can link back the custom template tag to the right component.

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

  • start_tag
  • end_tag
  • parse

For example, this is the implementation of ShorthandComponentFormatter

class ShorthandComponentFormatter(TagFormatterABC):\n    # Given a component name, generate the start template tag\n    def start_tag(self, name: str) -> str:\n        return name  # e.g. 'button'\n\n    # Given a component name, generate the start template tag\n    def end_tag(self, name: str) -> str:\n        return f\"end{name}\"  # e.g. 'endbutton'\n\n    # Given a tag, e.g.\n    # `{% button href=\"...\" disabled %}`\n    #\n    # The parser receives:\n    # `['button', 'href=\"...\"', 'disabled']`\n    def parse(self, tokens: List[str]) -> TagResult:\n        tokens = [*tokens]\n        name = tokens.pop(0)\n        return TagResult(\n            name,  # e.g. 'button'\n            tokens  # e.g. ['href=\"...\"', 'disabled']\n        )\n

That's it! And once your TagFormatter is ready, don't forget to update the settings!

"},{"location":"concepts/advanced/typing_and_validation/","title":"Typing and validation","text":""},{"location":"concepts/advanced/typing_and_validation/#adding-type-hints-with-generics","title":"Adding type hints with Generics","text":"

New in version 0.92

The Component class optionally accepts type parameters that allow you to specify the types of args, kwargs, slots, and data:

class Button(Component[Args, Kwargs, Slots, Data, JsData, CssData]):\n    ...\n
  • Args - Must be a Tuple or Any
  • Kwargs - Must be a TypedDict or Any
  • Data - Must be a TypedDict or Any
  • Slots - Must be a TypedDict or Any

Here's a full example:

from typing import NotRequired, Tuple, TypedDict, SlotContent, SlotFunc\n\n# Positional inputs\nArgs = Tuple[int, str]\n\n# Kwargs inputs\nclass Kwargs(TypedDict):\n    variable: str\n    another: int\n    maybe_var: NotRequired[int] # May be ommited\n\n# Data returned from `get_context_data`\nclass Data(TypedDict):\n    variable: str\n\n# The data available to the `my_slot` scoped slot\nclass MySlotData(TypedDict):\n    value: int\n\n# Slots\nclass Slots(TypedDict):\n    # Use SlotFunc for slot functions.\n    # The generic specifies the `data` dictionary\n    my_slot: NotRequired[SlotFunc[MySlotData]]\n    # SlotContent == Union[str, SafeString]\n    another_slot: SlotContent\n\nclass Button(Component[Args, Kwargs, Slots, Data, JsData, CssData]):\n    def get_context_data(self, variable, another):\n        return {\n            \"variable\": variable,\n        }\n

When you then call Component.render or Component.render_to_response, you will get type hints:

Button.render(\n    # Error: First arg must be `int`, got `float`\n    args=(1.25, \"abc\"),\n    # Error: Key \"another\" is missing\n    kwargs={\n        \"variable\": \"text\",\n    },\n)\n
"},{"location":"concepts/advanced/typing_and_validation/#usage-for-python-311","title":"Usage for Python <3.11","text":"

On Python 3.8-3.10, use typing_extensions

from typing_extensions import TypedDict, NotRequired\n

Additionally on Python 3.8-3.9, also import annotations:

from __future__ import annotations\n

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

See PEP-655 for more info.

"},{"location":"concepts/advanced/typing_and_validation/#passing-additional-args-or-kwargs","title":"Passing additional args or kwargs","text":"

You may have a function that supports any number of args or kwargs:

def get_context_data(self, *args, **kwargs):\n    ...\n

This is not supported with the typed components.

As a workaround:

  • For *args, set a positional argument that accepts a list of values:
# Tuple of one member of list of strings\nArgs = Tuple[List[str]]\n
  • For *kwargs, set a keyword argument that accepts a dictionary of values:
class Kwargs(TypedDict):\n    variable: str\n    another: int\n    # Pass any extra keys under `extra`\n    extra: Dict[str, any]\n
"},{"location":"concepts/advanced/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, you can use EmptyTuple and EmptyDict types:

from django_components import Component, EmptyDict, EmptyTuple\n\nArgs = EmptyTuple\nKwargs = Data = Slots = EmptyDict\n\nclass Button(Component[Args, Kwargs, Slots, Data, JsData, CssData]):\n    ...\n
"},{"location":"concepts/advanced/typing_and_validation/#runtime-input-validation-with-types","title":"Runtime input validation with types","text":"

New in version 0.96

NOTE: Kwargs, slots, and data validation is supported only for Python >=3.11

In Python 3.11 and later, when you specify the component types, you will get also runtime validation of the inputs you pass to Component.render or Component.render_to_response.

So, using the example from before, if you ignored the type errors and still ran the following code:

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

This would raise a TypeError:

Component 'Button' expected positional argument at index 0 to be <class 'int'>, got 1.25 of type <class 'float'>\n

In case you need to skip these errors, you can either set the faulty member to Any, e.g.:

# Changed `int` to `Any`\nArgs = Tuple[Any, str]\n

Or you can replace Args with Any altogether, to skip the validation of args:

# Replaced `Args` with `Any`\nclass Button(Component[Any, Kwargs, Slots, Data, JsData, CssData]):\n    ...\n

Same applies to kwargs, data, and slots.

"},{"location":"concepts/fundamentals/access_component_input/","title":"Accessing component inputs","text":"

When you call Component.render or Component.render_to_response, the inputs to these methods can be accessed from within the instance under self.input.

This means that you can use self.input inside:

  • get_context_data
  • get_template_name
  • get_template
  • on_render_before
  • on_render_after

self.input is only defined during the execution of Component.render, and raises a RuntimeError when called outside of this context.

self.input has the same fields as the input to Component.render:

class TestComponent(Component):\n    def get_context_data(self, var1, var2, variable, another, **attrs):\n        assert self.input.args == (123, \"str\")\n        assert self.input.kwargs == {\"variable\": \"test\", \"another\": 1}\n        assert self.input.slots == {\"my_slot\": \"MY_SLOT\"}\n        assert isinstance(self.input.context, Context)\n\n        return {\n            \"variable\": variable,\n        }\n\nrendered = TestComponent.render(\n    kwargs={\"variable\": \"test\", \"another\": 1},\n    args=(123, \"str\"),\n    slots={\"my_slot\": \"MY_SLOT\"},\n)\n

NOTE: The slots in self.input.slots are normalized to slot functions.

"},{"location":"concepts/fundamentals/autodiscovery/","title":"Autodiscovery","text":"

Every component that you want to use in the template with the {% component %} tag needs to be registered with the ComponentRegistry. Normally, we use the @register decorator for that:

from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    ...\n

But for the component to be registered, the code needs to be executed - the file needs to be imported as a module.

One way to do that is by importing all your components in apps.py:

from django.apps import AppConfig\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!

By default, the Python files in the COMPONENTS.dirs directories (and app-level [app]/components/) are auto-imported in order to auto-register the components.

Autodiscovery occurs when Django is loaded, during the AppConfig.ready hook of the apps.py file.

If you are using autodiscovery, keep a few points in mind:

  • Avoid defining any logic on the module-level inside the components dir, that you would not want to run anyway.
  • Components inside the auto-imported files still need to be registered with @registerp
  • Auto-imported component files must be valid Python modules, they must use suffix .py, and module name should follow PEP-8.

Autodiscovery can be disabled in the settings.

"},{"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_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_context_data by accessing the property self.outer_context.

"},{"location":"concepts/fundamentals/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_context_data. Here's how you might implement it:

class Calender(Component):\n\n    ...\n\n    def get_context_data(self):\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/fundamentals/component_context_scope/#context-behavior","title":"Context behavior","text":"

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

This has two modes:

  • \"django\"

    The default Django template behavior.

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

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

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

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

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

Warning

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

Consider this example:

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

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

"},{"location":"concepts/fundamentals/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_context_data(self):\n        return { \"my_var\": 123 }\n

Then if get_context_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/fundamentals/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_context_data(self):\n        return { \"my_var\": 123 }\n

Then if get_context_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_context_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/fundamentals/components_as_views/","title":"Components as views","text":"

New in version 0.34

Note: Since 0.92, Component no longer subclasses View. To configure the View class, set the nested Component.View class

Components can now be used as views:

  • Components define the Component.as_view() class method that can be used the same as View.as_view().

  • By default, you can define GET, POST or other HTTP handlers directly on the Component, same as you do with View. For example, you can override get and post to handle GET and POST requests, respectively.

  • In addition, Component now has a render_to_response method that renders the component template based on the provided context and slots' data and returns an HttpResponse object.

"},{"location":"concepts/fundamentals/components_as_views/#component-as-view-example","title":"Component as view example","text":"

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

# In a file called [project root]/components/calendar.py\nfrom django_components import Component, ComponentView, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n\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    # Handle GET requests\n    def get(self, request, *args, **kwargs):\n        context = {\n            \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n        }\n        slots = {\n            \"header\": \"Calendar header\",\n        }\n        # Return HttpResponse with the rendered content\n        return self.render_to_response(\n            context=context,\n            slots=slots,\n        )\n

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

# In a file called [project root]/components/urls.py\nfrom django.urls import path\nfrom components.calendar.calendar import Calendar\n\nurlpatterns = [\n    path(\"calendar/\", Calendar.as_view()),\n]\n

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

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

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

# In a file called [project root]/urls.py\nfrom django.urls import include, path\n\nurlpatterns = [\n    path(\"components/\", include(\"components.urls\")),\n]\n

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

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

"},{"location":"concepts/fundamentals/components_as_views/#modifying-the-view-class","title":"Modifying the View class","text":"

The View class that handles the requests is defined on Component.View.

When you define a GET or POST handlers on the Component class, like so:

class MyComponent(Component):\n    def get(self, request, *args, **kwargs):\n        return self.render_to_response(\n            context={\n                \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n            },\n        )\n\n    def post(self, request, *args, **kwargs) -> HttpResponse:\n        variable = request.POST.get(\"variable\")\n        return self.render_to_response(\n            kwargs={\"variable\": variable}\n        )\n

Then the request is still handled by Component.View.get() or Component.View.post() methods. However, by default, Component.View.get() points to Component.get(), and so on.

class ComponentView(View):\n    component: Component = None\n    ...\n\n    def get(self, request, *args, **kwargs):\n        return self.component.get(request, *args, **kwargs)\n\n    def post(self, request, *args, **kwargs):\n        return self.component.post(request, *args, **kwargs)\n\n    ...\n

If you want to define your own View class, you need to:

  1. Set the class as Component.View
  2. Subclass from ComponentView, so the View instance has access to the component instance.

In the example below, we added extra logic into View.setup().

Note that the POST handler is still defined at the top. This is because View subclasses ComponentView, which defines the post() method that calls Component.post().

If you were to overwrite the View.post() method, then Component.post() would be ignored.

from django_components import Component, ComponentView\n\nclass MyComponent(Component):\n\n    def post(self, request, *args, **kwargs) -> HttpResponse:\n        variable = request.POST.get(\"variable\")\n        return self.component.render_to_response(\n            kwargs={\"variable\": variable}\n        )\n\n    class View(ComponentView):\n        def setup(self, request, *args, **kwargs):\n            super(request, *args, **kwargs)\n\n            do_something_extra(request, *args, **kwargs)\n
"},{"location":"concepts/fundamentals/components_in_python/","title":"Components in Python","text":"

New in version 0.81

Components can be rendered outside of Django templates, calling them as regular functions (\"React-style\").

The component class defines render and render_to_response class methods. These methods accept positional args, kwargs, and slots, offering the same flexibility as the {% component %} tag:

class SimpleComponent(Component):\n    template = \"\"\"\n        {% load component_tags %}\n        hello: {{ hello }}\n        foo: {{ foo }}\n        kwargs: {{ kwargs|safe }}\n        slot_first: {% slot \"first\" required / %}\n    \"\"\"\n\n    def get_context_data(self, arg1, arg2, **kwargs):\n        return {\n            \"hello\": arg1,\n            \"foo\": arg2,\n            \"kwargs\": kwargs,\n        }\n\nrendered = SimpleComponent.render(\n    args=[\"world\", \"bar\"],\n    kwargs={\"kw1\": \"test\", \"kw2\": \"ooo\"},\n    slots={\"first\": \"FIRST_SLOT\"},\n    context={\"from_context\": 98},\n)\n

Renders:

hello: world\nfoo: bar\nkwargs: {'kw1': 'test', 'kw2': 'ooo'}\nslot_first: FIRST_SLOT\n
"},{"location":"concepts/fundamentals/components_in_python/#inputs-of-render-and-render_to_response","title":"Inputs of render and render_to_response","text":"

Both render and render_to_response accept the same input:

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

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

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

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

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

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

  • request - A Django request object. This is used to enable Django template context_processors to run, allowing for template tags like {% csrf_token %} and variables like {{ debug }}.

  • Similar behavior can be achieved with provide / inject.
  • This is used internally to convert context to a RequestContext. It does nothing if context is already a Context instance.
"},{"location":"concepts/fundamentals/components_in_python/#slotfunc","title":"SlotFunc","text":"

When rendering components with slots in render or render_to_response, you can pass either a string or a function.

The function has following signature:

def render_func(\n   context: Context,\n   data: Dict[str, Any],\n   slot_ref: SlotRef,\n) -> str | SafeString:\n    return nodelist.render(ctx)\n
  • context - Django's Context available to the Slot Node.
  • data - Data passed to the {% slot %} tag. See Scoped Slots.
  • slot_ref - The default slot content. See Accessing original content of slots.
  • NOTE: The slot is lazily evaluated. To render the slot, convert it to string with str(slot_ref).

Example:

def footer_slot(ctx, data, slot_ref):\n   return f\"\"\"\n      SLOT_DATA: {data['abc']}\n      ORIGINAL: {slot_ref}\n   \"\"\"\n\nMyComponent.render_to_response(\n    slots={\n        \"footer\": footer_slot,\n   },\n)\n
"},{"location":"concepts/fundamentals/components_in_python/#response-class-of-render_to_response","title":"Response class of render_to_response","text":"

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

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

class MyResponse(HttpResponse):\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 = MyResponse\n   template: types.django_html = \"HELLO\"\n\nresponse = SimpleComponent.render_to_response()\nassert isinstance(response, MyResponse)\n
"},{"location":"concepts/fundamentals/defining_js_css_html_files/","title":"Defining HTML / JS / CSS files","text":"

As you could have seen in the tutorial, there's multiple ways how you can associate HTML / JS / CSS with a component:

  • You can set Component.template, Component.css and Component.js to define the main HTML / CSS / JS for a component as inlined code.
  • You can set Component.template_file, Component.css_file and Component.js_file to define the main HTML / CSS / JS for a component in separate files.
  • You can link additional CSS / JS files using Component.Media.js and Component.Media.css.

Warning

You cannot use both inlined code and separate file for a single language type:

  • You can only either set Component.template or Component.template_file
  • You can only either set Component.css or Component.css_file
  • You can only either set Component.js or Component.js_file

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

Note

django-component's management of files is inspired by Django's Media class.

To be familiar with how Django handles static files, we recommend reading also:

  • How to manage static files (e.g. images, JavaScript, CSS)
"},{"location":"concepts/fundamentals/defining_js_css_html_files/#defining-file-paths-relative-to-component","title":"Defining file paths 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/defining_js_css_html_files/#defining-additional-js-and-css-files","title":"Defining additional JS and CSS files","text":"

Each component can have only a single template, and single main JS and CSS. However, you can define additional JS or CSS using the nested Component.Media class.

This Media class behaves similarly to Django's Media class:

  • Paths are generally handled as static file paths, and resolved URLs are rendered to HTML with media_class.render_js() or media_class.render_css().
  • A path that starts with http, https, or / is considered a URL, skipping the static file resolution. This path is still rendered to HTML with media_class.render_js() or media_class.render_css().
  • A SafeString, or a function (with __html__ method) is considered an already-formatted HTML tag, skipping both static file resolution and rendering with media_class.render_js() or media_class.render_css().

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. Our Media class does NOT support Django's extend keyword
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":"concepts/fundamentals/defining_js_css_html_files/#configuring-css-media-types","title":"Configuring 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

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/defining_js_css_html_files/#supported-types-for-file-paths","title":"Supported types for file paths","text":"

File paths can be any of:

  • str
  • bytes
  • PathLike (__fspath__ method)
  • SafeData (__html__ method)
  • Callable that returns any of the above, evaluated at class creation (__new__)

See 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/defining_js_css_html_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 full <script>/<link> tag.

This is an extension of Django's Paths as objects feature, where \"safe\" strings are taken as is, and accessed only at render time.

Because of that, the paths defined as \"safe\" strings are NEVER resolved, neither relative to component's directory, nor relative to COMPONENTS.dirs.

\"Safe\" strings can be used to lazily resolve a path, or to customize the <script> or <link> tag for individual paths:

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.

class ModuleJsPath:\n    def __init__(self, static_path: str) -> None:\n        self.static_path = static_path\n\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    def get_context_data(self, date):\n        return {\n            \"date\": date,\n        }\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/defining_js_css_html_files/#customize-how-paths-are-rendered-into-html-tags","title":"Customize how paths are rendered into HTML tags","text":"

Sometimes you may need to change how all CSS <link> or JS <script> tags are rendered for a given component. You can achieve this by providing your own subclass of Django's Media class to component's media_class attribute.

Normally, the JS and CSS paths are passed to Media class, which decides how the paths are resolved and how the <link> and <script> tags are constructed.

To change how the tags are constructed, you can override the Media.render_js and Media.render_css methods:

from django.forms.widgets import Media\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/defining_js_css_html_files/#accessing-components-html-js-css","title":"Accessing component's HTML / JS / CSS","text":"

Component's HTML / CSS / JS is resolved and loaded lazily.

This means that, when you specify any of template_file, js_file, css_file, or Media.js/css, these file paths will be resolved only once you either:

  1. Access any of the following attributes on the component:

    • media, template, template_file, js, js_file, css, css_file
  2. Render the component.

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

  • HTML from Component.template_file will be available under Component.template
  • CSS from Component.css_file will be available under Component.css
  • JS from Component.js_file will be available under Component.js

Thus, whether you define HTML via Component.template_file or Component.template, you can always access the HTML content under Component.template. And the same applies for JS and CSS.

Example:

# When we create Calendar component, the files like `calendar/template.html`\n# are not yet loaded!\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar/template.html\"\n    css_file = \"calendar/style.css\"\n    js_file = \"calendar/script.js\"\n\n    class Media:\n        css = \"calendar/style1.css\"\n        js = \"calendar/script2.js\"\n\n# It's only at this moment that django-components reads the files like `calendar/template.html`\nprint(Calendar.css)\n# Output:\n# .calendar {\n#   width: 200px;\n#   background: pink;\n# }\n

Warning

Do NOT modify HTML / CSS / JS after it has been loaded

django-components assumes that the component's media files like js_file or Media.js/css are static.

If you need to dynamically change these media files, consider instead defining multiple Components.

Modifying these files AFTER the component has been loaded at best does nothing. However, this is an untested behavior, which may lead to unexpected errors.

"},{"location":"concepts/fundamentals/defining_js_css_html_files/#accessing-components-media-files","title":"Accessing component's Media files","text":"

To access the files defined under Component.Media, you can access 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

If you want to modify the class that is instantiated for Component.media, you can configure Component.media_class (See example).

"},{"location":"concepts/fundamentals/html_attributes/","title":"HTML attributes","text":"

New in version 0.74:

You can use the html_attrs tag to render HTML attributes, given a dictionary of values.

So if you have a template:

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

You can simplify it with html_attrs tag:

<div {% html_attrs attrs %}>\n</div>\n

where attrs is:

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

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

"},{"location":"concepts/fundamentals/html_attributes/#removing-atttributes","title":"Removing atttributes","text":"

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

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/#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> <button>Click me!</button>\n

HTML rendering with html_attrs tag or attributes_to_string works the same way, where key=True is rendered simply as key, and key=False is not render at all.

So given this input:

attrs = {\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/#default-attributes","title":"Default attributes","text":"

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

<div {% html_attrs attrs defaults %}>\n    ...\n</div>\n

In the example above, if attrs contains e.g. the class key, html_attrs will render:

class=\"{{ attrs.class }}\"

Otherwise, html_attrs will render:

class=\"{{ defaults.class }}\"

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

We can achieve this by adding extra kwargs. These values will be appended, instead of overwriting the previous value.

So if we have a variable attrs:

attrs = {\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/#rules-for-html_attrs","title":"Rules for html_attrs","text":"
  1. Both attrs and defaults can be passed as positional args

{% html_attrs attrs defaults key=val %}

or as kwargs

{% html_attrs key=val defaults=defaults attrs=attrs %}

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

  2. Both attrs and defaults are dictionaries, and we can define them the same way we define dictionaries for the component tag. So either as attrs=attrs or attrs:key=value.

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

"},{"location":"concepts/fundamentals/html_attributes/#examples-for-html_attrs","title":"Examples for html_attrs","text":"

Assuming that:

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

Then:

  • Empty tag {% html_attr %}

renders (empty string):

  • Only kwargs {% html_attr class=\"some-class\" class=class_from_var data-id=\"123\" %}

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

  • Only attrs {% html_attr attrs %}

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

  • Attrs as kwarg {% html_attr attrs=attrs %}

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

  • Only defaults (as kwarg) {% html_attr defaults=defaults %}

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

  • Attrs using the prefix:key=value construct {% html_attr attrs:class=\"from-attrs\" attrs:type=\"submit\" %}

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

  • Defaults using the prefix:key=value construct {% html_attr defaults:class=\"from-defaults\" %}

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

  • All together (1) - attrs and defaults as positional args: {% html_attrs attrs defaults class=\"added_class\" class=class_from_var data-id=123 %}

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

  • All together (2) - attrs and defaults as kwargs args: {% html_attrs class=\"added_class\" class=class_from_var data-id=123 attrs=attrs defaults=defaults %}

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

  • All together (3) - mixed: {% html_attrs attrs defaults:class=\"default-class\" class=\"added_class\" class=class_from_var data-id=123 %}

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

"},{"location":"concepts/fundamentals/html_attributes/#full-example-for-html_attrs","title":"Full example for html_attrs","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_context_data(self, date: Date, attrs: dict):\n        return {\n            \"date\": date,\n            \"attrs\": attrs,\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_context_data(self, date: Date):\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\"

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_context_data of MyComp will receive attrs input 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_attributes/#rendering-html-attributes-outside-of-templates","title":"Rendering HTML attributes outside of templates","text":"

If you need to use serialize HTML attributes outside of Django template and the html_attrs tag, you can use attributes_to_string:

from django_components.attributes import attributes_to_string\n\nattrs = {\n    \"class\": \"my-class text-red pa-4\",\n    \"data-id\": 123,\n    \"required\": True,\n    \"disabled\": False,\n    \"ignored-attr\": None,\n}\n\nattributes_to_string(attrs)\n# 'class=\"my-class text-red pa-4\" data-id=\"123\" required'\n
"},{"location":"concepts/fundamentals/single_file_components/","title":"Single-file components","text":"

Components can be defined in a single file, which is useful for small components. To do this, you can use the template, js, and css class attributes instead of the template_file, js_file, and css_file.

For example, here's the calendar component from the Getting started tutorial, defined 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_context_data(self, date):\n        return {\n            \"date\": 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

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

To add syntax highlighting to these snippets, head over to Syntax highlighting.

"},{"location":"concepts/fundamentals/slots/","title":"Slots","text":"

New in version 0.26:

  • The slot tag now serves only to declare new slots inside the component template.
  • To override the content of a declared slot, use the newly introduced fill tag instead.
  • Whereas unfilled slots used to raise a warning, filling a slot is now optional by default.
  • To indicate that a slot must be filled, the new required option should be added at the end of the slot tag.

Components support something called 'slots'. When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content. This mechanism makes components more reusable and composable. This behavior is similar to slots in Vue.

In the example below we introduce two block tags that work hand in hand to make this work. These are...

  • {% slot <name> %}/{% endslot %}: Declares a new slot in the component template.
  • {% fill <name> %}/{% endfill %}: (Used inside a {% component %} tag pair.) Fills a declared slot with the specified content.

Let's update our calendar component to support more customization. We'll add slot tag pairs to its template, template.html.

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

When using the component, you specify which slots you want to fill and where you want to use the defaults from the template. It looks like this:

{% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"body\" %}\n        Can you believe it's already <span>{{ date }}</span>??\n    {% endfill %}\n{% endcomponent %}\n

Since the 'header' fill is unspecified, it's taken from the base template. If you put this in a template, and pass in date=2020-06-06, this is what gets rendered:

<div class=\"calendar-component\">\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/#named-slots","title":"Named slots","text":"

As seen in the previouse section, you can use {% fill slot_name %} to insert content into a specific slot.

You can define fills for multiple slot simply by defining them all within the {% component %} {% endcomponent %} tags:

{% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"header\" %}\n        Hi this is header!\n    {% endfill %}\n    {% fill \"body\" %}\n        Can you believe it's already <span>{{ date }}</span>??\n    {% endfill %}\n{% endcomponent %}\n

You can also use {% for %}, {% with %}, or other non-component tags (even {% include %}) to construct the {% fill %} tags, as long as these other tags do not leave any text behind!

{% component \"table\" %}\n  {% for slot_name in slots %}\n    {% fill name=slot_name %}\n      {{ slot_name }}\n    {% endfill %}\n  {% endfor %}\n\n  {% with slot_name=\"abc\" %}\n    {% fill name=slot_name %}\n      {{ slot_name }}\n    {% endfill %}\n  {% endwith %}\n{% endcomponent %}\n
"},{"location":"concepts/fundamentals/slots/#default-slot","title":"Default slot","text":"

Added in version 0.28

As you can see, component slots lets you write reusable containers that you fill in when you use a component. This makes for highly reusable components that can be used in different circumstances.

It can become tedious to use fill tags everywhere, especially when you're using a component that declares only one slot. To make things easier, slot tags can be marked with an optional keyword: default.

When added to the tag (as shown below), this option lets you pass filling content directly in the body of a component tag pair \u2013 without using a fill tag. Choose carefully, though: a component template may contain at most one slot that is marked as default. The default option can be combined with other slot options, e.g. required.

Here's the same example as before, except with default slots and implicit filling.

The template:

<div class=\"calendar-component\">\n    <div class=\"header\">\n        {% slot \"header\" %}Calendar header{% endslot %}\n    </div>\n    <div class=\"body\">\n        {% slot \"body\" default %}Today's date is <span>{{ date }}</span>{% endslot %}\n    </div>\n</div>\n

Including the component (notice how the fill tag is omitted):

{% component \"calendar\" date=\"2020-06-06\" %}\n    Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n

The rendered result (exactly the same as before):

<div class=\"calendar-component\">\n  <div class=\"header\">Calendar header</div>\n  <div class=\"body\">Can you believe it's already <span>2020-06-06</span>??</div>\n</div>\n

You may be tempted to combine implicit fills with explicit fill tags. This will not work. The following component template will raise an error when rendered.

{# DON'T DO THIS #}\n{% 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

Instead, you can use a named fill with name default to target the default fill:

{# THIS WORKS #}\n{% 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

NOTE: If you doubly-fill a slot, that is, that both {% fill \"default\" %} and {% fill \"header\" %} would point to the same slot, this will raise an error when rendered.

"},{"location":"concepts/fundamentals/slots/#accessing-default-slot-in-python","title":"Accessing default slot in Python","text":"

Since the default slot is stored under the slot name default, you can access the default slot like so:

class MyTable(Component):\n    def get_context_data(self, *args, **kwargs):\n        default_slot = self.input.slots[\"default\"]\n        return {\n            \"default_slot\": default_slot,\n        }\n
"},{"location":"concepts/fundamentals/slots/#render-fill-in-multiple-places","title":"Render fill in multiple places","text":"

Added in version 0.70

You can render the same content in multiple places by defining multiple slots with identical names:

<div class=\"calendar-component\">\n    <div class=\"header\">\n        {% slot \"image\" %}Image here{% endslot %}\n    </div>\n    <div class=\"body\">\n        {% slot \"image\" %}Image here{% endslot %}\n    </div>\n</div>\n

So if used like:

{% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"image\" %}\n        <img src=\"...\" />\n    {% endfill %}\n{% endcomponent %}\n

This renders:

<div class=\"calendar-component\">\n    <div class=\"header\">\n        <img src=\"...\" />\n    </div>\n    <div class=\"body\">\n        <img src=\"...\" />\n    </div>\n</div>\n
"},{"location":"concepts/fundamentals/slots/#default-and-required-slots","title":"Default and required slots","text":"

If you use a slot multiple times, you can still mark the slot as default or required. For that, you must mark each slot individually, 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

Which you can then use as regular default slot:

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

Since each slot is tagged individually, you can 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 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    {% if image_src %}\n        {% slot \"image\" default %}\n            <img src=\"{{ image_src }}\" />\n        {% endslot %}\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    {% else %}\n        {% slot \"image\" default required / %}\n    {% endif %}\n</div>\n
"},{"location":"concepts/fundamentals/slots/#accessing-original-content-of-slots","title":"Accessing original content of slots","text":"

Added in version 0.26

NOTE: In version 0.77, the syntax was changed from

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

to

{% fill \"my_slot\" default=\"slot_default\" %} {{ slot_default }}\n

Sometimes you may want to keep the original slot, but only wrap or prepend/append content to it. To do so, you can access the default slot via the default kwarg.

Similarly to the data attribute, you specify the variable name through which the default slot will be made available.

For instance, let's say you're filling a slot called 'body'. To render the original slot, assign it to a variable using the 'default' keyword. You then render this variable to insert the default content:

{% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"body\" default=\"body_default\" %}\n        {{ body_default }}. Have a great day!\n    {% endfill %}\n{% endcomponent %}\n

This produces:

<div class=\"calendar-component\">\n    <div class=\"header\">\n        Calendar header\n    </div>\n    <div class=\"body\">\n        Today's date is <span>2020-06-06</span>. Have a great day!\n    </div>\n</div>\n

To access the original content of a default slot, set the name to default:

{% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"default\" default=\"slot_default\" %}\n        {{ slot_default }}. Have a great day!\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"concepts/fundamentals/slots/#conditional-slots","title":"Conditional slots","text":"

Added in version 0.26.

NOTE: In version 0.70, {% if_filled %} tags were replaced with {{ component_vars.is_filled }} variables. If your slot name contained special characters, see the section Accessing is_filled of slot names with special characters.

In certain circumstances, you may want the behavior of slot filling to depend on whether or not a particular slot is filled.

For example, suppose we have the following component template:

<div class=\"frontmatter-component\">\n    <div class=\"title\">\n        {% slot \"title\" %}Title{% endslot %}\n    </div>\n    <div class=\"subtitle\">\n        {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n    </div>\n</div>\n

By default the slot named 'subtitle' is empty. Yet when the component is used without explicit fills, the div containing the slot is still rendered, as shown below:

<div class=\"frontmatter-component\">\n  <div class=\"title\">Title</div>\n  <div class=\"subtitle\"></div>\n</div>\n

This may not be what you want. What if instead the outer 'subtitle' div should only be included when the inner slot is in fact filled?

The answer is to use the {{ component_vars.is_filled.<name> }} variable. You can use this together with Django's {% if/elif/else/endif %} tags to define a block whose contents will be rendered only if the component slot with the corresponding 'name' is filled.

This is what our example looks like with component_vars.is_filled.

<div class=\"frontmatter-component\">\n    <div class=\"title\">\n        {% slot \"title\" %}Title{% endslot %}\n    </div>\n    {% if component_vars.is_filled.subtitle %}\n    <div class=\"subtitle\">\n        {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n    </div>\n    {% endif %}\n</div>\n

Here's our example with more complex branching.

<div class=\"frontmatter-component\">\n    <div class=\"title\">\n        {% slot \"title\" %}Title{% endslot %}\n    </div>\n    {% if component_vars.is_filled.subtitle %}\n    <div class=\"subtitle\">\n        {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n    </div>\n    {% elif component_vars.is_filled.title %}\n        ...\n    {% elif component_vars.is_filled.<name> %}\n        ...\n    {% endif %}\n</div>\n

Sometimes you're not interested in whether a slot is filled, but rather that it isn't. To negate the meaning of component_vars.is_filled, simply treat it as boolean and negate it with not:

{% if not component_vars.is_filled.subtitle %}\n<div class=\"subtitle\">\n    {% slot \"subtitle\" / %}\n</div>\n{% endif %}\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/slots/#conditional-fills","title":"Conditional fills","text":"

Similarly, you can use {% if %} and {% for %} when defining the {% fill %} tags, to conditionally fill the slots when using the componnet:

In the example below, the {% fill \"footer\" %} fill is used only if the condition is true. If falsy, the fill is ignored, and so the my_table component will use its default content for the footer slot.

{% component \"my_table\" %}\n    {% if editable %}\n        {% fill \"footer\" %}\n            <input name=\"name\" />\n        {% endfill %}\n    {% endif %}\n{% endcomponent %}\n

You can even combine {% if %} and {% for %}:

{% component \"my_table\" %}\n    {% for header in headers %}\n        {% if header != \"hyperlink\" %}\n            {# Generate fill name like `header.my_column` #}\n            {% fill name=\"header.\"|add:header\" %}\n                <b>{{ header }}</b>\n            {% endfill %}\n        {% endif %}\n    {% endfor %}\n{% endcomponent %}\n
"},{"location":"concepts/fundamentals/slots/#scoped-slots","title":"Scoped slots","text":"

Added in version 0.76:

Consider a component with slot(s). This component may do some processing on the inputs, and then use the processed variable in the slot's default template:

@register(\"my_comp\")\nclass MyComp(Component):\n    template = \"\"\"\n        <div>\n            {% slot \"content\" default %}\n                input: {{ input }}\n            {% endslot %}\n        </div>\n    \"\"\"\n\n    def get_context_data(self, input):\n        processed_input = do_something(input)\n        return {\"input\": processed_input}\n

You may want to design a component so that users of your component can still access the input variable, so they don't have to recompute it.

This behavior is called \"scoped slots\". This is inspired by Vue scoped slots and scoped slots of django-web-components.

Using scoped slots consists of two steps:

  1. Passing data to slot tag
  2. Accessing data in fill tag
"},{"location":"concepts/fundamentals/slots/#passing-data-to-slots","title":"Passing data to slots","text":"

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

@register(\"my_comp\")\nclass MyComp(Component):\n    template = \"\"\"\n        <div>\n            {% slot \"content\" default input=input %}\n                input: {{ input }}\n            {% endslot %}\n        </div>\n    \"\"\"\n\n    def get_context_data(self, input):\n        processed_input = do_something(input)\n        return {\n            \"input\": processed_input,\n        }\n
"},{"location":"concepts/fundamentals/slots/#accessing-slot-data-in-fill","title":"Accessing slot data in fill","text":"

Next, we head over to where we define a fill for this slot. Here, to access the slot data we set the data attribute to the name of the variable through which we want to access the slot data. In the example below, we set it to data:

{% component \"my_comp\" %}\n    {% fill \"content\" data=\"slot_data\" %}\n        {{ slot_data.input }}\n    {% endfill %}\n{% endcomponent %}\n

To access slot data on a default slot, you have to explictly define the {% fill %} tags.

So this works:

{% component \"my_comp\" %}\n    {% fill \"content\" data=\"slot_data\" %}\n        {{ slot_data.input }}\n    {% endfill %}\n{% endcomponent %}\n

While this does not:

{% component \"my_comp\" data=\"data\" %}\n    {{ data.input }}\n{% endcomponent %}\n

Note: You cannot set the data attribute and default attribute) to the same name. This raises an error:

{% component \"my_comp\" %}\n    {% fill \"content\" data=\"slot_var\" default=\"slot_var\" %}\n        {{ slot_var.input }}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"concepts/fundamentals/slots/#slot-data-of-default-slots","title":"Slot data of default slots","text":"

To access data of a default slot, you can specify {% fill name=\"default\" %}:

{% component \"my_comp\" %}\n    {% fill \"default\" data=\"slot_data\" %}\n        {{ slot_data.input }}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"concepts/fundamentals/slots/#dynamic-slots-and-fills","title":"Dynamic slots and fills","text":"

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

{% slot \"content\" / %}\n

However, sometimes you may want to generate slots based on the given input. One example of this is a table component like that of Vuetify, which creates a header and an item slots for each user-defined column.

In django_components you can achieve the same, simply by using a variable (or a template expression) instead of a string literal:

<table>\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  {# Make only the active column bold #}\n  {% fill \"header-{{ active_header_name }}\" data=\"data\" %}\n    <b>{{ data.value }}</b>\n  {% endfill %}\n{% endcomponent %}\n

NOTE: It's better to use static slot names whenever possible for clarity. The dynamic slot names should be reserved for advanced use only.

Lastly, in rare cases, you can also pass the slot name via the spread operator. This is possible, because the slot name argument is actually a shortcut for a name keyword argument.

So this:

{% slot \"content\" / %}\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
"},{"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    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":"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_context_data so:

@register(\"calendar\")\nclass Calendar(Component):\n    # Since # . @ - are not valid identifiers, we have to\n    # use `**kwargs` so the method can accept these args.\n    def get_context_data(self, **kwargs):\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/#use-template-tags-inside-component-inputs","title":"Use template tags inside component inputs","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_context_data(). But this can get messy if your components contain a lot of logic.

@register(\"calendar\")\nclass Calendar(Component):\n    def get_context_data(self, id: str, editable: bool):\n        return {\n            \"editable\": editable,\n            \"readonly\": not editable,\n            \"input_id\": f\"input-{id}\",\n            \"icon_id\": f\"icon-{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:

  • Component test receives a positional argument with value \"As positional arg \". The comment is omitted.
  • Kwarg title is passed as a string, e.g. John Doe
  • Kwarg id is passed as int, e.g. 15
  • Kwarg readonly is passed as bool, e.g. False
  • Kwarg author is passed as a string, e.g. John Wick (Comment omitted)

This is inspired by django-cotton.

"},{"location":"concepts/fundamentals/template_tag_syntax/#passing-data-as-string-vs-original-values","title":"Passing data as string vs original values","text":"

Sometimes you may want to use the template tags to transform or generate the data that is then passed to the component.

The data doesn't necessarily have to be strings. In the example above, the kwarg id was passed as an integer, NOT a string.

Although the string literals for components inputs are treated as regular Django templates, there is one special case:

When the string literal contains only a single template tag, with no extra text, then the value is passed as the original type instead of a string.

Here, page is an integer:

{% component 'blog_post' page=\"{% random_int 10 20 %}\" / %}\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_context_data(self, some_id: str):\n        attrs = {\n            \"class\": \"pa-4 flex\",\n            \"data-some-id\": 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_context_data(self, some_id: str):\n        return {\"some_id\": 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/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":"concepts/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":"concepts/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 JS and CSS output 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":"concepts/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 JS and CSS output 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":"concepts/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":"concepts/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_context_data(self):\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":"concepts/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. Our Media class does NOT support Django's extend keyword.

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            \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\",  # AlpineJS\n        ]\n        css = [\n            \"path/to/shared.css\",\n            \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\",  # Tailwind\n        ]\n\n    def get_context_data(self):\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":"concepts/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":"concepts/getting_started/adding_slots/","title":"Adding slots","text":"

Our calendar component's looking great! But we just got a new assignment from our colleague - The calendar date needs to be shown on 3 different pages:

  1. On one page, it needs to be shown as is
  2. On the second, the date needs to be bold
  3. On the third, the date needs to be in italics

As a reminder, this is what the component's template looks like:

<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n

There's many ways we could approach this:

  • Expose the date in a slot
  • Style .calendar > span differently on different pages
  • Pass a variable to the component that decides how the date is rendered
  • Create a new component

First two options are more flexible, because the custom styling is not baked into a component's implementation. And for the sake of demonstration, we'll solve this challenge with slots.

"},{"location":"concepts/getting_started/adding_slots/#1-what-are-slots","title":"1. What are slots","text":"

Components support something called Slots.

When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content.

This mechanism makes components more reusable and composable.

This behavior is similar to slots in Vue.

In the example below we introduce two tags that work hand in hand to make this work. These are...

  • {% slot <name> %}/{% endslot %}: Declares a new slot in the component template.
  • {% fill <name> %}/{% endfill %}: (Used inside a {% component %} tag pair.) Fills a declared slot with the specified content.
"},{"location":"concepts/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":"concepts/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":"concepts/getting_started/adding_slots/#5-wait-theres-a-bug","title":"5. 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_context_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_context_data(self, date: date, extra_class: str | None = None):\n        workweek_date = to_workweek_date(date)\n        return {\n            \"date\": workweek_date,\n            \"extra_class\": extra_class,\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":"concepts/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 the slot, 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":"concepts/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 static - 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":"concepts/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":"concepts/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_context_data(self):\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":"concepts/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 JS and CSS output 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":"concepts/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":"concepts/getting_started/parametrising_components/#1-understading-component-inputs","title":"1. Understading component inputs","text":"

In section Create your first component, we defined the get_context_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_context_data(self):\n        return {\n            \"date\": \"1970-01-01\",\n        }\n

What we didn't say is that get_context_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_context_data(date=\"2024-12-13\", extra_class=\"text-red\")\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_context_data(\"2024-12-13\", extra_class=\"text-red\")\n
"},{"location":"concepts/getting_started/parametrising_components/#2-define-inputs-for-get_context_data","title":"2. Define inputs for get_context_data","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_context_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_context_data(self, date: date, extra_class: str | None = None):\n        return {\n            \"date\": date,\n            \"extra_class\": extra_class,\n        }\n

Info

Since get_context_data() is just a regular Python function, type hints annotations work the same way as anywhere else.

Warning

Since get_context_data() is just a regular Python function, it will raise TypeError if it receives incorrect parameters.

Since extra_class is optional in the function signature, it's optional also in the template. So both following calls are valid:

{% component \"calendar\" \"2024-12-13\" / %}\n{% component \"calendar\" \"2024-12-13\" extra_class=\"text-red\" / %}\n

However, date is required. Thus we MUST provide it. Same with regular Python functions, date can be set either as positional or keyword argument. But either way it MUST be set:

\u2705\n{% component \"calendar\" \"2024-12-13\" / %}\n{% component \"calendar\" extra_class=\"text-red\" date=\"2024-12-13\" / %}\n\n\u274c\n{% component \"calendar\" extra_class=\"text-red\" / %}\n
"},{"location":"concepts/getting_started/parametrising_components/#3-process-inputs-in-get_context_data","title":"3. Process inputs in get_context_data","text":"

The get_context_data() method is powerful, because it allows us to decouple component inputs from the template variables. In other words, we can pre-process the component inputs, and massage them into a shape that's most appropriate for what the template needs. And it also allows us to pass in static data into the template.

Imagine our component receives data from the database that looks like below (taken from Django).

cities = [\n    {\"name\": \"Mumbai\", \"population\": \"19,000,000\", \"country\": \"India\"},\n    {\"name\": \"Calcutta\", \"population\": \"15,000,000\", \"country\": \"India\"},\n    {\"name\": \"New York\", \"population\": \"20,000,000\", \"country\": \"USA\"},\n    {\"name\": \"Chicago\", \"population\": \"7,000,000\", \"country\": \"USA\"},\n    {\"name\": \"Tokyo\", \"population\": \"33,000,000\", \"country\": \"Japan\"},\n]\n

We need to group the list items by size into following buckets by population:

  • 0-10,000,000
  • 10,000,001-20,000,000
  • 20,000,001-30,000,000
  • +30,000,001

So we want to end up with following data:

cities_by_pop = [\n    {\n      \"name\": \"0-10,000,000\",\n      \"items\": [\n          {\"name\": \"Chicago\", \"population\": \"7,000,000\", \"country\": \"USA\"},\n      ]\n    },\n    {\n      \"name\": \"10,000,001-20,000,000\",\n      \"items\": [\n          {\"name\": \"Calcutta\", \"population\": \"15,000,000\", \"country\": \"India\"},\n          {\"name\": \"Mumbai\", \"population\": \"19,000,000\", \"country\": \"India\"},\n          {\"name\": \"New York\", \"population\": \"20,000,000\", \"country\": \"USA\"},\n      ]\n    },\n    {\n      \"name\": \"30,000,001-40,000,000\",\n      \"items\": [\n          {\"name\": \"Tokyo\", \"population\": \"33,000,000\", \"country\": \"Japan\"},\n      ]\n    },\n]\n

Without the get_context_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_context_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_context_data(self, data):\n        return {\n            \"data\": group_by_pop(data),\n        }\n

Similarly we can make use of get_context_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_context_data(self, date: date, extra_class: str | None = None):\n        workweek_date = to_workweek_date(date)  # <--- new\n        return {\n            \"date\": workweek_date,  # <--- changed\n            \"extra_class\": extra_class,\n        }\n
"},{"location":"concepts/getting_started/parametrising_components/#4-pass-inputs-to-components","title":"4. Pass inputs to components","text":"

Once we're happy with Calendar.get_contex_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

Next, you will learn how to use slots give your components even more flexibility \u27a1\ufe0f

"},{"location":"concepts/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\n\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":"concepts/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":"concepts/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_context_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":"concepts/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":"concepts/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_context_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_context_data(self):\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
  1. 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.

  1. 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 extremely wasteful to copy-paste the JS / CSS 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.

  1. Last important thing is that we want the JS / CSS dependencies to work also with HTML fragments.

So normally, e.g. when a user hits URL of a web page, the server renders full HTML document, with <!doctype>, <html>, <head>, and <body>. In such case, we know about ALL JS and CSS dependencies at render time, so we can e.g. insert them into <head> and <body> ourselves.

However this renders only the initial state. HTML fragments is a common pattern where interactivity is added to the web page by fetching and replacing bits of HTML on the main HTML document after some user action.

In the case of HTML fragments, the HTML is NOT a proper document, but only the HTML that will be inserted somewhere into the DOM.

The challenge here is that Django template for the HTML fragment MAY contain components, and these components MAY have inlined or linked JS and CSS.

def fragment_view(request):\n    template = Template(\"\"\"\n      {% load component_tags %}\n      <div>\n        {% component \"my_table\" / %}\n      </div>\n    \"\"\")\n\n    fragment_str = template.render(Context({}))\n    return HttpResponse(fragment_str, status=200)\n

User may use different libraries to fetch and insert the HTML fragments (e.g. HTMX, AlpineJS, ...). From our perspective, the only thing that we can reliably say is that we expect that the HTML fragment WILL be eventually inserted into the DOM.

So to include the corresponding JS and CSS, a simple approach could be to append them to the HTML as <style> and <script>, e.g.:

<!-- Original content -->\n<div>...</div>\n<!-- Associated CSS files -->\n<link href=\"http://...\" />\n<style>\n  .my-class {\n    color: red;\n  }\n</style>\n<!-- Associated JS files -->\n<script src=\"http://...\"></script>\n<script>\n  console.log(123);\n</script>\n

But this has a number of issues:

  • The JS scripts would run for each instance of the component.
  • Bloating of the HTML file, as each inlined JS or CSS would be included fully for each component.
    • While this sound OK, this could really bloat the HTML files if we used a UI component library for the basic building blocks like buttons, lists, cards, etc.
"},{"location":"guides/devguides/dependency_mgmt/#flow","title":"Flow","text":"

So the solution should address all the points above. To achieve that, we manage the JS / CSS dependencies ourselves in the browser. So when a full HTML document is loaded, we keep track of which JS and CSS have been loaded. And when an HTML fragment is inserted, we check which JS / CSS dependencies it has, and load only those that have NOT been loaded yet.

This is how we achieve that:

  1. When a component is rendered, it inserts an HTML comment containing metadata about the rendered component.

So a template like this

{% load component_tags %}\n<div>\n  {% component \"my_table\" / %}\n</div>\n{% component \"button\" %}\n  Click me!\n{% endcomponent %}\n

May actually render:

<div>\n  <!-- _RENDERED \"my_table_10bc2c,c020ad\" -->\n  <table>\n    ...\n  </table>\n</div>\n<!-- _RENDERED \"button_309dcf,31c0da\" -->\n<button>Click me!</button>\n

Each <!-- _RENDERED --> comment includes comma-separated data - a unique hash for the component class, e.g. my_table_10bc2c, and the component ID, e.g. c020ad.

This way, we or the user can freely pass the rendered around or transform it, treating it as a string to add / remove / replace bits. As long as the <!-- _RENDERED --> comments remain in the rendered string, we will be able to deduce which JS and CSS dependencies the component needs.

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

  • The approach recommended to the users is to use the ComponentDependencyMiddleware middleware, which scans all outgoing HTML, and post-processes the <!-- _RENDERED --> comments.

  • If users are using Component.render() or Component.render_to_response(), these post-process the <!-- _RENDERED --> comments by default.

    • NOTE: Users are able to opt out of the post-processing by setting render_dependencies=False.
  • For advanced use cases, users may use render_dependencies() directly. This is the function that both ComponentDependencyMiddleware and Component.render() call internally.

render_dependencies(), whether called directly, via middleware 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.
  8. Server returns the post-processed HTML.

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

  1. To be able to fetch component's inlined JS and CSS, django-components adds a URL path under:

/components/cache/<str:comp_cls_hash>.<str:script_type>/

E.g. /components/cache/my_table_10bc2c.js/

This endpoint takes the component's unique hash, e.g. my_table_10bc2c, and looks up the component's inlined JS or CSS.

Thus, with this approach, we ensure that:

  1. All JS / CSS dependencies are loaded / executed only once.
  2. The approach is compatible with HTML fragments
  3. The approach is compatible with JS / CSS variables.
  4. Inlined JS / CSS may be post-processed by plugins
"},{"location":"guides/devguides/slot_rendering/","title":"Slot rendering","text":"

This doc serves as a primer on how component slots and fills are resolved.

"},{"location":"guides/devguides/slot_rendering/#flow","title":"Flow","text":"
  1. Imagine you have a template. Some kind of text, maybe HTML:

    | ------\n| ---------\n| ----\n| -------\n

  2. The template may contain some vars, tags, etc

    | -- {{ my_var }} --\n| ---------\n| ----\n| -------\n

  3. The template also contains some slots, etc

    | -- {{ my_var }} --\n| ---------\n| -- {% slot \"myslot\" %} ---\n| -- {% endslot %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| -- {% endslot %} ---\n| -------\n

  4. Slots may be nested

    | -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %} ---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- JKL {{ my_var }}\n| -- {% endslot %} ---\n| -------\n

  5. Some slots may be inside fills for other components

    | -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %}---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ------\n| -- {% component \"mycomp\" %} ---\n| ---- {% slot \"myslot\" %} ---\n| ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n| ---- {% endslot %} ---\n| -- {% endcomponent %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- PQR {{ my_var }}\n| -- {% endslot %} ---\n| -------\n

  6. The names of the slots and fills may be defined using variables

    | -- {% slot slot_name %} ---\n| ---- STU {{ my_var }}\n| -- {% endslot %} ---\n| -------\n

  7. The slot and fill names may be defined using for loops or other variables defined within the template (e.g. {% with %} tag or {% ... as var %} syntax)

    | -- {% for slot_name in slots %} ---\n| ---- {% slot slot_name %} ---\n| ------ STU {{ slot_name }}\n| ---- {% endslot %} ---\n| -- {% endfor %} ---\n| -------\n

  8. Variables for names and for loops allow us implement \"passthrough slots\" - that is, taking all slots that our component received, and passing them to a child component, dynamically.

    | -- {% component \"mycomp\" %} ---\n| ---- {% for slot_name in slots %} ---\n| ------ {% fill slot_name %} ---\n| -------- {% slot slot_name %} ---\n| ---------- XYZ {{ slot_name }}\n| --------- {% endslot %}\n| ------- {% endfill %}\n| ---- {% endfor %} ---\n| -- {% endcomponent %} ---\n| ----\n

  9. Putting that all together, a document may look like this:

    | -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %}---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ------\n| -- {% component \"mycomp\" %} ---\n| ---- {% slot \"myslot\" %} ---\n| ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n| ---- {% endslot %} ---\n| -- {% endcomponent %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- PQR {{ my_var }}\n| -- {% endslot %} ---\n| -------\n| -- {% for slot_name in slots %} ---\n| ---- {% component \"mycomp\" %} ---\n| ------- {% slot slot_name %}\n| ---------- STU {{ slot_name }}\n| ------- {% endslot %}\n| ---- {% endcomponent %} ---\n| -- {% endfor %} ---\n| ----\n| -- {% component \"mycomp\" %} ---\n| ---- {% for slot_name in slots %} ---\n| ------ {% fill slot_name %} ---\n| -------- {% slot slot_name %} ---\n| ---------- XYZ {{ slot_name }}\n| --------- {% endslot %}\n| ------- {% endfill %}\n| ---- {% endfor %} ---\n| -- {% endcomponent %} ---\n| -------\n

  10. Given the above, we want to render the slots with {% fill %} tag that were defined OUTSIDE of this template. How do I do that?

    NOTE: Before v0.110, slots were resolved statically, by walking down the Django Template and Nodes. However, this did not allow for using for loops or other variables defined in the template.

    Currently, this consists of 2 steps:

    1. If a component is rendered within a template using {% component %} tag, determine the given {% fill %} tags in the component's body (the content in between {% component %} and {% endcomponent %}).

      After this step, we know about all the fills that were passed to the component.

    2. Then we simply render the template as usual. And then we reach the {% slot %} tag, we search the context for the available fills.

      • If there IS a fill with the same name as the slot, we render the fill.
      • If the slot is marked default, and there is a fill named default, then we render that.
      • Otherwise, we render the slot's default content.
  11. Obtaining the fills from {% fill %}.

    When a component is rendered with {% component %} tag, and it has some content in between {% component %} and {% endcomponent %}, we want to figure out if that content is a default slot (no {% fill %} used), or if there is a collection of named {% fill %} tags:

    Default slot:

    | -- {% component \"mycomp\" %} ---\n| ---- STU {{ slot_name }}\n| -- {% endcomponent %} ---\n

    Named slots:

    | -- {% component \"mycomp\" %} ---\n| ---- {% fill \"slot_a\" %}\n| ------ STU\n| ---- {% endslot %}\n| ---- {% fill \"slot_b\" %}\n| ------ XYZ\n| ---- {% endslot %}\n| -- {% endcomponent %} ---\n

    To respect any forloops or other variables defined within the template to which the fills may have access, we:

    1. Render the content between {% component %} and {% endcomponent %} using the context outside of the component.
    2. When we reach a {% fill %} tag, we capture any variables that were created between the {% component %} and {% fill %} tags.
    3. When we reach {% fill %} tag, we do not continue rendering deeper. Instead we make a record that we found the fill tag with given name, kwargs, etc.
    4. After the rendering is done, we check if we've encountered any fills. If yes, we expect only named fills. If no, we assume that the the component's body is a default slot.
    5. Lastly we process the found fills, and make them available to the context, so any slots inside the component may access these fills.
  12. Rendering slots

    Slot rendering works similarly to collecting fills, in a sense that we do not search for the slots ahead of the time, but instead let Django handle the rendering of the template, and we step in only when Django come across as {% slot %} tag.

    When we reach a slot tag, we search the context for the available fills.

    • If there IS a fill with the same name as the slot, we render the fill.
    • If the slot is marked default, and there is a fill named default, then we render that.
    • Otherwise, we render the slot's default content.
"},{"location":"guides/devguides/slot_rendering/#using-the-correct-context-in-slotfill-tags","title":"Using the correct context in {% slot/fill %} tags","text":"

In previous section, we said that the {% fill %} tags should be already rendered by the time they are inserted into the {% slot %} tags.

This is not quite true. To help you understand, consider this complex case:

| -- {% for var in [1, 2, 3] %} ---\n| ---- {% component \"mycomp2\" %} ---\n| ------ {% fill \"first\" %}\n| ------- STU {{ my_var }}\n| -------     {{ var }}\n| ------ {% endfill %}\n| ------ {% fill \"second\" %}\n| -------- {% component var=var my_var=my_var %}\n| ---------- VWX {{ my_var }}\n| -------- {% endcomponent %}\n| ------ {% endfill %}\n| ---- {% endcomponent %} ---\n| -- {% endfor %} ---\n| -------\n

We want the forloop variables to be available inside the {% fill %} tags. Because of that, however, we CANNOT render the fills/slots in advance.

Instead, our solution is closer to how Vue handles slots. In Vue, slots are effectively functions that accept a context variables and render some content.

While we do not wrap the logic in a function, we do PREPARE IN ADVANCE: 1. The content that should be rendered for each slot 2. The context variables from get_context_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. So 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.

    So if you have a template `abc.html`:\n```django\n<div>\n  hello\n  {% slot \"body\" %}{% endslot %}\n</div>\n```\n\nAnd components that make use of `abc.html` via `include` or `extends`:\n```py\nfrom 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```\n\nThen you can set slot fill for the slot imported via `include/extends`:\n\n```django\n{% component \"my_comp_extends\" %}\n    {% fill \"body\" %}\n        123\n    {% endfill %}\n{% endcomponent %}\n```\n\nAnd it will render:\n```html\n<div>\n  hello\n  123\n</div>\n```\n
  2. Slot and block

    So 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 my 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):\ntemplate_file = \"\"\"\n{% extends \"abc.html\" %}\n\n            {% block inner %}\n                OVERRIDEN\n            {% endblock %}\n        \"\"\"\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_file = \"\"\"\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/setup/dev_server_setup/","title":"Running with development server","text":""},{"location":"guides/setup/dev_server_setup/#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.

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.

Note

This setting should be enabled only for the dev environment!

"},{"location":"guides/setup/logging_and_debugging/","title":"Logging and debugging","text":"

Django components supports logging with Django. This can help with troubleshooting.

To configure logging for Django components, set the django_components logger in LOGGING in settings.py (below).

Also see the settings.py file in sampleproject for a real-life example.

import logging\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
"},{"location":"guides/setup/syntax_highlight/","title":"Syntax highlighting","text":""},{"location":"guides/setup/syntax_highlight/#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/css/js 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
# In a file called [project root]/components/calendar.py\nfrom django_components import Component, register, types\n\n@register(\"calendar\")\nclass Calendar(Component):\n    def get_context_data(self, date):\n        return {\n            \"date\": date,\n        }\n\n    template: types.django_html = \"\"\"\n        <div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n    \"\"\"\n\n    css: types.css = \"\"\"\n        .calendar-component { width: 200px; background: pink; }\n        .calendar-component span { font-weight: bold; }\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":"guides/setup/syntax_highlight/#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_context_data(self, date):\n        return {\n            \"date\": date,\n        }\n\n    # language=HTML\n    template= \"\"\"\n        <div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n    \"\"\"\n\n    # language=CSS\n    css = \"\"\"\n        .calendar-component { width: 200px; background: pink; }\n        .calendar-component span { font-weight: bold; }\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":"overview/code_of_conduct/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"overview/code_of_conduct/#our-pledge","title":"Our Pledge","text":"

In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.

"},{"location":"overview/code_of_conduct/#our-standards","title":"Our Standards","text":"

Examples of behavior that contributes to creating a positive environment include:

  • Using welcoming and inclusive language
  • Being respectful of differing viewpoints and experiences
  • Gracefully accepting constructive criticism
  • Focusing on what is best for the community
  • Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

  • The use of sexualized language or imagery and unwelcome sexual attention or advances
  • Trolling, insulting/derogatory comments, and personal or political attacks
  • Public or private harassment
  • Publishing others' private information, such as a physical or electronic address, without explicit permission
  • Other conduct which could reasonably be considered inappropriate in a professional setting
"},{"location":"overview/code_of_conduct/#our-responsibilities","title":"Our Responsibilities","text":"

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.

"},{"location":"overview/code_of_conduct/#scope","title":"Scope","text":"

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

"},{"location":"overview/code_of_conduct/#enforcement","title":"Enforcement","text":"

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at emil@emilstenstrom.se. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

"},{"location":"overview/code_of_conduct/#attribution","title":"Attribution","text":"

This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq

"},{"location":"overview/community/","title":"Community","text":""},{"location":"overview/community/#community-questions","title":"Community questions","text":"

The best place to ask questions is in our Github Discussion board.

Please, before opening a new discussion, check if similar discussion wasn't opened already.

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

One of our goals with django-components is to make it easy to share components between projects (see how to package components). If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.

  • django-htmx-components: A set of components for use with htmx. Try out the live demo.
"},{"location":"overview/compatibility/","title":"Compatibility","text":""},{"location":"overview/compatibility/#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.0, 5.1 3.11 4.2, 5.0, 5.1 3.12 4.2, 5.0, 5.1 3.13 5.1"},{"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\n

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

pip install -r requirements-dev.txt\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
"},{"location":"overview/development/#running-playwright-tests","title":"Running Playwright tests","text":"

We use Playwright for end-to-end tests. You will therefore need to install Playwright to be able to run these tests.

Luckily, Playwright makes it very easy:

pip install -r requirements-dev.txt\nplaywright install chromium --with-deps\n

After Playwright is ready, simply run the tests with tox:

tox\n
"},{"location":"overview/development/#developing-against-live-django-app","title":"Developing against live Django app","text":"

How do you check that your changes to django-components project will work in an actual Django project?

Use the sampleproject demo project to validate the changes:

  1. Navigate to sampleproject directory:

    cd sampleproject\n
  2. Install dependencies from the requirements.txt file:

    pip install -r requirements.txt\n
  3. Link to your local version of django-components:

    pip install -e ..\n

    Note

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

  4. Start Django server

    python manage.py runserver\n

Once the server is up, it should be available at http://127.0.0.1:8000.

To display individual components, add them to the urls.py, like in the case of http://127.0.0.1:8000/greeting

"},{"location":"overview/development/#building-js-code","title":"Building JS code","text":"

django_components uses a bit of JS code to:

  • Manage the loading of JS and CSS files used by the components
  • Allow to pass data from Python to JS

When you make changes to this JS code, you also need to compile it:

  1. Make sure you are inside src/django_components_js:

    cd src/django_components_js\n
  2. Install the JS dependencies

    npm install\n
  3. Compile the JS/TS code:

    python build.py\n

    The script will combine all JS/TS code into a single .js file, minify it, and copy it to django_components/static/django_components/django_components.min.js.

"},{"location":"overview/development/#packaging-and-publishing","title":"Packaging and publishing","text":"

To package the library into a distribution that can be published to PyPI, run:

# Install pypa/build\npython -m pip install build --user\n# Build a binary wheel and a source tarball\npython -m build --sdist --wheel --outdir dist/ .\n

To publish the package to PyPI, use twine (See Python user guide):

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

See the full workflow here.

"},{"location":"overview/development/#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":"
  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 in your settings file:

    INSTALLED_APPS = [\n    ...,\n    'django_components',\n]\n
  3. BASE_DIR setting is required. Ensure that it is defined:

    from pathlib import Path\n\nBASE_DIR = Path(__file__).resolve().parent.parent\n
  4. Set COMPONENTS.dirs and/or COMPONENTS.app_dirs so django_components knows where to find component HTML, JS and CSS files:

    from django_components import ComponentsSettings\n\nCOMPONENTS = ComponentsSettings(\n    dirs=[\n        ...,\n        Path(BASE_DIR) / \"components\",\n    ],\n)\n

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

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

    Note

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

  5. Next, modify TEMPLATES section of settings.py as follows:

    • Remove 'APP_DIRS': True,
      • NOTE: Instead of APP_DIRS: True, we will use django.template.loaders.app_directories.Loader, which has the same effect.
    • Add loaders to OPTIONS list and set it to following value:

    This allows Django load component HTML files as Django templates.

    TEMPLATES = [\n    {\n        ...,\n        'OPTIONS': {\n            'loaders':[(\n                'django.template.loaders.cached.Loader', [\n                    # Default Django loader\n                    'django.template.loaders.filesystem.Loader',\n                    # Inluding 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
"},{"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. Add ComponentDependencyMiddleware to MIDDLEWARE setting.

    The middleware searches the outgoing HTML for all components that were rendered to generate the HTML, and adds the JS and CSS associated with those components.

    MIDDLEWARE = [\n    ...\n    \"django_components.middleware.ComponentDependencyMiddleware\",\n]\n

    Read more in Rendering JS/CSS dependencies.

  3. Add django-component's URL paths to your urlpatterns:

    from django.urls import include, path\n\nurlpatterns = [\n    ...\n    path(\"\", include(\"django_components.urls\")),\n]\n
  4. 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 JS and CSS output 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
"},{"location":"overview/installation/#optional","title":"Optional","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            'builtins': [\n                'django_components.templatetags.component_tags',\n            ]\n        },\n    },\n]\n

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

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

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

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

Note

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

"},{"location":"overview/security_notes/#static-files-prior-to-v0100","title":"Static files prior to v0.100","text":"

Prior to v0.100, if your were using django.contrib.staticfiles to collect static files, no distinction was made between the different kinds of files.

As a result, your Python code and templates may inadvertently become available on your static file server. You probably don't want this, as parts of your backend logic will be exposed, posing a potential security vulnerability.

From v0.27 until v0.100, django-components shipped with an additional installable app django_components.safer_staticfiles. It was a drop-in replacement for django.contrib.staticfiles. Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server.

To use it, add it to INSTALLED_APPS and remove django.contrib.staticfiles.

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

If you are on an pre-v0.27 version of django-components, your alternatives are:

  • a) passing --ignore <pattern> options to the collecstatic CLI command,
  • b) defining a subclass of StaticFilesConfig.

Both routes are described in the official docs of the staticfiles app.

Note that safer_staticfiles excludes the .py and .html files for collectstatic command:

python manage.py collectstatic\n

but it is ignored on the development server:

python manage.py runserver\n

For a step-by-step guide on deploying production server with static files, see the demo project.

See the older versions of the sampleproject for a setup with pre-v0.100 version.

"},{"location":"overview/welcome/","title":"Welcome to Django Components","text":"

django-components introduces component-based architecture to Django's server-side rendering. It combines Django's templating system with the modularity seen in modern frontend frameworks like Vue or React.

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\n\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
"},{"location":"overview/welcome/#features","title":"Features","text":"
  1. \ud83e\udde9 Reusability: Allows creation of self-contained, reusable UI elements.
  2. \ud83d\udce6 Encapsulation: Each component can include its own HTML, CSS, and JavaScript.
  3. \ud83d\ude80 Server-side rendering: Components render on the server, improving initial load times and SEO.
  4. \ud83d\udc0d Django integration: Works within the Django ecosystem, using familiar concepts like template tags.
  5. \u26a1 Asynchronous loading: Components can render independently opening up for integration with JS frameworks like HTMX or AlpineJS.

Potential benefits:

  • \ud83d\udd04 Reduced code duplication
  • \ud83d\udee0\ufe0f Improved maintainability through modular design
  • \ud83e\udde0 Easier management of complex UIs
  • \ud83e\udd1d Enhanced collaboration between frontend and backend developers

Django-components can be particularly useful for larger Django projects that require a more structured approach to UI development, without necessitating a shift to a separate frontend framework.

"},{"location":"overview/welcome/#quickstart","title":"Quickstart","text":"

django-components lets you create reusable blocks of code needed to generate the front end code you need for a modern app.

Define a component in components/calendar/calendar.py like this:

@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"template.html\"\n\n    def get_context_data(self, date):\n        return {\"date\": date}\n

With this template.html file:

<div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n

Use the component like this:

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

And this is what gets rendered:

<div class=\"calendar-component\">Today's date is <span>2024-11-06</span></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/#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. If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.

  • django-htmx-components: A set of components for use with htmx. Try out the live demo.
"},{"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.Component","title":"Component","text":"
Component(registered_name: Optional[str] = None, outer_context: Optional[Context] = None, registry: Optional[ComponentRegistry] = None)\n

Methods:

  • as_view \u2013
  • get_context_data \u2013
  • get_template \u2013
  • get_template_name \u2013
  • inject \u2013
  • on_render_after \u2013
  • on_render_before \u2013
  • render \u2013
  • render_to_response \u2013

Attributes:

  • Media (Optional[Type[ComponentMediaInput]]) \u2013
  • View \u2013
  • css (Optional[str]) \u2013
  • css_file (Optional[str]) \u2013
  • id (str) \u2013
  • input (RenderInput[ArgsType, KwargsType, SlotsType]) \u2013
  • is_filled (SlotIsFilled) \u2013
  • js (Optional[str]) \u2013
  • js_file (Optional[str]) \u2013
  • media (Optional[Media]) \u2013
  • media_class (Type[Media]) \u2013
  • name (str) \u2013
  • outer_context (Context) \u2013
  • registered_name (Optional[str]) \u2013
  • registry \u2013
  • response_class \u2013
  • template (Optional[Union[str, Template]]) \u2013
  • template_file (Optional[str]) \u2013
  • template_name (Optional[str]) \u2013
"},{"location":"reference/api/#django_components.Component.Media","title":"Media class-attribute instance-attribute","text":"
Media: Optional[Type[ComponentMediaInput]] = None\n

See source code

Defines JS and CSS media files associated with this component.

This Media class behaves similarly to Django's Media class:

  • Paths are generally handled as static file paths, and resolved URLs are rendered to HTML with media_class.render_js() or media_class.render_css().
  • A path that starts with http, https, or / is considered a URL, skipping the static file resolution. This path is still rendered to HTML with media_class.render_js() or media_class.render_css().
  • A SafeString (with __html__ method) is considered an already-formatted HTML tag, skipping both static file resolution and rendering with media_class.render_js() or media_class.render_css().

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. Our Media class does NOT support Django's extend keyword

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.View","title":"View class-attribute instance-attribute","text":"
View = ComponentView\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.

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
"},{"location":"reference/api/#django_components.Component.css_file","title":"css_file class-attribute instance-attribute","text":"
css_file: Optional[str] = None\n

See source code

Main CSS associated with this component as file path.

The filepath must be either:

  • Relative to the directory where the Component's Python file is defined.
  • Relative to one of the component directories, as set by COMPONENTS.dirs or COMPONENTS.app_dirs (e.g. <root>/components/).
  • Relative to the staticfiles directories, as set by Django's STATICFILES_DIRS setting (e.g. <root>/static/).

When you create a Component class with css_file, these will happen:

  1. If the file path is relative to the directory where the component's Python file is, the path is resolved.
  2. The file is read and its contents is set to Component.css.

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.id","title":"id property","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.

Raises RuntimeError if accessed outside of rendering execution.

A single render ID has a chance of collision 1 in 3.3M. However, due to birthday paradox, the chance of collision increases when approaching ~1,000 render IDs.

Thus, there is a soft-cap of 1,000 components rendered on a single page.

If you need to more than that, please open an issue on GitHub.

Example:

class MyComponent(Component):\n    def get_context_data(self):\n        print(f\"Rendering '{self.id}'\")\n        return {}\n\nMyComponent.render()\n# Rendering 'ab3c4d'\n
"},{"location":"reference/api/#django_components.Component.input","title":"input property","text":"
input: RenderInput[ArgsType, KwargsType, SlotsType]\n

See source code

Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the render method.

"},{"location":"reference/api/#django_components.Component.is_filled","title":"is_filled property","text":"
is_filled: SlotIsFilled\n

See source code

Dictionary describing which slots have or have not been filled.

This attribute is available for use only within the template as {{ component_vars.is_filled.slot_name }}, and within on_render_before and on_render_after hooks.

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

Only one of js or js_file must be defined.

Example:

class MyComponent(Component):\n    js = \"console.log('Hello, World!');\"\n
"},{"location":"reference/api/#django_components.Component.js_file","title":"js_file class-attribute instance-attribute","text":"
js_file: Optional[str] = None\n

See source code

Main JS associated with this component as file path.

The filepath must be either:

  • Relative to the directory where the Component's Python file is defined.
  • Relative to one of the component directories, as set by COMPONENTS.dirs or COMPONENTS.app_dirs (e.g. <root>/components/).
  • Relative to the staticfiles directories, as set by Django's STATICFILES_DIRS setting (e.g. <root>/static/).

When you create a Component class with js_file, these will happen:

  1. If the file path is relative to the directory where the component's Python file is, the path is resolved.
  2. The file is read and its contents is set to Component.js.

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.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 instance-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 property","text":"
name: str\n
"},{"location":"reference/api/#django_components.Component.outer_context","title":"outer_context instance-attribute","text":"
outer_context: Context = outer_context or Context()\n
"},{"location":"reference/api/#django_components.Component.registered_name","title":"registered_name instance-attribute","text":"
registered_name: Optional[str] = registered_name\n
"},{"location":"reference/api/#django_components.Component.registry","title":"registry instance-attribute","text":"
registry = registry or registry\n
"},{"location":"reference/api/#django_components.Component.response_class","title":"response_class class-attribute instance-attribute","text":"
response_class = HttpResponse\n

See source code

This allows to configure what class is used to generate response from render_to_response

"},{"location":"reference/api/#django_components.Component.template","title":"template class-attribute instance-attribute","text":"
template: Optional[Union[str, Template]] = None\n

See source code

Inlined Django template associated with this component. Can be a plain string or a Template instance.

Only one of template_file, get_template_name, template or get_template must be defined.

Example:

class MyComponent(Component):\n    template = \"Hello, {{ name }}!\"\n\n    def get_context_data(self):\n        return {\"name\": \"World\"}\n
"},{"location":"reference/api/#django_components.Component.template_file","title":"template_file class-attribute instance-attribute","text":"
template_file: Optional[str] = None\n

See source code

Filepath to the Django template associated with this component.

The filepath must be either:

  • Relative to the directory where the Component's Python file is defined.
  • Relative to one of the component directories, as set by COMPONENTS.dirs or COMPONENTS.app_dirs (e.g. <root>/components/).
  • Relative to the template directories, as set by Django's TEMPLATES setting (e.g. <root>/templates/).

Only one of template_file, get_template_name, template or get_template must be defined.

Example:

class MyComponent(Component):\n    template_file = \"path/to/template.html\"\n\n    def get_context_data(self):\n        return {\"name\": \"World\"}\n
"},{"location":"reference/api/#django_components.Component.template_name","title":"template_name instance-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.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.

"},{"location":"reference/api/#django_components.Component.get_context_data","title":"get_context_data","text":"
get_context_data(*args: Any, **kwargs: Any) -> DataType\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

Inlined Django template associated with this component. Can be a plain string or a Template instance.

Only one of template_file, get_template_name, template or get_template must be defined.

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

Filepath to the Django template associated with this component.

The filepath must be relative to either the file where the component class was defined, or one of the roots of STATIFILES_DIRS.

Only one of template_file, get_template_name, template or get_template must be defined.

"},{"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 mut be used inside the get_context_data() method and raises an error if called elsewhere.

Example:

Given this template:

{% provide \"provider\" hello=\"world\" %}\n    {% component \"my_comp\" %}\n    {% endcomponent %}\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 {{ data.hello }}!\"\n    def get_context_data(self):\n        data = self.inject(\"provider\")\n        return {\"data\": data}\n

This renders into:

hi world!\n

As the {{ data.hello }} is taken from the \"provider\".

"},{"location":"reference/api/#django_components.Component.on_render_after","title":"on_render_after","text":"
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n

See source code

Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.

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

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

"},{"location":"reference/api/#django_components.Component.on_render_before","title":"on_render_before","text":"
on_render_before(context: Context, template: Template) -> None\n

See source code

Hook that runs just before the component's template is rendered.

You can use this hook to access or modify the context or the template.

"},{"location":"reference/api/#django_components.Component.render","title":"render classmethod","text":"
render(\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    args: Optional[ArgsType] = None,\n    kwargs: Optional[KwargsType] = None,\n    slots: Optional[SlotsType] = None,\n    escape_slots_content: bool = True,\n    type: RenderType = \"document\",\n    render_dependencies: bool = True,\n    request: Optional[HttpRequest] = None,\n) -> str\n

See source code

Render the component into a string.

Inputs: - args - Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %} - kwargs - Kwargs for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %} - slots - Component slot fills. This is the same as pasing {% fill %} tags to the component. Accepts a dictionary of { slot_name: slot_content } where slot_content can be a string or render function. - escape_slots_content - Whether the content from slots should be escaped. - context - A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. - type - Configure how to handle JS and CSS dependencies. - \"document\" (default) - JS dependencies are inserted into {% component_js_dependencies %}, or to the end of the <body> tag. CSS dependencies are inserted into {% component_css_dependencies %}, or the end of the <head> tag. - render_dependencies - Set this to False if you want to insert the resulting HTML into another component. - request - The request object. This is only required when needing to use RequestContext, e.g. to enable template context_processors. Unused if context is already an instance of Context Example:

MyComponent.render(\n    args=[1, \"two\", {}],\n    kwargs={\n        \"key\": 123,\n    },\n    slots={\n        \"header\": 'STATIC TEXT HERE',\n        \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n    },\n    escape_slots_content=False,\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    slots: Optional[SlotsType] = None,\n    escape_slots_content: bool = True,\n    args: Optional[ArgsType] = None,\n    kwargs: Optional[KwargsType] = None,\n    type: RenderType = \"document\",\n    request: Optional[HttpRequest] = None,\n    *response_args: Any,\n    **response_kwargs: Any\n) -> HttpResponse\n

See source code

Render the component and wrap the content in the response class.

The response class is taken from Component.response_class. Defaults to django.http.HttpResponse.

This is the interface for the django.views.View class which allows us to use components as Django views with component.as_view().

Inputs: - args - Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %} - kwargs - Kwargs for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %} - slots - Component slot fills. This is the same as pasing {% fill %} tags to the component. Accepts a dictionary of { slot_name: slot_content } where slot_content can be a string or render function. - escape_slots_content - Whether the content from slots should be escaped. - context - A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. - type - Configure how to handle JS and CSS dependencies. - \"document\" (default) - JS dependencies are inserted into {% component_js_dependencies %}, or to the end of the <body> tag. CSS dependencies are inserted into {% component_css_dependencies %}, or the end of the <head> tag. - request - The request object. This is only required when needing to use RequestContext, e.g. to enable template context_processors. Unused if context is already an instance of Context

Any additional args and kwargs are passed to the response_class.

Example:

MyComponent.render_to_response(\n    args=[1, \"two\", {}],\n    kwargs={\n        \"key\": 123,\n    },\n    slots={\n        \"header\": 'STATIC TEXT HERE',\n        \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n    },\n    escape_slots_content=False,\n    # HttpResponse input\n    status=201,\n    headers={...},\n)\n# HttpResponse(content=..., status=201, headers=...)\n

"},{"location":"reference/api/#django_components.ComponentFileEntry","title":"ComponentFileEntry","text":"

Bases: tuple

See source code

Result returned by get_component_files().

Attributes:

  • dot_path (str) \u2013
  • filepath (Path) \u2013
"},{"location":"reference/api/#django_components.ComponentFileEntry.dot_path","title":"dot_path instance-attribute","text":"
dot_path: str\n

See source code

The python import path for the module. E.g. app.components.mycomp

"},{"location":"reference/api/#django_components.ComponentFileEntry.filepath","title":"filepath instance-attribute","text":"
filepath: Path\n

See source code

The filesystem path to the module. E.g. /path/to/project/app/components/mycomp.py

"},{"location":"reference/api/#django_components.ComponentMediaInput","title":"ComponentMediaInput","text":"

Bases: typing.Protocol

See source code

Defines JS and CSS media files associated with a Component.

class MyTable(Component):\n    class Media:\n        js = [\n            \"path/to/script.js\",\n            \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\",  # AlpineJS\n        ]\n        css = {\n            \"all\": [\n                \"path/to/style.css\",\n                \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\",  # TailwindCSS\n            ],\n            \"print\": [\"path/to/style2.css\"],\n        }\n

Attributes:

  • css (Optional[Union[ComponentMediaInputPath, List[ComponentMediaInputPath], Dict[str, ComponentMediaInputPath], Dict[str, List[ComponentMediaInputPath]]]]) \u2013
  • js (Optional[Union[ComponentMediaInputPath, List[ComponentMediaInputPath]]]) \u2013
"},{"location":"reference/api/#django_components.ComponentMediaInput.css","title":"css class-attribute instance-attribute","text":"
css: Optional[\n    Union[\n        ComponentMediaInputPath, List[ComponentMediaInputPath], Dict[str, ComponentMediaInputPath], Dict[str, List[ComponentMediaInputPath]]\n    ]\n] = None\n

See source code

CSS files associated with a Component.

  • If a string, it's assumed to be a path to a CSS file.

  • If a list, each entry is assumed to be a path to a CSS file.

  • If a dict, the keys are media types (e.g. \"all\", \"print\", \"screen\", etc.), and the values are either:

    • A string, assumed to be a path to a CSS file.
    • A list, each entry is assumed to be a path to a CSS file.

Each entry can be a string, bytes, SafeString, PathLike, or a callable that returns one of the former (see ComponentMediaInputPath).

Examples:

class MyComponent(Component):\n    class Media:\n        css = \"path/to/style.css\"\n

class MyComponent(Component):\n    class Media:\n        css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n
class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": \"path/to/style.css\",\n            \"print\": \"path/to/print.css\",\n        }\n
class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": [\"path/to/style1.css\", \"path/to/style2.css\"],\n            \"print\": \"path/to/print.css\",\n        }\n
"},{"location":"reference/api/#django_components.ComponentMediaInput.js","title":"js class-attribute instance-attribute","text":"
js: Optional[Union[ComponentMediaInputPath, List[ComponentMediaInputPath]]] = None\n

See source code

JS files associated with a Component.

  • If a string, it's assumed to be a path to a JS file.

  • If a list, each entry is assumed to be a path to a JS file.

Each entry can be a string, bytes, SafeString, PathLike, or a callable that returns one of the former (see ComponentMediaInputPath).

Examples:

class MyComponent(Component):\n    class Media:\n        js = \"path/to/script.js\"\n

class MyComponent(Component):\n    class Media:\n        js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n
class MyComponent(Component):\n    class Media:\n        js = lambda: [\"path/to/script1.js\", \"path/to/script2.js\"]\n
"},{"location":"reference/api/#django_components.ComponentMediaInputPath","title":"ComponentMediaInputPath module-attribute","text":"
ComponentMediaInputPath = Union[str, bytes, SafeData, Path, PathLike, Callable[[], Union[str, bytes, SafeData, Path, PathLike]]]\n

See source code

A type representing an entry in Media.js or Media.css.

If an entry is a SafeString (or has __html__ method), then entry is assumed to be a formatted HTML tag. Otherwise, it's assumed to be a path to a file.

Example:

class MyComponent\n    class Media:\n        js = [\n            \"path/to/script.js\",\n            b\"script.js\",\n            SafeString(\"<script src='path/to/script.js'></script>\"),\n        ]\n        css = [\n            Path(\"path/to/style.css\"),\n            lambda: \"path/to/style.css\",\n            lambda: Path(\"path/to/style.css\"),\n        ]\n
"},{"location":"reference/api/#django_components.ComponentRegistry","title":"ComponentRegistry","text":"
ComponentRegistry(\n    library: Optional[Library] = None, settings: Optional[Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]] = None\n)\n

Bases: object

See source code

Manages components and makes them available in the template, by default as {% component %} tags.

{% component \"my_comp\" key=value %}\n{% endcomponent %}\n

To enable a component to be used in a template, the component must be registered with a component registry.

When you register a component to a registry, behind the scenes the registry automatically adds the component's template tag (e.g. {% component %} to the Library. And the opposite happens when you unregister a component - the tag is removed.

See Registering components.

Parameters:

  • library (Library, default: None ) \u2013

    Django Library associated with this registry. If omitted, the default Library instance from django_components is used.

  • settings (Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]], default: None ) \u2013

    Configure how the components registered with this registry will behave when rendered. See RegistrySettings. Can be either a static value or a callable that returns the settings. If omitted, the settings from COMPONENTS are used.

Notes:

  • The default registry is available as django_components.registry.
  • The default registry is used when registering components with @register decorator.

Example:

# Use with default Library\nregistry = ComponentRegistry()\n\n# Or a custom one\nmy_lib = Library()\nregistry = ComponentRegistry(library=my_lib)\n\n# Usage\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\nregistry.all()\nregistry.clear()\nregistry.get()\n
"},{"location":"reference/api/#django_components.ComponentRegistry--using-registry-to-share-components","title":"Using registry to share components","text":"

You can use component registry for isolating or \"packaging\" components:

  1. Create new instance of ComponentRegistry and Library:

    my_comps = Library()\nmy_comps_reg = ComponentRegistry(library=my_comps)\n

  2. Register components to the registry:

    my_comps_reg.register(\"my_button\", ButtonComponent)\nmy_comps_reg.register(\"my_card\", CardComponent)\n

  3. In your target project, load the Library associated with the registry:

    {% load my_comps %}\n

  4. Use the registered components in your templates:

    {% component \"button\" %}\n{% endcomponent %}\n

Methods:

  • all \u2013
  • clear \u2013
  • get \u2013
  • register \u2013
  • unregister \u2013

Attributes:

  • library (Library) \u2013
  • settings (InternalRegistrySettings) \u2013
"},{"location":"reference/api/#django_components.ComponentRegistry.library","title":"library property","text":"
library: Library\n

See source code

The template tag Library that is associated with the registry.

"},{"location":"reference/api/#django_components.ComponentRegistry.settings","title":"settings property","text":"
settings: InternalRegistrySettings\n

See source code

Registry settings configured for this registry.

"},{"location":"reference/api/#django_components.ComponentRegistry.all","title":"all","text":"
all() -> Dict[str, Type[Component]]\n

See source code

Retrieve all registered Component classes.

Returns:

  • Dict[str, Type[Component]] \u2013

    Dict[str, Type[Component]]: A dictionary of component names to component classes

Example:

# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then get all\nregistry.all()\n# > {\n# >   \"button\": ButtonComponent,\n# >   \"card\": CardComponent,\n# > }\n
"},{"location":"reference/api/#django_components.ComponentRegistry.clear","title":"clear","text":"
clear() -> None\n

See source code

Clears the registry, unregistering all components.

Example:

# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then clear\nregistry.clear()\n# Then get all\nregistry.all()\n# > {}\n
"},{"location":"reference/api/#django_components.ComponentRegistry.get","title":"get","text":"
get(name: str) -> Type[Component]\n

See source code

Retrieve a Component class registered under the given name.

Parameters:

  • name (str) \u2013

    The name under which the component was registered. Required.

Returns:

  • Type[Component] \u2013

    Type[Component]: The component class registered under the given name.

Raises:

  • NotRegistered if the given name is not registered.

Example:

# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then get\nregistry.get(\"button\")\n# > ButtonComponent\n
"},{"location":"reference/api/#django_components.ComponentRegistry.register","title":"register","text":"
register(name: str, component: Type[Component]) -> None\n

See source code

Register a Component class with this registry under the given name.

A component MUST be registered before it can be used in a template such as:

{% component \"my_comp\" %}\n{% endcomponent %}\n

Parameters:

  • name (str) \u2013

    The name under which the component will be registered. Required.

  • component (Type[Component]) \u2013

    The component class to register. Required.

Raises:

  • AlreadyRegistered if a different component was already registered under the same name.

Example:

registry.register(\"button\", ButtonComponent)\n
"},{"location":"reference/api/#django_components.ComponentRegistry.unregister","title":"unregister","text":"
unregister(name: str) -> None\n

See source code

Unregister the Component class that was registered under the given name.

Once a component is unregistered, it is no longer available in the templates.

Parameters:

  • name (str) \u2013

    The name under which the component is registered. Required.

Raises:

  • NotRegistered if the given name is not registered.

Example:

# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
"},{"location":"reference/api/#django_components.ComponentVars","title":"ComponentVars","text":"

Bases: tuple

See source code

Type for the variables available inside the component templates.

All variables here are scoped under component_vars., so e.g. attribute is_filled on this class is accessible inside the template as:

{{ component_vars.is_filled }}\n

Attributes:

  • is_filled (Dict[str, bool]) \u2013
"},{"location":"reference/api/#django_components.ComponentVars.is_filled","title":"is_filled instance-attribute","text":"
is_filled: Dict[str, bool]\n

See source code

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_context_data(self, *args, **kwargs):\n        return {\n            \"my_slot_filled\": \"my_slot\" in self.input.slots\n        }\n
"},{"location":"reference/api/#django_components.ComponentView","title":"ComponentView","text":"
ComponentView(component: Component, **kwargs: Any)\n

Bases: django.views.generic.base.View

See source code

Subclass of django.views.View where the Component instance is available via self.component.

Attributes:

  • component \u2013
"},{"location":"reference/api/#django_components.ComponentView.component","title":"component class-attribute instance-attribute","text":"
component = component\n
"},{"location":"reference/api/#django_components.ComponentsSettings","title":"ComponentsSettings","text":"

Bases: tuple

See source code

Settings available for django_components.

Example:

COMPONENTS = ComponentsSettings(\n    autodiscover=False,\n    dirs = [BASE_DIR / \"components\"],\n)\n

Attributes:

  • app_dirs (Optional[Sequence[str]]) \u2013
  • autodiscover (Optional[bool]) \u2013
  • context_behavior (Optional[ContextBehaviorType]) \u2013
  • dirs (Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]]) \u2013
  • dynamic_component_name (Optional[str]) \u2013
  • forbidden_static_files (Optional[List[Union[str, Pattern]]]) \u2013
  • libraries (Optional[List[str]]) \u2013
  • multiline_tags (Optional[bool]) \u2013
  • reload_on_file_change (Optional[bool]) \u2013
  • reload_on_template_change (Optional[bool]) \u2013
  • static_files_allowed (Optional[List[Union[str, Pattern]]]) \u2013
  • static_files_forbidden (Optional[List[Union[str, Pattern]]]) \u2013
  • tag_formatter (Optional[Union[TagFormatterABC, str]]) \u2013
  • template_cache_size (Optional[int]) \u2013
"},{"location":"reference/api/#django_components.ComponentsSettings.app_dirs","title":"app_dirs class-attribute instance-attribute","text":"
app_dirs: Optional[Sequence[str]] = None\n

See source code

Specify the app-level directories that contain your components.

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

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

COMPONENTS = ComponentsSettings(\n    app_dirs=[\"my_comps\"],\n)\n

To search for <app>/my_comps/.

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

Set to empty list to disable app-level components:

COMPONENTS = ComponentsSettings(\n    app_dirs=[],\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.autodiscover","title":"autodiscover class-attribute instance-attribute","text":"
autodiscover: Optional[bool] = None\n

See source code

Toggle whether to run autodiscovery at the Django server startup.

Defaults to True

COMPONENTS = ComponentsSettings(\n    autodiscover=False,\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.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.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.forbidden_static_files","title":"forbidden_static_files class-attribute instance-attribute","text":"
forbidden_static_files: Optional[List[Union[str, Pattern]]] = None\n

See source code

Deprecated. Use COMPONENTS.static_files_forbidden instead.

"},{"location":"reference/api/#django_components.ComponentsSettings.libraries","title":"libraries class-attribute instance-attribute","text":"
libraries: Optional[List[str]] = None\n

See source code

Configure extra python modules that should be loaded.

This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.

Expects a list of python module paths. Defaults to empty list.

Example:

COMPONENTS = ComponentsSettings(\n    libraries=[\n        \"mysite.components.forms\",\n        \"mysite.components.buttons\",\n        \"mysite.components.cards\",\n    ],\n)\n

This would be the equivalent of importing these modules from within Django's AppConfig.ready():

class MyAppConfig(AppConfig):\n    def ready(self):\n        import \"mysite.components.forms\"\n        import \"mysite.components.buttons\"\n        import \"mysite.components.cards\"\n
"},{"location":"reference/api/#django_components.ComponentsSettings.libraries--manually-loading-libraries","title":"Manually loading libraries","text":"

In the rare case that you need to manually trigger the import of libraries, you can use the import_libraries() function:

from django_components import import_libraries\n\nimport_libraries()\n
"},{"location":"reference/api/#django_components.ComponentsSettings.multiline_tags","title":"multiline_tags class-attribute instance-attribute","text":"
multiline_tags: Optional[bool] = None\n

See source code

Enable / disable multiline support for template tags. If True, template tags like {% component %} or {{ my_var }} can span multiple lines.

Defaults to True.

Disable this setting if you are making custom modifications to Django's regular expression for parsing templates at django.template.base.tag_re.

COMPONENTS = ComponentsSettings(\n    multiline_tags=False,\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.reload_on_file_change","title":"reload_on_file_change class-attribute instance-attribute","text":"
reload_on_file_change: Optional[bool] = None\n

See source code

This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.

In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.

Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.

The setting reload_on_file_change fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.

If True, django_components configures Django to reload when files inside COMPONENTS.dirs or COMPONENTS.app_dirs change.

See Reload dev server on component file changes.

Defaults to False.

Warning

This setting should be enabled only for the dev environment!

"},{"location":"reference/api/#django_components.ComponentsSettings.reload_on_template_change","title":"reload_on_template_change class-attribute instance-attribute","text":"
reload_on_template_change: Optional[bool] = None\n

See source code

Deprecated. Use COMPONENTS.reload_on_file_change instead.

"},{"location":"reference/api/#django_components.ComponentsSettings.static_files_allowed","title":"static_files_allowed class-attribute instance-attribute","text":"
static_files_allowed: Optional[List[Union[str, Pattern]]] = None\n

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs are treated as static files.

If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running collectstatic, and can be accessed under the static file endpoint.

You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

By default, JS, CSS, and common image and font file formats are considered static files:

COMPONENTS = ComponentsSettings(\n    static_files_allowed=[\n        \".css\",\n        \".js\", \".jsx\", \".ts\", \".tsx\",\n        # Images\n        \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n        \".jpeg\",  \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n        \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n        # Fonts\n        \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n    ],\n)\n

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

"},{"location":"reference/api/#django_components.ComponentsSettings.static_files_forbidden","title":"static_files_forbidden class-attribute instance-attribute","text":"
static_files_forbidden: Optional[List[Union[str, Pattern]]] = None\n

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs will NEVER be treated as static files.

If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in static_files_allowed.

Use this setting together with static_files_allowed for a fine control over what file types will be exposed.

You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

By default, any HTML and Python are considered NOT static files:

COMPONENTS = ComponentsSettings(\n    static_files_forbidden=[\n        \".html\", \".django\", \".dj\", \".tpl\",\n        # Python files\n        \".py\", \".pyc\",\n    ],\n)\n

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

"},{"location":"reference/api/#django_components.ComponentsSettings.tag_formatter","title":"tag_formatter class-attribute instance-attribute","text":"
tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n

See source code

Configure what syntax is used inside Django templates to render components. See the available tag formatters.

Defaults to \"django_components.component_formatter\".

Learn more about Customizing component tags with TagFormatter.

Can be set either as direct reference:

from django_components import component_formatter\n\nCOMPONENTS = ComponentsSettings(\n    \"tag_formatter\": component_formatter\n)\n

Or as an import string;

COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_formatter\"\n)\n

Examples:

  • \"django_components.component_formatter\"

    Set

    COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_formatter\"\n)\n

    To write components like this:

    {% component \"button\" href=\"...\" %}\n    Click me!\n{% endcomponent %}\n
  • django_components.component_shorthand_formatter

    Set

    COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_shorthand_formatter\"\n)\n

    To write components like this:

    {% button href=\"...\" %}\n    Click me!\n{% endbutton %}\n
"},{"location":"reference/api/#django_components.ComponentsSettings.template_cache_size","title":"template_cache_size class-attribute instance-attribute","text":"
template_cache_size: Optional[int] = None\n

See source code

Configure the maximum amount of Django templates to be cached.

Defaults to 128.

Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.

By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding Component.get_template() to render many dynamic templates, you can increase this number.

COMPONENTS = ComponentsSettings(\n    template_cache_size=256,\n)\n

To remove the cache limit altogether and cache everything, set template_cache_size to None.

COMPONENTS = ComponentsSettings(\n    template_cache_size=None,\n)\n

If you want to add templates to the cache yourself, you can use cached_template():

from django_components import cached_template\n\ncached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n    pass\n\ncached_template(\n    \"Variable: {{ variable }}\",\n    template_cls=MyTemplate,\n    name=...\n    origin=...\n    engine=...\n)\n
"},{"location":"reference/api/#django_components.ContextBehavior","title":"ContextBehavior","text":"

Bases: str, enum.Enum

See source code

Configure how (and whether) the context is passed to the component fills and what variables are available inside the {% fill %} tags.

Also see Component context and scope.

Options:

  • django: With this setting, component fills behave as usual Django tags.
  • isolated: This setting makes the component fills behave similar to Vue or React.

Attributes:

  • DJANGO \u2013
  • ISOLATED \u2013
"},{"location":"reference/api/#django_components.ContextBehavior.DJANGO","title":"DJANGO class-attribute instance-attribute","text":"
DJANGO = 'django'\n

See source code

With this setting, component fills behave as usual Django tags. That is, they enrich the context, and pass it along.

  1. Component fills use the context of the component they are within.
  2. Variables from Component.get_context_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_context_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_context_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_context_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.EmptyDict","title":"EmptyDict","text":"

Bases: dict

See source code

TypedDict with no members.

You can use this to define a Component that accepts NO kwargs, or NO slots, or returns NO data from Component.get_context_data() / Component.get_js_data() / Component.get_css_data():

Accepts NO kwargs:

from django_components import Component, EmptyDict\n\nclass Table(Component(Any, EmptyDict, Any, Any, Any, Any))\n    ...\n

Accepts NO slots:

from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, EmptyDict, Any, Any, Any))\n    ...\n

Returns NO data from get_context_data():

from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, Any, EmptyDict, Any, Any))\n    ...\n

Going back to the example with NO kwargs, when you then call Component.render() or Component.render_to_response(), the kwargs parameter will raise type error if kwargs is anything else than an empty dict.

Table.render(\n    kwargs: {},\n)\n

Omitting kwargs is also fine:

Table.render()\n

Other values are not allowed. This will raise an error with MyPy:

Table.render(\n    kwargs: {\n        \"one\": 2,\n        \"three\": 4,\n    },\n)\n
"},{"location":"reference/api/#django_components.EmptyTuple","title":"EmptyTuple module-attribute","text":"
EmptyTuple = Tuple[]\n

See source code

Tuple with no members.

You can use this to define a Component that accepts NO positional arguments:

from django_components import Component, EmptyTuple\n\nclass Table(Component(EmptyTuple, Any, Any, Any, Any, Any))\n    ...\n

After that, when you call Component.render() or Component.render_to_response(), the args parameter will raise type error if args is anything else than an empty tuple.

Table.render(\n    args: (),\n)\n

Omitting args is also fine:

Table.render()\n

Other values are not allowed. This will raise an error with MyPy:

Table.render(\n    args: (\"one\", 2, \"three\"),\n)\n
"},{"location":"reference/api/#django_components.RegistrySettings","title":"RegistrySettings","text":"

Bases: tuple

See source code

Configuration for a ComponentRegistry.

These settings define how the components registered with this registry will behave when rendered.

from django_components import ComponentRegistry, RegistrySettings\n\nregistry_settings = RegistrySettings(\n    context_behavior=\"django\",\n    tag_formatter=\"django_components.component_shorthand_formatter\",\n)\n\nregistry = ComponentRegistry(settings=registry_settings)\n

Attributes:

  • CONTEXT_BEHAVIOR (Optional[ContextBehaviorType]) \u2013
  • TAG_FORMATTER (Optional[Union[TagFormatterABC, str]]) \u2013
  • context_behavior (Optional[ContextBehaviorType]) \u2013
  • tag_formatter (Optional[Union[TagFormatterABC, str]]) \u2013
"},{"location":"reference/api/#django_components.RegistrySettings.CONTEXT_BEHAVIOR","title":"CONTEXT_BEHAVIOR class-attribute instance-attribute","text":"
CONTEXT_BEHAVIOR: Optional[ContextBehaviorType] = None\n

See source code

Deprecated. Use context_behavior instead. Will be removed in v1.

Same as the global COMPONENTS.context_behavior setting, but for this registry.

If omitted, defaults to the global COMPONENTS.context_behavior setting.

"},{"location":"reference/api/#django_components.RegistrySettings.TAG_FORMATTER","title":"TAG_FORMATTER class-attribute instance-attribute","text":"
TAG_FORMATTER: Optional[Union[TagFormatterABC, str]] = None\n

See source code

Deprecated. Use tag_formatter instead. Will be removed in v1.

Same as the global COMPONENTS.tag_formatter setting, but for this registry.

If omitted, defaults to the global COMPONENTS.tag_formatter setting.

"},{"location":"reference/api/#django_components.RegistrySettings.context_behavior","title":"context_behavior class-attribute instance-attribute","text":"
context_behavior: Optional[ContextBehaviorType] = None\n

See source code

Same as the global COMPONENTS.context_behavior setting, but for this registry.

If omitted, defaults to the global COMPONENTS.context_behavior setting.

"},{"location":"reference/api/#django_components.RegistrySettings.tag_formatter","title":"tag_formatter class-attribute instance-attribute","text":"
tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n

See source code

Same as the global COMPONENTS.tag_formatter setting, but for this registry.

If omitted, defaults to the global COMPONENTS.tag_formatter setting.

"},{"location":"reference/api/#django_components.Slot","title":"Slot dataclass","text":"
Slot(content_func: SlotFunc[TSlotData])\n

Bases: typing.Generic

See source code

This class holds the slot content function along with related metadata.

Attributes:

  • content_func (SlotFunc[TSlotData]) \u2013
  • do_not_call_in_templates (bool) \u2013
"},{"location":"reference/api/#django_components.Slot.content_func","title":"content_func instance-attribute","text":"
content_func: SlotFunc[TSlotData]\n
"},{"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
"},{"location":"reference/api/#django_components.SlotContent","title":"SlotContent module-attribute","text":"
SlotContent = Union[SlotResult, SlotFunc[TSlotData], 'Slot[TSlotData]']\n
"},{"location":"reference/api/#django_components.SlotFunc","title":"SlotFunc","text":""},{"location":"reference/api/#django_components.SlotRef","title":"SlotRef","text":"
SlotRef(slot: SlotNode, context: Context)\n

Bases: object

See source code

SlotRef allows to treat a slot as a variable. The slot is rendered only once the instance is coerced to string.

This is used to access slots as variables inside the templates. When a SlotRef is rendered in the template with {{ my_lazy_slot }}, it will output the contents of the slot.

"},{"location":"reference/api/#django_components.SlotResult","title":"SlotResult module-attribute","text":"
SlotResult = Union[str, SafeString]\n
"},{"location":"reference/api/#django_components.TagFormatterABC","title":"TagFormatterABC","text":"

Bases: abc.ABC

See source code

Abstract base class for defining custom tag formatters.

Tag formatters define how the component tags are used in the template.

Read more about Tag formatter.

For example, with the default tag formatter (ComponentFormatter), components are written as:

{% component \"comp_name\" %}\n{% endcomponent %}\n

While with the shorthand tag formatter (ShorthandComponentFormatter), components are written as:

{% comp_name %}\n{% endcomp_name %}\n

Example:

Implementation for ShorthandComponentFormatter:

from djagno_components import TagFormatterABC, TagResult\n\nclass ShorthandComponentFormatter(TagFormatterABC):\n    def start_tag(self, name: str) -> str:\n        return name\n\n    def end_tag(self, name: str) -> str:\n        return f\"end{name}\"\n\n    def parse(self, tokens: List[str]) -> TagResult:\n        tokens = [*tokens]\n        name = tokens.pop(0)\n        return TagResult(name, tokens)\n

Methods:

  • end_tag \u2013
  • parse \u2013
  • start_tag \u2013
"},{"location":"reference/api/#django_components.TagFormatterABC.end_tag","title":"end_tag abstractmethod","text":"
end_tag(name: str) -> str\n

See source code

Formats the end tag of a block component.

Parameters:

  • name (str) \u2013

    Component's registered name. Required.

Returns:

  • str ( str ) \u2013

    The formatted end tag.

"},{"location":"reference/api/#django_components.TagFormatterABC.parse","title":"parse abstractmethod","text":"
parse(tokens: List[str]) -> TagResult\n

See source code

Given the tokens (words) passed to a component start tag, this function extracts the component name from the tokens list, and returns TagResult, which is a tuple of (component_name, remaining_tokens).

Parameters:

  • tokens ([List(str]) \u2013

    List of tokens passed to the component tag.

Returns:

  • TagResult ( TagResult ) \u2013

    Parsed component name and remaining tokens.

Example:

Assuming we used a component in a template like this:

{% component \"my_comp\" key=val key2=val2 %}\n{% endcomponent %}\n

This function receives a list of tokens:

['component', '\"my_comp\"', 'key=val', 'key2=val2']\n
  • component is the tag name, which we drop.
  • \"my_comp\" is the component name, but we must remove the extra quotes.
  • The remaining tokens we pass unmodified, as that's the input to the component.

So in the end, we return:

TagResult('my_comp', ['key=val', 'key2=val2'])\n
"},{"location":"reference/api/#django_components.TagFormatterABC.start_tag","title":"start_tag abstractmethod","text":"
start_tag(name: str) -> str\n

See source code

Formats the start tag of a component.

Parameters:

  • name (str) \u2013

    Component's registered name. Required.

Returns:

  • str ( str ) \u2013

    The formatted start tag.

"},{"location":"reference/api/#django_components.TagResult","title":"TagResult","text":"

Bases: tuple

See source code

The return value from TagFormatter.parse().

Read more about Tag formatter.

Attributes:

  • component_name (str) \u2013
  • tokens (List[str]) \u2013
"},{"location":"reference/api/#django_components.TagResult.component_name","title":"component_name instance-attribute","text":"
component_name: str\n

See source code

Component name extracted from the template tag

For example, if we had tag

{% component \"my_comp\" key=val key2=val2 %}\n

Then component_name would be my_comp.

"},{"location":"reference/api/#django_components.TagResult.tokens","title":"tokens instance-attribute","text":"
tokens: List[str]\n

See source code

Remaining tokens (words) that were passed to the tag, with component name removed

For example, if we had tag

{% component \"my_comp\" key=val key2=val2 %}\n

Then tokens would be ['key=val', 'key2=val2'].

"},{"location":"reference/api/#django_components.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.

Parameters:

  • map_module (Callable[[str], str], default: None ) \u2013

    Map the module paths with map_module function. This serves as an escape hatch for when you need to use this function in tests.

Returns:

  • List[str] \u2013

    List[str]: A list of module paths of imported files.

To get the same list of modules that autodiscover() would return, but without importing them, use get_component_files():

from django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
"},{"location":"reference/api/#django_components.cached_template","title":"cached_template","text":"
cached_template(\n    template_string: str,\n    template_cls: Optional[Type[Template]] = None,\n    origin: Optional[Origin] = None,\n    name: Optional[str] = None,\n    engine: Optional[Any] = None,\n) -> Template\n

See source code

Create a Template instance that will be cached as per the COMPONENTS.template_cache_size setting.

Parameters:

  • template_string (str) \u2013

    Template as a string, same as the first argument to Django's Template. Required.

  • template_cls (Type[Template], default: None ) \u2013

    Specify the Template class that should be instantiated. Defaults to Django's Template class.

  • origin (Type[Origin], default: None ) \u2013

    Sets Template.Origin.

  • name (Type[str], default: None ) \u2013

    Sets Template.name

  • engine (Type[Any], default: None ) \u2013

    Sets Template.engine

from django_components import cached_template\n\ntemplate = cached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n    pass\n\ntemplate = cached_template(\n    \"Variable: {{ variable }}\",\n    template_cls=MyTemplate,\n    name=...\n    origin=...\n    engine=...\n)\n
"},{"location":"reference/api/#django_components.get_component_dirs","title":"get_component_dirs","text":"
get_component_dirs(include_apps: bool = True) -> List[Path]\n

See source code

Get directories that may contain component files.

This is the heart of all features that deal with filesystem and file lookup. Autodiscovery, Django template resolution, static file resolution - They all use this.

Parameters:

  • include_apps (bool, default: True ) \u2013

    Include directories from installed Django apps. Defaults to True.

Returns:

  • List[Path] \u2013

    List[Path]: A list of directories that may contain component files.

get_component_dirs() searches for dirs set in COMPONENTS.dirs settings. If none set, defaults to searching for a \"components\" app.

In addition to that, also all installed Django apps are checked whether they contain directories as set in COMPONENTS.app_dirs (e.g. [app]/components).

Notes:

  • Paths that do not point to directories are ignored.

  • BASE_DIR setting is required.

  • The paths in COMPONENTS.dirs must be absolute paths.

"},{"location":"reference/api/#django_components.get_component_files","title":"get_component_files","text":"
get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]\n

See source code

Search for files within the component directories (as defined in get_component_dirs()).

Requires BASE_DIR setting to be set.

Parameters:

  • suffix (Optional[str], default: None ) \u2013

    The suffix to search for. E.g. .py, .js, .css. Defaults to None, which will search for all files.

Returns:

  • List[ComponentFileEntry] \u2013

    List[ComponentFileEntry] A list of entries that contain both the filesystem path and the python import path (dot path).

Example:

from django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
"},{"location":"reference/api/#django_components.import_libraries","title":"import_libraries","text":"
import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n

See source code

Import modules set in COMPONENTS.libraries setting.

See Autodiscovery.

Parameters:

  • map_module (Callable[[str], str], default: None ) \u2013

    Map the module paths with map_module function. This serves as an escape hatch for when you need to use this function in tests.

Returns:

  • List[str] \u2013

    List[str]: A list of module paths of imported files.

Examples:

Normal usage - load libraries after Django has loaded

from django_components import import_libraries\n\nclass MyAppConfig(AppConfig):\n    def ready(self):\n        import_libraries()\n

Potential usage in tests

from django_components import import_libraries\n\nimport_libraries(lambda path: path.replace(\"tests.\", \"myapp.\"))\n

"},{"location":"reference/api/#django_components.register","title":"register","text":"
register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[\n    [Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]]],\n    Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]],\n]\n

See source code

Class decorator for registering a component to a component registry.

See Registering components.

Parameters:

  • name (str) \u2013

    Registered name. This is the name by which the component will be accessed from within a template when using the {% component %} tag. Required.

  • registry (ComponentRegistry, default: None ) \u2013

    Specify the registry to which to register this component. If omitted, component is registered to the default registry.

Raises:

  • AlreadyRegistered \u2013

    If there is already a component registered under the same name.

Examples:

from django_components import Component, register\n\n@register(\"my_component\")\nclass MyComponent(Component):\n    ...\n

Specifing ComponentRegistry the component should be registered to by setting the registry kwarg:

from django.template import Library\nfrom django_components import Component, ComponentRegistry, register\n\nmy_lib = Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n    ...\n
"},{"location":"reference/api/#django_components.registry","title":"registry module-attribute","text":"
registry: ComponentRegistry = ComponentRegistry()\n

See source code

The default and global component registry. Use this instance to directly register or remove components:

See Registering components.

# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get single\nregistry.get(\"button\")\n\n# Get all\nregistry.all()\n\n# 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, type: RenderType = '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/commands/","title":"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/#upgradecomponent","title":"upgradecomponent","text":"
usage: manage.py upgradecomponent [-h] [--path PATH] [--version]\n                                  [-v {0,1,2,3}] [--settings SETTINGS]\n                                  [--pythonpath PYTHONPATH] [--traceback]\n                                  [--no-color] [--force-color] [--skip-checks]\n

See source code

Updates component and component_block tags to the new syntax

Options:

  • -h, --help
    • show this help message and exit
  • --path PATH
    • Path to search for components
  • --version
    • Show program's version number and exit.
  • -v {0,1,2,3}, --verbosity {0,1,2,3}
    • Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output
  • --settings SETTINGS
    • The Python path to a settings module, e.g. \"myproject.settings.main\". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used.
  • --pythonpath PYTHONPATH
    • A directory to add to the Python path, e.g. \"/home/djangoprojects/myproject\".
  • --traceback
    • Raise on CommandError exceptions.
  • --no-color
    • Don't colorize the command output.
  • --force-color
    • Force colorization of the command output.
  • --skip-checks
    • Skip system checks.
"},{"location":"reference/commands/#startcomponent","title":"startcomponent","text":"
usage: manage.py startcomponent [-h] [--path PATH] [--js JS] [--css CSS]\n                                [--template TEMPLATE] [--force] [--verbose]\n                                [--dry-run] [--version] [-v {0,1,2,3}]\n                                [--settings SETTINGS]\n                                [--pythonpath PYTHONPATH] [--traceback]\n                                [--no-color] [--force-color] [--skip-checks]\n                                name\n

See source code

Create a new django component.

Positional Arguments:

  • name
    • The name of the component to create. This is a required argument.

Options:

  • -h, --help
    • show this help message and exit
  • --path PATH
    • The path to the component's directory. This is an optional argument. If not provided, the command will use the COMPONENTS.dirs setting from your Django settings.
  • --js JS
    • The name of the JavaScript file. This is an optional argument. The default value is script.js.
  • --css CSS
    • The name of the CSS file. This is an optional argument. The default value is style.css.
  • --template TEMPLATE
    • The name of the template file. This is an optional argument. The default value is template.html.
  • --force
    • This option allows you to overwrite existing files if they exist. This is an optional argument.
  • --verbose
    • This option allows the command to print additional information during component creation. This is an optional argument.
  • --dry-run
    • This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False.
  • --version
    • Show program's version number and exit.
  • -v {0,1,2,3}, --verbosity {0,1,2,3}
    • Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output
  • --settings SETTINGS
    • The Python path to a settings module, e.g. \"myproject.settings.main\". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used.
  • --pythonpath PYTHONPATH
    • A directory to add to the Python path, e.g. \"/home/djangoprojects/myproject\".
  • --traceback
    • Raise on CommandError exceptions.
  • --no-color
    • Don't colorize the command output.
  • --force-color
    • Force colorization of the command output.
  • --skip-checks
    • Skip system checks.
"},{"location":"reference/commands/#management-command-usage","title":"Management Command Usage","text":"

To use the command, run the following command in your terminal:

python manage.py startcomponent <name> --path <path> --js <js_filename> --css <css_filename> --template <template_filename> --force --verbose --dry-run\n

Replace <name>, <path>, <js_filename>, <css_filename>, and <template_filename> with your desired values.

"},{"location":"reference/commands/#management-command-examples","title":"Management Command Examples","text":"

Here are some examples of how you can use the command:

"},{"location":"reference/commands/#creating-a-component-with-default-settings","title":"Creating a Component with Default Settings","text":"

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

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

"},{"location":"reference/commands/#creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"

You can also create a component with custom settings by providing additional arguments:

python manage.py startcomponent new_component --path my_components --js my_script.js --css my_style.css --template my_template.html\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.

"},{"location":"reference/commands/#overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"

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

python manage.py startcomponent my_component --force\n

This will overwrite the existing my_component if it exists.

"},{"location":"reference/commands/#simulating-component-creation","title":"Simulating Component Creation","text":"

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 startcomponent my_component --dry-run\n

This will simulate the creation of my_component without creating any files.

"},{"location":"reference/components/","title":"Components","text":""},{"location":"reference/components/#components","title":"Components","text":"

These are the components provided by django_components.

"},{"location":"reference/components/#django_components.components.dynamic.DynamicComponent","title":"DynamicComponent","text":"

Bases: django_components.component.Component

See source code

This component is given a registered name or a reference to another component, and behaves as if the other component was in its place.

The args, kwargs, and slot fills are all passed down to the underlying component.

Parameters:

  • is (str | Type[Component]) \u2013

    Component that should be rendered. Either a registered name of a component, or a Component class directly. Required.

  • registry (ComponentRegistry, default: None ) \u2013

    Specify the registry to search for the registered name. If omitted, all registries are searched until the first match.

  • *args \u2013

    Additional data passed to the component.

  • **kwargs \u2013

    Additional data passed to the component.

Slots:

  • Any slots, depending on the actual component.

Examples:

Django

{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% endcomponent %}\n

Or in case you use the django_components.component_shorthand_formatter tag formatter:

{% dynamic is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% enddynamic %}\n

Python

from django_components import DynamicComponent\n\nDynamicComponent.render(\n    kwargs={\n        \"is\": table_comp,\n        \"data\": table_data,\n        \"headers\": table_headers,\n    },\n    slots={\n        \"pagination\": PaginationComponent.render(\n            render_dependencies=False,\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/middlewares/","title":"Middlewares","text":""},{"location":"reference/middlewares/#middlewares","title":"Middlewares","text":""},{"location":"reference/middlewares/#django_components.dependencies.ComponentDependencyMiddleware","title":"ComponentDependencyMiddleware","text":"

Bases: object

See source code

Middleware that inserts CSS/JS dependencies for all rendered components at points marked with template tags.

"},{"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    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    dynamic_component_name=\"dynamic\",\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.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.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.forbidden_static_files","title":"forbidden_static_files","text":"
forbidden_static_files: Optional[List[Union[str, Pattern]]] = None\n

See source code

Deprecated. Use COMPONENTS.static_files_forbidden instead.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.libraries","title":"libraries","text":"
libraries: Optional[List[str]] = None\n

See source code

Configure extra python modules that should be loaded.

This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.

Expects a list of python module paths. Defaults to empty list.

Example:

COMPONENTS = ComponentsSettings(\n    libraries=[\n        \"mysite.components.forms\",\n        \"mysite.components.buttons\",\n        \"mysite.components.cards\",\n    ],\n)\n

This would be the equivalent of importing these modules from within Django's AppConfig.ready():

class MyAppConfig(AppConfig):\n    def ready(self):\n        import \"mysite.components.forms\"\n        import \"mysite.components.buttons\"\n        import \"mysite.components.cards\"\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.libraries--manually-loading-libraries","title":"Manually loading libraries","text":"

In the rare case that you need to manually trigger the import of libraries, you can use the import_libraries() function:

from django_components import import_libraries\n\nimport_libraries()\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.multiline_tags","title":"multiline_tags","text":"
multiline_tags: Optional[bool] = None\n

See source code

Enable / disable multiline support for template tags. If True, template tags like {% component %} or {{ my_var }} can span multiple lines.

Defaults to True.

Disable this setting if you are making custom modifications to Django's regular expression for parsing templates at django.template.base.tag_re.

COMPONENTS = ComponentsSettings(\n    multiline_tags=False,\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.reload_on_file_change","title":"reload_on_file_change","text":"
reload_on_file_change: Optional[bool] = None\n

See source code

This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.

In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.

Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.

The setting reload_on_file_change fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.

If True, django_components configures Django to reload when files inside COMPONENTS.dirs or COMPONENTS.app_dirs change.

See Reload dev server on component file changes.

Defaults to False.

Warning

This setting should be enabled only for the dev environment!

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.reload_on_template_change","title":"reload_on_template_change","text":"
reload_on_template_change: Optional[bool] = None\n

See source code

Deprecated. Use COMPONENTS.reload_on_file_change instead.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.static_files_allowed","title":"static_files_allowed","text":"
static_files_allowed: Optional[List[Union[str, Pattern]]] = None\n

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs are treated as static files.

If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running collectstatic, and can be accessed under the static file endpoint.

You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

By default, JS, CSS, and common image and font file formats are considered static files:

COMPONENTS = ComponentsSettings(\n    static_files_allowed=[\n        \".css\",\n        \".js\", \".jsx\", \".ts\", \".tsx\",\n        # Images\n        \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n        \".jpeg\",  \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n        \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n        # Fonts\n        \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n    ],\n)\n

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.static_files_forbidden","title":"static_files_forbidden","text":"
static_files_forbidden: Optional[List[Union[str, Pattern]]] = None\n

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs will NEVER be treated as static files.

If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in static_files_allowed.

Use this setting together with static_files_allowed for a fine control over what file types will be exposed.

You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

By default, any HTML and Python are considered NOT static files:

COMPONENTS = ComponentsSettings(\n    static_files_forbidden=[\n        \".html\", \".django\", \".dj\", \".tpl\",\n        # Python files\n        \".py\", \".pyc\",\n    ],\n)\n

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.tag_formatter","title":"tag_formatter","text":"
tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n

See source code

Configure what syntax is used inside Django templates to render components. See the available tag formatters.

Defaults to \"django_components.component_formatter\".

Learn more about Customizing component tags with TagFormatter.

Can be set either as direct reference:

from django_components import component_formatter\n\nCOMPONENTS = ComponentsSettings(\n    \"tag_formatter\": component_formatter\n)\n

Or as an import string;

COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_formatter\"\n)\n

Examples:

  • \"django_components.component_formatter\"

    Set

    COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_formatter\"\n)\n

    To write components like this:

    {% component \"button\" href=\"...\" %}\n    Click me!\n{% endcomponent %}\n
  • django_components.component_shorthand_formatter

    Set

    COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_shorthand_formatter\"\n)\n

    To write components like this:

    {% button href=\"...\" %}\n    Click me!\n{% endbutton %}\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.template_cache_size","title":"template_cache_size","text":"
template_cache_size: Optional[int] = None\n

See source code

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/tag_formatters/","title":"Tag formatters","text":""},{"location":"reference/tag_formatters/#tag-formatters","title":"Tag Formatters","text":"

Tag formatters allow you to change the syntax for calling components from within the Django templates.

Tag formatter are set via the tag_formatter setting.

"},{"location":"reference/tag_formatters/#available-tag-formatters","title":"Available tag formatters","text":"
  • django_components.component_formatter for ComponentFormatter

  • django_components.component_shorthand_formatter for ShorthandComponentFormatter

"},{"location":"reference/tag_formatters/#django_components.tag_formatter.ComponentFormatter","title":"ComponentFormatter","text":"

Bases: django_components.tag_formatter.TagFormatterABC

See source code

The original django_component's component tag formatter, it uses the {% component %} and {% endcomponent %} tags, and the component name is given as the first positional arg.

Example as block:

{% component \"mycomp\" abc=123 %}\n    {% fill \"myfill\" %}\n        ...\n    {% endfill %}\n{% endcomponent %}\n

Example as inlined tag:

{% component \"mycomp\" abc=123 / %}\n

"},{"location":"reference/tag_formatters/#django_components.tag_formatter.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":"

Bases: django_components.tag_formatter.TagFormatterABC

See source code

The component tag formatter that uses {% <name> %} / {% end<name> %} tags.

This is similar to django-web-components and django-slippers syntax.

Example as block:

{% mycomp abc=123 %}\n    {% fill \"myfill\" %}\n        ...\n    {% endfill %}\n{% endmycomp %}\n

Example as inlined tag:

{% mycomp abc=123 / %}\n

"},{"location":"reference/template_tags/","title":"Template tags","text":""},{"location":"reference/template_tags/#template-tags","title":"Template tags","text":"

All following template tags are defined in

django_components.templatetags.component_tags

Import as

{% load component_tags %}\n

"},{"location":"reference/template_tags/#component","title":"component","text":"
{% component [arg, ...] **kwargs [only] %}\n{% endcomponent %}\n

See source code

Renders one of the components that was previously registered with @register() decorator.

Args:

  • name (str, required): Registered name of the component to render
  • All other args and kwargs are defined based on the component itself.

If you defined a component \"my_table\"

from django_component import Component, register\n\n@register(\"my_table\")\nclass MyTable(Component):\n    template = \"\"\"\n      <table>\n        <thead>\n          {% for header in headers %}\n            <th>{{ header }}</th>\n          {% endfor %}\n        </thead>\n        <tbody>\n          {% for row in rows %}\n            <tr>\n              {% for cell in row %}\n                <td>{{ cell }}</td>\n              {% endfor %}\n            </tr>\n          {% endfor %}\n        <tbody>\n      </table>\n    \"\"\"\n\n    def get_context_data(self, rows: List, headers: List):\n        return {\n            \"rows\": rows,\n            \"headers\": headers,\n        }\n

Then you can render this component by referring to MyTable via its registered name \"my_table\":

{% component \"my_table\" rows=rows headers=headers ... / %}\n
"},{"location":"reference/template_tags/#component-input","title":"Component input","text":"

Positional and keyword arguments can be literals or template variables.

The component name must be a single- or double-quotes string and must be either:

  • The first positional argument after component:

    {% component \"my_table\" rows=rows headers=headers ... / %}\n
  • Passed as kwarg name:

    {% component rows=rows headers=headers name=\"my_table\" ... / %}\n
"},{"location":"reference/template_tags/#inserting-into-slots","title":"Inserting into slots","text":"

If the component defined any slots, you can pass in the content to be placed inside those slots by inserting {% fill %} tags, directly within the {% component %} tag:

{% component \"my_table\" rows=rows headers=headers ... / %}\n  {% fill \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endfill %}\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
"},{"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 JS and CSS output 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 JS and CSS output 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/#fill","title":"fill","text":"
{% fill name data=None default=None %}\n{% endfill %}\n

See source code

Use this tag to insert content into component's slots.

{% fill %} tag may be used only within a {% component %}..{% endcomponent %} block. Runtime checks should prohibit other usages.

Args:

  • name (str, required): Name of the slot to insert this content into. Use \"default\" for the default slot.
  • default (str, optional): This argument allows you to access the original content of the slot under the specified variable name. See Accessing original content of slots
  • data (str, optional): This argument allows you to access the data passed to the slot under the specified variable name. See Scoped slots

Examples:

Basic usage:

{% component \"my_table\" %}\n  {% fill \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endfill %}\n{% endcomponent %}\n

"},{"location":"reference/template_tags/#accessing-slots-default-content-with-the-default-kwarg","title":"Accessing slot's default content with the default kwarg","text":"
{# my_table.html #}\n<table>\n  ...\n  {% slot \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endslot %}\n</table>\n
{% component \"my_table\" %}\n  {% fill \"pagination\" default=\"default_pag\" %}\n    <div class=\"my-class\">\n      {{ default_pag }}\n    </div>\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/template_tags/#accessing-slots-data-with-the-data-kwarg","title":"Accessing slot's data with the data kwarg","text":"
{# my_table.html #}\n<table>\n  ...\n  {% slot \"pagination\" pages=pages %}\n    < 1 | 2 | 3 >\n  {% endslot %}\n</table>\n
{% 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/#accessing-slot-data-and-default-content-on-the-default-slot","title":"Accessing slot data and default content on the default slot","text":"

To access slot data and the default slot content on the default slot, use {% fill %} with name set to \"default\":

{% component \"button\" %}\n  {% fill name=\"default\" data=\"slot_data\" default=\"default_slot\" %}\n    You clicked me {{ slot_data.count }} times!\n    {{ default_slot }}\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/template_tags/#html_attrs","title":"html_attrs","text":"
{% html_attrs attrs=None defaults=None **kwargs %}\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 with the internal. See how to in Passing HTML attributes to components.

Args:

  • attrs (dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides values in the default dictionary.
  • default (str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden with values in the attrs dictionary.
  • Any extra kwargs will be appended to the corresponding keys

The attributes in attrs and defaults are merged and resulting dict is rendered as HTML attributes (key=\"value\").

Extra kwargs (key=value) are concatenated to existing keys. So if we have

attrs = {\"class\": \"my-class\"}\n

Then

{% html_attrs attrs class=\"extra-class\" %}\n

will result in class=\"my-class extra-class\".

Example:

<div {% html_attrs\n    attrs\n    defaults:class=\"default-class\"\n    class=\"extra-class\"\n    data-id=\"123\"\n%}>\n

renders

<div class=\"my-class extra-class\" data-id=\"123\">\n

See more usage examples in HTML attributes.

"},{"location":"reference/template_tags/#provide","title":"provide","text":"
{% provide name **kwargs %}\n{% endprovide %}\n

See source code

The \"provider\" part of the provide / inject feature. Pass kwargs to this tag to define the provider's data. Any components defined within the {% provide %}..{% endprovide %} tags will be able to access this data with Component.inject().

This is similar to React's ContextProvider, or Vue's provide().

Args:

  • name (str, required): Provider name. This is the name you will then use in Component.inject().
  • **kwargs: Any extra kwargs will be passed as the provided data.

Example:

Provide the \"user_data\" in parent component:

@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      <div>\n        {% provide \"user_data\" user=user %}\n          {% component \"child\" / %}\n        {% endprovide %}\n      </div>\n    \"\"\"\n\n    def get_context_data(self, user: User):\n        return {\n            \"user\": 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_context_data(self):\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 **kwargs [default] [required] %}\n{% endslot %}\n

See source code

Slot tag marks a place inside a component where content can be inserted from outside.

Learn more about using slots.

This is similar to slots as seen in Web components, Vue or React's children.

Args:

  • name (str, required): Registered name of the component to render
  • default: Optional flag. If there is a default slot, you can pass the component slot content without using the {% fill %} tag. See Default slot
  • required: Optional flag. Will raise an error if a slot is required but not given.
  • **kwargs: Any extra kwargs will be passed as the slot data.

Example:

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        {% slot \"content\" default %}\n          This is shown if not overriden!\n        {% endslot %}\n      </div>\n      <aside>\n        {% slot \"sidebar\" required / %}\n      </aside>\n    \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      <div>\n        {% component \"child\" %}\n          {% fill \"content\" %}\n            \ud83d\uddde\ufe0f\ud83d\udcf0\n          {% endfill %}\n\n          {% fill \"sidebar\" %}\n            \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n          {% endfill %}\n        {% endcomponent %}\n      </div>\n    \"\"\"\n
"},{"location":"reference/template_tags/#passing-data-to-slots","title":"Passing data to slots","text":"

Any extra kwargs will be considered as slot data, and will be accessible in the {% fill %} tag via fill's data kwarg:

@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/#accessing-default-slot-content","title":"Accessing default slot content","text":"

The content between the {% slot %}..{% endslot %} tags is the default content that will be rendered if no fill is given for the slot.

This default content can then be accessed from within the {% fill %} tag using the fill's default 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 default content!\n        {% endslot %}\n      </div>\n    \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      {# Parent can access the slot's default content #}\n      {% component \"child\" %}\n        {% fill \"content\" default=\"default\" %}\n          {{ default }}\n        {% endfill %}\n      {% endcomponent %}\n    \"\"\"\n
"},{"location":"reference/template_vars/","title":"Template vars","text":""},{"location":"reference/template_vars/#template-variables","title":"Template variables","text":"

Here is a list of all variables that are automatically available from inside the component's template and in on_render_before / on_render_after hooks.

"},{"location":"reference/template_vars/#django_components.component.ComponentVars.is_filled","title":"is_filled instance-attribute","text":"
is_filled: Dict[str, bool]\n

See source code

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_context_data(self, *args, **kwargs):\n        return {\n            \"my_slot_filled\": \"my_slot\" in self.input.slots\n        }\n
"},{"location":"reference/urls/","title":"Urls","text":""},{"location":"reference/urls/#urls","title":"URLs","text":"

Below are all the URL patterns that will be added by adding django_components.urls.

See Installation on how to add these URLs to your Django project.

Django components already prefixes all URLs with components/. So when you are adding the URLs to urlpatterns, you can use an empty string as the first argument:

from django.urls import include, path\n\nurlpatterns = [\n    ...\n    path(\"\", include(\"django_components.urls\")),\n]\n
"},{"location":"reference/urls/#list-of-urls","title":"List of URLs","text":"
  • components/cache/<str:comp_cls_hash>.<str:input_hash>.<str:script_type>

  • components/cache/<str:comp_cls_hash>.<str:script_type>

"}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Welcome to Django Components","text":"

django-components introduces component-based architecture to Django's server-side rendering. It combines Django's templating system with the modularity seen in modern frontend frameworks like Vue or React.

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\n\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
"},{"location":"#features","title":"Features","text":"
  1. \ud83e\udde9 Reusability: Allows creation of self-contained, reusable UI elements.
  2. \ud83d\udce6 Encapsulation: Each component can include its own HTML, CSS, and JavaScript.
  3. \ud83d\ude80 Server-side rendering: Components render on the server, improving initial load times and SEO.
  4. \ud83d\udc0d Django integration: Works within the Django ecosystem, using familiar concepts like template tags.
  5. \u26a1 Asynchronous loading: Components can render independently opening up for integration with JS frameworks like HTMX or AlpineJS.

Potential benefits:

  • \ud83d\udd04 Reduced code duplication
  • \ud83d\udee0\ufe0f Improved maintainability through modular design
  • \ud83e\udde0 Easier management of complex UIs
  • \ud83e\udd1d Enhanced collaboration between frontend and backend developers

Django-components can be particularly useful for larger Django projects that require a more structured approach to UI development, without necessitating a shift to a separate frontend framework.

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

django-components lets you create reusable blocks of code needed to generate the front end code you need for a modern app.

Define a component in components/calendar/calendar.py like this:

@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"template.html\"\n\n    def get_context_data(self, date):\n        return {\"date\": date}\n

With this template.html file:

<div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n

Use the component like this:

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

And this is what gets rendered:

<div class=\"calendar-component\">Today's date is <span>2024-11-06</span></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":"#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. If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.

  • django-htmx-components: A set of components for use with htmx. Try out the live demo.
"},{"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":"SUMMARY/","title":"SUMMARY","text":"
  • Get Started
  • Concepts
  • Getting started
  • Fundamentals
  • Advanced
  • Guides
  • Setup
  • Dev guides
  • API Documentation
  • Release notes
"},{"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/#v0124","title":"v0.124","text":""},{"location":"release_notes/#feat","title":"Feat","text":"
  • Instead of inlining the JS and CSS under Component.js and Component.css, you can move them to their own files, and link the JS/CSS files with Component.js_file and Component.css_file.

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

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

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

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

    See the updated \"Getting Started\" tutorial

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  • Fix compatibility with AlpineJS

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

AlpineJS can be configured like so:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    to

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Following is now possible

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Internally, django-components handles slot fills as functions.

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

Now, something like this is possible:

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

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

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

Before:

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

After:

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

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

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

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

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

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

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

{% component \"child\" %}\n  {% fill slot=\"default\" %}\n    Hello from default slot\n  {% endfill %}\n  {% fill slot=\"content\" data=\"data\" %}\n    Hello from content slot\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"release_notes/#v0100","title":"\ud83d\udea8\ud83d\udce2 v0.100","text":""},{"location":"release_notes/#breaking-changes_2","title":"BREAKING CHANGES","text":"
  • django_components.safer_staticfiles app was removed. It is no longer needed.

  • Installation changes:

    • Instead of defining component directories in STATICFILES_DIRS, set them to COMPONENTS.dirs.
    • You now must define STATICFILES_FINDERS

    • See here how to migrate your settings.py

"},{"location":"release_notes/#feat_5","title":"Feat","text":"
  • Beside the top-level /components directory, you can now define also app-level components dirs, e.g. [app]/components (See COMPONENTS.app_dirs).
"},{"location":"release_notes/#refactor_6","title":"Refactor","text":"
  • When you call as_view() on a component instance, that instance will be passed to View.as_view()
"},{"location":"release_notes/#v097","title":"v0.97","text":""},{"location":"release_notes/#fix_13","title":"Fix","text":"
  • Fixed template caching. You can now also manually create cached templates with cached_template()
"},{"location":"release_notes/#refactor_7","title":"Refactor","text":"
  • The previously undocumented get_template was made private.

  • In it's place, there's a new get_template, which supersedes get_template_string (will be removed in v1). The new get_template is the same as get_template_string, except it allows to return either a string or a Template instance.

  • You now must use only one of template, get_template, template_name, or get_template_name.

"},{"location":"release_notes/#v096","title":"v0.96","text":""},{"location":"release_notes/#feat_6","title":"Feat","text":"
  • Run-time type validation for Python 3.11+ - If the Component class is typed, e.g. Component[Args, Kwargs, ...], the args, kwargs, slots, and data are validated against the given types. (See Runtime input validation with types)

  • Render hooks - Set on_render_before and on_render_after methods on Component to intercept or modify the template or context before rendering, or the rendered result afterwards. (See Component hooks)

  • component_vars.is_filled context variable can be accessed from within on_render_before and on_render_after hooks as self.is_filled.my_slot

"},{"location":"release_notes/#095","title":"0.95","text":""},{"location":"release_notes/#feat_7","title":"Feat","text":"
  • Added support for dynamic components, where the component name is passed as a variable. (See Dynamic components)
"},{"location":"release_notes/#refactor_8","title":"Refactor","text":"
  • Changed Component.input to raise RuntimeError if accessed outside of render context. Previously it returned None if unset.
"},{"location":"release_notes/#v094","title":"v0.94","text":""},{"location":"release_notes/#feat_8","title":"Feat","text":"
  • django_components now automatically configures Django to support multi-line tags. (See Multi-line tags)

  • New setting reload_on_template_change. Set this to True to reload the dev server on changes to component template files. (See Reload dev server on component file changes)

"},{"location":"release_notes/#v093","title":"v0.93","text":""},{"location":"release_notes/#feat_9","title":"Feat","text":"
  • Spread operator ...dict inside template tags. (See Spread operator)

  • Use template tags inside string literals in component inputs. (See Use template tags inside component inputs)

  • Dynamic slots, fills and provides - The name argument for these can now be a variable, a template expression, or via spread operator

  • Component library authors can now configure CONTEXT_BEHAVIOR and TAG_FORMATTER settings independently from user settings.

"},{"location":"release_notes/#v092","title":"\ud83d\udea8\ud83d\udce2 v0.92","text":""},{"location":"release_notes/#breaking-changes_3","title":"BREAKING CHANGES","text":"
  • Component class is no longer a subclass of View. To configure the View class, set the Component.View nested class. HTTP methods like get or post can still be defined directly on Component class, and Component.as_view() internally calls Component.View.as_view(). (See Modifying the View class)
"},{"location":"release_notes/#feat_10","title":"Feat","text":"
  • The inputs (args, kwargs, slots, context, ...) that you pass to Component.render() can be accessed from within get_context_data, get_template and get_template_name via self.input. (See Accessing data passed to the component)

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

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

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

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

    The default is django_components.component_formatter:

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

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

    {% button href=\"...\" disabled %}\n    Click me!\n{% endbutton %}\n
"},{"location":"release_notes/#v085","title":"\ud83d\udea8\ud83d\udce2 v0.85","text":""},{"location":"release_notes/#breaking-changes_4","title":"BREAKING CHANGES","text":"
  • Autodiscovery module resolution changed. Following undocumented behavior was removed:

    • Previously, autodiscovery also imported any [app]/components.py files, and used SETTINGS_MODULE to search for component dirs.

      To migrate from:

      • [app]/components.py - Define each module in COMPONENTS.libraries setting, or import each module inside the AppConfig.ready() hook in respective apps.py files.

      • SETTINGS_MODULE - Define component dirs using STATICFILES_DIRS

    • Previously, autodiscovery handled relative files in STATICFILES_DIRS. To align with Django, STATICFILES_DIRS now must be full paths (Django docs).

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

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

"},{"location":"release_notes/#v080","title":"v0.80","text":""},{"location":"release_notes/#feat_13","title":"Feat","text":"
  • Vue-like provide/inject with the {% provide %} tag and inject() method.
"},{"location":"release_notes/#v079","title":"\ud83d\udea8\ud83d\udce2 v0.79","text":""},{"location":"release_notes/#breaking-changes_6","title":"BREAKING CHANGES","text":"
  • Default value for the COMPONENTS.context_behavior setting was changes from \"isolated\" to \"django\". If you did not set this value explicitly before, this may be a breaking change. See the rationale for change here.
"},{"location":"release_notes/#v077","title":"\ud83d\udea8\ud83d\udce2 v0.77","text":""},{"location":"release_notes/#breaking","title":"BREAKING","text":"
  • The syntax for accessing default slot content has changed from

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

    to

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

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

"},{"location":"release_notes/#v070","title":"\ud83d\udea8\ud83d\udce2 v0.70","text":""},{"location":"release_notes/#breaking-changes_7","title":"BREAKING CHANGES","text":"
  • {% if_filled \"my_slot\" %} tags were replaced with {{ component_vars.is_filled.my_slot }} variables.

  • Simplified settings - slot_context_behavior and context_behavior were merged. See the documentation for more details.

"},{"location":"release_notes/#v067","title":"v0.67","text":""},{"location":"release_notes/#refactor_9","title":"Refactor","text":"
  • Changed the default way how context variables are resolved in slots. See the documentation for more details.
"},{"location":"release_notes/#v050","title":"\ud83d\udea8\ud83d\udce2 v0.50","text":""},{"location":"release_notes/#breaking-changes_8","title":"BREAKING CHANGES","text":"
  • {% component_block %} is now {% component %}, and {% component %} blocks need an ending {% endcomponent %} tag.

    The new python manage.py upgradecomponent command can be used to upgrade a directory (use --path argument to point to each dir) of templates that use components to the new syntax automatically.

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

"},{"location":"release_notes/#v034","title":"v0.34","text":""},{"location":"release_notes/#feat_15","title":"Feat","text":"
  • Components as views, which allows you to handle requests and render responses from within a component. See the documentation for more details.
"},{"location":"release_notes/#v028","title":"v0.28","text":""},{"location":"release_notes/#feat_16","title":"Feat","text":"
  • 'implicit' slot filling and the default option for slot tags.
"},{"location":"release_notes/#v027","title":"v0.27","text":""},{"location":"release_notes/#feat_17","title":"Feat","text":"
  • A second installable app django_components.safer_staticfiles. It provides the same behavior as django.contrib.staticfiles but with extra security guarantees (more info below in Security Notes).
"},{"location":"release_notes/#v026","title":"\ud83d\udea8\ud83d\udce2 v0.26","text":""},{"location":"release_notes/#breaking-changes_9","title":"BREAKING CHANGES","text":"
  • Changed the syntax for {% slot %} tags. From now on, we separate defining a slot ({% slot %}) from filling a slot with content ({% fill %}). This means you will likely need to change a lot of slot tags to fill.

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

"},{"location":"release_notes/#v022","title":"v0.22","text":""},{"location":"release_notes/#feat_18","title":"Feat","text":"
  • All files inside components subdirectores are autoimported to simplify setup.

    An existing project might start to get AlreadyRegistered errors because of this. To solve this, either remove your custom loading of components, or set \"autodiscover\": False in settings.COMPONENTS.

"},{"location":"release_notes/#v017","title":"v0.17","text":""},{"location":"release_notes/#breaking-changes_10","title":"BREAKING CHANGES","text":"
  • Renamed Component.context and Component.template to get_context_data and get_template_name. The old methods still work, but emit a deprecation warning.

    This change was done to sync naming with Django's class based views, and make using django-components more familiar to Django users. Component.context and Component.template will be removed when version 1.0 is released.

"},{"location":"concepts/advanced/authoring_component_libraries/","title":"Authoring component libraries","text":"

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

"},{"location":"concepts/advanced/authoring_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 Dict, NotRequired, Optional, Tuple, TypedDict\n\nfrom django_components import Component, SlotFunc, register, types\n\nfrom myapp.templatetags.mytags import comp_registry\n\n# Define the types\nclass EmptyDict(TypedDict):\n    pass\n\ntype MyMenuArgs = Tuple[int, str]\n\nclass MyMenuSlots(TypedDict):\n    default: NotRequired[Optional[SlotFunc[EmptyDict]]]\n\nclass MyMenuProps(TypedDict):\n    vertical: NotRequired[bool]\n    klass: NotRequired[str]\n    style: NotRequired[str]\n\n# Define the component\n# NOTE: Don't forget to set the `registry`!\n@register(\"my_menu\", registry=comp_registry)\nclass MyMenu(Component[MyMenuArgs, MyMenuProps, MyMenuSlots, Any, Any, Any]):\n    def get_context_data(\n        self,\n        *args,\n        attrs: Optional[Dict] = None,\n    ):\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/authoring_component_libraries/#publishing-component-libraries","title":"Publishing component libraries","text":"

Once you are ready to share your library, you need to build a distribution and then publish it to PyPI.

django_components uses the build utility to build a distribution:

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

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

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

Notes on publishing:

  • If you use components where the HTML / CSS / JS files are separate, you may need to define MANIFEST.in to include those files with the distribution (see user guide).
"},{"location":"concepts/advanced/authoring_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_context_data(self, date):\n        return {\n            \"date\": 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# Unregister single component\nregistry.unregister(\"card\")\n\n# Unregister all components\nregistry.clear()\n
"},{"location":"concepts/advanced/component_registry/#registering-components-to-custom-componentregistry","title":"Registering components to custom ComponentRegistry","text":"

If you are writing a component library to be shared with others, you may want to manage your own instance of ComponentRegistry and register components onto a different Library instance than the default one.

The Library instance can be set at instantiation of ComponentRegistry. If omitted, then the default Library instance from django_components is used.

from django.template import Library\nfrom django_components import ComponentRegistry\n\nmy_library = Library(...)\nmy_registry = ComponentRegistry(library=my_library)\n

When you have defined your own ComponentRegistry, you can either register the components with my_registry.register(), or pass the registry to the @component.register() decorator via the registry kwarg:

from path.to.my.registry import my_registry\n\n@register(\"my_component\", registry=my_registry)\nclass MyComponent(Component):\n    ...\n

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

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

When you are creating an instance of ComponentRegistry, you can define the components' behavior within the template.

The registry accepts these settings:

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

These settings are the same as the ones you can set for django_components.

In fact, when you set COMPONENT.tag_formatter or COMPONENT.context_behavior, these are forwarded to the default ComponentRegistry.

This makes it possible to have multiple registries with different settings in one projects, and makes sharing of component libraries possible.

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

New in version 0.96

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

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

Hook that runs just before the component's template is rendered.

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

def on_render_before(self, context, template) -> None:\n    # Insert value into the Context\n    context[\"from_on_before\"] = \":)\"\n\n    # Append text into the Template\n    template.nodelist.append(TextNode(\"FROM_ON_BEFORE\"))\n
  • on_render_after
def on_render_after(\n    self: Component,\n    context: Context,\n    template: Template,\n    content: str\n) -> None | str | SafeString:\n

Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.

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

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

def on_render_after(self, context, template, content):\n    # Prepend text to the rendered content\n    return \"Chocolate cookie recipe: \" + content\n
"},{"location":"concepts/advanced/hooks/#component-hooks-example","title":"Component hooks 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_tragments/","title":"HTML fragments","text":"

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

When you define a component that has extra JS or CSS, and you use django-components to render the fragment, django-components will:

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

Info

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

It is one of the methods for updating the state in the browser UI upon user interaction.

How it works is that:

  1. User makes an action - clicks a button or submits a form
  2. The action causes a request to be made from the client to the server.
  3. Server processes the request (e.g. form submission), and responds with HTML of some part of the UI (e.g. a new entry in a table).
  4. A library like HTMX, AlpineJS, or custom function inserts the new HTML into the correct place.
"},{"location":"concepts/advanced/html_tragments/#document-and-fragment-types","title":"Document and fragment types","text":"

Components support two modes of rendering - As a \"document\" or as a \"fragment\".

What's the difference?

"},{"location":"concepts/advanced/html_tragments/#document-mode","title":"Document mode","text":"

Document mode assumes that the rendered components will be embedded into the HTML of the initial page load. This means that:

  • The JS and CSS is embedded into the HTML as <script> and <style> tags (see JS and CSS output locations)
  • Django-components injects a JS script for managing JS and CSS assets

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

  • It is embedded inside a template as {% component %}
  • It is rendered with Component.render() or Component.render_to_response() with the type kwarg set to \"document\" (default)

Example:

MyTable.render(\n    kwargs={...},\n)\n\n# or\n\nMyTable.render(\n    kwargs={...},\n    type=\"document\",\n)\n
"},{"location":"concepts/advanced/html_tragments/#fragment-mode","title":"Fragment mode","text":"

Fragment mode assumes that the main HTML has already been rendered and loaded on the page. The component renders HTML that will be inserted into the page as a fragment, at a LATER time:

  • JS and CSS is not directly embedded to avoid duplicately executing the same JS scripts. So template tags like {% component_js_dependencies %} inside of fragments are ignored.
  • Instead, django-components appends the fragment's content with a JSON <script> to trigger a call to its asset manager JS script, which will load the JS and CSS smartly.
  • The asset manager JS script is assumed to be already loaded on the page.

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

  • It is rendered with Component.render() or Component.render_to_response() with the type kwarg set to \"fragment\"

Example:

MyTable.render(\n    kwargs={...},\n    type=\"fragment\",\n)\n
"},{"location":"concepts/advanced/html_tragments/#live-examples","title":"Live examples","text":"

For live interactive examples, start our demo project (sampleproject).

Then navigate to these URLs:

  • /fragment/base/alpine
  • /fragment/base/htmx
  • /fragment/base/js
"},{"location":"concepts/advanced/html_tragments/#example-htmx","title":"Example - HTMX","text":""},{"location":"concepts/advanced/html_tragments/#1-define-document-html","title":"1. Define document HTML","text":"[root]/components/demo.py
from django_components import Component, types\n\n# HTML into which a fragment will be loaded using HTMX\nclass MyPage(Component):\n    def get(self, request):\n        return self.render_to_response()\n\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
"},{"location":"concepts/advanced/html_tragments/#2-define-fragment-html","title":"2. Define fragment HTML","text":"[root]/components/demo.py
class Frag(Component):\n    def get(self, request):\n        return self.render_to_response(\n            # IMPORTANT: Don't forget `type=\"fragment\"`\n            type=\"fragment\",\n        )\n\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
"},{"location":"concepts/advanced/html_tragments/#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_tragments/#example-alpinejs","title":"Example - AlpineJS","text":""},{"location":"concepts/advanced/html_tragments/#1-define-document-html_1","title":"1. Define document HTML","text":"[root]/components/demo.py
from django_components import Component, types\n\n# HTML into which a fragment will be loaded using AlpineJS\nclass MyPage(Component):\n    def get(self, request):\n        return self.render_to_response()\n\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
"},{"location":"concepts/advanced/html_tragments/#2-define-fragment-html_1","title":"2. Define fragment HTML","text":"[root]/components/demo.py
class Frag(Component):\n    def get(self, request):\n        # IMPORTANT: Don't forget `type=\"fragment\"`\n        return self.render_to_response(\n            type=\"fragment\",\n        )\n\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
"},{"location":"concepts/advanced/html_tragments/#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_tragments/#example-vanilla-js","title":"Example - Vanilla JS","text":""},{"location":"concepts/advanced/html_tragments/#1-define-document-html_2","title":"1. Define document HTML","text":"[root]/components/demo.py
from django_components import Component, types\n\n# HTML into which a fragment will be loaded using JS\nclass MyPage(Component):\n    def get(self, request):\n        return self.render_to_response()\n\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
"},{"location":"concepts/advanced/html_tragments/#2-define-fragment-html_2","title":"2. Define fragment HTML","text":"[root]/components/demo.py
class Frag(Component):\n    def get(self, request):\n        return self.render_to_response(\n            # IMPORTANT: Don't forget `type=\"fragment\"`\n            type=\"fragment\",\n        )\n\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
"},{"location":"concepts/advanced/html_tragments/#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 or ContextProvider pattern with the combination of:

  1. {% provide %} tag
  2. inject() method of the Component class
"},{"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.

"},{"location":"concepts/advanced/provide_inject/#how-to-use-provide-inject","title":"How to use provide / inject","text":"

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/#using-provide-tag","title":"Using {% provide %} tag","text":"

First we use the {% provide %} tag to define the data we want to \"provide\" (make available).

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

Notice that the provide tag REQUIRES a name as a first argument. This is the key by which we can then access the data passed to this tag.

provide tag name must resolve to a valid identifier (AKA a valid Python variable name).

Once you've set the name, you define the data you want to \"provide\" by passing it as keyword arguments. This is similar to how you pass data to the {% with %} tag.

NOTE: Kwargs passed to {% provide %} are NOT added to the context. In the example below, the {{ key }} won't render anything:

{% provide \"my_data\" key=\"hi\" another=123 %}\n    {{ key }}\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:

{% provide name=name ... %}\n    ...\n{% provide %}\n</table>\n
"},{"location":"concepts/advanced/provide_inject/#using-inject-method","title":"Using inject() method","text":"

To \"inject\" (access) the data defined on the provide tag, you can use the inject() method inside of get_context_data().

For a component to be able to \"inject\" some data, the component ({% component %} tag) must be nested inside the {% provide %} tag.

In the example from previous section, we've defined two kwargs: key=\"hi\" another=123. That means that if we now inject \"my_data\", we get an object with 2 attributes - key and another.

class ChildComponent(Component):\n    def get_context_data(self):\n        my_data = self.inject(\"my_data\")\n        print(my_data.key)     # hi\n        print(my_data.another) # 123\n        return {}\n

First argument to inject is the key (or name) of the provided data. This must match the string that you used in the provide tag. If no provider with given key is found, inject raises a KeyError.

To avoid the error, you can pass a second argument to inject to which will act as a default value, similar to dict.get(key, default):

class ChildComponent(Component):\n    def get_context_data(self):\n        my_data = self.inject(\"invalid_key\", DEFAULT_DATA)\n        assert my_data == DEFAUKT_DATA\n        return {}\n

The instance returned from inject() is a subclass of NamedTuple, so the instance is immutable. This ensures that the data returned from inject will always have all the keys that were passed to the provide tag.

NOTE: inject() works strictly only in get_context_data. If you try to call it from elsewhere, it will raise an error.

"},{"location":"concepts/advanced/provide_inject/#full-example","title":"Full example","text":"
@register(\"child\")\nclass ChildComponent(Component):\n    template = \"\"\"\n        <div> {{ my_data.key }} </div>\n        <div> {{ my_data.another }} </div>\n    \"\"\"\n\n    def get_context_data(self):\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\" key=\"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/#js-and-css-output-locations","title":"JS and CSS output locations","text":"

If:

  1. Your components use JS and CSS via any of:
    • Component.css
    • Component.js
    • Component.Media.css
    • Component.Media.js
  2. And you use the ComponentDependencyMiddleware middleware

Then, by default, the components' JS and CSS will be automatically inserted into the HTML:

  • CSS styles will be inserted at the end of the <head>
  • JS scripts will be inserted at the end of the <body>

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

  • {% component_js_dependencies %} - Set new location(s) for JS scripts
  • {% component_css_dependencies %} - Set new location(s) for CSS styles

So if you have a component with JS and CSS:

from django_components import Component, types\n\nclass MyButton(Component):\n    template: types.django_html = \"\"\"\n        <button class=\"my-button\">\n            Click me!\n        </button>\n    \"\"\"\n    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    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 the JS from MyButton.js and MyButton.Media.js will be rendered at the default place, or in {% component_js_dependencies %}.

And the CSS from MyButton.css and MyButton.Media.css will be rendered at the default place, or in {% component_css_dependencies %}.

And if you don't specify {% component_dependencies %} tags, it is the equivalent of:

<!doctype html>\n<html>\n  <head>\n    <title>MyPage</title>\n    ...\n    {% component_css_dependencies %}\n  </head>\n  <body>\n    <main>\n      ...\n    </main>\n    {% component_js_dependencies %}\n  </body>\n</html>\n
"},{"location":"concepts/advanced/rendering_js_css/#setting-up-the-middleware","title":"Setting up the middleware","text":"

ComponentDependencyMiddleware is a Django middleware designed to manage and inject CSS / JS dependencies of rendered components dynamically. It ensures that only the necessary stylesheets and scripts are loaded in your HTML responses, based on the components used in your Django templates.

To set it up, add the middleware to your MIDDLEWARE in settings.py:

MIDDLEWARE = [\n    # ... other middleware classes ...\n    'django_components.middleware.ComponentDependencyMiddleware'\n    # ... other middleware classes ...\n]\n
"},{"location":"concepts/advanced/rendering_js_css/#render_dependencies-and-rendering-js-css-without-the-middleware","title":"render_dependencies and rendering JS / CSS without the middleware","text":"

For most scenarios, using the ComponentDependencyMiddleware middleware will be just fine.

However, this section is for you if you want to:

  • Render HTML that will NOT be sent as a server response
  • Insert pre-rendered HTML into another component
  • Render HTML fragments (partials)

Every time there is an HTML string that has parts which were rendered using components, and any of those components has JS / CSS, then this HTML string MUST be processed with render_dependencies().

It is actually render_dependencies() that finds all used components in the HTML string, and inserts the component's JS and CSS into {% component_dependencies %} tags, or at the default locations.

"},{"location":"concepts/advanced/rendering_js_css/#render-js-css-without-the-middleware","title":"Render JS / CSS without the middleware","text":"

The truth is that the ComponentDependencyMiddleware middleware just calls render_dependencies(), passing in the HTML content. So if you render a template that contained {% component %} tags, you MUST pass the result through render_dependencies(). And the middleware is just one of the options.

Here is how you can achieve the same, without the middleware, using render_dependencies():

from django.template.base import Template\nfrom django.template.context import Context\nfrom django_component 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())\nrendered = render_dependencies(rendered)\n

Same applies if you render a template using Django's django.shortcuts.render:

from django.shortcuts import render\n\ndef my_view(request):\n    rendered = render(request, \"pages/home.html\")\n    rendered = render_dependencies(rendered)\n    return rendered\n

Alternatively, when you render HTML with Component.render() or Component.render_to_response(), these, by default, call render_dependencies() for you, so you don't have to:

from django_components import Component\n\nclass MyButton(Component):\n    ...\n\n# No need to call `render_dependencies()`\nrendered = MyButton.render()\n
"},{"location":"concepts/advanced/rendering_js_css/#inserting-pre-rendered-html-into-another-component","title":"Inserting pre-rendered HTML into another component","text":"

In previous section we've shown that render_dependencies() does NOT need to be called when you render a component via Component.render().

API of django_components makes it possible to compose components in a \"React-like\" way, where we pre-render a piece of HTML and then insert it into a larger structure.

To do this, you must add render_dependencies=False to the nested components:

card_actions = CardActions.render(\n    kwargs={\"editable\": editable},\n    render_dependencies=False,\n)\n\ncard = Card.render(\n    slots={\"actions\": card_actions},\n    render_dependencies=False,\n)\n\npage = MyPage.render(\n    slots={\"card\": card},\n)\n

Why is render_dependencies=False required?

This is a technical limitation of the current implementation.

As mentioned earlier, each time we call Component.render(), we also call render_dependencies().

However, there is a problem here - When we call render_dependencies() inside CardActions.render(), we extract and REMOVE the info on components' JS and CSS from the HTML. But the template of CardActions contains no {% component_depedencies %} tags, and nor <head> nor <body> HTML tags. So the component's JS and CSS will NOT be inserted, and will be lost.

To work around this, you must set render_dependencies=False when rendering pieces of HTML with Component.render() and inserting them into larger structures.

"},{"location":"concepts/advanced/rendering_js_css/#summary","title":"Summary","text":"
  1. Every time you render HTML that contained components, you have to call render_dependencies() on the rendered output.
  2. There are several ways to call render_dependencies():
    • Using the ComponentDependencyMiddleware middleware
    • Rendering the HTML by calling Component.render() with render_dependencies=True (default)
    • Rendering the HTML by calling Component.render_to_response() (always renders dependencies)
    • Directly passing rendered HTML to render_dependencies()
  3. If you pre-render one component to pass it into another, the pre-rendered component must be rendered with render_dependencies=False.
"},{"location":"concepts/advanced/tag_formatter/","title":"Tag formatters","text":""},{"location":"concepts/advanced/tag_formatter/#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_formatter/#available-tagformatters","title":"Available TagFormatters","text":"

django_components provides following predefined TagFormatters:

  • ComponentFormatter (django_components.component_formatter)

Default

Uses the component and endcomponent tags, and the component name is gives as the first positional argument.

Example as block:

{% component \"button\" href=\"...\" %}\n    {% fill \"content\" %}\n        ...\n    {% endfill %}\n{% endcomponent %}\n

Example as inlined tag:

{% component \"button\" href=\"...\" / %}\n
  • ShorthandComponentFormatter (django_components.component_shorthand_formatter)

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

Example as block:

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

Example as inlined tag:

{% button href=\"...\" / %}\n
"},{"location":"concepts/advanced/tag_formatter/#writing-your-own-tagformatter","title":"Writing your own TagFormatter","text":""},{"location":"concepts/advanced/tag_formatter/#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_formatter/#tagformatter","title":"TagFormatter","text":"

TagFormatter handles following parts of the process above:

  • Generates start/end tags, given a component. This is what you then call from within your template as {% component %}.

  • When you {% component %}, tag formatter pre-processes the tag contents, so it can link back the custom template tag to the right component.

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

  • start_tag
  • end_tag
  • parse

For example, this is the implementation of ShorthandComponentFormatter

class ShorthandComponentFormatter(TagFormatterABC):\n    # Given a component name, generate the start template tag\n    def start_tag(self, name: str) -> str:\n        return name  # e.g. 'button'\n\n    # Given a component name, generate the start template tag\n    def end_tag(self, name: str) -> str:\n        return f\"end{name}\"  # e.g. 'endbutton'\n\n    # Given a tag, e.g.\n    # `{% button href=\"...\" disabled %}`\n    #\n    # The parser receives:\n    # `['button', 'href=\"...\"', 'disabled']`\n    def parse(self, tokens: List[str]) -> TagResult:\n        tokens = [*tokens]\n        name = tokens.pop(0)\n        return TagResult(\n            name,  # e.g. 'button'\n            tokens  # e.g. ['href=\"...\"', 'disabled']\n        )\n

That's it! And once your TagFormatter is ready, don't forget to update the settings!

"},{"location":"concepts/advanced/typing_and_validation/","title":"Typing and validation","text":""},{"location":"concepts/advanced/typing_and_validation/#adding-type-hints-with-generics","title":"Adding type hints with Generics","text":"

New in version 0.92

The Component class optionally accepts type parameters that allow you to specify the types of args, kwargs, slots, and data:

class Button(Component[Args, Kwargs, Slots, Data, JsData, CssData]):\n    ...\n
  • Args - Must be a Tuple or Any
  • Kwargs - Must be a TypedDict or Any
  • Data - Must be a TypedDict or Any
  • Slots - Must be a TypedDict or Any

Here's a full example:

from typing import NotRequired, Tuple, TypedDict, SlotContent, SlotFunc\n\n# Positional inputs\nArgs = Tuple[int, str]\n\n# Kwargs inputs\nclass Kwargs(TypedDict):\n    variable: str\n    another: int\n    maybe_var: NotRequired[int] # May be ommited\n\n# Data returned from `get_context_data`\nclass Data(TypedDict):\n    variable: str\n\n# The data available to the `my_slot` scoped slot\nclass MySlotData(TypedDict):\n    value: int\n\n# Slots\nclass Slots(TypedDict):\n    # Use SlotFunc for slot functions.\n    # The generic specifies the `data` dictionary\n    my_slot: NotRequired[SlotFunc[MySlotData]]\n    # SlotContent == Union[str, SafeString]\n    another_slot: SlotContent\n\nclass Button(Component[Args, Kwargs, Slots, Data, JsData, CssData]):\n    def get_context_data(self, variable, another):\n        return {\n            \"variable\": variable,\n        }\n

When you then call Component.render or Component.render_to_response, you will get type hints:

Button.render(\n    # Error: First arg must be `int`, got `float`\n    args=(1.25, \"abc\"),\n    # Error: Key \"another\" is missing\n    kwargs={\n        \"variable\": \"text\",\n    },\n)\n
"},{"location":"concepts/advanced/typing_and_validation/#usage-for-python-311","title":"Usage for Python <3.11","text":"

On Python 3.8-3.10, use typing_extensions

from typing_extensions import TypedDict, NotRequired\n

Additionally on Python 3.8-3.9, also import annotations:

from __future__ import annotations\n

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

See PEP-655 for more info.

"},{"location":"concepts/advanced/typing_and_validation/#passing-additional-args-or-kwargs","title":"Passing additional args or kwargs","text":"

You may have a function that supports any number of args or kwargs:

def get_context_data(self, *args, **kwargs):\n    ...\n

This is not supported with the typed components.

As a workaround:

  • For *args, set a positional argument that accepts a list of values:
# Tuple of one member of list of strings\nArgs = Tuple[List[str]]\n
  • For *kwargs, set a keyword argument that accepts a dictionary of values:
class Kwargs(TypedDict):\n    variable: str\n    another: int\n    # Pass any extra keys under `extra`\n    extra: Dict[str, any]\n
"},{"location":"concepts/advanced/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, you can use EmptyTuple and EmptyDict types:

from django_components import Component, EmptyDict, EmptyTuple\n\nArgs = EmptyTuple\nKwargs = Data = Slots = EmptyDict\n\nclass Button(Component[Args, Kwargs, Slots, Data, JsData, CssData]):\n    ...\n
"},{"location":"concepts/advanced/typing_and_validation/#runtime-input-validation-with-types","title":"Runtime input validation with types","text":"

New in version 0.96

NOTE: Kwargs, slots, and data validation is supported only for Python >=3.11

In Python 3.11 and later, when you specify the component types, you will get also runtime validation of the inputs you pass to Component.render or Component.render_to_response.

So, using the example from before, if you ignored the type errors and still ran the following code:

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

This would raise a TypeError:

Component 'Button' expected positional argument at index 0 to be <class 'int'>, got 1.25 of type <class 'float'>\n

In case you need to skip these errors, you can either set the faulty member to Any, e.g.:

# Changed `int` to `Any`\nArgs = Tuple[Any, str]\n

Or you can replace Args with Any altogether, to skip the validation of args:

# Replaced `Args` with `Any`\nclass Button(Component[Any, Kwargs, Slots, Data, JsData, CssData]):\n    ...\n

Same applies to kwargs, data, and slots.

"},{"location":"concepts/fundamentals/access_component_input/","title":"Accessing component inputs","text":"

When you call Component.render or Component.render_to_response, the inputs to these methods can be accessed from within the instance under self.input.

This means that you can use self.input inside:

  • get_context_data
  • get_template_name
  • get_template
  • on_render_before
  • on_render_after

self.input is only defined during the execution of Component.render, and raises a RuntimeError when called outside of this context.

self.input has the same fields as the input to Component.render:

class TestComponent(Component):\n    def get_context_data(self, var1, var2, variable, another, **attrs):\n        assert self.input.args == (123, \"str\")\n        assert self.input.kwargs == {\"variable\": \"test\", \"another\": 1}\n        assert self.input.slots == {\"my_slot\": \"MY_SLOT\"}\n        assert isinstance(self.input.context, Context)\n\n        return {\n            \"variable\": variable,\n        }\n\nrendered = TestComponent.render(\n    kwargs={\"variable\": \"test\", \"another\": 1},\n    args=(123, \"str\"),\n    slots={\"my_slot\": \"MY_SLOT\"},\n)\n

NOTE: The slots in self.input.slots are normalized to slot functions.

"},{"location":"concepts/fundamentals/autodiscovery/","title":"Autodiscovery","text":"

Every component that you want to use in the template with the {% component %} tag needs to be registered with the ComponentRegistry. Normally, we use the @register decorator for that:

from django_components import Component, register\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.

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!

By default, the Python files in the COMPONENTS.dirs directories (and app-level [app]/components/) are auto-imported in order to auto-register the components.

Autodiscovery occurs when Django is loaded, during the AppConfig.ready hook of the apps.py file.

If you are using autodiscovery, keep a few points in mind:

  • Avoid defining any logic on the module-level inside the components dir, that you would not want to run anyway.
  • Components inside the auto-imported files still need to be registered with @register
  • Auto-imported component files must be valid Python modules, they must use suffix .py, and module name should follow PEP-8.
  • Subdirectories and files starting with an underscore _ (except __init__.py) are ignored.

Autodiscovery can be disabled in the settings.

"},{"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_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_context_data by accessing the property self.outer_context.

"},{"location":"concepts/fundamentals/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_context_data. Here's how you might implement it:

class Calender(Component):\n\n    ...\n\n    def get_context_data(self):\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/fundamentals/component_context_scope/#context-behavior","title":"Context behavior","text":"

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

This has two modes:

  • \"django\"

    The default Django template behavior.

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

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

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

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

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

Warning

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

Consider this example:

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

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

"},{"location":"concepts/fundamentals/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_context_data(self):\n        return { \"my_var\": 123 }\n

Then if get_context_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/fundamentals/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_context_data(self):\n        return { \"my_var\": 123 }\n

Then if get_context_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_context_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/fundamentals/components_as_views/","title":"Components as views","text":"

New in version 0.34

Note: Since 0.92, Component no longer subclasses View. To configure the View class, set the nested Component.View class

Components can now be used as views:

  • Components define the Component.as_view() class method that can be used the same as View.as_view().

  • By default, you can define GET, POST or other HTTP handlers directly on the Component, same as you do with View. For example, you can override get and post to handle GET and POST requests, respectively.

  • In addition, Component now has a render_to_response method that renders the component template based on the provided context and slots' data and returns an HttpResponse object.

"},{"location":"concepts/fundamentals/components_as_views/#component-as-view-example","title":"Component as view example","text":"

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

# In a file called [project root]/components/calendar.py\nfrom django_components import Component, ComponentView, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n\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    # Handle GET requests\n    def get(self, request, *args, **kwargs):\n        context = {\n            \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n        }\n        slots = {\n            \"header\": \"Calendar header\",\n        }\n        # Return HttpResponse with the rendered content\n        return self.render_to_response(\n            context=context,\n            slots=slots,\n        )\n

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

# In a file called [project root]/components/urls.py\nfrom django.urls import path\nfrom components.calendar.calendar import Calendar\n\nurlpatterns = [\n    path(\"calendar/\", Calendar.as_view()),\n]\n

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

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

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

# In a file called [project root]/urls.py\nfrom django.urls import include, path\n\nurlpatterns = [\n    path(\"components/\", include(\"components.urls\")),\n]\n

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

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

"},{"location":"concepts/fundamentals/components_as_views/#modifying-the-view-class","title":"Modifying the View class","text":"

The View class that handles the requests is defined on Component.View.

When you define a GET or POST handlers on the Component class, like so:

class MyComponent(Component):\n    def get(self, request, *args, **kwargs):\n        return self.render_to_response(\n            context={\n                \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n            },\n        )\n\n    def post(self, request, *args, **kwargs) -> HttpResponse:\n        variable = request.POST.get(\"variable\")\n        return self.render_to_response(\n            kwargs={\"variable\": variable}\n        )\n

Then the request is still handled by Component.View.get() or Component.View.post() methods. However, by default, Component.View.get() points to Component.get(), and so on.

class ComponentView(View):\n    component: Component = None\n    ...\n\n    def get(self, request, *args, **kwargs):\n        return self.component.get(request, *args, **kwargs)\n\n    def post(self, request, *args, **kwargs):\n        return self.component.post(request, *args, **kwargs)\n\n    ...\n

If you want to define your own View class, you need to:

  1. Set the class as Component.View
  2. Subclass from ComponentView, so the View instance has access to the component instance.

In the example below, we added extra logic into View.setup().

Note that the POST handler is still defined at the top. This is because View subclasses ComponentView, which defines the post() method that calls Component.post().

If you were to overwrite the View.post() method, then Component.post() would be ignored.

from django_components import Component, ComponentView\n\nclass MyComponent(Component):\n\n    def post(self, request, *args, **kwargs) -> HttpResponse:\n        variable = request.POST.get(\"variable\")\n        return self.component.render_to_response(\n            kwargs={\"variable\": variable}\n        )\n\n    class View(ComponentView):\n        def setup(self, request, *args, **kwargs):\n            super(request, *args, **kwargs)\n\n            do_something_extra(request, *args, **kwargs)\n
"},{"location":"concepts/fundamentals/components_in_python/","title":"Components in Python","text":"

New in version 0.81

Components can be rendered outside of Django templates, calling them as regular functions (\"React-style\").

The component class defines render and render_to_response class methods. These methods accept positional args, kwargs, and slots, offering the same flexibility as the {% component %} tag:

class SimpleComponent(Component):\n    template = \"\"\"\n        {% load component_tags %}\n        hello: {{ hello }}\n        foo: {{ foo }}\n        kwargs: {{ kwargs|safe }}\n        slot_first: {% slot \"first\" required / %}\n    \"\"\"\n\n    def get_context_data(self, arg1, arg2, **kwargs):\n        return {\n            \"hello\": arg1,\n            \"foo\": arg2,\n            \"kwargs\": kwargs,\n        }\n\nrendered = SimpleComponent.render(\n    args=[\"world\", \"bar\"],\n    kwargs={\"kw1\": \"test\", \"kw2\": \"ooo\"},\n    slots={\"first\": \"FIRST_SLOT\"},\n    context={\"from_context\": 98},\n)\n

Renders:

hello: world\nfoo: bar\nkwargs: {'kw1': 'test', 'kw2': 'ooo'}\nslot_first: FIRST_SLOT\n
"},{"location":"concepts/fundamentals/components_in_python/#inputs-of-render-and-render_to_response","title":"Inputs of render and render_to_response","text":"

Both render and render_to_response accept the same input:

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

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

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

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

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

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

  • request - A Django request object. This is used to enable Django template context_processors to run, allowing for template tags like {% csrf_token %} and variables like {{ debug }}.

  • Similar behavior can be achieved with provide / inject.
  • This is used internally to convert context to a RequestContext. It does nothing if context is already a Context instance.
"},{"location":"concepts/fundamentals/components_in_python/#slotfunc","title":"SlotFunc","text":"

When rendering components with slots in render or render_to_response, you can pass either a string or a function.

The function has following signature:

def render_func(\n   context: Context,\n   data: Dict[str, Any],\n   slot_ref: SlotRef,\n) -> str | SafeString:\n    return nodelist.render(ctx)\n
  • context - Django's Context available to the Slot Node.
  • data - Data passed to the {% slot %} tag. See Scoped Slots.
  • slot_ref - The default slot content. See Accessing original content of slots.
  • NOTE: The slot is lazily evaluated. To render the slot, convert it to string with str(slot_ref).

Example:

def footer_slot(ctx, data, slot_ref):\n   return f\"\"\"\n      SLOT_DATA: {data['abc']}\n      ORIGINAL: {slot_ref}\n   \"\"\"\n\nMyComponent.render_to_response(\n    slots={\n        \"footer\": footer_slot,\n   },\n)\n
"},{"location":"concepts/fundamentals/components_in_python/#response-class-of-render_to_response","title":"Response class of render_to_response","text":"

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

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

class MyResponse(HttpResponse):\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 = MyResponse\n   template: types.django_html = \"HELLO\"\n\nresponse = SimpleComponent.render_to_response()\nassert isinstance(response, MyResponse)\n
"},{"location":"concepts/fundamentals/defining_js_css_html_files/","title":"Defining HTML / JS / CSS files","text":"

As you could have seen in the tutorial, there's multiple ways how you can associate HTML / JS / CSS with a component:

  • You can set Component.template, Component.css and Component.js to define the main HTML / CSS / JS for a component as inlined code.
  • You can set Component.template_file, Component.css_file and Component.js_file to define the main HTML / CSS / JS for a component in separate files.
  • You can link additional CSS / JS files using Component.Media.js and Component.Media.css.

Warning

You cannot use both inlined code and separate file for a single language type:

  • You can only either set Component.template or Component.template_file
  • You can only either set Component.css or Component.css_file
  • You can only either set Component.js or Component.js_file

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

Note

django-component's management of files is inspired by Django's Media class.

To be familiar with how Django handles static files, we recommend reading also:

  • How to manage static files (e.g. images, JavaScript, CSS)
"},{"location":"concepts/fundamentals/defining_js_css_html_files/#defining-file-paths-relative-to-component","title":"Defining file paths 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/defining_js_css_html_files/#defining-additional-js-and-css-files","title":"Defining additional JS and CSS files","text":"

Each component can have only a single template, and single main JS and CSS. However, you can define additional JS or CSS using the nested Component.Media class.

This Media class behaves similarly to Django's Media class:

  • Paths are generally handled as static file paths, and resolved URLs are rendered to HTML with media_class.render_js() or media_class.render_css().
  • A path that starts with http, https, or / is considered a URL, skipping the static file resolution. This path is still rendered to HTML with media_class.render_js() or media_class.render_css().
  • A SafeString, or a function (with __html__ method) is considered an already-formatted HTML tag, skipping both static file resolution and rendering with media_class.render_js() or media_class.render_css().

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. Our Media class does NOT support Django's extend keyword
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":"concepts/fundamentals/defining_js_css_html_files/#configuring-css-media-types","title":"Configuring 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

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/defining_js_css_html_files/#supported-types-for-file-paths","title":"Supported types for file paths","text":"

File paths can be any of:

  • str
  • bytes
  • PathLike (__fspath__ method)
  • SafeData (__html__ method)
  • Callable that returns any of the above, evaluated at class creation (__new__)

See 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/defining_js_css_html_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 full <script>/<link> tag.

This is an extension of Django's Paths as objects feature, where \"safe\" strings are taken as is, and accessed only at render time.

Because of that, the paths defined as \"safe\" strings are NEVER resolved, neither relative to component's directory, nor relative to COMPONENTS.dirs.

\"Safe\" strings can be used to lazily resolve a path, or to customize the <script> or <link> tag for individual paths:

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.

class ModuleJsPath:\n    def __init__(self, static_path: str) -> None:\n        self.static_path = static_path\n\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    def get_context_data(self, date):\n        return {\n            \"date\": date,\n        }\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/defining_js_css_html_files/#customize-how-paths-are-rendered-into-html-tags","title":"Customize how paths are rendered into HTML tags","text":"

Sometimes you may need to change how all CSS <link> or JS <script> tags are rendered for a given component. You can achieve this by providing your own subclass of Django's Media class to component's media_class attribute.

Normally, the JS and CSS paths are passed to Media class, which decides how the paths are resolved and how the <link> and <script> tags are constructed.

To change how the tags are constructed, you can override the Media.render_js and Media.render_css methods:

from django.forms.widgets import Media\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/defining_js_css_html_files/#accessing-components-html-js-css","title":"Accessing component's HTML / JS / CSS","text":"

Component's HTML / CSS / JS is resolved and loaded lazily.

This means that, when you specify any of template_file, js_file, css_file, or Media.js/css, these file paths will be resolved only once you either:

  1. Access any of the following attributes on the component:

    • media, template, template_file, js, js_file, css, css_file
  2. Render the component.

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

  • HTML from Component.template_file will be available under Component.template
  • CSS from Component.css_file will be available under Component.css
  • JS from Component.js_file will be available under Component.js

Thus, whether you define HTML via Component.template_file or Component.template, you can always access the HTML content under Component.template. And the same applies for JS and CSS.

Example:

# When we create Calendar component, the files like `calendar/template.html`\n# are not yet loaded!\n@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"calendar/template.html\"\n    css_file = \"calendar/style.css\"\n    js_file = \"calendar/script.js\"\n\n    class Media:\n        css = \"calendar/style1.css\"\n        js = \"calendar/script2.js\"\n\n# It's only at this moment that django-components reads the files like `calendar/template.html`\nprint(Calendar.css)\n# Output:\n# .calendar {\n#   width: 200px;\n#   background: pink;\n# }\n

Warning

Do NOT modify HTML / CSS / JS after it has been loaded

django-components assumes that the component's media files like js_file or Media.js/css are static.

If you need to dynamically change these media files, consider instead defining multiple Components.

Modifying these files AFTER the component has been loaded at best does nothing. However, this is an untested behavior, which may lead to unexpected errors.

"},{"location":"concepts/fundamentals/defining_js_css_html_files/#accessing-components-media-files","title":"Accessing component's Media files","text":"

To access the files defined under Component.Media, you can access 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

If you want to modify the class that is instantiated for Component.media, you can configure Component.media_class (See example).

"},{"location":"concepts/fundamentals/html_attributes/","title":"HTML attributes","text":"

New in version 0.74:

You can use the html_attrs tag to render HTML attributes, given a dictionary of values.

So if you have a template:

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

You can simplify it with html_attrs tag:

<div {% html_attrs attrs %}>\n</div>\n

where attrs is:

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

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

"},{"location":"concepts/fundamentals/html_attributes/#removing-atttributes","title":"Removing atttributes","text":"

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

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/#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> <button>Click me!</button>\n

HTML rendering with html_attrs tag or attributes_to_string works the same way, where key=True is rendered simply as key, and key=False is not render at all.

So given this input:

attrs = {\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/#default-attributes","title":"Default attributes","text":"

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

<div {% html_attrs attrs defaults %}>\n    ...\n</div>\n

In the example above, if attrs contains e.g. the class key, html_attrs will render:

class=\"{{ attrs.class }}\"

Otherwise, html_attrs will render:

class=\"{{ defaults.class }}\"

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

We can achieve this by adding extra kwargs. These values will be appended, instead of overwriting the previous value.

So if we have a variable attrs:

attrs = {\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/#rules-for-html_attrs","title":"Rules for html_attrs","text":"
  1. Both attrs and defaults can be passed as positional args

{% html_attrs attrs defaults key=val %}

or as kwargs

{% html_attrs key=val defaults=defaults attrs=attrs %}

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

  2. Both attrs and defaults are dictionaries, and we can define them the same way we define dictionaries for the component tag. So either as attrs=attrs or attrs:key=value.

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

"},{"location":"concepts/fundamentals/html_attributes/#examples-for-html_attrs","title":"Examples for html_attrs","text":"

Assuming that:

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

Then:

  • Empty tag {% html_attr %}

renders (empty string):

  • Only kwargs {% html_attr class=\"some-class\" class=class_from_var data-id=\"123\" %}

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

  • Only attrs {% html_attr attrs %}

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

  • Attrs as kwarg {% html_attr attrs=attrs %}

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

  • Only defaults (as kwarg) {% html_attr defaults=defaults %}

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

  • Attrs using the prefix:key=value construct {% html_attr attrs:class=\"from-attrs\" attrs:type=\"submit\" %}

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

  • Defaults using the prefix:key=value construct {% html_attr defaults:class=\"from-defaults\" %}

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

  • All together (1) - attrs and defaults as positional args: {% html_attrs attrs defaults class=\"added_class\" class=class_from_var data-id=123 %}

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

  • All together (2) - attrs and defaults as kwargs args: {% html_attrs class=\"added_class\" class=class_from_var data-id=123 attrs=attrs defaults=defaults %}

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

  • All together (3) - mixed: {% html_attrs attrs defaults:class=\"default-class\" class=\"added_class\" class=class_from_var data-id=123 %}

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

"},{"location":"concepts/fundamentals/html_attributes/#full-example-for-html_attrs","title":"Full example for html_attrs","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_context_data(self, date: Date, attrs: dict):\n        return {\n            \"date\": date,\n            \"attrs\": attrs,\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_context_data(self, date: Date):\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\"

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_context_data of MyComp will receive attrs input 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_attributes/#rendering-html-attributes-outside-of-templates","title":"Rendering HTML attributes outside of templates","text":"

If you need to use serialize HTML attributes outside of Django template and the html_attrs tag, you can use attributes_to_string:

from django_components.attributes import attributes_to_string\n\nattrs = {\n    \"class\": \"my-class text-red pa-4\",\n    \"data-id\": 123,\n    \"required\": True,\n    \"disabled\": False,\n    \"ignored-attr\": None,\n}\n\nattributes_to_string(attrs)\n# 'class=\"my-class text-red pa-4\" data-id=\"123\" required'\n
"},{"location":"concepts/fundamentals/single_file_components/","title":"Single-file components","text":"

Components can be defined in a single file, which is useful for small components. To do this, you can use the template, js, and css class attributes instead of the template_file, js_file, and css_file.

For example, here's the calendar component from the Getting started tutorial, defined 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_context_data(self, date):\n        return {\n            \"date\": 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

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

To add syntax highlighting to these snippets, head over to Syntax highlighting.

"},{"location":"concepts/fundamentals/slots/","title":"Slots","text":"

New in version 0.26:

  • The slot tag now serves only to declare new slots inside the component template.
  • To override the content of a declared slot, use the newly introduced fill tag instead.
  • Whereas unfilled slots used to raise a warning, filling a slot is now optional by default.
  • To indicate that a slot must be filled, the new required option should be added at the end of the slot tag.

Components support something called 'slots'. When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content. This mechanism makes components more reusable and composable. This behavior is similar to slots in Vue.

In the example below we introduce two block tags that work hand in hand to make this work. These are...

  • {% slot <name> %}/{% endslot %}: Declares a new slot in the component template.
  • {% fill <name> %}/{% endfill %}: (Used inside a {% component %} tag pair.) Fills a declared slot with the specified content.

Let's update our calendar component to support more customization. We'll add slot tag pairs to its template, template.html.

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

When using the component, you specify which slots you want to fill and where you want to use the defaults from the template. It looks like this:

{% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"body\" %}\n        Can you believe it's already <span>{{ date }}</span>??\n    {% endfill %}\n{% endcomponent %}\n

Since the 'header' fill is unspecified, it's taken from the base template. If you put this in a template, and pass in date=2020-06-06, this is what gets rendered:

<div class=\"calendar-component\">\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/#named-slots","title":"Named slots","text":"

As seen in the previouse section, you can use {% fill slot_name %} to insert content into a specific slot.

You can define fills for multiple slot simply by defining them all within the {% component %} {% endcomponent %} tags:

{% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"header\" %}\n        Hi this is header!\n    {% endfill %}\n    {% fill \"body\" %}\n        Can you believe it's already <span>{{ date }}</span>??\n    {% endfill %}\n{% endcomponent %}\n

You can also use {% for %}, {% with %}, or other non-component tags (even {% include %}) to construct the {% fill %} tags, as long as these other tags do not leave any text behind!

{% component \"table\" %}\n  {% for slot_name in slots %}\n    {% fill name=slot_name %}\n      {{ slot_name }}\n    {% endfill %}\n  {% endfor %}\n\n  {% with slot_name=\"abc\" %}\n    {% fill name=slot_name %}\n      {{ slot_name }}\n    {% endfill %}\n  {% endwith %}\n{% endcomponent %}\n
"},{"location":"concepts/fundamentals/slots/#default-slot","title":"Default slot","text":"

Added in version 0.28

As you can see, component slots lets you write reusable containers that you fill in when you use a component. This makes for highly reusable components that can be used in different circumstances.

It can become tedious to use fill tags everywhere, especially when you're using a component that declares only one slot. To make things easier, slot tags can be marked with an optional keyword: default.

When added to the tag (as shown below), this option lets you pass filling content directly in the body of a component tag pair \u2013 without using a fill tag. Choose carefully, though: a component template may contain at most one slot that is marked as default. The default option can be combined with other slot options, e.g. required.

Here's the same example as before, except with default slots and implicit filling.

The template:

<div class=\"calendar-component\">\n    <div class=\"header\">\n        {% slot \"header\" %}Calendar header{% endslot %}\n    </div>\n    <div class=\"body\">\n        {% slot \"body\" default %}Today's date is <span>{{ date }}</span>{% endslot %}\n    </div>\n</div>\n

Including the component (notice how the fill tag is omitted):

{% component \"calendar\" date=\"2020-06-06\" %}\n    Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n

The rendered result (exactly the same as before):

<div class=\"calendar-component\">\n  <div class=\"header\">Calendar header</div>\n  <div class=\"body\">Can you believe it's already <span>2020-06-06</span>??</div>\n</div>\n

You may be tempted to combine implicit fills with explicit fill tags. This will not work. The following component template will raise an error when rendered.

{# DON'T DO THIS #}\n{% 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

Instead, you can use a named fill with name default to target the default fill:

{# THIS WORKS #}\n{% 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

NOTE: If you doubly-fill a slot, that is, that both {% fill \"default\" %} and {% fill \"header\" %} would point to the same slot, this will raise an error when rendered.

"},{"location":"concepts/fundamentals/slots/#accessing-default-slot-in-python","title":"Accessing default slot in Python","text":"

Since the default slot is stored under the slot name default, you can access the default slot like so:

class MyTable(Component):\n    def get_context_data(self, *args, **kwargs):\n        default_slot = self.input.slots[\"default\"]\n        return {\n            \"default_slot\": default_slot,\n        }\n
"},{"location":"concepts/fundamentals/slots/#render-fill-in-multiple-places","title":"Render fill in multiple places","text":"

Added in version 0.70

You can render the same content in multiple places by defining multiple slots with identical names:

<div class=\"calendar-component\">\n    <div class=\"header\">\n        {% slot \"image\" %}Image here{% endslot %}\n    </div>\n    <div class=\"body\">\n        {% slot \"image\" %}Image here{% endslot %}\n    </div>\n</div>\n

So if used like:

{% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"image\" %}\n        <img src=\"...\" />\n    {% endfill %}\n{% endcomponent %}\n

This renders:

<div class=\"calendar-component\">\n    <div class=\"header\">\n        <img src=\"...\" />\n    </div>\n    <div class=\"body\">\n        <img src=\"...\" />\n    </div>\n</div>\n
"},{"location":"concepts/fundamentals/slots/#default-and-required-slots","title":"Default and required slots","text":"

If you use a slot multiple times, you can still mark the slot as default or required. For that, you must mark each slot individually, 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

Which you can then use as regular default slot:

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

Since each slot is tagged individually, you can 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 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    {% if image_src %}\n        {% slot \"image\" default %}\n            <img src=\"{{ image_src }}\" />\n        {% endslot %}\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    {% else %}\n        {% slot \"image\" default required / %}\n    {% endif %}\n</div>\n
"},{"location":"concepts/fundamentals/slots/#accessing-original-content-of-slots","title":"Accessing original content of slots","text":"

Added in version 0.26

NOTE: In version 0.77, the syntax was changed from

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

to

{% fill \"my_slot\" default=\"slot_default\" %} {{ slot_default }}\n

Sometimes you may want to keep the original slot, but only wrap or prepend/append content to it. To do so, you can access the default slot via the default kwarg.

Similarly to the data attribute, you specify the variable name through which the default slot will be made available.

For instance, let's say you're filling a slot called 'body'. To render the original slot, assign it to a variable using the 'default' keyword. You then render this variable to insert the default content:

{% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"body\" default=\"body_default\" %}\n        {{ body_default }}. Have a great day!\n    {% endfill %}\n{% endcomponent %}\n

This produces:

<div class=\"calendar-component\">\n    <div class=\"header\">\n        Calendar header\n    </div>\n    <div class=\"body\">\n        Today's date is <span>2020-06-06</span>. Have a great day!\n    </div>\n</div>\n

To access the original content of a default slot, set the name to default:

{% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"default\" default=\"slot_default\" %}\n        {{ slot_default }}. Have a great day!\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"concepts/fundamentals/slots/#conditional-slots","title":"Conditional slots","text":"

Added in version 0.26.

NOTE: In version 0.70, {% if_filled %} tags were replaced with {{ component_vars.is_filled }} variables. If your slot name contained special characters, see the section Accessing is_filled of slot names with special characters.

In certain circumstances, you may want the behavior of slot filling to depend on whether or not a particular slot is filled.

For example, suppose we have the following component template:

<div class=\"frontmatter-component\">\n    <div class=\"title\">\n        {% slot \"title\" %}Title{% endslot %}\n    </div>\n    <div class=\"subtitle\">\n        {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n    </div>\n</div>\n

By default the slot named 'subtitle' is empty. Yet when the component is used without explicit fills, the div containing the slot is still rendered, as shown below:

<div class=\"frontmatter-component\">\n  <div class=\"title\">Title</div>\n  <div class=\"subtitle\"></div>\n</div>\n

This may not be what you want. What if instead the outer 'subtitle' div should only be included when the inner slot is in fact filled?

The answer is to use the {{ component_vars.is_filled.<name> }} variable. You can use this together with Django's {% if/elif/else/endif %} tags to define a block whose contents will be rendered only if the component slot with the corresponding 'name' is filled.

This is what our example looks like with component_vars.is_filled.

<div class=\"frontmatter-component\">\n    <div class=\"title\">\n        {% slot \"title\" %}Title{% endslot %}\n    </div>\n    {% if component_vars.is_filled.subtitle %}\n    <div class=\"subtitle\">\n        {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n    </div>\n    {% endif %}\n</div>\n

Here's our example with more complex branching.

<div class=\"frontmatter-component\">\n    <div class=\"title\">\n        {% slot \"title\" %}Title{% endslot %}\n    </div>\n    {% if component_vars.is_filled.subtitle %}\n    <div class=\"subtitle\">\n        {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n    </div>\n    {% elif component_vars.is_filled.title %}\n        ...\n    {% elif component_vars.is_filled.<name> %}\n        ...\n    {% endif %}\n</div>\n

Sometimes you're not interested in whether a slot is filled, but rather that it isn't. To negate the meaning of component_vars.is_filled, simply treat it as boolean and negate it with not:

{% if not component_vars.is_filled.subtitle %}\n<div class=\"subtitle\">\n    {% slot \"subtitle\" / %}\n</div>\n{% endif %}\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/slots/#conditional-fills","title":"Conditional fills","text":"

Similarly, you can use {% if %} and {% for %} when defining the {% fill %} tags, to conditionally fill the slots when using the componnet:

In the example below, the {% fill \"footer\" %} fill is used only if the condition is true. If falsy, the fill is ignored, and so the my_table component will use its default content for the footer slot.

{% component \"my_table\" %}\n    {% if editable %}\n        {% fill \"footer\" %}\n            <input name=\"name\" />\n        {% endfill %}\n    {% endif %}\n{% endcomponent %}\n

You can even combine {% if %} and {% for %}:

{% component \"my_table\" %}\n    {% for header in headers %}\n        {% if header != \"hyperlink\" %}\n            {# Generate fill name like `header.my_column` #}\n            {% fill name=\"header.\"|add:header\" %}\n                <b>{{ header }}</b>\n            {% endfill %}\n        {% endif %}\n    {% endfor %}\n{% endcomponent %}\n
"},{"location":"concepts/fundamentals/slots/#scoped-slots","title":"Scoped slots","text":"

Added in version 0.76:

Consider a component with slot(s). This component may do some processing on the inputs, and then use the processed variable in the slot's default template:

@register(\"my_comp\")\nclass MyComp(Component):\n    template = \"\"\"\n        <div>\n            {% slot \"content\" default %}\n                input: {{ input }}\n            {% endslot %}\n        </div>\n    \"\"\"\n\n    def get_context_data(self, input):\n        processed_input = do_something(input)\n        return {\"input\": processed_input}\n

You may want to design a component so that users of your component can still access the input variable, so they don't have to recompute it.

This behavior is called \"scoped slots\". This is inspired by Vue scoped slots and scoped slots of django-web-components.

Using scoped slots consists of two steps:

  1. Passing data to slot tag
  2. Accessing data in fill tag
"},{"location":"concepts/fundamentals/slots/#passing-data-to-slots","title":"Passing data to slots","text":"

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

@register(\"my_comp\")\nclass MyComp(Component):\n    template = \"\"\"\n        <div>\n            {% slot \"content\" default input=input %}\n                input: {{ input }}\n            {% endslot %}\n        </div>\n    \"\"\"\n\n    def get_context_data(self, input):\n        processed_input = do_something(input)\n        return {\n            \"input\": processed_input,\n        }\n
"},{"location":"concepts/fundamentals/slots/#accessing-slot-data-in-fill","title":"Accessing slot data in fill","text":"

Next, we head over to where we define a fill for this slot. Here, to access the slot data we set the data attribute to the name of the variable through which we want to access the slot data. In the example below, we set it to data:

{% component \"my_comp\" %}\n    {% fill \"content\" data=\"slot_data\" %}\n        {{ slot_data.input }}\n    {% endfill %}\n{% endcomponent %}\n

To access slot data on a default slot, you have to explictly define the {% fill %} tags.

So this works:

{% component \"my_comp\" %}\n    {% fill \"content\" data=\"slot_data\" %}\n        {{ slot_data.input }}\n    {% endfill %}\n{% endcomponent %}\n

While this does not:

{% component \"my_comp\" data=\"data\" %}\n    {{ data.input }}\n{% endcomponent %}\n

Note: You cannot set the data attribute and default attribute) to the same name. This raises an error:

{% component \"my_comp\" %}\n    {% fill \"content\" data=\"slot_var\" default=\"slot_var\" %}\n        {{ slot_var.input }}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"concepts/fundamentals/slots/#slot-data-of-default-slots","title":"Slot data of default slots","text":"

To access data of a default slot, you can specify {% fill name=\"default\" %}:

{% component \"my_comp\" %}\n    {% fill \"default\" data=\"slot_data\" %}\n        {{ slot_data.input }}\n    {% endfill %}\n{% endcomponent %}\n
"},{"location":"concepts/fundamentals/slots/#dynamic-slots-and-fills","title":"Dynamic slots and fills","text":"

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

{% slot \"content\" / %}\n

However, sometimes you may want to generate slots based on the given input. One example of this is a table component like that of Vuetify, which creates a header and an item slots for each user-defined column.

In django_components you can achieve the same, simply by using a variable (or a template expression) instead of a string literal:

<table>\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  {# Make only the active column bold #}\n  {% fill \"header-{{ active_header_name }}\" data=\"data\" %}\n    <b>{{ data.value }}</b>\n  {% endfill %}\n{% endcomponent %}\n

NOTE: It's better to use static slot names whenever possible for clarity. The dynamic slot names should be reserved for advanced use only.

Lastly, in rare cases, you can also pass the slot name via the spread operator. This is possible, because the slot name argument is actually a shortcut for a name keyword argument.

So this:

{% slot \"content\" / %}\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
"},{"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    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":"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_context_data so:

@register(\"calendar\")\nclass Calendar(Component):\n    # Since # . @ - are not valid identifiers, we have to\n    # use `**kwargs` so the method can accept these args.\n    def get_context_data(self, **kwargs):\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/#use-template-tags-inside-component-inputs","title":"Use template tags inside component inputs","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_context_data(). But this can get messy if your components contain a lot of logic.

@register(\"calendar\")\nclass Calendar(Component):\n    def get_context_data(self, id: str, editable: bool):\n        return {\n            \"editable\": editable,\n            \"readonly\": not editable,\n            \"input_id\": f\"input-{id}\",\n            \"icon_id\": f\"icon-{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:

  • Component test receives a positional argument with value \"As positional arg \". The comment is omitted.
  • Kwarg title is passed as a string, e.g. John Doe
  • Kwarg id is passed as int, e.g. 15
  • Kwarg readonly is passed as bool, e.g. False
  • Kwarg author is passed as a string, e.g. John Wick (Comment omitted)

This is inspired by django-cotton.

"},{"location":"concepts/fundamentals/template_tag_syntax/#passing-data-as-string-vs-original-values","title":"Passing data as string vs original values","text":"

Sometimes you may want to use the template tags to transform or generate the data that is then passed to the component.

The data doesn't necessarily have to be strings. In the example above, the kwarg id was passed as an integer, NOT a string.

Although the string literals for components inputs are treated as regular Django templates, there is one special case:

When the string literal contains only a single template tag, with no extra text, then the value is passed as the original type instead of a string.

Here, page is an integer:

{% component 'blog_post' page=\"{% random_int 10 20 %}\" / %}\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_context_data(self, some_id: str):\n        attrs = {\n            \"class\": \"pa-4 flex\",\n            \"data-some-id\": 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_context_data(self, some_id: str):\n        return {\"some_id\": 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/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":"concepts/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":"concepts/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 JS and CSS output 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":"concepts/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 JS and CSS output 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":"concepts/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":"concepts/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_context_data(self):\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":"concepts/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. Our Media class does NOT support Django's extend keyword.

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            \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\",  # AlpineJS\n        ]\n        css = [\n            \"path/to/shared.css\",\n            \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\",  # Tailwind\n        ]\n\n    def get_context_data(self):\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":"concepts/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":"concepts/getting_started/adding_slots/","title":"Adding slots","text":"

Our calendar component's looking great! But we just got a new assignment from our colleague - The calendar date needs to be shown on 3 different pages:

  1. On one page, it needs to be shown as is
  2. On the second, the date needs to be bold
  3. On the third, the date needs to be in italics

As a reminder, this is what the component's template looks like:

<div class=\"calendar\">\n  Today's date is <span>{{ date }}</span>\n</div>\n

There's many ways we could approach this:

  • Expose the date in a slot
  • Style .calendar > span differently on different pages
  • Pass a variable to the component that decides how the date is rendered
  • Create a new component

First two options are more flexible, because the custom styling is not baked into a component's implementation. And for the sake of demonstration, we'll solve this challenge with slots.

"},{"location":"concepts/getting_started/adding_slots/#1-what-are-slots","title":"1. What are slots","text":"

Components support something called Slots.

When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content.

This mechanism makes components more reusable and composable.

This behavior is similar to slots in Vue.

In the example below we introduce two tags that work hand in hand to make this work. These are...

  • {% slot <name> %}/{% endslot %}: Declares a new slot in the component template.
  • {% fill <name> %}/{% endfill %}: (Used inside a {% component %} tag pair.) Fills a declared slot with the specified content.
"},{"location":"concepts/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":"concepts/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":"concepts/getting_started/adding_slots/#5-wait-theres-a-bug","title":"5. 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_context_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_context_data(self, date: date, extra_class: str | None = None):\n        workweek_date = to_workweek_date(date)\n        return {\n            \"date\": workweek_date,\n            \"extra_class\": extra_class,\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":"concepts/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 the slot, 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":"concepts/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 static - 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":"concepts/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":"concepts/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_context_data(self):\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":"concepts/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 JS and CSS output 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":"concepts/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":"concepts/getting_started/parametrising_components/#1-understading-component-inputs","title":"1. Understading component inputs","text":"

In section Create your first component, we defined the get_context_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_context_data(self):\n        return {\n            \"date\": \"1970-01-01\",\n        }\n

What we didn't say is that get_context_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_context_data(date=\"2024-12-13\", extra_class=\"text-red\")\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_context_data(\"2024-12-13\", extra_class=\"text-red\")\n
"},{"location":"concepts/getting_started/parametrising_components/#2-define-inputs-for-get_context_data","title":"2. Define inputs for get_context_data","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_context_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_context_data(self, date: date, extra_class: str | None = None):\n        return {\n            \"date\": date,\n            \"extra_class\": extra_class,\n        }\n

Info

Since get_context_data() is just a regular Python function, type hints annotations work the same way as anywhere else.

Warning

Since get_context_data() is just a regular Python function, it will raise TypeError if it receives incorrect parameters.

Since extra_class is optional in the function signature, it's optional also in the template. So both following calls are valid:

{% component \"calendar\" \"2024-12-13\" / %}\n{% component \"calendar\" \"2024-12-13\" extra_class=\"text-red\" / %}\n

However, date is required. Thus we MUST provide it. Same with regular Python functions, date can be set either as positional or keyword argument. But either way it MUST be set:

\u2705\n{% component \"calendar\" \"2024-12-13\" / %}\n{% component \"calendar\" extra_class=\"text-red\" date=\"2024-12-13\" / %}\n\n\u274c\n{% component \"calendar\" extra_class=\"text-red\" / %}\n
"},{"location":"concepts/getting_started/parametrising_components/#3-process-inputs-in-get_context_data","title":"3. Process inputs in get_context_data","text":"

The get_context_data() method is powerful, because it allows us to decouple component inputs from the template variables. In other words, we can pre-process the component inputs, and massage them into a shape that's most appropriate for what the template needs. And it also allows us to pass in static data into the template.

Imagine our component receives data from the database that looks like below (taken from Django).

cities = [\n    {\"name\": \"Mumbai\", \"population\": \"19,000,000\", \"country\": \"India\"},\n    {\"name\": \"Calcutta\", \"population\": \"15,000,000\", \"country\": \"India\"},\n    {\"name\": \"New York\", \"population\": \"20,000,000\", \"country\": \"USA\"},\n    {\"name\": \"Chicago\", \"population\": \"7,000,000\", \"country\": \"USA\"},\n    {\"name\": \"Tokyo\", \"population\": \"33,000,000\", \"country\": \"Japan\"},\n]\n

We need to group the list items by size into following buckets by population:

  • 0-10,000,000
  • 10,000,001-20,000,000
  • 20,000,001-30,000,000
  • +30,000,001

So we want to end up with following data:

cities_by_pop = [\n    {\n      \"name\": \"0-10,000,000\",\n      \"items\": [\n          {\"name\": \"Chicago\", \"population\": \"7,000,000\", \"country\": \"USA\"},\n      ]\n    },\n    {\n      \"name\": \"10,000,001-20,000,000\",\n      \"items\": [\n          {\"name\": \"Calcutta\", \"population\": \"15,000,000\", \"country\": \"India\"},\n          {\"name\": \"Mumbai\", \"population\": \"19,000,000\", \"country\": \"India\"},\n          {\"name\": \"New York\", \"population\": \"20,000,000\", \"country\": \"USA\"},\n      ]\n    },\n    {\n      \"name\": \"30,000,001-40,000,000\",\n      \"items\": [\n          {\"name\": \"Tokyo\", \"population\": \"33,000,000\", \"country\": \"Japan\"},\n      ]\n    },\n]\n

Without the get_context_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_context_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_context_data(self, data):\n        return {\n            \"data\": group_by_pop(data),\n        }\n

Similarly we can make use of get_context_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_context_data(self, date: date, extra_class: str | None = None):\n        workweek_date = to_workweek_date(date)  # <--- new\n        return {\n            \"date\": workweek_date,  # <--- changed\n            \"extra_class\": extra_class,\n        }\n
"},{"location":"concepts/getting_started/parametrising_components/#4-pass-inputs-to-components","title":"4. Pass inputs to components","text":"

Once we're happy with Calendar.get_contex_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

Next, you will learn how to use slots give your components even more flexibility \u27a1\ufe0f

"},{"location":"concepts/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\n\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":"concepts/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":"concepts/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_context_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":"concepts/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":"concepts/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_context_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_context_data(self):\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
  1. 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.

  1. 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 extremely wasteful to copy-paste the JS / CSS 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.

  1. Last important thing is that we want the JS / CSS dependencies to work also with HTML fragments.

So normally, e.g. when a user hits URL of a web page, the server renders full HTML document, with <!doctype>, <html>, <head>, and <body>. In such case, we know about ALL JS and CSS dependencies at render time, so we can e.g. insert them into <head> and <body> ourselves.

However this renders only the initial state. HTML fragments is a common pattern where interactivity is added to the web page by fetching and replacing bits of HTML on the main HTML document after some user action.

In the case of HTML fragments, the HTML is NOT a proper document, but only the HTML that will be inserted somewhere into the DOM.

The challenge here is that Django template for the HTML fragment MAY contain components, and these components MAY have inlined or linked JS and CSS.

def fragment_view(request):\n    template = Template(\"\"\"\n      {% load component_tags %}\n      <div>\n        {% component \"my_table\" / %}\n      </div>\n    \"\"\")\n\n    fragment_str = template.render(Context({}))\n    return HttpResponse(fragment_str, status=200)\n

User may use different libraries to fetch and insert the HTML fragments (e.g. HTMX, AlpineJS, ...). From our perspective, the only thing that we can reliably say is that we expect that the HTML fragment WILL be eventually inserted into the DOM.

So to include the corresponding JS and CSS, a simple approach could be to append them to the HTML as <style> and <script>, e.g.:

<!-- Original content -->\n<div>...</div>\n<!-- Associated CSS files -->\n<link href=\"http://...\" />\n<style>\n  .my-class {\n    color: red;\n  }\n</style>\n<!-- Associated JS files -->\n<script src=\"http://...\"></script>\n<script>\n  console.log(123);\n</script>\n

But this has a number of issues:

  • The JS scripts would run for each instance of the component.
  • Bloating of the HTML file, as each inlined JS or CSS would be included fully for each component.
    • While this sound OK, this could really bloat the HTML files if we used a UI component library for the basic building blocks like buttons, lists, cards, etc.
"},{"location":"guides/devguides/dependency_mgmt/#flow","title":"Flow","text":"

So the solution should address all the points above. To achieve that, we manage the JS / CSS dependencies ourselves in the browser. So when a full HTML document is loaded, we keep track of which JS and CSS have been loaded. And when an HTML fragment is inserted, we check which JS / CSS dependencies it has, and load only those that have NOT been loaded yet.

This is how we achieve that:

  1. When a component is rendered, it inserts an HTML comment containing metadata about the rendered component.

So a template like this

{% load component_tags %}\n<div>\n  {% component \"my_table\" / %}\n</div>\n{% component \"button\" %}\n  Click me!\n{% endcomponent %}\n

May actually render:

<div>\n  <!-- _RENDERED \"my_table_10bc2c,c020ad\" -->\n  <table>\n    ...\n  </table>\n</div>\n<!-- _RENDERED \"button_309dcf,31c0da\" -->\n<button>Click me!</button>\n

Each <!-- _RENDERED --> comment includes comma-separated data - a unique hash for the component class, e.g. my_table_10bc2c, and the component ID, e.g. c020ad.

This way, we or the user can freely pass the rendered around or transform it, treating it as a string to add / remove / replace bits. As long as the <!-- _RENDERED --> comments remain in the rendered string, we will be able to deduce which JS and CSS dependencies the component needs.

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

  • The approach recommended to the users is to use the ComponentDependencyMiddleware middleware, which scans all outgoing HTML, and post-processes the <!-- _RENDERED --> comments.

  • If users are using Component.render() or Component.render_to_response(), these post-process the <!-- _RENDERED --> comments by default.

    • NOTE: Users are able to opt out of the post-processing by setting render_dependencies=False.
  • For advanced use cases, users may use render_dependencies() directly. This is the function that both ComponentDependencyMiddleware and Component.render() call internally.

render_dependencies(), whether called directly, via middleware 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.
  8. Server returns the post-processed HTML.

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

  1. To be able to fetch component's inlined JS and CSS, django-components adds a URL path under:

/components/cache/<str:comp_cls_hash>.<str:script_type>/

E.g. /components/cache/my_table_10bc2c.js/

This endpoint takes the component's unique hash, e.g. my_table_10bc2c, and looks up the component's inlined JS or CSS.

Thus, with this approach, we ensure that:

  1. All JS / CSS dependencies are loaded / executed only once.
  2. The approach is compatible with HTML fragments
  3. The approach is compatible with JS / CSS variables.
  4. Inlined JS / CSS may be post-processed by plugins
"},{"location":"guides/devguides/slot_rendering/","title":"Slot rendering","text":"

This doc serves as a primer on how component slots and fills are resolved.

"},{"location":"guides/devguides/slot_rendering/#flow","title":"Flow","text":"
  1. Imagine you have a template. Some kind of text, maybe HTML:

    | ------\n| ---------\n| ----\n| -------\n

  2. The template may contain some vars, tags, etc

    | -- {{ my_var }} --\n| ---------\n| ----\n| -------\n

  3. The template also contains some slots, etc

    | -- {{ my_var }} --\n| ---------\n| -- {% slot \"myslot\" %} ---\n| -- {% endslot %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| -- {% endslot %} ---\n| -------\n

  4. Slots may be nested

    | -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %} ---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- JKL {{ my_var }}\n| -- {% endslot %} ---\n| -------\n

  5. Some slots may be inside fills for other components

    | -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %}---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ------\n| -- {% component \"mycomp\" %} ---\n| ---- {% slot \"myslot\" %} ---\n| ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n| ---- {% endslot %} ---\n| -- {% endcomponent %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- PQR {{ my_var }}\n| -- {% endslot %} ---\n| -------\n

  6. The names of the slots and fills may be defined using variables

    | -- {% slot slot_name %} ---\n| ---- STU {{ my_var }}\n| -- {% endslot %} ---\n| -------\n

  7. The slot and fill names may be defined using for loops or other variables defined within the template (e.g. {% with %} tag or {% ... as var %} syntax)

    | -- {% for slot_name in slots %} ---\n| ---- {% slot slot_name %} ---\n| ------ STU {{ slot_name }}\n| ---- {% endslot %} ---\n| -- {% endfor %} ---\n| -------\n

  8. Variables for names and for loops allow us implement \"passthrough slots\" - that is, taking all slots that our component received, and passing them to a child component, dynamically.

    | -- {% component \"mycomp\" %} ---\n| ---- {% for slot_name in slots %} ---\n| ------ {% fill slot_name %} ---\n| -------- {% slot slot_name %} ---\n| ---------- XYZ {{ slot_name }}\n| --------- {% endslot %}\n| ------- {% endfill %}\n| ---- {% endfor %} ---\n| -- {% endcomponent %} ---\n| ----\n

  9. Putting that all together, a document may look like this:

    | -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %}---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ------\n| -- {% component \"mycomp\" %} ---\n| ---- {% slot \"myslot\" %} ---\n| ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n| ---- {% endslot %} ---\n| -- {% endcomponent %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- PQR {{ my_var }}\n| -- {% endslot %} ---\n| -------\n| -- {% for slot_name in slots %} ---\n| ---- {% component \"mycomp\" %} ---\n| ------- {% slot slot_name %}\n| ---------- STU {{ slot_name }}\n| ------- {% endslot %}\n| ---- {% endcomponent %} ---\n| -- {% endfor %} ---\n| ----\n| -- {% component \"mycomp\" %} ---\n| ---- {% for slot_name in slots %} ---\n| ------ {% fill slot_name %} ---\n| -------- {% slot slot_name %} ---\n| ---------- XYZ {{ slot_name }}\n| --------- {% endslot %}\n| ------- {% endfill %}\n| ---- {% endfor %} ---\n| -- {% endcomponent %} ---\n| -------\n

  10. Given the above, we want to render the slots with {% fill %} tag that were defined OUTSIDE of this template. How do I do that?

    NOTE: Before v0.110, slots were resolved statically, by walking down the Django Template and Nodes. However, this did not allow for using for loops or other variables defined in the template.

    Currently, this consists of 2 steps:

    1. If a component is rendered within a template using {% component %} tag, determine the given {% fill %} tags in the component's body (the content in between {% component %} and {% endcomponent %}).

      After this step, we know about all the fills that were passed to the component.

    2. Then we simply render the template as usual. And then we reach the {% slot %} tag, we search the context for the available fills.

      • If there IS a fill with the same name as the slot, we render the fill.
      • If the slot is marked default, and there is a fill named default, then we render that.
      • Otherwise, we render the slot's default content.
  11. Obtaining the fills from {% fill %}.

    When a component is rendered with {% component %} tag, and it has some content in between {% component %} and {% endcomponent %}, we want to figure out if that content is a default slot (no {% fill %} used), or if there is a collection of named {% fill %} tags:

    Default slot:

    | -- {% component \"mycomp\" %} ---\n| ---- STU {{ slot_name }}\n| -- {% endcomponent %} ---\n

    Named slots:

    | -- {% component \"mycomp\" %} ---\n| ---- {% fill \"slot_a\" %}\n| ------ STU\n| ---- {% endslot %}\n| ---- {% fill \"slot_b\" %}\n| ------ XYZ\n| ---- {% endslot %}\n| -- {% endcomponent %} ---\n

    To respect any forloops or other variables defined within the template to which the fills may have access, we:

    1. Render the content between {% component %} and {% endcomponent %} using the context outside of the component.
    2. When we reach a {% fill %} tag, we capture any variables that were created between the {% component %} and {% fill %} tags.
    3. When we reach {% fill %} tag, we do not continue rendering deeper. Instead we make a record that we found the fill tag with given name, kwargs, etc.
    4. After the rendering is done, we check if we've encountered any fills. If yes, we expect only named fills. If no, we assume that the the component's body is a default slot.
    5. Lastly we process the found fills, and make them available to the context, so any slots inside the component may access these fills.
  12. Rendering slots

    Slot rendering works similarly to collecting fills, in a sense that we do not search for the slots ahead of the time, but instead let Django handle the rendering of the template, and we step in only when Django come across as {% slot %} tag.

    When we reach a slot tag, we search the context for the available fills.

    • If there IS a fill with the same name as the slot, we render the fill.
    • If the slot is marked default, and there is a fill named default, then we render that.
    • Otherwise, we render the slot's default content.
"},{"location":"guides/devguides/slot_rendering/#using-the-correct-context-in-slotfill-tags","title":"Using the correct context in {% slot/fill %} tags","text":"

In previous section, we said that the {% fill %} tags should be already rendered by the time they are inserted into the {% slot %} tags.

This is not quite true. To help you understand, consider this complex case:

| -- {% for var in [1, 2, 3] %} ---\n| ---- {% component \"mycomp2\" %} ---\n| ------ {% fill \"first\" %}\n| ------- STU {{ my_var }}\n| -------     {{ var }}\n| ------ {% endfill %}\n| ------ {% fill \"second\" %}\n| -------- {% component var=var my_var=my_var %}\n| ---------- VWX {{ my_var }}\n| -------- {% endcomponent %}\n| ------ {% endfill %}\n| ---- {% endcomponent %} ---\n| -- {% endfor %} ---\n| -------\n

We want the forloop variables to be available inside the {% fill %} tags. Because of that, however, we CANNOT render the fills/slots in advance.

Instead, our solution is closer to how Vue handles slots. In Vue, slots are effectively functions that accept a context variables and render some content.

While we do not wrap the logic in a function, we do PREPARE IN ADVANCE: 1. The content that should be rendered for each slot 2. The context variables from get_context_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. So 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.

    So if you have a template `abc.html`:\n```django\n<div>\n  hello\n  {% slot \"body\" %}{% endslot %}\n</div>\n```\n\nAnd components that make use of `abc.html` via `include` or `extends`:\n```py\nfrom 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```\n\nThen you can set slot fill for the slot imported via `include/extends`:\n\n```django\n{% component \"my_comp_extends\" %}\n    {% fill \"body\" %}\n        123\n    {% endfill %}\n{% endcomponent %}\n```\n\nAnd it will render:\n```html\n<div>\n  hello\n  123\n</div>\n```\n
  2. Slot and block

    So 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 my 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):\ntemplate_file = \"\"\"\n{% extends \"abc.html\" %}\n\n            {% block inner %}\n                OVERRIDEN\n            {% endblock %}\n        \"\"\"\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_file = \"\"\"\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/setup/dev_server_setup/","title":"Running with development server","text":""},{"location":"guides/setup/dev_server_setup/#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.

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.

Note

This setting should be enabled only for the dev environment!

"},{"location":"guides/setup/logging_and_debugging/","title":"Logging and debugging","text":"

Django components supports logging with Django. This can help with troubleshooting.

To configure logging for Django components, set the django_components logger in LOGGING in settings.py (below).

Also see the settings.py file in sampleproject for a real-life example.

import logging\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
"},{"location":"guides/setup/syntax_highlight/","title":"Syntax highlighting","text":""},{"location":"guides/setup/syntax_highlight/#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/css/js 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
# In a file called [project root]/components/calendar.py\nfrom django_components import Component, register, types\n\n@register(\"calendar\")\nclass Calendar(Component):\n    def get_context_data(self, date):\n        return {\n            \"date\": date,\n        }\n\n    template: types.django_html = \"\"\"\n        <div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n    \"\"\"\n\n    css: types.css = \"\"\"\n        .calendar-component { width: 200px; background: pink; }\n        .calendar-component span { font-weight: bold; }\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":"guides/setup/syntax_highlight/#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_context_data(self, date):\n        return {\n            \"date\": date,\n        }\n\n    # language=HTML\n    template= \"\"\"\n        <div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n    \"\"\"\n\n    # language=CSS\n    css = \"\"\"\n        .calendar-component { width: 200px; background: pink; }\n        .calendar-component span { font-weight: bold; }\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":"overview/code_of_conduct/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"overview/code_of_conduct/#our-pledge","title":"Our Pledge","text":"

In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.

"},{"location":"overview/code_of_conduct/#our-standards","title":"Our Standards","text":"

Examples of behavior that contributes to creating a positive environment include:

  • Using welcoming and inclusive language
  • Being respectful of differing viewpoints and experiences
  • Gracefully accepting constructive criticism
  • Focusing on what is best for the community
  • Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

  • The use of sexualized language or imagery and unwelcome sexual attention or advances
  • Trolling, insulting/derogatory comments, and personal or political attacks
  • Public or private harassment
  • Publishing others' private information, such as a physical or electronic address, without explicit permission
  • Other conduct which could reasonably be considered inappropriate in a professional setting
"},{"location":"overview/code_of_conduct/#our-responsibilities","title":"Our Responsibilities","text":"

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.

"},{"location":"overview/code_of_conduct/#scope","title":"Scope","text":"

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

"},{"location":"overview/code_of_conduct/#enforcement","title":"Enforcement","text":"

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at emil@emilstenstrom.se. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

"},{"location":"overview/code_of_conduct/#attribution","title":"Attribution","text":"

This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq

"},{"location":"overview/community/","title":"Community","text":""},{"location":"overview/community/#community-questions","title":"Community questions","text":"

The best place to ask questions is in our Github Discussion board.

Please, before opening a new discussion, check if similar discussion wasn't opened already.

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

One of our goals with django-components is to make it easy to share components between projects (see how to package components). If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.

  • django-htmx-components: A set of components for use with htmx. Try out the live demo.
"},{"location":"overview/compatibility/","title":"Compatibility","text":""},{"location":"overview/compatibility/#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.0, 5.1 3.11 4.2, 5.0, 5.1 3.12 4.2, 5.0, 5.1 3.13 5.1"},{"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\n

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

pip install -r requirements-dev.txt\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
"},{"location":"overview/development/#running-playwright-tests","title":"Running Playwright tests","text":"

We use Playwright for end-to-end tests. You will therefore need to install Playwright to be able to run these tests.

Luckily, Playwright makes it very easy:

pip install -r requirements-dev.txt\nplaywright install chromium --with-deps\n

After Playwright is ready, simply run the tests with tox:

tox\n
"},{"location":"overview/development/#developing-against-live-django-app","title":"Developing against live Django app","text":"

How do you check that your changes to django-components project will work in an actual Django project?

Use the sampleproject demo project to validate the changes:

  1. Navigate to sampleproject directory:

    cd sampleproject\n
  2. Install dependencies from the requirements.txt file:

    pip install -r requirements.txt\n
  3. Link to your local version of django-components:

    pip install -e ..\n

    Note

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

  4. Start Django server

    python manage.py runserver\n

Once the server is up, it should be available at http://127.0.0.1:8000.

To display individual components, add them to the urls.py, like in the case of http://127.0.0.1:8000/greeting

"},{"location":"overview/development/#building-js-code","title":"Building JS code","text":"

django_components uses a bit of JS code to:

  • Manage the loading of JS and CSS files used by the components
  • Allow to pass data from Python to JS

When you make changes to this JS code, you also need to compile it:

  1. Make sure you are inside src/django_components_js:

    cd src/django_components_js\n
  2. Install the JS dependencies

    npm install\n
  3. Compile the JS/TS code:

    python build.py\n

    The script will combine all JS/TS code into a single .js file, minify it, and copy it to django_components/static/django_components/django_components.min.js.

"},{"location":"overview/development/#packaging-and-publishing","title":"Packaging and publishing","text":"

To package the library into a distribution that can be published to PyPI, run:

# Install pypa/build\npython -m pip install build --user\n# Build a binary wheel and a source tarball\npython -m build --sdist --wheel --outdir dist/ .\n

To publish the package to PyPI, use twine (See Python user guide):

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

See the full workflow here.

"},{"location":"overview/development/#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":"
  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 in your settings file:

    INSTALLED_APPS = [\n    ...,\n    'django_components',\n]\n
  3. BASE_DIR setting is required. Ensure that it is defined:

    from pathlib import Path\n\nBASE_DIR = Path(__file__).resolve().parent.parent\n
  4. Set COMPONENTS.dirs and/or COMPONENTS.app_dirs so django_components knows where to find component HTML, JS and CSS files:

    from django_components import ComponentsSettings\n\nCOMPONENTS = ComponentsSettings(\n    dirs=[\n        ...,\n        Path(BASE_DIR) / \"components\",\n    ],\n)\n

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

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

    Note

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

  5. Next, modify TEMPLATES section of settings.py as follows:

    • Remove 'APP_DIRS': True,
      • NOTE: Instead of APP_DIRS: True, we will use django.template.loaders.app_directories.Loader, which has the same effect.
    • Add loaders to OPTIONS list and set it to following value:

    This allows Django load component HTML files as Django templates.

    TEMPLATES = [\n    {\n        ...,\n        'OPTIONS': {\n            'loaders':[(\n                'django.template.loaders.cached.Loader', [\n                    # Default Django loader\n                    'django.template.loaders.filesystem.Loader',\n                    # Inluding 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
"},{"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. Add ComponentDependencyMiddleware to MIDDLEWARE setting.

    The middleware searches the outgoing HTML for all components that were rendered to generate the HTML, and adds the JS and CSS associated with those components.

    MIDDLEWARE = [\n    ...\n    \"django_components.middleware.ComponentDependencyMiddleware\",\n]\n

    Read more in Rendering JS/CSS dependencies.

  3. Add django-component's URL paths to your urlpatterns:

    from django.urls import include, path\n\nurlpatterns = [\n    ...\n    path(\"\", include(\"django_components.urls\")),\n]\n
  4. 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 JS and CSS output 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
"},{"location":"overview/installation/#optional","title":"Optional","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            'builtins': [\n                'django_components.templatetags.component_tags',\n            ]\n        },\n    },\n]\n

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

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

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

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

Note

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

"},{"location":"overview/security_notes/#static-files-prior-to-v0100","title":"Static files prior to v0.100","text":"

Prior to v0.100, if your were using django.contrib.staticfiles to collect static files, no distinction was made between the different kinds of files.

As a result, your Python code and templates may inadvertently become available on your static file server. You probably don't want this, as parts of your backend logic will be exposed, posing a potential security vulnerability.

From v0.27 until v0.100, django-components shipped with an additional installable app django_components.safer_staticfiles. It was a drop-in replacement for django.contrib.staticfiles. Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server.

To use it, add it to INSTALLED_APPS and remove django.contrib.staticfiles.

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

If you are on an pre-v0.27 version of django-components, your alternatives are:

  • a) passing --ignore <pattern> options to the collecstatic CLI command,
  • b) defining a subclass of StaticFilesConfig.

Both routes are described in the official docs of the staticfiles app.

Note that safer_staticfiles excludes the .py and .html files for collectstatic command:

python manage.py collectstatic\n

but it is ignored on the development server:

python manage.py runserver\n

For a step-by-step guide on deploying production server with static files, see the demo project.

See the older versions of the sampleproject for a setup with pre-v0.100 version.

"},{"location":"overview/welcome/","title":"Welcome to Django Components","text":"

django-components introduces component-based architecture to Django's server-side rendering. It combines Django's templating system with the modularity seen in modern frontend frameworks like Vue or React.

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\n\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
"},{"location":"overview/welcome/#features","title":"Features","text":"
  1. \ud83e\udde9 Reusability: Allows creation of self-contained, reusable UI elements.
  2. \ud83d\udce6 Encapsulation: Each component can include its own HTML, CSS, and JavaScript.
  3. \ud83d\ude80 Server-side rendering: Components render on the server, improving initial load times and SEO.
  4. \ud83d\udc0d Django integration: Works within the Django ecosystem, using familiar concepts like template tags.
  5. \u26a1 Asynchronous loading: Components can render independently opening up for integration with JS frameworks like HTMX or AlpineJS.

Potential benefits:

  • \ud83d\udd04 Reduced code duplication
  • \ud83d\udee0\ufe0f Improved maintainability through modular design
  • \ud83e\udde0 Easier management of complex UIs
  • \ud83e\udd1d Enhanced collaboration between frontend and backend developers

Django-components can be particularly useful for larger Django projects that require a more structured approach to UI development, without necessitating a shift to a separate frontend framework.

"},{"location":"overview/welcome/#quickstart","title":"Quickstart","text":"

django-components lets you create reusable blocks of code needed to generate the front end code you need for a modern app.

Define a component in components/calendar/calendar.py like this:

@register(\"calendar\")\nclass Calendar(Component):\n    template_file = \"template.html\"\n\n    def get_context_data(self, date):\n        return {\"date\": date}\n

With this template.html file:

<div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n

Use the component like this:

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

And this is what gets rendered:

<div class=\"calendar-component\">Today's date is <span>2024-11-06</span></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/#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. If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.

  • django-htmx-components: A set of components for use with htmx. Try out the live demo.
"},{"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.Component","title":"Component","text":"
Component(registered_name: Optional[str] = None, outer_context: Optional[Context] = None, registry: Optional[ComponentRegistry] = None)\n

Methods:

  • as_view \u2013
  • get_context_data \u2013
  • get_template \u2013
  • get_template_name \u2013
  • inject \u2013
  • on_render_after \u2013
  • on_render_before \u2013
  • render \u2013
  • render_to_response \u2013

Attributes:

  • Media (Optional[Type[ComponentMediaInput]]) \u2013
  • View \u2013
  • css (Optional[str]) \u2013
  • css_file (Optional[str]) \u2013
  • id (str) \u2013
  • input (RenderInput[ArgsType, KwargsType, SlotsType]) \u2013
  • is_filled (SlotIsFilled) \u2013
  • js (Optional[str]) \u2013
  • js_file (Optional[str]) \u2013
  • media (Optional[Media]) \u2013
  • media_class (Type[Media]) \u2013
  • name (str) \u2013
  • outer_context (Context) \u2013
  • registered_name (Optional[str]) \u2013
  • registry \u2013
  • response_class \u2013
  • template (Optional[Union[str, Template]]) \u2013
  • template_file (Optional[str]) \u2013
  • template_name (Optional[str]) \u2013
"},{"location":"reference/api/#django_components.Component.Media","title":"Media class-attribute instance-attribute","text":"
Media: Optional[Type[ComponentMediaInput]] = None\n

See source code

Defines JS and CSS media files associated with this component.

This Media class behaves similarly to Django's Media class:

  • Paths are generally handled as static file paths, and resolved URLs are rendered to HTML with media_class.render_js() or media_class.render_css().
  • A path that starts with http, https, or / is considered a URL, skipping the static file resolution. This path is still rendered to HTML with media_class.render_js() or media_class.render_css().
  • A SafeString (with __html__ method) is considered an already-formatted HTML tag, skipping both static file resolution and rendering with media_class.render_js() or media_class.render_css().

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. Our Media class does NOT support Django's extend keyword

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.View","title":"View class-attribute instance-attribute","text":"
View = ComponentView\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.

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
"},{"location":"reference/api/#django_components.Component.css_file","title":"css_file class-attribute instance-attribute","text":"
css_file: Optional[str] = None\n

See source code

Main CSS associated with this component as file path.

The filepath must be either:

  • Relative to the directory where the Component's Python file is defined.
  • Relative to one of the component directories, as set by COMPONENTS.dirs or COMPONENTS.app_dirs (e.g. <root>/components/).
  • Relative to the staticfiles directories, as set by Django's STATICFILES_DIRS setting (e.g. <root>/static/).

When you create a Component class with css_file, these will happen:

  1. If the file path is relative to the directory where the component's Python file is, the path is resolved.
  2. The file is read and its contents is set to Component.css.

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.id","title":"id property","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.

Raises RuntimeError if accessed outside of rendering execution.

A single render ID has a chance of collision 1 in 3.3M. However, due to birthday paradox, the chance of collision increases when approaching ~1,000 render IDs.

Thus, there is a soft-cap of 1,000 components rendered on a single page.

If you need to more than that, please open an issue on GitHub.

Example:

class MyComponent(Component):\n    def get_context_data(self):\n        print(f\"Rendering '{self.id}'\")\n        return {}\n\nMyComponent.render()\n# Rendering 'ab3c4d'\n
"},{"location":"reference/api/#django_components.Component.input","title":"input property","text":"
input: RenderInput[ArgsType, KwargsType, SlotsType]\n

See source code

Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the render method.

"},{"location":"reference/api/#django_components.Component.is_filled","title":"is_filled property","text":"
is_filled: SlotIsFilled\n

See source code

Dictionary describing which slots have or have not been filled.

This attribute is available for use only within the template as {{ component_vars.is_filled.slot_name }}, and within on_render_before and on_render_after hooks.

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

Only one of js or js_file must be defined.

Example:

class MyComponent(Component):\n    js = \"console.log('Hello, World!');\"\n
"},{"location":"reference/api/#django_components.Component.js_file","title":"js_file class-attribute instance-attribute","text":"
js_file: Optional[str] = None\n

See source code

Main JS associated with this component as file path.

The filepath must be either:

  • Relative to the directory where the Component's Python file is defined.
  • Relative to one of the component directories, as set by COMPONENTS.dirs or COMPONENTS.app_dirs (e.g. <root>/components/).
  • Relative to the staticfiles directories, as set by Django's STATICFILES_DIRS setting (e.g. <root>/static/).

When you create a Component class with js_file, these will happen:

  1. If the file path is relative to the directory where the component's Python file is, the path is resolved.
  2. The file is read and its contents is set to Component.js.

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.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 instance-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 property","text":"
name: str\n
"},{"location":"reference/api/#django_components.Component.outer_context","title":"outer_context instance-attribute","text":"
outer_context: Context = outer_context or Context()\n
"},{"location":"reference/api/#django_components.Component.registered_name","title":"registered_name instance-attribute","text":"
registered_name: Optional[str] = registered_name\n
"},{"location":"reference/api/#django_components.Component.registry","title":"registry instance-attribute","text":"
registry = registry or registry\n
"},{"location":"reference/api/#django_components.Component.response_class","title":"response_class class-attribute instance-attribute","text":"
response_class = HttpResponse\n

See source code

This allows to configure what class is used to generate response from render_to_response

"},{"location":"reference/api/#django_components.Component.template","title":"template class-attribute instance-attribute","text":"
template: Optional[Union[str, Template]] = None\n

See source code

Inlined Django template associated with this component. Can be a plain string or a Template instance.

Only one of template_file, get_template_name, template or get_template must be defined.

Example:

class MyComponent(Component):\n    template = \"Hello, {{ name }}!\"\n\n    def get_context_data(self):\n        return {\"name\": \"World\"}\n
"},{"location":"reference/api/#django_components.Component.template_file","title":"template_file class-attribute instance-attribute","text":"
template_file: Optional[str] = None\n

See source code

Filepath to the Django template associated with this component.

The filepath must be either:

  • Relative to the directory where the Component's Python file is defined.
  • Relative to one of the component directories, as set by COMPONENTS.dirs or COMPONENTS.app_dirs (e.g. <root>/components/).
  • Relative to the template directories, as set by Django's TEMPLATES setting (e.g. <root>/templates/).

Only one of template_file, get_template_name, template or get_template must be defined.

Example:

class MyComponent(Component):\n    template_file = \"path/to/template.html\"\n\n    def get_context_data(self):\n        return {\"name\": \"World\"}\n
"},{"location":"reference/api/#django_components.Component.template_name","title":"template_name instance-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.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.

"},{"location":"reference/api/#django_components.Component.get_context_data","title":"get_context_data","text":"
get_context_data(*args: Any, **kwargs: Any) -> DataType\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

Inlined Django template associated with this component. Can be a plain string or a Template instance.

Only one of template_file, get_template_name, template or get_template must be defined.

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

Filepath to the Django template associated with this component.

The filepath must be relative to either the file where the component class was defined, or one of the roots of STATIFILES_DIRS.

Only one of template_file, get_template_name, template or get_template must be defined.

"},{"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 mut be used inside the get_context_data() method and raises an error if called elsewhere.

Example:

Given this template:

{% provide \"provider\" hello=\"world\" %}\n    {% component \"my_comp\" %}\n    {% endcomponent %}\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 {{ data.hello }}!\"\n    def get_context_data(self):\n        data = self.inject(\"provider\")\n        return {\"data\": data}\n

This renders into:

hi world!\n

As the {{ data.hello }} is taken from the \"provider\".

"},{"location":"reference/api/#django_components.Component.on_render_after","title":"on_render_after","text":"
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n

See source code

Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.

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

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

"},{"location":"reference/api/#django_components.Component.on_render_before","title":"on_render_before","text":"
on_render_before(context: Context, template: Template) -> None\n

See source code

Hook that runs just before the component's template is rendered.

You can use this hook to access or modify the context or the template.

"},{"location":"reference/api/#django_components.Component.render","title":"render classmethod","text":"
render(\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    args: Optional[ArgsType] = None,\n    kwargs: Optional[KwargsType] = None,\n    slots: Optional[SlotsType] = None,\n    escape_slots_content: bool = True,\n    type: RenderType = \"document\",\n    render_dependencies: bool = True,\n    request: Optional[HttpRequest] = None,\n) -> str\n

See source code

Render the component into a string.

Inputs: - args - Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %} - kwargs - Kwargs for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %} - slots - Component slot fills. This is the same as pasing {% fill %} tags to the component. Accepts a dictionary of { slot_name: slot_content } where slot_content can be a string or render function. - escape_slots_content - Whether the content from slots should be escaped. - context - A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. - type - Configure how to handle JS and CSS dependencies. - \"document\" (default) - JS dependencies are inserted into {% component_js_dependencies %}, or to the end of the <body> tag. CSS dependencies are inserted into {% component_css_dependencies %}, or the end of the <head> tag. - render_dependencies - Set this to False if you want to insert the resulting HTML into another component. - request - The request object. This is only required when needing to use RequestContext, e.g. to enable template context_processors. Unused if context is already an instance of Context Example:

MyComponent.render(\n    args=[1, \"two\", {}],\n    kwargs={\n        \"key\": 123,\n    },\n    slots={\n        \"header\": 'STATIC TEXT HERE',\n        \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n    },\n    escape_slots_content=False,\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    slots: Optional[SlotsType] = None,\n    escape_slots_content: bool = True,\n    args: Optional[ArgsType] = None,\n    kwargs: Optional[KwargsType] = None,\n    type: RenderType = \"document\",\n    request: Optional[HttpRequest] = None,\n    *response_args: Any,\n    **response_kwargs: Any\n) -> HttpResponse\n

See source code

Render the component and wrap the content in the response class.

The response class is taken from Component.response_class. Defaults to django.http.HttpResponse.

This is the interface for the django.views.View class which allows us to use components as Django views with component.as_view().

Inputs: - args - Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %} - kwargs - Kwargs for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %} - slots - Component slot fills. This is the same as pasing {% fill %} tags to the component. Accepts a dictionary of { slot_name: slot_content } where slot_content can be a string or render function. - escape_slots_content - Whether the content from slots should be escaped. - context - A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. - type - Configure how to handle JS and CSS dependencies. - \"document\" (default) - JS dependencies are inserted into {% component_js_dependencies %}, or to the end of the <body> tag. CSS dependencies are inserted into {% component_css_dependencies %}, or the end of the <head> tag. - request - The request object. This is only required when needing to use RequestContext, e.g. to enable template context_processors. Unused if context is already an instance of Context

Any additional args and kwargs are passed to the response_class.

Example:

MyComponent.render_to_response(\n    args=[1, \"two\", {}],\n    kwargs={\n        \"key\": 123,\n    },\n    slots={\n        \"header\": 'STATIC TEXT HERE',\n        \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n    },\n    escape_slots_content=False,\n    # HttpResponse input\n    status=201,\n    headers={...},\n)\n# HttpResponse(content=..., status=201, headers=...)\n

"},{"location":"reference/api/#django_components.ComponentFileEntry","title":"ComponentFileEntry","text":"

Bases: tuple

See source code

Result returned by get_component_files().

Attributes:

  • dot_path (str) \u2013
  • filepath (Path) \u2013
"},{"location":"reference/api/#django_components.ComponentFileEntry.dot_path","title":"dot_path instance-attribute","text":"
dot_path: str\n

See source code

The python import path for the module. E.g. app.components.mycomp

"},{"location":"reference/api/#django_components.ComponentFileEntry.filepath","title":"filepath instance-attribute","text":"
filepath: Path\n

See source code

The filesystem path to the module. E.g. /path/to/project/app/components/mycomp.py

"},{"location":"reference/api/#django_components.ComponentMediaInput","title":"ComponentMediaInput","text":"

Bases: typing.Protocol

See source code

Defines JS and CSS media files associated with a Component.

class MyTable(Component):\n    class Media:\n        js = [\n            \"path/to/script.js\",\n            \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\",  # AlpineJS\n        ]\n        css = {\n            \"all\": [\n                \"path/to/style.css\",\n                \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\",  # TailwindCSS\n            ],\n            \"print\": [\"path/to/style2.css\"],\n        }\n

Attributes:

  • css (Optional[Union[ComponentMediaInputPath, List[ComponentMediaInputPath], Dict[str, ComponentMediaInputPath], Dict[str, List[ComponentMediaInputPath]]]]) \u2013
  • js (Optional[Union[ComponentMediaInputPath, List[ComponentMediaInputPath]]]) \u2013
"},{"location":"reference/api/#django_components.ComponentMediaInput.css","title":"css class-attribute instance-attribute","text":"
css: Optional[\n    Union[\n        ComponentMediaInputPath, List[ComponentMediaInputPath], Dict[str, ComponentMediaInputPath], Dict[str, List[ComponentMediaInputPath]]\n    ]\n] = None\n

See source code

CSS files associated with a Component.

  • If a string, it's assumed to be a path to a CSS file.

  • If a list, each entry is assumed to be a path to a CSS file.

  • If a dict, the keys are media types (e.g. \"all\", \"print\", \"screen\", etc.), and the values are either:

    • A string, assumed to be a path to a CSS file.
    • A list, each entry is assumed to be a path to a CSS file.

Each entry can be a string, bytes, SafeString, PathLike, or a callable that returns one of the former (see ComponentMediaInputPath).

Examples:

class MyComponent(Component):\n    class Media:\n        css = \"path/to/style.css\"\n

class MyComponent(Component):\n    class Media:\n        css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n
class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": \"path/to/style.css\",\n            \"print\": \"path/to/print.css\",\n        }\n
class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": [\"path/to/style1.css\", \"path/to/style2.css\"],\n            \"print\": \"path/to/print.css\",\n        }\n
"},{"location":"reference/api/#django_components.ComponentMediaInput.js","title":"js class-attribute instance-attribute","text":"
js: Optional[Union[ComponentMediaInputPath, List[ComponentMediaInputPath]]] = None\n

See source code

JS files associated with a Component.

  • If a string, it's assumed to be a path to a JS file.

  • If a list, each entry is assumed to be a path to a JS file.

Each entry can be a string, bytes, SafeString, PathLike, or a callable that returns one of the former (see ComponentMediaInputPath).

Examples:

class MyComponent(Component):\n    class Media:\n        js = \"path/to/script.js\"\n

class MyComponent(Component):\n    class Media:\n        js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n
class MyComponent(Component):\n    class Media:\n        js = lambda: [\"path/to/script1.js\", \"path/to/script2.js\"]\n
"},{"location":"reference/api/#django_components.ComponentMediaInputPath","title":"ComponentMediaInputPath module-attribute","text":"
ComponentMediaInputPath = Union[str, bytes, SafeData, Path, PathLike, Callable[[], Union[str, bytes, SafeData, Path, PathLike]]]\n

See source code

A type representing an entry in Media.js or Media.css.

If an entry is a SafeString (or has __html__ method), then entry is assumed to be a formatted HTML tag. Otherwise, it's assumed to be a path to a file.

Example:

class MyComponent\n    class Media:\n        js = [\n            \"path/to/script.js\",\n            b\"script.js\",\n            SafeString(\"<script src='path/to/script.js'></script>\"),\n        ]\n        css = [\n            Path(\"path/to/style.css\"),\n            lambda: \"path/to/style.css\",\n            lambda: Path(\"path/to/style.css\"),\n        ]\n
"},{"location":"reference/api/#django_components.ComponentRegistry","title":"ComponentRegistry","text":"
ComponentRegistry(\n    library: Optional[Library] = None, settings: Optional[Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]] = None\n)\n

Bases: object

See source code

Manages components and makes them available in the template, by default as {% component %} tags.

{% component \"my_comp\" key=value %}\n{% endcomponent %}\n

To enable a component to be used in a template, the component must be registered with a component registry.

When you register a component to a registry, behind the scenes the registry automatically adds the component's template tag (e.g. {% component %} to the Library. And the opposite happens when you unregister a component - the tag is removed.

See Registering components.

Parameters:

  • library (Library, default: None ) \u2013

    Django Library associated with this registry. If omitted, the default Library instance from django_components is used.

  • settings (Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]], default: None ) \u2013

    Configure how the components registered with this registry will behave when rendered. See RegistrySettings. Can be either a static value or a callable that returns the settings. If omitted, the settings from COMPONENTS are used.

Notes:

  • The default registry is available as django_components.registry.
  • The default registry is used when registering components with @register decorator.

Example:

# Use with default Library\nregistry = ComponentRegistry()\n\n# Or a custom one\nmy_lib = Library()\nregistry = ComponentRegistry(library=my_lib)\n\n# Usage\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\nregistry.all()\nregistry.clear()\nregistry.get()\n
"},{"location":"reference/api/#django_components.ComponentRegistry--using-registry-to-share-components","title":"Using registry to share components","text":"

You can use component registry for isolating or \"packaging\" components:

  1. Create new instance of ComponentRegistry and Library:

    my_comps = Library()\nmy_comps_reg = ComponentRegistry(library=my_comps)\n

  2. Register components to the registry:

    my_comps_reg.register(\"my_button\", ButtonComponent)\nmy_comps_reg.register(\"my_card\", CardComponent)\n

  3. In your target project, load the Library associated with the registry:

    {% load my_comps %}\n

  4. Use the registered components in your templates:

    {% component \"button\" %}\n{% endcomponent %}\n

Methods:

  • all \u2013
  • clear \u2013
  • get \u2013
  • register \u2013
  • unregister \u2013

Attributes:

  • library (Library) \u2013
  • settings (InternalRegistrySettings) \u2013
"},{"location":"reference/api/#django_components.ComponentRegistry.library","title":"library property","text":"
library: Library\n

See source code

The template tag Library that is associated with the registry.

"},{"location":"reference/api/#django_components.ComponentRegistry.settings","title":"settings property","text":"
settings: InternalRegistrySettings\n

See source code

Registry settings configured for this registry.

"},{"location":"reference/api/#django_components.ComponentRegistry.all","title":"all","text":"
all() -> Dict[str, Type[Component]]\n

See source code

Retrieve all registered Component classes.

Returns:

  • Dict[str, Type[Component]] \u2013

    Dict[str, Type[Component]]: A dictionary of component names to component classes

Example:

# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then get all\nregistry.all()\n# > {\n# >   \"button\": ButtonComponent,\n# >   \"card\": CardComponent,\n# > }\n
"},{"location":"reference/api/#django_components.ComponentRegistry.clear","title":"clear","text":"
clear() -> None\n

See source code

Clears the registry, unregistering all components.

Example:

# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then clear\nregistry.clear()\n# Then get all\nregistry.all()\n# > {}\n
"},{"location":"reference/api/#django_components.ComponentRegistry.get","title":"get","text":"
get(name: str) -> Type[Component]\n

See source code

Retrieve a Component class registered under the given name.

Parameters:

  • name (str) \u2013

    The name under which the component was registered. Required.

Returns:

  • Type[Component] \u2013

    Type[Component]: The component class registered under the given name.

Raises:

  • NotRegistered if the given name is not registered.

Example:

# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then get\nregistry.get(\"button\")\n# > ButtonComponent\n
"},{"location":"reference/api/#django_components.ComponentRegistry.register","title":"register","text":"
register(name: str, component: Type[Component]) -> None\n

See source code

Register a Component class with this registry under the given name.

A component MUST be registered before it can be used in a template such as:

{% component \"my_comp\" %}\n{% endcomponent %}\n

Parameters:

  • name (str) \u2013

    The name under which the component will be registered. Required.

  • component (Type[Component]) \u2013

    The component class to register. Required.

Raises:

  • AlreadyRegistered if a different component was already registered under the same name.

Example:

registry.register(\"button\", ButtonComponent)\n
"},{"location":"reference/api/#django_components.ComponentRegistry.unregister","title":"unregister","text":"
unregister(name: str) -> None\n

See source code

Unregister the Component class that was registered under the given name.

Once a component is unregistered, it is no longer available in the templates.

Parameters:

  • name (str) \u2013

    The name under which the component is registered. Required.

Raises:

  • NotRegistered if the given name is not registered.

Example:

# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
"},{"location":"reference/api/#django_components.ComponentVars","title":"ComponentVars","text":"

Bases: tuple

See source code

Type for the variables available inside the component templates.

All variables here are scoped under component_vars., so e.g. attribute is_filled on this class is accessible inside the template as:

{{ component_vars.is_filled }}\n

Attributes:

  • is_filled (Dict[str, bool]) \u2013
"},{"location":"reference/api/#django_components.ComponentVars.is_filled","title":"is_filled instance-attribute","text":"
is_filled: Dict[str, bool]\n

See source code

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_context_data(self, *args, **kwargs):\n        return {\n            \"my_slot_filled\": \"my_slot\" in self.input.slots\n        }\n
"},{"location":"reference/api/#django_components.ComponentView","title":"ComponentView","text":"
ComponentView(component: Component, **kwargs: Any)\n

Bases: django.views.generic.base.View

See source code

Subclass of django.views.View where the Component instance is available via self.component.

Attributes:

  • component \u2013
"},{"location":"reference/api/#django_components.ComponentView.component","title":"component class-attribute instance-attribute","text":"
component = component\n
"},{"location":"reference/api/#django_components.ComponentsSettings","title":"ComponentsSettings","text":"

Bases: tuple

See source code

Settings available for django_components.

Example:

COMPONENTS = ComponentsSettings(\n    autodiscover=False,\n    dirs = [BASE_DIR / \"components\"],\n)\n

Attributes:

  • app_dirs (Optional[Sequence[str]]) \u2013
  • autodiscover (Optional[bool]) \u2013
  • context_behavior (Optional[ContextBehaviorType]) \u2013
  • dirs (Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]]) \u2013
  • dynamic_component_name (Optional[str]) \u2013
  • forbidden_static_files (Optional[List[Union[str, Pattern]]]) \u2013
  • libraries (Optional[List[str]]) \u2013
  • multiline_tags (Optional[bool]) \u2013
  • reload_on_file_change (Optional[bool]) \u2013
  • reload_on_template_change (Optional[bool]) \u2013
  • static_files_allowed (Optional[List[Union[str, Pattern]]]) \u2013
  • static_files_forbidden (Optional[List[Union[str, Pattern]]]) \u2013
  • tag_formatter (Optional[Union[TagFormatterABC, str]]) \u2013
  • template_cache_size (Optional[int]) \u2013
"},{"location":"reference/api/#django_components.ComponentsSettings.app_dirs","title":"app_dirs class-attribute instance-attribute","text":"
app_dirs: Optional[Sequence[str]] = None\n

See source code

Specify the app-level directories that contain your components.

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

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

COMPONENTS = ComponentsSettings(\n    app_dirs=[\"my_comps\"],\n)\n

To search for <app>/my_comps/.

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

Set to empty list to disable app-level components:

COMPONENTS = ComponentsSettings(\n    app_dirs=[],\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.autodiscover","title":"autodiscover class-attribute instance-attribute","text":"
autodiscover: Optional[bool] = None\n

See source code

Toggle whether to run autodiscovery at the Django server startup.

Defaults to True

COMPONENTS = ComponentsSettings(\n    autodiscover=False,\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.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.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.forbidden_static_files","title":"forbidden_static_files class-attribute instance-attribute","text":"
forbidden_static_files: Optional[List[Union[str, Pattern]]] = None\n

See source code

Deprecated. Use COMPONENTS.static_files_forbidden instead.

"},{"location":"reference/api/#django_components.ComponentsSettings.libraries","title":"libraries class-attribute instance-attribute","text":"
libraries: Optional[List[str]] = None\n

See source code

Configure extra python modules that should be loaded.

This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.

Expects a list of python module paths. Defaults to empty list.

Example:

COMPONENTS = ComponentsSettings(\n    libraries=[\n        \"mysite.components.forms\",\n        \"mysite.components.buttons\",\n        \"mysite.components.cards\",\n    ],\n)\n

This would be the equivalent of importing these modules from within Django's AppConfig.ready():

class MyAppConfig(AppConfig):\n    def ready(self):\n        import \"mysite.components.forms\"\n        import \"mysite.components.buttons\"\n        import \"mysite.components.cards\"\n
"},{"location":"reference/api/#django_components.ComponentsSettings.libraries--manually-loading-libraries","title":"Manually loading libraries","text":"

In the rare case that you need to manually trigger the import of libraries, you can use the import_libraries() function:

from django_components import import_libraries\n\nimport_libraries()\n
"},{"location":"reference/api/#django_components.ComponentsSettings.multiline_tags","title":"multiline_tags class-attribute instance-attribute","text":"
multiline_tags: Optional[bool] = None\n

See source code

Enable / disable multiline support for template tags. If True, template tags like {% component %} or {{ my_var }} can span multiple lines.

Defaults to True.

Disable this setting if you are making custom modifications to Django's regular expression for parsing templates at django.template.base.tag_re.

COMPONENTS = ComponentsSettings(\n    multiline_tags=False,\n)\n
"},{"location":"reference/api/#django_components.ComponentsSettings.reload_on_file_change","title":"reload_on_file_change class-attribute instance-attribute","text":"
reload_on_file_change: Optional[bool] = None\n

See source code

This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.

In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.

Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.

The setting reload_on_file_change fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.

If True, django_components configures Django to reload when files inside COMPONENTS.dirs or COMPONENTS.app_dirs change.

See Reload dev server on component file changes.

Defaults to False.

Warning

This setting should be enabled only for the dev environment!

"},{"location":"reference/api/#django_components.ComponentsSettings.reload_on_template_change","title":"reload_on_template_change class-attribute instance-attribute","text":"
reload_on_template_change: Optional[bool] = None\n

See source code

Deprecated. Use COMPONENTS.reload_on_file_change instead.

"},{"location":"reference/api/#django_components.ComponentsSettings.static_files_allowed","title":"static_files_allowed class-attribute instance-attribute","text":"
static_files_allowed: Optional[List[Union[str, Pattern]]] = None\n

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs are treated as static files.

If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running collectstatic, and can be accessed under the static file endpoint.

You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

By default, JS, CSS, and common image and font file formats are considered static files:

COMPONENTS = ComponentsSettings(\n    static_files_allowed=[\n        \".css\",\n        \".js\", \".jsx\", \".ts\", \".tsx\",\n        # Images\n        \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n        \".jpeg\",  \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n        \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n        # Fonts\n        \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n    ],\n)\n

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

"},{"location":"reference/api/#django_components.ComponentsSettings.static_files_forbidden","title":"static_files_forbidden class-attribute instance-attribute","text":"
static_files_forbidden: Optional[List[Union[str, Pattern]]] = None\n

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs will NEVER be treated as static files.

If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in static_files_allowed.

Use this setting together with static_files_allowed for a fine control over what file types will be exposed.

You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

By default, any HTML and Python are considered NOT static files:

COMPONENTS = ComponentsSettings(\n    static_files_forbidden=[\n        \".html\", \".django\", \".dj\", \".tpl\",\n        # Python files\n        \".py\", \".pyc\",\n    ],\n)\n

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

"},{"location":"reference/api/#django_components.ComponentsSettings.tag_formatter","title":"tag_formatter class-attribute instance-attribute","text":"
tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n

See source code

Configure what syntax is used inside Django templates to render components. See the available tag formatters.

Defaults to \"django_components.component_formatter\".

Learn more about Customizing component tags with TagFormatter.

Can be set either as direct reference:

from django_components import component_formatter\n\nCOMPONENTS = ComponentsSettings(\n    \"tag_formatter\": component_formatter\n)\n

Or as an import string;

COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_formatter\"\n)\n

Examples:

  • \"django_components.component_formatter\"

    Set

    COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_formatter\"\n)\n

    To write components like this:

    {% component \"button\" href=\"...\" %}\n    Click me!\n{% endcomponent %}\n
  • django_components.component_shorthand_formatter

    Set

    COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_shorthand_formatter\"\n)\n

    To write components like this:

    {% button href=\"...\" %}\n    Click me!\n{% endbutton %}\n
"},{"location":"reference/api/#django_components.ComponentsSettings.template_cache_size","title":"template_cache_size class-attribute instance-attribute","text":"
template_cache_size: Optional[int] = None\n

See source code

Configure the maximum amount of Django templates to be cached.

Defaults to 128.

Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.

By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding Component.get_template() to render many dynamic templates, you can increase this number.

COMPONENTS = ComponentsSettings(\n    template_cache_size=256,\n)\n

To remove the cache limit altogether and cache everything, set template_cache_size to None.

COMPONENTS = ComponentsSettings(\n    template_cache_size=None,\n)\n

If you want to add templates to the cache yourself, you can use cached_template():

from django_components import cached_template\n\ncached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n    pass\n\ncached_template(\n    \"Variable: {{ variable }}\",\n    template_cls=MyTemplate,\n    name=...\n    origin=...\n    engine=...\n)\n
"},{"location":"reference/api/#django_components.ContextBehavior","title":"ContextBehavior","text":"

Bases: str, enum.Enum

See source code

Configure how (and whether) the context is passed to the component fills and what variables are available inside the {% fill %} tags.

Also see Component context and scope.

Options:

  • django: With this setting, component fills behave as usual Django tags.
  • isolated: This setting makes the component fills behave similar to Vue or React.

Attributes:

  • DJANGO \u2013
  • ISOLATED \u2013
"},{"location":"reference/api/#django_components.ContextBehavior.DJANGO","title":"DJANGO class-attribute instance-attribute","text":"
DJANGO = 'django'\n

See source code

With this setting, component fills behave as usual Django tags. That is, they enrich the context, and pass it along.

  1. Component fills use the context of the component they are within.
  2. Variables from Component.get_context_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_context_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_context_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_context_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.EmptyDict","title":"EmptyDict","text":"

Bases: dict

See source code

TypedDict with no members.

You can use this to define a Component that accepts NO kwargs, or NO slots, or returns NO data from Component.get_context_data() / Component.get_js_data() / Component.get_css_data():

Accepts NO kwargs:

from django_components import Component, EmptyDict\n\nclass Table(Component(Any, EmptyDict, Any, Any, Any, Any))\n    ...\n

Accepts NO slots:

from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, EmptyDict, Any, Any, Any))\n    ...\n

Returns NO data from get_context_data():

from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, Any, EmptyDict, Any, Any))\n    ...\n

Going back to the example with NO kwargs, when you then call Component.render() or Component.render_to_response(), the kwargs parameter will raise type error if kwargs is anything else than an empty dict.

Table.render(\n    kwargs: {},\n)\n

Omitting kwargs is also fine:

Table.render()\n

Other values are not allowed. This will raise an error with MyPy:

Table.render(\n    kwargs: {\n        \"one\": 2,\n        \"three\": 4,\n    },\n)\n
"},{"location":"reference/api/#django_components.EmptyTuple","title":"EmptyTuple module-attribute","text":"
EmptyTuple = Tuple[]\n

See source code

Tuple with no members.

You can use this to define a Component that accepts NO positional arguments:

from django_components import Component, EmptyTuple\n\nclass Table(Component(EmptyTuple, Any, Any, Any, Any, Any))\n    ...\n

After that, when you call Component.render() or Component.render_to_response(), the args parameter will raise type error if args is anything else than an empty tuple.

Table.render(\n    args: (),\n)\n

Omitting args is also fine:

Table.render()\n

Other values are not allowed. This will raise an error with MyPy:

Table.render(\n    args: (\"one\", 2, \"three\"),\n)\n
"},{"location":"reference/api/#django_components.RegistrySettings","title":"RegistrySettings","text":"

Bases: tuple

See source code

Configuration for a ComponentRegistry.

These settings define how the components registered with this registry will behave when rendered.

from django_components import ComponentRegistry, RegistrySettings\n\nregistry_settings = RegistrySettings(\n    context_behavior=\"django\",\n    tag_formatter=\"django_components.component_shorthand_formatter\",\n)\n\nregistry = ComponentRegistry(settings=registry_settings)\n

Attributes:

  • CONTEXT_BEHAVIOR (Optional[ContextBehaviorType]) \u2013
  • TAG_FORMATTER (Optional[Union[TagFormatterABC, str]]) \u2013
  • context_behavior (Optional[ContextBehaviorType]) \u2013
  • tag_formatter (Optional[Union[TagFormatterABC, str]]) \u2013
"},{"location":"reference/api/#django_components.RegistrySettings.CONTEXT_BEHAVIOR","title":"CONTEXT_BEHAVIOR class-attribute instance-attribute","text":"
CONTEXT_BEHAVIOR: Optional[ContextBehaviorType] = None\n

See source code

Deprecated. Use context_behavior instead. Will be removed in v1.

Same as the global COMPONENTS.context_behavior setting, but for this registry.

If omitted, defaults to the global COMPONENTS.context_behavior setting.

"},{"location":"reference/api/#django_components.RegistrySettings.TAG_FORMATTER","title":"TAG_FORMATTER class-attribute instance-attribute","text":"
TAG_FORMATTER: Optional[Union[TagFormatterABC, str]] = None\n

See source code

Deprecated. Use tag_formatter instead. Will be removed in v1.

Same as the global COMPONENTS.tag_formatter setting, but for this registry.

If omitted, defaults to the global COMPONENTS.tag_formatter setting.

"},{"location":"reference/api/#django_components.RegistrySettings.context_behavior","title":"context_behavior class-attribute instance-attribute","text":"
context_behavior: Optional[ContextBehaviorType] = None\n

See source code

Same as the global COMPONENTS.context_behavior setting, but for this registry.

If omitted, defaults to the global COMPONENTS.context_behavior setting.

"},{"location":"reference/api/#django_components.RegistrySettings.tag_formatter","title":"tag_formatter class-attribute instance-attribute","text":"
tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n

See source code

Same as the global COMPONENTS.tag_formatter setting, but for this registry.

If omitted, defaults to the global COMPONENTS.tag_formatter setting.

"},{"location":"reference/api/#django_components.Slot","title":"Slot dataclass","text":"
Slot(content_func: SlotFunc[TSlotData])\n

Bases: typing.Generic

See source code

This class holds the slot content function along with related metadata.

Attributes:

  • content_func (SlotFunc[TSlotData]) \u2013
  • do_not_call_in_templates (bool) \u2013
"},{"location":"reference/api/#django_components.Slot.content_func","title":"content_func instance-attribute","text":"
content_func: SlotFunc[TSlotData]\n
"},{"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
"},{"location":"reference/api/#django_components.SlotContent","title":"SlotContent module-attribute","text":"
SlotContent = Union[SlotResult, SlotFunc[TSlotData], 'Slot[TSlotData]']\n
"},{"location":"reference/api/#django_components.SlotFunc","title":"SlotFunc","text":""},{"location":"reference/api/#django_components.SlotRef","title":"SlotRef","text":"
SlotRef(slot: SlotNode, context: Context)\n

Bases: object

See source code

SlotRef allows to treat a slot as a variable. The slot is rendered only once the instance is coerced to string.

This is used to access slots as variables inside the templates. When a SlotRef is rendered in the template with {{ my_lazy_slot }}, it will output the contents of the slot.

"},{"location":"reference/api/#django_components.SlotResult","title":"SlotResult module-attribute","text":"
SlotResult = Union[str, SafeString]\n
"},{"location":"reference/api/#django_components.TagFormatterABC","title":"TagFormatterABC","text":"

Bases: abc.ABC

See source code

Abstract base class for defining custom tag formatters.

Tag formatters define how the component tags are used in the template.

Read more about Tag formatter.

For example, with the default tag formatter (ComponentFormatter), components are written as:

{% component \"comp_name\" %}\n{% endcomponent %}\n

While with the shorthand tag formatter (ShorthandComponentFormatter), components are written as:

{% comp_name %}\n{% endcomp_name %}\n

Example:

Implementation for ShorthandComponentFormatter:

from djagno_components import TagFormatterABC, TagResult\n\nclass ShorthandComponentFormatter(TagFormatterABC):\n    def start_tag(self, name: str) -> str:\n        return name\n\n    def end_tag(self, name: str) -> str:\n        return f\"end{name}\"\n\n    def parse(self, tokens: List[str]) -> TagResult:\n        tokens = [*tokens]\n        name = tokens.pop(0)\n        return TagResult(name, tokens)\n

Methods:

  • end_tag \u2013
  • parse \u2013
  • start_tag \u2013
"},{"location":"reference/api/#django_components.TagFormatterABC.end_tag","title":"end_tag abstractmethod","text":"
end_tag(name: str) -> str\n

See source code

Formats the end tag of a block component.

Parameters:

  • name (str) \u2013

    Component's registered name. Required.

Returns:

  • str ( str ) \u2013

    The formatted end tag.

"},{"location":"reference/api/#django_components.TagFormatterABC.parse","title":"parse abstractmethod","text":"
parse(tokens: List[str]) -> TagResult\n

See source code

Given the tokens (words) passed to a component start tag, this function extracts the component name from the tokens list, and returns TagResult, which is a tuple of (component_name, remaining_tokens).

Parameters:

  • tokens ([List(str]) \u2013

    List of tokens passed to the component tag.

Returns:

  • TagResult ( TagResult ) \u2013

    Parsed component name and remaining tokens.

Example:

Assuming we used a component in a template like this:

{% component \"my_comp\" key=val key2=val2 %}\n{% endcomponent %}\n

This function receives a list of tokens:

['component', '\"my_comp\"', 'key=val', 'key2=val2']\n
  • component is the tag name, which we drop.
  • \"my_comp\" is the component name, but we must remove the extra quotes.
  • The remaining tokens we pass unmodified, as that's the input to the component.

So in the end, we return:

TagResult('my_comp', ['key=val', 'key2=val2'])\n
"},{"location":"reference/api/#django_components.TagFormatterABC.start_tag","title":"start_tag abstractmethod","text":"
start_tag(name: str) -> str\n

See source code

Formats the start tag of a component.

Parameters:

  • name (str) \u2013

    Component's registered name. Required.

Returns:

  • str ( str ) \u2013

    The formatted start tag.

"},{"location":"reference/api/#django_components.TagResult","title":"TagResult","text":"

Bases: tuple

See source code

The return value from TagFormatter.parse().

Read more about Tag formatter.

Attributes:

  • component_name (str) \u2013
  • tokens (List[str]) \u2013
"},{"location":"reference/api/#django_components.TagResult.component_name","title":"component_name instance-attribute","text":"
component_name: str\n

See source code

Component name extracted from the template tag

For example, if we had tag

{% component \"my_comp\" key=val key2=val2 %}\n

Then component_name would be my_comp.

"},{"location":"reference/api/#django_components.TagResult.tokens","title":"tokens instance-attribute","text":"
tokens: List[str]\n

See source code

Remaining tokens (words) that were passed to the tag, with component name removed

For example, if we had tag

{% component \"my_comp\" key=val key2=val2 %}\n

Then tokens would be ['key=val', 'key2=val2'].

"},{"location":"reference/api/#django_components.autodiscover","title":"autodiscover","text":"
autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n

See source code

Search for all python files in COMPONENTS.dirs and COMPONENTS.app_dirs and import them.

See Autodiscovery.

NOTE: Subdirectories and files starting with an underscore _ (except for __init__.py are ignored.

Parameters:

  • map_module (Callable[[str], str], default: None ) \u2013

    Map the module paths with map_module function. This serves as an escape hatch for when you need to use this function in tests.

Returns:

  • List[str] \u2013

    List[str]: A list of module paths of imported files.

To get the same list of modules that autodiscover() would return, but without importing them, use get_component_files():

from django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
"},{"location":"reference/api/#django_components.cached_template","title":"cached_template","text":"
cached_template(\n    template_string: str,\n    template_cls: Optional[Type[Template]] = None,\n    origin: Optional[Origin] = None,\n    name: Optional[str] = None,\n    engine: Optional[Any] = None,\n) -> Template\n

See source code

Create a Template instance that will be cached as per the COMPONENTS.template_cache_size setting.

Parameters:

  • template_string (str) \u2013

    Template as a string, same as the first argument to Django's Template. Required.

  • template_cls (Type[Template], default: None ) \u2013

    Specify the Template class that should be instantiated. Defaults to Django's Template class.

  • origin (Type[Origin], default: None ) \u2013

    Sets Template.Origin.

  • name (Type[str], default: None ) \u2013

    Sets Template.name

  • engine (Type[Any], default: None ) \u2013

    Sets Template.engine

from django_components import cached_template\n\ntemplate = cached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n    pass\n\ntemplate = cached_template(\n    \"Variable: {{ variable }}\",\n    template_cls=MyTemplate,\n    name=...\n    origin=...\n    engine=...\n)\n
"},{"location":"reference/api/#django_components.get_component_dirs","title":"get_component_dirs","text":"
get_component_dirs(include_apps: bool = True) -> List[Path]\n

See source code

Get directories that may contain component files.

This is the heart of all features that deal with filesystem and file lookup. Autodiscovery, Django template resolution, static file resolution - They all use this.

Parameters:

  • include_apps (bool, default: True ) \u2013

    Include directories from installed Django apps. Defaults to True.

Returns:

  • List[Path] \u2013

    List[Path]: A list of directories that may contain component files.

get_component_dirs() searches for dirs set in COMPONENTS.dirs settings. If none set, defaults to searching for a \"components\" app.

In addition to that, also all installed Django apps are checked whether they contain directories as set in COMPONENTS.app_dirs (e.g. [app]/components).

Notes:

  • Paths that do not point to directories are ignored.

  • BASE_DIR setting is required.

  • The paths in COMPONENTS.dirs must be absolute paths.

"},{"location":"reference/api/#django_components.get_component_files","title":"get_component_files","text":"
get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]\n

See source code

Search for files within the component directories (as defined in get_component_dirs()).

Requires BASE_DIR setting to be set.

Subdirectories and files starting with an underscore _ (except __init__.py) are ignored.

Parameters:

  • suffix (Optional[str], default: None ) \u2013

    The suffix to search for. E.g. .py, .js, .css. Defaults to None, which will search for all files.

Returns:

  • List[ComponentFileEntry] \u2013

    List[ComponentFileEntry] A list of entries that contain both the filesystem path and the python import path (dot path).

Example:

from django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
"},{"location":"reference/api/#django_components.import_libraries","title":"import_libraries","text":"
import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n

See source code

Import modules set in COMPONENTS.libraries setting.

See Autodiscovery.

Parameters:

  • map_module (Callable[[str], str], default: None ) \u2013

    Map the module paths with map_module function. This serves as an escape hatch for when you need to use this function in tests.

Returns:

  • List[str] \u2013

    List[str]: A list of module paths of imported files.

Examples:

Normal usage - load libraries after Django has loaded

from django_components import import_libraries\n\nclass MyAppConfig(AppConfig):\n    def ready(self):\n        import_libraries()\n

Potential usage in tests

from django_components import import_libraries\n\nimport_libraries(lambda path: path.replace(\"tests.\", \"myapp.\"))\n

"},{"location":"reference/api/#django_components.register","title":"register","text":"
register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[\n    [Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]]],\n    Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]],\n]\n

See source code

Class decorator for registering a component to a component registry.

See Registering components.

Parameters:

  • name (str) \u2013

    Registered name. This is the name by which the component will be accessed from within a template when using the {% component %} tag. Required.

  • registry (ComponentRegistry, default: None ) \u2013

    Specify the registry to which to register this component. If omitted, component is registered to the default registry.

Raises:

  • AlreadyRegistered \u2013

    If there is already a component registered under the same name.

Examples:

from django_components import Component, register\n\n@register(\"my_component\")\nclass MyComponent(Component):\n    ...\n

Specifing ComponentRegistry the component should be registered to by setting the registry kwarg:

from django.template import Library\nfrom django_components import Component, ComponentRegistry, register\n\nmy_lib = Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n    ...\n
"},{"location":"reference/api/#django_components.registry","title":"registry module-attribute","text":"
registry: ComponentRegistry = ComponentRegistry()\n

See source code

The default and global component registry. Use this instance to directly register or remove components:

See Registering components.

# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get single\nregistry.get(\"button\")\n\n# Get all\nregistry.all()\n\n# 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, type: RenderType = '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/commands/","title":"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/#upgradecomponent","title":"upgradecomponent","text":"
usage: manage.py upgradecomponent [-h] [--path PATH] [--version]\n                                  [-v {0,1,2,3}] [--settings SETTINGS]\n                                  [--pythonpath PYTHONPATH] [--traceback]\n                                  [--no-color] [--force-color] [--skip-checks]\n

See source code

Updates component and component_block tags to the new syntax

Options:

  • -h, --help
    • show this help message and exit
  • --path PATH
    • Path to search for components
  • --version
    • Show program's version number and exit.
  • -v {0,1,2,3}, --verbosity {0,1,2,3}
    • Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output
  • --settings SETTINGS
    • The Python path to a settings module, e.g. \"myproject.settings.main\". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used.
  • --pythonpath PYTHONPATH
    • A directory to add to the Python path, e.g. \"/home/djangoprojects/myproject\".
  • --traceback
    • Raise on CommandError exceptions.
  • --no-color
    • Don't colorize the command output.
  • --force-color
    • Force colorization of the command output.
  • --skip-checks
    • Skip system checks.
"},{"location":"reference/commands/#startcomponent","title":"startcomponent","text":"
usage: manage.py startcomponent [-h] [--path PATH] [--js JS] [--css CSS]\n                                [--template TEMPLATE] [--force] [--verbose]\n                                [--dry-run] [--version] [-v {0,1,2,3}]\n                                [--settings SETTINGS]\n                                [--pythonpath PYTHONPATH] [--traceback]\n                                [--no-color] [--force-color] [--skip-checks]\n                                name\n

See source code

Create a new django component.

Positional Arguments:

  • name
    • The name of the component to create. This is a required argument.

Options:

  • -h, --help
    • show this help message and exit
  • --path PATH
    • The path to the component's directory. This is an optional argument. If not provided, the command will use the COMPONENTS.dirs setting from your Django settings.
  • --js JS
    • The name of the JavaScript file. This is an optional argument. The default value is script.js.
  • --css CSS
    • The name of the CSS file. This is an optional argument. The default value is style.css.
  • --template TEMPLATE
    • The name of the template file. This is an optional argument. The default value is template.html.
  • --force
    • This option allows you to overwrite existing files if they exist. This is an optional argument.
  • --verbose
    • This option allows the command to print additional information during component creation. This is an optional argument.
  • --dry-run
    • This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False.
  • --version
    • Show program's version number and exit.
  • -v {0,1,2,3}, --verbosity {0,1,2,3}
    • Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output
  • --settings SETTINGS
    • The Python path to a settings module, e.g. \"myproject.settings.main\". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used.
  • --pythonpath PYTHONPATH
    • A directory to add to the Python path, e.g. \"/home/djangoprojects/myproject\".
  • --traceback
    • Raise on CommandError exceptions.
  • --no-color
    • Don't colorize the command output.
  • --force-color
    • Force colorization of the command output.
  • --skip-checks
    • Skip system checks.
"},{"location":"reference/commands/#management-command-usage","title":"Management Command Usage","text":"

To use the command, run the following command in your terminal:

python manage.py startcomponent <name> --path <path> --js <js_filename> --css <css_filename> --template <template_filename> --force --verbose --dry-run\n

Replace <name>, <path>, <js_filename>, <css_filename>, and <template_filename> with your desired values.

"},{"location":"reference/commands/#management-command-examples","title":"Management Command Examples","text":"

Here are some examples of how you can use the command:

"},{"location":"reference/commands/#creating-a-component-with-default-settings","title":"Creating a Component with Default Settings","text":"

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

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

"},{"location":"reference/commands/#creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"

You can also create a component with custom settings by providing additional arguments:

python manage.py startcomponent new_component --path my_components --js my_script.js --css my_style.css --template my_template.html\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.

"},{"location":"reference/commands/#overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"

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

python manage.py startcomponent my_component --force\n

This will overwrite the existing my_component if it exists.

"},{"location":"reference/commands/#simulating-component-creation","title":"Simulating Component Creation","text":"

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 startcomponent my_component --dry-run\n

This will simulate the creation of my_component without creating any files.

"},{"location":"reference/components/","title":"Components","text":""},{"location":"reference/components/#components","title":"Components","text":"

These are the components provided by django_components.

"},{"location":"reference/components/#django_components.components.dynamic.DynamicComponent","title":"DynamicComponent","text":"

Bases: django_components.component.Component

See source code

This component is given a registered name or a reference to another component, and behaves as if the other component was in its place.

The args, kwargs, and slot fills are all passed down to the underlying component.

Parameters:

  • is (str | Type[Component]) \u2013

    Component that should be rendered. Either a registered name of a component, or a Component class directly. Required.

  • registry (ComponentRegistry, default: None ) \u2013

    Specify the registry to search for the registered name. If omitted, all registries are searched until the first match.

  • *args \u2013

    Additional data passed to the component.

  • **kwargs \u2013

    Additional data passed to the component.

Slots:

  • Any slots, depending on the actual component.

Examples:

Django

{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% endcomponent %}\n

Or in case you use the django_components.component_shorthand_formatter tag formatter:

{% dynamic is=table_comp data=table_data headers=table_headers %}\n    {% fill \"pagination\" %}\n        {% component \"pagination\" / %}\n    {% endfill %}\n{% enddynamic %}\n

Python

from django_components import DynamicComponent\n\nDynamicComponent.render(\n    kwargs={\n        \"is\": table_comp,\n        \"data\": table_data,\n        \"headers\": table_headers,\n    },\n    slots={\n        \"pagination\": PaginationComponent.render(\n            render_dependencies=False,\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/middlewares/","title":"Middlewares","text":""},{"location":"reference/middlewares/#middlewares","title":"Middlewares","text":""},{"location":"reference/middlewares/#django_components.dependencies.ComponentDependencyMiddleware","title":"ComponentDependencyMiddleware","text":"

Bases: object

See source code

Middleware that inserts CSS/JS dependencies for all rendered components at points marked with template tags.

"},{"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    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    dynamic_component_name=\"dynamic\",\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.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.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.forbidden_static_files","title":"forbidden_static_files","text":"
forbidden_static_files: Optional[List[Union[str, Pattern]]] = None\n

See source code

Deprecated. Use COMPONENTS.static_files_forbidden instead.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.libraries","title":"libraries","text":"
libraries: Optional[List[str]] = None\n

See source code

Configure extra python modules that should be loaded.

This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.

Expects a list of python module paths. Defaults to empty list.

Example:

COMPONENTS = ComponentsSettings(\n    libraries=[\n        \"mysite.components.forms\",\n        \"mysite.components.buttons\",\n        \"mysite.components.cards\",\n    ],\n)\n

This would be the equivalent of importing these modules from within Django's AppConfig.ready():

class MyAppConfig(AppConfig):\n    def ready(self):\n        import \"mysite.components.forms\"\n        import \"mysite.components.buttons\"\n        import \"mysite.components.cards\"\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.libraries--manually-loading-libraries","title":"Manually loading libraries","text":"

In the rare case that you need to manually trigger the import of libraries, you can use the import_libraries() function:

from django_components import import_libraries\n\nimport_libraries()\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.multiline_tags","title":"multiline_tags","text":"
multiline_tags: Optional[bool] = None\n

See source code

Enable / disable multiline support for template tags. If True, template tags like {% component %} or {{ my_var }} can span multiple lines.

Defaults to True.

Disable this setting if you are making custom modifications to Django's regular expression for parsing templates at django.template.base.tag_re.

COMPONENTS = ComponentsSettings(\n    multiline_tags=False,\n)\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.reload_on_file_change","title":"reload_on_file_change","text":"
reload_on_file_change: Optional[bool] = None\n

See source code

This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.

In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.

Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.

The setting reload_on_file_change fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.

If True, django_components configures Django to reload when files inside COMPONENTS.dirs or COMPONENTS.app_dirs change.

See Reload dev server on component file changes.

Defaults to False.

Warning

This setting should be enabled only for the dev environment!

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.reload_on_template_change","title":"reload_on_template_change","text":"
reload_on_template_change: Optional[bool] = None\n

See source code

Deprecated. Use COMPONENTS.reload_on_file_change instead.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.static_files_allowed","title":"static_files_allowed","text":"
static_files_allowed: Optional[List[Union[str, Pattern]]] = None\n

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs are treated as static files.

If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running collectstatic, and can be accessed under the static file endpoint.

You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

By default, JS, CSS, and common image and font file formats are considered static files:

COMPONENTS = ComponentsSettings(\n    static_files_allowed=[\n        \".css\",\n        \".js\", \".jsx\", \".ts\", \".tsx\",\n        # Images\n        \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n        \".jpeg\",  \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n        \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n        # Fonts\n        \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n    ],\n)\n

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.static_files_forbidden","title":"static_files_forbidden","text":"
static_files_forbidden: Optional[List[Union[str, Pattern]]] = None\n

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs will NEVER be treated as static files.

If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in static_files_allowed.

Use this setting together with static_files_allowed for a fine control over what file types will be exposed.

You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

By default, any HTML and Python are considered NOT static files:

COMPONENTS = ComponentsSettings(\n    static_files_forbidden=[\n        \".html\", \".django\", \".dj\", \".tpl\",\n        # Python files\n        \".py\", \".pyc\",\n    ],\n)\n

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.tag_formatter","title":"tag_formatter","text":"
tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n

See source code

Configure what syntax is used inside Django templates to render components. See the available tag formatters.

Defaults to \"django_components.component_formatter\".

Learn more about Customizing component tags with TagFormatter.

Can be set either as direct reference:

from django_components import component_formatter\n\nCOMPONENTS = ComponentsSettings(\n    \"tag_formatter\": component_formatter\n)\n

Or as an import string;

COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_formatter\"\n)\n

Examples:

  • \"django_components.component_formatter\"

    Set

    COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_formatter\"\n)\n

    To write components like this:

    {% component \"button\" href=\"...\" %}\n    Click me!\n{% endcomponent %}\n
  • django_components.component_shorthand_formatter

    Set

    COMPONENTS = ComponentsSettings(\n    \"tag_formatter\": \"django_components.component_shorthand_formatter\"\n)\n

    To write components like this:

    {% button href=\"...\" %}\n    Click me!\n{% endbutton %}\n
"},{"location":"reference/settings/#django_components.app_settings.ComponentsSettings.template_cache_size","title":"template_cache_size","text":"
template_cache_size: Optional[int] = None\n

See source code

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/tag_formatters/","title":"Tag formatters","text":""},{"location":"reference/tag_formatters/#tag-formatters","title":"Tag Formatters","text":"

Tag formatters allow you to change the syntax for calling components from within the Django templates.

Tag formatter are set via the tag_formatter setting.

"},{"location":"reference/tag_formatters/#available-tag-formatters","title":"Available tag formatters","text":"
  • django_components.component_formatter for ComponentFormatter

  • django_components.component_shorthand_formatter for ShorthandComponentFormatter

"},{"location":"reference/tag_formatters/#django_components.tag_formatter.ComponentFormatter","title":"ComponentFormatter","text":"

Bases: django_components.tag_formatter.TagFormatterABC

See source code

The original django_component's component tag formatter, it uses the {% component %} and {% endcomponent %} tags, and the component name is given as the first positional arg.

Example as block:

{% component \"mycomp\" abc=123 %}\n    {% fill \"myfill\" %}\n        ...\n    {% endfill %}\n{% endcomponent %}\n

Example as inlined tag:

{% component \"mycomp\" abc=123 / %}\n

"},{"location":"reference/tag_formatters/#django_components.tag_formatter.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":"

Bases: django_components.tag_formatter.TagFormatterABC

See source code

The component tag formatter that uses {% <name> %} / {% end<name> %} tags.

This is similar to django-web-components and django-slippers syntax.

Example as block:

{% mycomp abc=123 %}\n    {% fill \"myfill\" %}\n        ...\n    {% endfill %}\n{% endmycomp %}\n

Example as inlined tag:

{% mycomp abc=123 / %}\n

"},{"location":"reference/template_tags/","title":"Template tags","text":""},{"location":"reference/template_tags/#template-tags","title":"Template tags","text":"

All following template tags are defined in

django_components.templatetags.component_tags

Import as

{% load component_tags %}\n

"},{"location":"reference/template_tags/#component","title":"component","text":"
{% component [arg, ...] **kwargs [only] %}\n{% endcomponent %}\n

See source code

Renders one of the components that was previously registered with @register() decorator.

Args:

  • name (str, required): Registered name of the component to render
  • All other args and kwargs are defined based on the component itself.

If you defined a component \"my_table\"

from django_component import Component, register\n\n@register(\"my_table\")\nclass MyTable(Component):\n    template = \"\"\"\n      <table>\n        <thead>\n          {% for header in headers %}\n            <th>{{ header }}</th>\n          {% endfor %}\n        </thead>\n        <tbody>\n          {% for row in rows %}\n            <tr>\n              {% for cell in row %}\n                <td>{{ cell }}</td>\n              {% endfor %}\n            </tr>\n          {% endfor %}\n        <tbody>\n      </table>\n    \"\"\"\n\n    def get_context_data(self, rows: List, headers: List):\n        return {\n            \"rows\": rows,\n            \"headers\": headers,\n        }\n

Then you can render this component by referring to MyTable via its registered name \"my_table\":

{% component \"my_table\" rows=rows headers=headers ... / %}\n
"},{"location":"reference/template_tags/#component-input","title":"Component input","text":"

Positional and keyword arguments can be literals or template variables.

The component name must be a single- or double-quotes string and must be either:

  • The first positional argument after component:

    {% component \"my_table\" rows=rows headers=headers ... / %}\n
  • Passed as kwarg name:

    {% component rows=rows headers=headers name=\"my_table\" ... / %}\n
"},{"location":"reference/template_tags/#inserting-into-slots","title":"Inserting into slots","text":"

If the component defined any slots, you can pass in the content to be placed inside those slots by inserting {% fill %} tags, directly within the {% component %} tag:

{% component \"my_table\" rows=rows headers=headers ... / %}\n  {% fill \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endfill %}\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
"},{"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 JS and CSS output 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 JS and CSS output 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/#fill","title":"fill","text":"
{% fill name data=None default=None %}\n{% endfill %}\n

See source code

Use this tag to insert content into component's slots.

{% fill %} tag may be used only within a {% component %}..{% endcomponent %} block. Runtime checks should prohibit other usages.

Args:

  • name (str, required): Name of the slot to insert this content into. Use \"default\" for the default slot.
  • default (str, optional): This argument allows you to access the original content of the slot under the specified variable name. See Accessing original content of slots
  • data (str, optional): This argument allows you to access the data passed to the slot under the specified variable name. See Scoped slots

Examples:

Basic usage:

{% component \"my_table\" %}\n  {% fill \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endfill %}\n{% endcomponent %}\n

"},{"location":"reference/template_tags/#accessing-slots-default-content-with-the-default-kwarg","title":"Accessing slot's default content with the default kwarg","text":"
{# my_table.html #}\n<table>\n  ...\n  {% slot \"pagination\" %}\n    < 1 | 2 | 3 >\n  {% endslot %}\n</table>\n
{% component \"my_table\" %}\n  {% fill \"pagination\" default=\"default_pag\" %}\n    <div class=\"my-class\">\n      {{ default_pag }}\n    </div>\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/template_tags/#accessing-slots-data-with-the-data-kwarg","title":"Accessing slot's data with the data kwarg","text":"
{# my_table.html #}\n<table>\n  ...\n  {% slot \"pagination\" pages=pages %}\n    < 1 | 2 | 3 >\n  {% endslot %}\n</table>\n
{% 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/#accessing-slot-data-and-default-content-on-the-default-slot","title":"Accessing slot data and default content on the default slot","text":"

To access slot data and the default slot content on the default slot, use {% fill %} with name set to \"default\":

{% component \"button\" %}\n  {% fill name=\"default\" data=\"slot_data\" default=\"default_slot\" %}\n    You clicked me {{ slot_data.count }} times!\n    {{ default_slot }}\n  {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/template_tags/#html_attrs","title":"html_attrs","text":"
{% html_attrs attrs=None defaults=None **kwargs %}\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 with the internal. See how to in Passing HTML attributes to components.

Args:

  • attrs (dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides values in the default dictionary.
  • default (str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden with values in the attrs dictionary.
  • Any extra kwargs will be appended to the corresponding keys

The attributes in attrs and defaults are merged and resulting dict is rendered as HTML attributes (key=\"value\").

Extra kwargs (key=value) are concatenated to existing keys. So if we have

attrs = {\"class\": \"my-class\"}\n

Then

{% html_attrs attrs class=\"extra-class\" %}\n

will result in class=\"my-class extra-class\".

Example:

<div {% html_attrs\n    attrs\n    defaults:class=\"default-class\"\n    class=\"extra-class\"\n    data-id=\"123\"\n%}>\n

renders

<div class=\"my-class extra-class\" data-id=\"123\">\n

See more usage examples in HTML attributes.

"},{"location":"reference/template_tags/#provide","title":"provide","text":"
{% provide name **kwargs %}\n{% endprovide %}\n

See source code

The \"provider\" part of the provide / inject feature. Pass kwargs to this tag to define the provider's data. Any components defined within the {% provide %}..{% endprovide %} tags will be able to access this data with Component.inject().

This is similar to React's ContextProvider, or Vue's provide().

Args:

  • name (str, required): Provider name. This is the name you will then use in Component.inject().
  • **kwargs: Any extra kwargs will be passed as the provided data.

Example:

Provide the \"user_data\" in parent component:

@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      <div>\n        {% provide \"user_data\" user=user %}\n          {% component \"child\" / %}\n        {% endprovide %}\n      </div>\n    \"\"\"\n\n    def get_context_data(self, user: User):\n        return {\n            \"user\": 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_context_data(self):\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 **kwargs [default] [required] %}\n{% endslot %}\n

See source code

Slot tag marks a place inside a component where content can be inserted from outside.

Learn more about using slots.

This is similar to slots as seen in Web components, Vue or React's children.

Args:

  • name (str, required): Registered name of the component to render
  • default: Optional flag. If there is a default slot, you can pass the component slot content without using the {% fill %} tag. See Default slot
  • required: Optional flag. Will raise an error if a slot is required but not given.
  • **kwargs: Any extra kwargs will be passed as the slot data.

Example:

@register(\"child\")\nclass Child(Component):\n    template = \"\"\"\n      <div>\n        {% slot \"content\" default %}\n          This is shown if not overriden!\n        {% endslot %}\n      </div>\n      <aside>\n        {% slot \"sidebar\" required / %}\n      </aside>\n    \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      <div>\n        {% component \"child\" %}\n          {% fill \"content\" %}\n            \ud83d\uddde\ufe0f\ud83d\udcf0\n          {% endfill %}\n\n          {% fill \"sidebar\" %}\n            \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n          {% endfill %}\n        {% endcomponent %}\n      </div>\n    \"\"\"\n
"},{"location":"reference/template_tags/#passing-data-to-slots","title":"Passing data to slots","text":"

Any extra kwargs will be considered as slot data, and will be accessible in the {% fill %} tag via fill's data kwarg:

@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/#accessing-default-slot-content","title":"Accessing default slot content","text":"

The content between the {% slot %}..{% endslot %} tags is the default content that will be rendered if no fill is given for the slot.

This default content can then be accessed from within the {% fill %} tag using the fill's default 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 default content!\n        {% endslot %}\n      </div>\n    \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n    template = \"\"\"\n      {# Parent can access the slot's default content #}\n      {% component \"child\" %}\n        {% fill \"content\" default=\"default\" %}\n          {{ default }}\n        {% endfill %}\n      {% endcomponent %}\n    \"\"\"\n
"},{"location":"reference/template_vars/","title":"Template vars","text":""},{"location":"reference/template_vars/#template-variables","title":"Template variables","text":"

Here is a list of all variables that are automatically available from inside the component's template and in on_render_before / on_render_after hooks.

"},{"location":"reference/template_vars/#django_components.component.ComponentVars.is_filled","title":"is_filled instance-attribute","text":"
is_filled: Dict[str, bool]\n

See source code

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_context_data(self, *args, **kwargs):\n        return {\n            \"my_slot_filled\": \"my_slot\" in self.input.slots\n        }\n
"},{"location":"reference/urls/","title":"Urls","text":""},{"location":"reference/urls/#urls","title":"URLs","text":"

Below are all the URL patterns that will be added by adding django_components.urls.

See Installation on how to add these URLs to your Django project.

Django components already prefixes all URLs with components/. So when you are adding the URLs to urlpatterns, you can use an empty string as the first argument:

from django.urls import include, path\n\nurlpatterns = [\n    ...\n    path(\"\", include(\"django_components.urls\")),\n]\n
"},{"location":"reference/urls/#list-of-urls","title":"List of URLs","text":"
  • components/cache/<str:comp_cls_hash>.<str:input_hash>.<str:script_type>

  • components/cache/<str:comp_cls_hash>.<str:script_type>

"}]} \ No newline at end of file diff --git a/versions.json b/versions.json index b6107582..dc9c58d4 100644 --- a/versions.json +++ b/versions.json @@ -1,7 +1,7 @@ [ { "version": "dev", - "title": "dev (1e4b556)", + "title": "dev (203d29f)", "aliases": [] }, {