diff --git a/dev/404.html b/dev/404.html index a9413510..81f4565f 100644 --- a/dev/404.html +++ b/dev/404.html @@ -1 +1 @@ - Django-Components

404 - Not found

\ No newline at end of file + Django-Components

404 - Not found

\ No newline at end of file diff --git a/dev/CHANGELOG/index.html b/dev/CHANGELOG/index.html index afc7aaa2..5230f76c 100644 --- a/dev/CHANGELOG/index.html +++ b/dev/CHANGELOG/index.html @@ -1,4 +1,4 @@ - Changelog - Django-Components
Skip to content

Release notes¤

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

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

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

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

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

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

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

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

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

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

{# Before #}
+ Changelog - Django-Components      

Release notes¤

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

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

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

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

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

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

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

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

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

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

{# Before #}
 {% component "button" %}{% endcomponent %}
 {# After #}
 {% component "button" / %}
@@ -10,7 +10,7 @@
 {% endcomponent %}
 ```
 
-While `django_components.shorthand_component_formatter` allows you to write components like so:
+While `django_components.component_shorthand_formatter` allows you to write components like so:
 
 ```django
 {% button href="..." disabled %}
@@ -547,7 +547,7 @@ def on_render_after(self, context, template, content):
     {% endfill %}
 {% endcomponent %}
 

Example as inlined tag:

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

  • ShorthandComponentFormatter (django_components.shorthand_component_formatter)

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

    Example as block:

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

  • 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="..." %}
         Click me!
     {% endbutton %}
     

    Example as inlined tag:

    {% button href="..." / %}
    diff --git a/dev/CODE_OF_CONDUCT/index.html b/dev/CODE_OF_CONDUCT/index.html
    index 14e40d35..5af213fa 100644
    --- a/dev/CODE_OF_CONDUCT/index.html
    +++ b/dev/CODE_OF_CONDUCT/index.html
    @@ -1 +1 @@
    - Code of Conduct - Django-Components      

    Contributor Covenant Code of Conduct¤

    Our Pledge¤

    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.

    Our Standards¤

    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

    Our Responsibilities¤

    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.

    Scope¤

    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.

    Enforcement¤

    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.

    Attribution¤

    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

    \ No newline at end of file + Code of Conduct - Django-Components

    Contributor Covenant Code of Conduct¤

    Our Pledge¤

    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.

    Our Standards¤

    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

    Our Responsibilities¤

    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.

    Scope¤

    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.

    Enforcement¤

    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.

    Attribution¤

    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

    \ No newline at end of file diff --git a/dev/SUMMARY/index.html b/dev/SUMMARY/index.html index c3bbbb84..b28a6fa5 100644 --- a/dev/SUMMARY/index.html +++ b/dev/SUMMARY/index.html @@ -1 +1 @@ - SUMMARY - Django-Components
    \ No newline at end of file + SUMMARY - Django-Components
    \ No newline at end of file diff --git a/dev/assets/_mkdocstrings.css b/dev/assets/_mkdocstrings.css index 85449ec7..b500381b 100644 --- a/dev/assets/_mkdocstrings.css +++ b/dev/assets/_mkdocstrings.css @@ -26,20 +26,33 @@ float: right; } +/* Parameter headings must be inline, not blocks. */ +.doc-heading-parameter { + display: inline; +} + +/* Prefer space on the right, not the left of parameter permalinks. */ +.doc-heading-parameter .headerlink { + margin-left: 0 !important; + margin-right: 0.2rem; +} + /* Backward-compatibility: docstring section titles in bold. */ .doc-section-title { font-weight: bold; } /* Symbols in Navigation and ToC. */ -:root, +:root, :host, [data-md-color-scheme="default"] { + --doc-symbol-parameter-fg-color: #df50af; --doc-symbol-attribute-fg-color: #953800; --doc-symbol-function-fg-color: #8250df; --doc-symbol-method-fg-color: #8250df; --doc-symbol-class-fg-color: #0550ae; --doc-symbol-module-fg-color: #5cad0f; + --doc-symbol-parameter-bg-color: #df50af1a; --doc-symbol-attribute-bg-color: #9538001a; --doc-symbol-function-bg-color: #8250df1a; --doc-symbol-method-bg-color: #8250df1a; @@ -48,12 +61,14 @@ } [data-md-color-scheme="slate"] { + --doc-symbol-parameter-fg-color: #ffa8cc; --doc-symbol-attribute-fg-color: #ffa657; --doc-symbol-function-fg-color: #d2a8ff; --doc-symbol-method-fg-color: #d2a8ff; --doc-symbol-class-fg-color: #79c0ff; --doc-symbol-module-fg-color: #baff79; + --doc-symbol-parameter-bg-color: #ffa8cc1a; --doc-symbol-attribute-bg-color: #ffa6571a; --doc-symbol-function-bg-color: #d2a8ff1a; --doc-symbol-method-bg-color: #d2a8ff1a; @@ -68,6 +83,15 @@ code.doc-symbol { font-weight: bold; } +code.doc-symbol-parameter { + color: var(--doc-symbol-parameter-fg-color); + background-color: var(--doc-symbol-parameter-bg-color); +} + +code.doc-symbol-parameter::after { + content: "param"; +} + code.doc-symbol-attribute { color: var(--doc-symbol-attribute-fg-color); background-color: var(--doc-symbol-attribute-bg-color); diff --git a/dev/index.html b/dev/index.html index 112238d1..c4c44531 100644 --- a/dev/index.html +++ b/dev/index.html @@ -1,4 +1,4 @@ - Index - Django-Components

    django-components¤

    PyPI - Version PyPI - Python Version PyPI - License PyPI - Downloads GitHub Actions Workflow Status

    Docs (Work in progress)

    Django-components is a package that introduces component-based architecture to Django's server-side rendering. It aims to combine Django's templating system with the modularity seen in modern frontend frameworks.

    Features¤

    1. 🧩 Reusability: Allows creation of self-contained, reusable UI elements.
    2. 📦 Encapsulation: Each component can include its own HTML, CSS, and JavaScript.
    3. 🚀 Server-side rendering: Components render on the server, improving initial load times and SEO.
    4. 🐍 Django integration: Works within the Django ecosystem, using familiar concepts like template tags.
    5. Asynchronous loading: Components can render independently opening up for integration with JS frameworks like HTMX or AlpineJS.

    Potential benefits:

    • 🔄 Reduced code duplication
    • 🛠️ Improved maintainability through modular design
    • 🧠 Easier management of complex UIs
    • 🤝 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.

    Summary¤

    It lets you create "template components", that contains both the template, the Javascript and the CSS needed to generate the front end code you need for a modern app. Use components like this:

    {% component "calendar" date="2015-06-19" %}{% endcomponent %}
    + Index - Django-Components      

    django-components¤

    PyPI - Version PyPI - Python Version PyPI - License PyPI - Downloads GitHub Actions Workflow Status

    Docs (Work in progress)

    Django-components is a package that introduces component-based architecture to Django's server-side rendering. It aims to combine Django's templating system with the modularity seen in modern frontend frameworks.

    Features¤

    1. 🧩 Reusability: Allows creation of self-contained, reusable UI elements.
    2. 📦 Encapsulation: Each component can include its own HTML, CSS, and JavaScript.
    3. 🚀 Server-side rendering: Components render on the server, improving initial load times and SEO.
    4. 🐍 Django integration: Works within the Django ecosystem, using familiar concepts like template tags.
    5. Asynchronous loading: Components can render independently opening up for integration with JS frameworks like HTMX or AlpineJS.

    Potential benefits:

    • 🔄 Reduced code duplication
    • 🛠️ Improved maintainability through modular design
    • 🧠 Easier management of complex UIs
    • 🤝 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.

    Summary¤

    It lets you create "template components", that contains both the template, the Javascript and the CSS needed to generate the front end code you need for a modern app. Use components like this:

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

    And this is what gets rendered (plus the CSS and Javascript you've specified):

    <div class="calendar-component">Today's date is <span>2015-06-19</span></div>
     

    See the example project or read on to learn about the details!

    Table of Contents¤

    Release notes¤

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

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

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

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

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

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

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

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

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

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

    {# Before #}
     {% component "button" %}{% endcomponent %}
    @@ -12,7 +12,7 @@
     {% endcomponent %}
     ```
     
    -While `django_components.shorthand_component_formatter` allows you to write components like so:
    +While `django_components.component_shorthand_formatter` allows you to write components like so:
     
     ```django
     {% button href="..." disabled %}
    @@ -1082,7 +1082,7 @@ def on_render_after(self, context, template, content):
     {# or #}
     
     {% component "button" href="..." disabled / %}
    -

    You can change this behaviour in the settings under the COMPONENTS.tag_formatter.

    For example, if you set the tag formatter to django_components.shorthand_component_formatter, the components will use their name as the template tags:

    {% button href="..." disabled %}
    +

    You can change this behaviour in the settings under the COMPONENTS.tag_formatter.

    For example, if you set the tag formatter to django_components.component_shorthand_formatter, the components will use their name as the template tags:

    {% button href="..." disabled %}
       Click me!
     {% endbutton %}
     
    @@ -1095,7 +1095,7 @@ def on_render_after(self, context, template, content):
         {% endfill %}
     {% endcomponent %}
     

    Example as inlined tag:

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

  • ShorthandComponentFormatter (django_components.shorthand_component_formatter)

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

    Example as block:

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

  • 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="..." %}
         Click me!
     {% endbutton %}
     

    Example as inlined tag:

    {% button href="..." / %}
    diff --git a/dev/license/index.html b/dev/license/index.html
    index af475570..38046877 100644
    --- a/dev/license/index.html
    +++ b/dev/license/index.html
    @@ -1 +1 @@
    - License - Django-Components      

    License¤

    MIT License

    Copyright (c) 2019 Emil Stenström

    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.

    \ No newline at end of file + License - Django-Components

    License¤

    MIT License

    Copyright (c) 2019 Emil Stenström

    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.

    \ No newline at end of file diff --git a/dev/migrating_from_safer_staticfiles/index.html b/dev/migrating_from_safer_staticfiles/index.html index f5166a61..f1ec9ecd 100644 --- a/dev/migrating_from_safer_staticfiles/index.html +++ b/dev/migrating_from_safer_staticfiles/index.html @@ -1,4 +1,4 @@ - Migrating from safer_staticfiles - Django-Components

    Migrating from safer_staticfiles¤

    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 = [
    + Migrating from safer_staticfiles - Django-Components      

    Migrating from safer_staticfiles¤

    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 = [
        "django.contrib.admin",
        ...
        # "django.contrib.staticfiles",  # <-- ADD
    diff --git a/dev/reference/SUMMARY/index.html b/dev/reference/SUMMARY/index.html
    index af6d31e7..d539e55c 100644
    --- a/dev/reference/SUMMARY/index.html
    +++ b/dev/reference/SUMMARY/index.html
    @@ -1 +1 @@
    - SUMMARY - Django-Components     
    \ No newline at end of file + SUMMARY - Django-Components
    \ No newline at end of file diff --git a/dev/reference/django_components/app_settings/index.html b/dev/reference/django_components/app_settings/index.html index 2c5ad9a2..5734b7fe 100644 --- a/dev/reference/django_components/app_settings/index.html +++ b/dev/reference/django_components/app_settings/index.html @@ -1,4 +1,4 @@ - app_settings - Django-Components
    app_settings - Django-Components" >
    app_settings - Django-Components" >

    app_settings ¤

    ContextBehavior ¤

    Bases: str, Enum

    DJANGO class-attribute instance-attribute ¤

    DJANGO = 'django'
    + app_settings - Django-Components app_settings - Django-Components" >  app_settings - Django-Components" >       

    app_settings ¤

    Classes:

    ContextBehavior ¤

    Bases: str, Enum

    Attributes:

    • DJANGO

      With this setting, component fills behave as usual Django tags.

    • ISOLATED

      This setting makes the component fills behave similar to Vue or React, where

    DJANGO class-attribute instance-attribute ¤

    DJANGO = 'django'
     

    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 get_context_data are available to the component fill.

    Example:

    Given this template

    {% with cheese="feta" %}
       {% component 'my_comp' %}
         {{ my_var }}  # my_var
    diff --git a/dev/reference/django_components/apps/index.html b/dev/reference/django_components/apps/index.html
    index 098ef1de..4506d6d5 100644
    --- a/dev/reference/django_components/apps/index.html
    +++ b/dev/reference/django_components/apps/index.html
    @@ -1 +1 @@
    - apps - Django-Components apps - Django-Components" >  apps - Django-Components" >       
    \ No newline at end of file + apps - Django-Components apps - Django-Components" > apps - Django-Components" >
    \ No newline at end of file diff --git a/dev/reference/django_components/attributes/index.html b/dev/reference/django_components/attributes/index.html index f9d19391..ce03f530 100644 --- a/dev/reference/django_components/attributes/index.html +++ b/dev/reference/django_components/attributes/index.html @@ -1,4 +1,4 @@ - attributes - Django-Components attributes - Django-Components" >
    attributes - Django-Components" >

    attributes ¤

    append_attributes ¤

    append_attributes(*args: Tuple[str, Any]) -> Dict
    + attributes - Django-Components attributes - Django-Components" >  attributes - Django-Components" >       

    attributes ¤

    Functions:

    append_attributes ¤

    append_attributes(*args: Tuple[str, Any]) -> Dict
     

    Merges the key-value pairs and returns a new dictionary.

    If a key is present multiple times, its values are concatenated with a space character as separator in the final dictionary.

    Source code in src/django_components/attributes.py
    71
     72
     73
    diff --git a/dev/reference/django_components/autodiscover/index.html b/dev/reference/django_components/autodiscover/index.html
    index 508ca95c..bc426126 100644
    --- a/dev/reference/django_components/autodiscover/index.html
    +++ b/dev/reference/django_components/autodiscover/index.html
    @@ -1,4 +1,4 @@
    - autodiscover - Django-Components autodiscover - Django-Components" >  autodiscover - Django-Components" >       

    autodiscover ¤

    autodiscover ¤

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

    autodiscover ¤

    Functions:

    • autodiscover

      Search for component files and import them. Returns a list of module

    • import_libraries

      Import modules set in COMPONENTS.libraries setting.

    • search_dirs

      Search the directories for the given glob pattern. Glob search results are returned

    autodiscover ¤

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

    Search for component files and import them. Returns a list of module paths of imported files.

    Autodiscover searches in the locations as defined by Loader.get_dirs.

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

    Source code in src/django_components/autodiscover.py
    15
     16
     17
    diff --git a/dev/reference/django_components/component/index.html b/dev/reference/django_components/component/index.html
    index 01284576..b1e821bd 100644
    --- a/dev/reference/django_components/component/index.html
    +++ b/dev/reference/django_components/component/index.html
    @@ -1,11 +1,11 @@
    - component - Django-Components component - Django-Components" >  component - Django-Components" >       

    component ¤

    Component ¤

    Component(
    + component - Django-Components component - Django-Components" >  component - Django-Components" >       

    component ¤

    Classes:

    • Component
    • ComponentNode

      Django.template.Node subclass that renders a django-components component

    • ComponentView

      Subclass of django.views.View where the Component instance is available

    Component ¤

    Component(
         registered_name: Optional[str] = None,
         component_id: Optional[str] = None,
         outer_context: Optional[Context] = None,
         fill_content: Optional[Dict[str, FillContent]] = None,
         registry: Optional[ComponentRegistry] = None,
     )
    -

    Bases: Generic[ArgsType, KwargsType, DataType, SlotsType]

    Source code in src/django_components/component.py
    233
    +

    Bases: Generic[ArgsType, KwargsType, DataType, SlotsType]

    Methods:

    • as_view

      Shortcut for calling Component.View.as_view and passing component instance to it.

    • get_template

      Inlined Django template associated with this component. Can be a plain string or a Template instance.

    • get_template_name

      Filepath to the Django template associated with this component.

    • inject

      Use this method to retrieve the data that was passed to a {% provide %} tag

    • on_render_after

      Hook that runs just after the component's template was rendered.

    • on_render_before

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

    • render

      Render the component into a string.

    • render_css_dependencies

      Render only CSS dependencies available in the media class or provided as a string.

    • render_dependencies

      Helper function to render all dependencies for a component.

    • render_js_dependencies

      Render only JS dependencies available in the media class or provided as a string.

    • render_to_response

      Render the component and wrap the content in the response class.

    Attributes:

    • Media

      Defines JS and CSS media files associated with this component.

    • css (Optional[str]) –

      Inlined CSS associated with this component.

    • input (RenderInput[ArgsType, KwargsType, SlotsType]) –

      Input holds the data (like arg, kwargs, slots) that were passsed to

    • is_filled (Dict[str, bool]) –

      Dictionary describing which slots have or have not been filled.

    • js (Optional[str]) –

      Inlined JS associated with this component.

    • media (Media) –

      Normalized definition of JS and CSS media files associated with this component.

    • response_class

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

    • template (Optional[Union[str, Template]]) –

      Inlined Django template associated with this component. Can be a plain string or a Template instance.

    • template_name (Optional[str]) –

      Filepath to the Django template associated with this component.

    Source code in src/django_components/component.py
    233
     234
     235
     236
    diff --git a/dev/reference/django_components/component_media/index.html b/dev/reference/django_components/component_media/index.html
    index aec94a02..8dfec5e8 100644
    --- a/dev/reference/django_components/component_media/index.html
    +++ b/dev/reference/django_components/component_media/index.html
    @@ -1,4 +1,4 @@
    - component_media - Django-Components component_media - Django-Components" >  component_media - Django-Components" >       

    component_media ¤

    ComponentMediaInput ¤

    Defines JS and CSS media files associated with this component.

    MediaMeta ¤

    Bases: MediaDefiningClass

    Metaclass for handling media files for components.

    Similar to MediaDefiningClass, this class supports the use of Media attribute to define associated JS/CSS files, which are then available under media attribute as a instance of Media class.

    This subclass has following changes:

    1. Support for multiple interfaces of JS/CSS¤
    1. As plain strings

      class MyComponent(Component):
      + component_media - Django-Components component_media - Django-Components" >  component_media - Django-Components" >       

      component_media ¤

      Classes:

      • ComponentMediaInput

        Defines JS and CSS media files associated with this component.

      • MediaMeta

        Metaclass for handling media files for components.

      ComponentMediaInput ¤

      Defines JS and CSS media files associated with this component.

      MediaMeta ¤

      Bases: MediaDefiningClass

      Metaclass for handling media files for components.

      Similar to MediaDefiningClass, this class supports the use of Media attribute to define associated JS/CSS files, which are then available under media attribute as a instance of Media class.

      This subclass has following changes:

      1. Support for multiple interfaces of JS/CSS¤
      1. As plain strings

        class MyComponent(Component):
             class Media:
                 js = "path/to/script.js"
                 css = "path/to/style.css"
        diff --git a/dev/reference/django_components/component_registry/index.html b/dev/reference/django_components/component_registry/index.html
        index bc4e56db..d96b66e6 100644
        --- a/dev/reference/django_components/component_registry/index.html
        +++ b/dev/reference/django_components/component_registry/index.html
        @@ -1,4 +1,4 @@
        - component_registry - Django-Components component_registry - Django-Components" >  component_registry - Django-Components" >       

        component_registry ¤

        registry module-attribute ¤

        registry: ComponentRegistry = ComponentRegistry()
        + component_registry - Django-Components component_registry - Django-Components" >  component_registry - Django-Components" >       

        component_registry ¤

        Classes:

        Functions:

        • register

          Class decorator to register a component.

        Attributes:

        registry module-attribute ¤

        The default and global component registry. Use this instance to directly register or remove components:

        # Register components
         registry.register("button", ButtonComponent)
         registry.register("card", CardComponent)
        @@ -26,7 +26,7 @@
         registry.all()
         registry.clear()
         registry.get()
        -
        Source code in src/django_components/component_registry.py
        86
        +

        Methods:

        • all

          Retrieve all registered component classes.

        • clear

          Clears the registry, unregistering all components.

        • get

          Retrieve a component class registered under the given name.

        • register

          Register a component with this registry under the given name.

        • unregister

          Unlinks a previously-registered component from the registry under the given name.

        Attributes:

        • library (Library) –

          The template tag library with which the component registry is associated.

        Source code in src/django_components/component_registry.py
        86
         87
         88
         89
        diff --git a/dev/reference/django_components/components/dynamic/index.html b/dev/reference/django_components/components/dynamic/index.html
        index 36ad419f..a75440be 100644
        --- a/dev/reference/django_components/components/dynamic/index.html
        +++ b/dev/reference/django_components/components/dynamic/index.html
        @@ -1,11 +1,11 @@
        - dynamic - Django-Components dynamic - Django-Components" >  dynamic - Django-Components" >       

        dynamic ¤

        DynamicComponent ¤

        DynamicComponent(
        + dynamic - Django-Components dynamic - Django-Components" >  dynamic - Django-Components" >       

        dynamic ¤

        Modules:

        • types

          Helper types for IDEs.

        Classes:

        • DynamicComponent

          Dynamic component - This component takes inputs and renders the outputs depending on the

        DynamicComponent ¤

        DynamicComponent(
             registered_name: Optional[str] = None,
             component_id: Optional[str] = None,
             outer_context: Optional[Context] = None,
             fill_content: Optional[Dict[str, FillContent]] = None,
             registry: Optional[ComponentRegistry] = None,
         )
        -

        Bases: Component

        Dynamic component - This component takes inputs and renders the outputs depending on the is and registry arguments.

        • is - required - The component class or registered name of the component that will be rendered in this place.

        • registry - optional - Specify the registry to search for the registered name. If omitted, all registries are searched.

        Source code in src/django_components/component.py
        233
        +

        Bases: Component

        Dynamic component - This component takes inputs and renders the outputs depending on the is and registry arguments.

        • is - required - The component class or registered name of the component that will be rendered in this place.

        • registry - optional - Specify the registry to search for the registered name. If omitted, all registries are searched.

        Methods:

        • as_view

          Shortcut for calling Component.View.as_view and passing component instance to it.

        • get_template

          Inlined Django template associated with this component. Can be a plain string or a Template instance.

        • get_template_name

          Filepath to the Django template associated with this component.

        • inject

          Use this method to retrieve the data that was passed to a {% provide %} tag

        • on_render_after

          Hook that runs just after the component's template was rendered.

        • on_render_before

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

        • render

          Render the component into a string.

        • render_css_dependencies

          Render only CSS dependencies available in the media class or provided as a string.

        • render_dependencies

          Helper function to render all dependencies for a component.

        • render_js_dependencies

          Render only JS dependencies available in the media class or provided as a string.

        • render_to_response

          Render the component and wrap the content in the response class.

        Attributes:

        • Media

          Defines JS and CSS media files associated with this component.

        • css (Optional[str]) –

          Inlined CSS associated with this component.

        • input (RenderInput[ArgsType, KwargsType, SlotsType]) –

          Input holds the data (like arg, kwargs, slots) that were passsed to

        • is_filled (Dict[str, bool]) –

          Dictionary describing which slots have or have not been filled.

        • js (Optional[str]) –

          Inlined JS associated with this component.

        • media (Media) –

          Normalized definition of JS and CSS media files associated with this component.

        • response_class

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

        • template_name (Optional[str]) –

          Filepath to the Django template associated with this component.

        Source code in src/django_components/component.py
        233
         234
         235
         236
        diff --git a/dev/reference/django_components/components/index.html b/dev/reference/django_components/components/index.html
        index 242a6861..9f36d656 100644
        --- a/dev/reference/django_components/components/index.html
        +++ b/dev/reference/django_components/components/index.html
        @@ -1,11 +1,11 @@
        - Index - Django-Components      

        components ¤

        dynamic ¤

        DynamicComponent ¤

        DynamicComponent(
        + Index - Django-Components      

        components ¤

        Modules:

        dynamic ¤

        Modules:

        • types

          Helper types for IDEs.

        Classes:

        • DynamicComponent

          Dynamic component - This component takes inputs and renders the outputs depending on the

        DynamicComponent ¤

        DynamicComponent(
             registered_name: Optional[str] = None,
             component_id: Optional[str] = None,
             outer_context: Optional[Context] = None,
             fill_content: Optional[Dict[str, FillContent]] = None,
             registry: Optional[ComponentRegistry] = None,
         )
        -

        Bases: Component

        Dynamic component - This component takes inputs and renders the outputs depending on the is and registry arguments.

        • is - required - The component class or registered name of the component that will be rendered in this place.

        • registry - optional - Specify the registry to search for the registered name. If omitted, all registries are searched.

        Source code in src/django_components/component.py
        233
        +

        Bases: Component

        Dynamic component - This component takes inputs and renders the outputs depending on the is and registry arguments.

        • is - required - The component class or registered name of the component that will be rendered in this place.

        • registry - optional - Specify the registry to search for the registered name. If omitted, all registries are searched.

        Methods:

        • as_view

          Shortcut for calling Component.View.as_view and passing component instance to it.

        • get_template

          Inlined Django template associated with this component. Can be a plain string or a Template instance.

        • get_template_name

          Filepath to the Django template associated with this component.

        • inject

          Use this method to retrieve the data that was passed to a {% provide %} tag

        • on_render_after

          Hook that runs just after the component's template was rendered.

        • on_render_before

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

        • render

          Render the component into a string.

        • render_css_dependencies

          Render only CSS dependencies available in the media class or provided as a string.

        • render_dependencies

          Helper function to render all dependencies for a component.

        • render_js_dependencies

          Render only JS dependencies available in the media class or provided as a string.

        • render_to_response

          Render the component and wrap the content in the response class.

        Attributes:

        • Media

          Defines JS and CSS media files associated with this component.

        • css (Optional[str]) –

          Inlined CSS associated with this component.

        • input (RenderInput[ArgsType, KwargsType, SlotsType]) –

          Input holds the data (like arg, kwargs, slots) that were passsed to

        • is_filled (Dict[str, bool]) –

          Dictionary describing which slots have or have not been filled.

        • js (Optional[str]) –

          Inlined JS associated with this component.

        • media (Media) –

          Normalized definition of JS and CSS media files associated with this component.

        • response_class

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

        • template_name (Optional[str]) –

          Filepath to the Django template associated with this component.

        Source code in src/django_components/component.py
        233
         234
         235
         236
        diff --git a/dev/reference/django_components/context/index.html b/dev/reference/django_components/context/index.html
        index a47b0f45..6de7935f 100644
        --- a/dev/reference/django_components/context/index.html
        +++ b/dev/reference/django_components/context/index.html
        @@ -1,4 +1,4 @@
        - context - Django-Components context - Django-Components" >  context - Django-Components" >       

        context ¤

        This file centralizes various ways we use Django's Context class pass data across components, nodes, slots, and contexts.

        You can think of the Context as our storage system.

        copy_forloop_context ¤

        copy_forloop_context(from_context: Context, to_context: Context) -> None
        + context - Django-Components context - Django-Components" >  context - Django-Components" >       

        context ¤

        This file centralizes various ways we use Django's Context class pass data across components, nodes, slots, and contexts.

        You can think of the Context as our storage system.

        Functions:

        copy_forloop_context ¤

        copy_forloop_context(from_context: Context, to_context: Context) -> None
         

        Forward the info about the current loop

        Source code in src/django_components/context.py
        62
         63
         64
        diff --git a/dev/reference/django_components/expression/index.html b/dev/reference/django_components/expression/index.html
        index 3fa1b4d2..a1573b8d 100644
        --- a/dev/reference/django_components/expression/index.html
        +++ b/dev/reference/django_components/expression/index.html
        @@ -1,4 +1,4 @@
        - expression - Django-Components expression - Django-Components" >  expression - Django-Components" >       

        expression ¤

        Operator ¤

        Bases: ABC

        Operator describes something that somehow changes the inputs to template tags (the {% %}).

        For example, a SpreadOperator inserts one or more kwargs at the specified location.

        SpreadOperator ¤

        SpreadOperator(expr: Expression)
        + expression - Django-Components expression - Django-Components" >  expression - Django-Components" >       

        expression ¤

        Classes:

        • Operator

          Operator describes something that somehow changes the inputs

        • SpreadOperator

          Operator that inserts one or more kwargs at the specified location.

        Functions:

        Operator ¤

        Bases: ABC

        Operator describes something that somehow changes the inputs to template tags (the {% %}).

        For example, a SpreadOperator inserts one or more kwargs at the specified location.

        SpreadOperator ¤

        SpreadOperator(expr: Expression)
         

        Bases: Operator

        Operator that inserts one or more kwargs at the specified location.

        Source code in src/django_components/expression.py
        def __init__(self, expr: Expression) -> None:
             self.expr = expr
        diff --git a/dev/reference/django_components/finders/index.html b/dev/reference/django_components/finders/index.html
        index 2b4de7a6..3fc04fdd 100644
        --- a/dev/reference/django_components/finders/index.html
        +++ b/dev/reference/django_components/finders/index.html
        @@ -1,5 +1,5 @@
        - finders - Django-Components finders - Django-Components" >  finders - Django-Components" >       

        finders ¤

        ComponentsFileSystemFinder ¤

        ComponentsFileSystemFinder(app_names: Any = None, *args: Any, **kwargs: Any)
        -

        Bases: BaseFinder

        A static files finder based on FileSystemFinder.

        Differences: - This finder uses COMPONENTS.dirs setting to locate files instead of STATICFILES_DIRS. - Whether a file within COMPONENTS.dirs is considered a STATIC file is configured by COMPONENTS.static_files_allowed and COMPONENTS.forbidden_static_files. - If COMPONENTS.dirs is not set, defaults to settings.BASE_DIR / "components"

        Source code in src/django_components/finders.py
        36
        + finders - Django-Components finders - Django-Components" >  finders - Django-Components" >       

        finders ¤

        Classes:

        ComponentsFileSystemFinder ¤

        ComponentsFileSystemFinder(app_names: Any = None, *args: Any, **kwargs: Any)
        +

        Bases: BaseFinder

        A static files finder based on FileSystemFinder.

        Differences: - This finder uses COMPONENTS.dirs setting to locate files instead of STATICFILES_DIRS. - Whether a file within COMPONENTS.dirs is considered a STATIC file is configured by COMPONENTS.static_files_allowed and COMPONENTS.forbidden_static_files. - If COMPONENTS.dirs is not set, defaults to settings.BASE_DIR / "components"

        Methods:

        • find

          Look for files in the extra locations as defined in COMPONENTS.dirs.

        • find_location

          Find a requested static file in a location and return the found

        • list

          List all files in all locations.

        Source code in src/django_components/finders.py
        36
         37
         38
         39
        diff --git a/dev/reference/django_components/index.html b/dev/reference/django_components/index.html
        index 8b3e6325..6f5e77f4 100644
        --- a/dev/reference/django_components/index.html
        +++ b/dev/reference/django_components/index.html
        @@ -1,4 +1,4 @@
        - Index - Django-Components      

        django_components ¤

        Main package for Django Components.

        app_settings ¤

        ContextBehavior ¤

        Bases: str, Enum

        DJANGO class-attribute instance-attribute ¤

        DJANGO = 'django'
        + Index - Django-Components      

        django_components ¤

        Main package for Django Components.

        Modules:

        app_settings ¤

        Classes:

        ContextBehavior ¤

        Bases: str, Enum

        Attributes:

        • DJANGO

          With this setting, component fills behave as usual Django tags.

        • ISOLATED

          This setting makes the component fills behave similar to Vue or React, where

        DJANGO class-attribute instance-attribute ¤

        DJANGO = 'django'
         

        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 get_context_data are available to the component fill.

        Example:

        Given this template

        {% with cheese="feta" %}
           {% component 'my_comp' %}
             {{ my_var }}  # my_var
        @@ -20,7 +20,7 @@
         

        Then if component "my_comp" defines context

        { "my_var": 456 }
         

        Then this will render:

        123   # my_var
               # cheese
        -

        Because both variables "my_var" and "cheese" are taken from the root context. Since "cheese" is not defined in root context, it's empty.

        attributes ¤

        append_attributes ¤

        append_attributes(*args: Tuple[str, Any]) -> Dict
        +

        Because both variables "my_var" and "cheese" are taken from the root context. Since "cheese" is not defined in root context, it's empty.

        attributes ¤

        Functions:

        append_attributes ¤

        append_attributes(*args: Tuple[str, Any]) -> Dict
         

        Merges the key-value pairs and returns a new dictionary.

        If a key is present multiple times, its values are concatenated with a space character as separator in the final dictionary.

        Source code in src/django_components/attributes.py
        71
         72
         73
        @@ -78,7 +78,7 @@
                     attr_list.append(format_html('{}="{}"', key, value))
         
             return mark_safe(SafeString(" ").join(attr_list))
        -

        autodiscover ¤

        autodiscover ¤

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

        autodiscover ¤

        Functions:

        • autodiscover

          Search for component files and import them. Returns a list of module

        • import_libraries

          Import modules set in COMPONENTS.libraries setting.

        • search_dirs

          Search the directories for the given glob pattern. Glob search results are returned

        autodiscover ¤

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

        Search for component files and import them. Returns a list of module paths of imported files.

        Autodiscover searches in the locations as defined by Loader.get_dirs.

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

        Source code in src/django_components/autodiscover.py
        15
         16
         17
        @@ -246,14 +246,14 @@
                     matched_files.append(Path(path))
         
             return matched_files
        -

        component ¤

        Component ¤

        Component(
        +

        component ¤

        Classes:

        • Component
        • ComponentNode

          Django.template.Node subclass that renders a django-components component

        • ComponentView

          Subclass of django.views.View where the Component instance is available

        Component ¤

        Component(
             registered_name: Optional[str] = None,
             component_id: Optional[str] = None,
             outer_context: Optional[Context] = None,
             fill_content: Optional[Dict[str, FillContent]] = None,
             registry: Optional[ComponentRegistry] = None,
         )
        -

        Bases: Generic[ArgsType, KwargsType, DataType, SlotsType]

        Source code in src/django_components/component.py
        233
        +

        Bases: Generic[ArgsType, KwargsType, DataType, SlotsType]

        Methods:

        • as_view

          Shortcut for calling Component.View.as_view and passing component instance to it.

        • get_template

          Inlined Django template associated with this component. Can be a plain string or a Template instance.

        • get_template_name

          Filepath to the Django template associated with this component.

        • inject

          Use this method to retrieve the data that was passed to a {% provide %} tag

        • on_render_after

          Hook that runs just after the component's template was rendered.

        • on_render_before

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

        • render

          Render the component into a string.

        • render_css_dependencies

          Render only CSS dependencies available in the media class or provided as a string.

        • render_dependencies

          Helper function to render all dependencies for a component.

        • render_js_dependencies

          Render only JS dependencies available in the media class or provided as a string.

        • render_to_response

          Render the component and wrap the content in the response class.

        Attributes:

        • Media

          Defines JS and CSS media files associated with this component.

        • css (Optional[str]) –

          Inlined CSS associated with this component.

        • input (RenderInput[ArgsType, KwargsType, SlotsType]) –

          Input holds the data (like arg, kwargs, slots) that were passsed to

        • is_filled (Dict[str, bool]) –

          Dictionary describing which slots have or have not been filled.

        • js (Optional[str]) –

          Inlined JS associated with this component.

        • media (Media) –

          Normalized definition of JS and CSS media files associated with this component.

        • response_class

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

        • template (Optional[Union[str, Template]]) –

          Inlined Django template associated with this component. Can be a plain string or a Template instance.

        • template_name (Optional[str]) –

          Filepath to the Django template associated with this component.

        Source code in src/django_components/component.py
        233
         234
         235
         236
        @@ -888,7 +888,7 @@
         149
        def __init__(self, component: "Component", **kwargs: Any) -> None:
             super().__init__(**kwargs)
             self.component = component
        -

        component_media ¤

        ComponentMediaInput ¤

        Defines JS and CSS media files associated with this component.

        MediaMeta ¤

        Bases: MediaDefiningClass

        Metaclass for handling media files for components.

        Similar to MediaDefiningClass, this class supports the use of Media attribute to define associated JS/CSS files, which are then available under media attribute as a instance of Media class.

        This subclass has following changes:

        1. Support for multiple interfaces of JS/CSS¤
        1. As plain strings

          class MyComponent(Component):
          +

        component_media ¤

        Classes:

        • ComponentMediaInput

          Defines JS and CSS media files associated with this component.

        • MediaMeta

          Metaclass for handling media files for components.

        ComponentMediaInput ¤

        Defines JS and CSS media files associated with this component.

        MediaMeta ¤

        Bases: MediaDefiningClass

        Metaclass for handling media files for components.

        Similar to MediaDefiningClass, this class supports the use of Media attribute to define associated JS/CSS files, which are then available under media attribute as a instance of Media class.

        This subclass has following changes:

        1. Support for multiple interfaces of JS/CSS¤
        1. As plain strings

          class MyComponent(Component):
               class Media:
                   js = "path/to/script.js"
                   css = "path/to/style.css"
          @@ -927,7 +927,7 @@
               media_class = MyMedia
               def get_context_data(self):
                   assert isinstance(self.media, MyMedia)
          -

        component_registry ¤

        registry module-attribute ¤

        component_registry ¤

        Classes:

        Functions:

        • register

          Class decorator to register a component.

        Attributes:

        registry module-attribute ¤

        The default and global component registry. Use this instance to directly register or remove components:

        # Register components
         registry.register("button", ButtonComponent)
         registry.register("card", CardComponent)
        @@ -955,7 +955,7 @@
         registry.all()
         registry.clear()
         registry.get()
        -
        Source code in src/django_components/component_registry.py
        86
        +

        Methods:

        • all

          Retrieve all registered component classes.

        • clear

          Clears the registry, unregistering all components.

        • get

          Retrieve a component class registered under the given name.

        • register

          Register a component with this registry under the given name.

        • unregister

          Unlinks a previously-registered component from the registry under the given name.

        Attributes:

        • library (Library) –

          The template tag library with which the component registry is associated.

        Source code in src/django_components/component_registry.py
        86
         87
         88
         89
        @@ -1359,14 +1359,14 @@
                 return component
         
             return decorator
        -

        components ¤

        dynamic ¤

        DynamicComponent ¤

        DynamicComponent(
        +

        components ¤

        Modules:

        dynamic ¤

        Modules:

        • types

          Helper types for IDEs.

        Classes:

        • DynamicComponent

          Dynamic component - This component takes inputs and renders the outputs depending on the

        DynamicComponent ¤

        DynamicComponent(
             registered_name: Optional[str] = None,
             component_id: Optional[str] = None,
             outer_context: Optional[Context] = None,
             fill_content: Optional[Dict[str, FillContent]] = None,
             registry: Optional[ComponentRegistry] = None,
         )
        -

        Bases: Component

        Dynamic component - This component takes inputs and renders the outputs depending on the is and registry arguments.

        • is - required - The component class or registered name of the component that will be rendered in this place.

        • registry - optional - Specify the registry to search for the registered name. If omitted, all registries are searched.

        Source code in src/django_components/component.py
        233
        +

        Bases: Component

        Dynamic component - This component takes inputs and renders the outputs depending on the is and registry arguments.

        • is - required - The component class or registered name of the component that will be rendered in this place.

        • registry - optional - Specify the registry to search for the registered name. If omitted, all registries are searched.

        Methods:

        • as_view

          Shortcut for calling Component.View.as_view and passing component instance to it.

        • get_template

          Inlined Django template associated with this component. Can be a plain string or a Template instance.

        • get_template_name

          Filepath to the Django template associated with this component.

        • inject

          Use this method to retrieve the data that was passed to a {% provide %} tag

        • on_render_after

          Hook that runs just after the component's template was rendered.

        • on_render_before

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

        • render

          Render the component into a string.

        • render_css_dependencies

          Render only CSS dependencies available in the media class or provided as a string.

        • render_dependencies

          Helper function to render all dependencies for a component.

        • render_js_dependencies

          Render only JS dependencies available in the media class or provided as a string.

        • render_to_response

          Render the component and wrap the content in the response class.

        Attributes:

        • Media

          Defines JS and CSS media files associated with this component.

        • css (Optional[str]) –

          Inlined CSS associated with this component.

        • input (RenderInput[ArgsType, KwargsType, SlotsType]) –

          Input holds the data (like arg, kwargs, slots) that were passsed to

        • is_filled (Dict[str, bool]) –

          Dictionary describing which slots have or have not been filled.

        • js (Optional[str]) –

          Inlined JS associated with this component.

        • media (Media) –

          Normalized definition of JS and CSS media files associated with this component.

        • response_class

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

        • template_name (Optional[str]) –

          Filepath to the Django template associated with this component.

        Source code in src/django_components/component.py
        233
         234
         235
         236
        @@ -1954,7 +1954,7 @@
                 escape_slots_content=escape_slots_content,
             )
             return cls.response_class(content, *response_args, **response_kwargs)
        -

        context ¤

        This file centralizes various ways we use Django's Context class pass data across components, nodes, slots, and contexts.

        You can think of the Context as our storage system.

        copy_forloop_context ¤

        copy_forloop_context(from_context: Context, to_context: Context) -> None
        +

        context ¤

        This file centralizes various ways we use Django's Context class pass data across components, nodes, slots, and contexts.

        You can think of the Context as our storage system.

        Functions:

        copy_forloop_context ¤

        copy_forloop_context(from_context: Context, to_context: Context) -> None
         

        Forward the info about the current loop

        Source code in src/django_components/context.py
        62
         63
         64
        @@ -2126,7 +2126,7 @@
         
             internal_key = _INJECT_CONTEXT_KEY_PREFIX + key
             context[internal_key] = payload
        -

        expression ¤

        Operator ¤

        Bases: ABC

        Operator describes something that somehow changes the inputs to template tags (the {% %}).

        For example, a SpreadOperator inserts one or more kwargs at the specified location.

        SpreadOperator ¤

        SpreadOperator(expr: Expression)
        +

        expression ¤

        Classes:

        • Operator

          Operator describes something that somehow changes the inputs

        • SpreadOperator

          Operator that inserts one or more kwargs at the specified location.

        Functions:

        Operator ¤

        Bases: ABC

        Operator describes something that somehow changes the inputs to template tags (the {% %}).

        For example, a SpreadOperator inserts one or more kwargs at the specified location.

        SpreadOperator ¤

        SpreadOperator(expr: Expression)
         

        Bases: Operator

        Operator that inserts one or more kwargs at the specified location.

        Source code in src/django_components/expression.py
        def __init__(self, expr: Expression) -> None:
             self.expr = expr
        @@ -2290,8 +2290,8 @@
                 processed_kwargs[key] = val
         
             return processed_kwargs
        -

        finders ¤

        ComponentsFileSystemFinder ¤

        ComponentsFileSystemFinder(app_names: Any = None, *args: Any, **kwargs: Any)
        -

        Bases: BaseFinder

        A static files finder based on FileSystemFinder.

        Differences: - This finder uses COMPONENTS.dirs setting to locate files instead of STATICFILES_DIRS. - Whether a file within COMPONENTS.dirs is considered a STATIC file is configured by COMPONENTS.static_files_allowed and COMPONENTS.forbidden_static_files. - If COMPONENTS.dirs is not set, defaults to settings.BASE_DIR / "components"

        Source code in src/django_components/finders.py
        36
        +

        finders ¤

        Classes:

        ComponentsFileSystemFinder ¤

        ComponentsFileSystemFinder(app_names: Any = None, *args: Any, **kwargs: Any)
        +

        Bases: BaseFinder

        A static files finder based on FileSystemFinder.

        Differences: - This finder uses COMPONENTS.dirs setting to locate files instead of STATICFILES_DIRS. - Whether a file within COMPONENTS.dirs is considered a STATIC file is configured by COMPONENTS.static_files_allowed and COMPONENTS.forbidden_static_files. - If COMPONENTS.dirs is not set, defaults to settings.BASE_DIR / "components"

        Methods:

        • find

          Look for files in the extra locations as defined in COMPONENTS.dirs.

        • find_location

          Find a requested static file in a location and return the found

        • list

          List all files in all locations.

        Source code in src/django_components/finders.py
        36
         37
         38
         39
        @@ -2418,7 +2418,7 @@
                     for path in get_files(storage, ignore_patterns):
                         if self._is_path_valid(path):
                             yield path, storage
        -

        library ¤

        Module for interfacing with Django's Library (django.template.library)

        PROTECTED_TAGS module-attribute ¤

        PROTECTED_TAGS = [
        +

        library ¤

        Module for interfacing with Django's Library (django.template.library)

        Attributes:

        • PROTECTED_TAGS

          These are the names that users cannot choose for their components,

        PROTECTED_TAGS module-attribute ¤

        PROTECTED_TAGS = [
             "component_dependencies",
             "component_css_dependencies",
             "component_js_dependencies",
        @@ -2427,7 +2427,7 @@
             "provide",
             "slot",
         ]
        -

        These are the names that users cannot choose for their components, as they would conflict with other tags in the Library.

        logger ¤

        trace ¤

        trace(logger: Logger, message: str, *args: Any, **kwargs: Any) -> None
        +

        These are the names that users cannot choose for their components, as they would conflict with other tags in the Library.

        logger ¤

        Functions:

        • trace

          TRACE level logger.

        • trace_msg

          TRACE level logger with opinionated format for tracing interaction of components,

        trace ¤

        trace(logger: Logger, message: str, *args: Any, **kwargs: Any) -> None
         

        TRACE level logger.

        To display TRACE logs, set the logging level to 5.

        Example:

        LOGGING = {
             "version": 1,
             "disable_existing_loggers": False,
        @@ -2570,7 +2570,7 @@
             # NOTE: When debugging tests during development, it may be easier to change
             # this to `print()`
             trace(logger, full_msg)
        -

        middleware ¤

        ComponentDependencyMiddleware ¤

        ComponentDependencyMiddleware(get_response: Callable[[HttpRequest], HttpResponse])
        +

        middleware ¤

        Classes:

        • ComponentDependencyMiddleware

          Middleware that inserts CSS/JS dependencies for all rendered components at points marked with template tags.

        • DependencyReplacer

          Replacer for use in re.sub that replaces the first placeholder CSS and JS

        Functions:

        • join_media

          Return combined media object for iterable of components.

        ComponentDependencyMiddleware ¤

        ComponentDependencyMiddleware(get_response: Callable[[HttpRequest], HttpResponse])
         

        Middleware that inserts CSS/JS dependencies for all rendered components at points marked with template tags.

        Source code in src/django_components/middleware.py
        36
         37
         38
        @@ -2594,7 +2594,7 @@
             """Return combined media object for iterable of components."""
         
             return sum([component.media for component in components], Media())
        -

        node ¤

        BaseNode ¤

        BaseNode(
        +

        node ¤

        Classes:

        • BaseNode

          Shared behavior for our subclasses of Django's Node

        Functions:

        BaseNode ¤

        BaseNode(
             nodelist: Optional[NodeList] = None,
             node_id: Optional[str] = None,
             args: Optional[List[Expression]] = None,
        @@ -2765,7 +2765,7 @@
                 child_nodes = get_node_children(traverse.node, context)
                 child_traverses = [NodeTraverse(node=child_node, parent=traverse) for child_node in child_nodes]
                 node_queue.extend(child_traverses)
        -

        provide ¤

        ProvideNode ¤

        ProvideNode(nodelist: NodeList, trace_id: str, node_id: Optional[str] = None, kwargs: Optional[RuntimeKwargs] = None)
        +

        provide ¤

        Classes:

        • ProvideNode

          Implementation of the {% provide %} tag.

        ProvideNode ¤

        ProvideNode(nodelist: NodeList, trace_id: str, node_id: Optional[str] = None, kwargs: Optional[RuntimeKwargs] = None)
         

        Bases: BaseNode

        Implementation of the {% provide %} tag. For more info see Component.inject.

        Source code in src/django_components/provide.py
        22
         23
         24
        @@ -2791,7 +2791,7 @@
             self.node_id = node_id or gen_id()
             self.trace_id = trace_id
             self.kwargs = kwargs or RuntimeKwargs({})
        -

        slots ¤

        FillContent dataclass ¤

        FillContent(content_func: SlotFunc[TSlotData], slot_default_var: Optional[SlotDefaultName], slot_data_var: Optional[SlotDataName])
        +

        slots ¤

        Classes:

        • FillContent

          This represents content set with the {% fill %} tag, e.g.:

        • FillNode

          Set when a component tag pair is passed template content that

        • Slot

          This represents content set with the {% slot %} tag, e.g.:

        • SlotFill

          SlotFill describes what WILL be rendered.

        • SlotNode
        • SlotRef

          SlotRef allows to treat a slot as a variable. The slot is rendered only once

        Functions:

        FillContent dataclass ¤

        FillContent(content_func: SlotFunc[TSlotData], slot_default_var: Optional[SlotDefaultName], slot_data_var: Optional[SlotDataName])
         

        Bases: Generic[TSlotData]

        This represents content set with the {% fill %} tag, e.g.:

        {% component "my_comp" %}
             {% fill "first_slot" %} <--- This
                 hi
        @@ -3225,7 +3225,7 @@
             # By the time we get here, we should know, for each slot, how it will be rendered
             # -> Whether it will be replaced with a fill, or whether we render slot's defaults.
             return slots, resolved_slots
        -

    tag_formatter ¤

    ComponentFormatter ¤

    ComponentFormatter(tag: str)
    +

    tag_formatter ¤

    Classes:

    Functions:

    • get_tag_formatter

      Returns an instance of the currently configured component tag formatter.

    ComponentFormatter ¤

    ComponentFormatter(tag: str)
     

    Bases: TagFormatterABC

    The original django_component's component tag formatter, it uses the component and endcomponent tags, and the component name is gives as the first positional arg.

    Example as block:

    {% component "mycomp" abc=123 %}
         {% fill "myfill" %}
             ...
    @@ -3245,7 +3245,7 @@
         {% endfill %}
     {% endmycomp %}
     

    Example as inlined tag:

    {% mycomp abc=123 / %}
    -

    TagFormatterABC ¤

    Bases: ABC

    end_tag abstractmethod ¤

    end_tag(name: str) -> str
    +

    TagFormatterABC ¤

    Bases: ABC

    Methods:

    • end_tag

      Formats the end tag of a block component.

    • parse

      Given the tokens (words) of a component start tag, this function extracts

    • start_tag

      Formats the start tag of a component.

    end_tag abstractmethod ¤

    end_tag(name: str) -> str
     

    Formats the end tag of a block component.

    Source code in src/django_components/tag_formatter.py
    34
     35
     36
    @@ -3313,7 +3313,7 @@
     def start_tag(self, name: str) -> str:
         """Formats the start tag of a component."""
         ...
    -

    TagResult ¤

    Bases: NamedTuple

    The return value from TagFormatter.parse()

    component_name instance-attribute ¤

    component_name: str
    +

    TagResult ¤

    Bases: NamedTuple

    The return value from TagFormatter.parse()

    Attributes:

    • component_name (str) –

      Component name extracted from the template tag

    • tokens (List[str]) –

      Remaining tokens (words) that were passed to the tag, with component name removed

    component_name instance-attribute ¤

    component_name: str
     

    Component name extracted from the template tag

    tokens instance-attribute ¤

    tokens: List[str]
     

    Remaining tokens (words) that were passed to the tag, with component name removed

    get_tag_formatter ¤

    get_tag_formatter(registry: ComponentRegistry) -> InternalTagFormatter
     

    Returns an instance of the currently configured component tag formatter.

    Source code in src/django_components/tag_formatter.py
    207
    @@ -3337,7 +3337,7 @@
             tag_formatter = formatter_cls_or_str
     
         return InternalTagFormatter(tag_formatter)
    -

    template ¤

    cached_template ¤

    cached_template(
    +

    template ¤

    Functions:

    • cached_template

      Create a Template instance that will be cached as per the TEMPLATE_CACHE_SIZE setting.

    cached_template ¤

    cached_template(
         template_string: str,
         template_cls: Optional[Type[Template]] = None,
         origin: Optional[Origin] = None,
    @@ -3379,7 +3379,7 @@
             template._dc_cached = True
     
         return template
    -

    template_loader ¤

    Template loader that loads templates from each Django app's "components" directory.

    Loader ¤

    Bases: Loader

    get_dirs ¤

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

    template_loader ¤

    Template loader that loads templates from each Django app's "components" directory.

    Classes:

    Functions:

    • get_dirs

      Helper for using django_component's FilesystemLoader class to obtain a list

    Loader ¤

    Bases: Loader

    Methods:

    • get_dirs

      Prepare directories that may contain component files:

    get_dirs ¤

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

    Prepare directories that may contain component files:

    Searches for dirs set in COMPONENTS.dirs settings. If none set, defaults to searching for a "components" app. The dirs in COMPONENTS.dirs must be absolute paths.

    In addition to that, also all apps are checked for [app]/components dirs.

    Paths are accepted only if they resolve to a directory. E.g. /path/to/django_project/my_app/components/.

    BASE_DIR setting is required.

    Source code in src/django_components/template_loader.py
    21
     22
     23
    @@ -3541,7 +3541,7 @@
     
         loader = Loader(current_engine)
         return loader.get_dirs(include_apps)
    -

    template_parser ¤

    Overrides for the Django Template system to allow finer control over template parsing.

    Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py

    parse_bits ¤

    parse_bits(
    +

    template_parser ¤

    Overrides for the Django Template system to allow finer control over template parsing.

    Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py

    Functions:

    • parse_bits

      Parse bits for template tag helpers simple_tag and inclusion_tag, in

    • token_kwargs

      Parse token keyword arguments and return a dictionary of the arguments

    parse_bits ¤

    parse_bits(
         parser: Parser, bits: List[str], params: List[str], name: str
     ) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]
     

    Parse bits for template tag helpers simple_tag and inclusion_tag, in particular by detecting syntax errors and by extracting positional and keyword arguments.

    This is a simplified version of django.template.library.parse_bits where we use custom regex to handle special characters in keyword names.

    Furthermore, our version allows duplicate keys, and instead of return kwargs as a dict, we return it as a list of key-value pairs. So it is up to the user of this function to decide whether they support duplicate keys or not.

    Source code in src/django_components/template_parser.py
    155
    @@ -3733,7 +3733,7 @@
                     return kwargs
                 del bits[:1]
         return kwargs
    -

    templatetags ¤

    component_tags ¤

    component ¤

    component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode
    +

    templatetags ¤

    Modules:

    component_tags ¤

    Functions:

    component ¤

    component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode
     
    To give the component access to the template context

    {% component "name" positional_arg keyword_arg=value ... %}

    To render the component in an isolated context

    {% component "name" positional_arg keyword_arg=value ... only %}

    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 or, if there are no positional arguments, passed as 'name'.

    Source code in src/django_components/templatetags/component_tags.py
    206
     207
     208
    @@ -4106,7 +4106,7 @@
             kwargs=tag.kwargs,
             kwarg_pairs=tag.kwarg_pairs,
         )
    -

    types ¤

    Helper types for IDEs.

    utils ¤

    gen_id ¤

    gen_id(length: int = 5) -> str
    +

    types ¤

    Helper types for IDEs.

    utils ¤

    Functions:

    • gen_id

      Generate a unique ID that can be associated with a Node

    • lazy_cache

      Decorator that caches the given function similarly to functools.lru_cache.

    gen_id ¤

    gen_id(length: int = 5) -> str
     

    Generate a unique ID that can be associated with a Node

    Source code in src/django_components/utils.py
    14
     15
     16
    diff --git a/dev/reference/django_components/library/index.html b/dev/reference/django_components/library/index.html
    index ba670a2e..4a693a8a 100644
    --- a/dev/reference/django_components/library/index.html
    +++ b/dev/reference/django_components/library/index.html
    @@ -1,4 +1,4 @@
    - library - Django-Components library - Django-Components" >  library - Django-Components" >       

    library ¤

    Module for interfacing with Django's Library (django.template.library)

    PROTECTED_TAGS module-attribute ¤

    PROTECTED_TAGS = [
    + library - Django-Components library - Django-Components" >  library - Django-Components" >       

    library ¤

    Module for interfacing with Django's Library (django.template.library)

    Attributes:

    • PROTECTED_TAGS

      These are the names that users cannot choose for their components,

    PROTECTED_TAGS module-attribute ¤

    PROTECTED_TAGS = [
         "component_dependencies",
         "component_css_dependencies",
         "component_js_dependencies",
    diff --git a/dev/reference/django_components/logger/index.html b/dev/reference/django_components/logger/index.html
    index 0a3d9fa0..71f9cf35 100644
    --- a/dev/reference/django_components/logger/index.html
    +++ b/dev/reference/django_components/logger/index.html
    @@ -1,4 +1,4 @@
    - logger - Django-Components logger - Django-Components" >  logger - Django-Components" >       

    logger ¤

    trace ¤

    trace(logger: Logger, message: str, *args: Any, **kwargs: Any) -> None
    + logger - Django-Components logger - Django-Components" >  logger - Django-Components" >       

    logger ¤

    Functions:

    • trace

      TRACE level logger.

    • trace_msg

      TRACE level logger with opinionated format for tracing interaction of components,

    trace ¤

    trace(logger: Logger, message: str, *args: Any, **kwargs: Any) -> None
     

    TRACE level logger.

    To display TRACE logs, set the logging level to 5.

    Example:

    LOGGING = {
         "version": 1,
         "disable_existing_loggers": False,
    diff --git a/dev/reference/django_components/management/commands/index.html b/dev/reference/django_components/management/commands/index.html
    index 9cb6d406..14b93d3f 100644
    --- a/dev/reference/django_components/management/commands/index.html
    +++ b/dev/reference/django_components/management/commands/index.html
    @@ -1 +1 @@
    - Index - Django-Components      
    \ No newline at end of file + Index - Django-Components
    \ No newline at end of file diff --git a/dev/reference/django_components/management/commands/startcomponent/index.html b/dev/reference/django_components/management/commands/startcomponent/index.html index ae9ae752..cf64fb06 100644 --- a/dev/reference/django_components/management/commands/startcomponent/index.html +++ b/dev/reference/django_components/management/commands/startcomponent/index.html @@ -1 +1 @@ - startcomponent - Django-Components
    startcomponent - Django-Components" > startcomponent - Django-Components" >
    \ No newline at end of file + startcomponent - Django-Components startcomponent - Django-Components" > startcomponent - Django-Components" >
    \ No newline at end of file diff --git a/dev/reference/django_components/management/commands/upgradecomponent/index.html b/dev/reference/django_components/management/commands/upgradecomponent/index.html index f73e10bd..c5fd08d2 100644 --- a/dev/reference/django_components/management/commands/upgradecomponent/index.html +++ b/dev/reference/django_components/management/commands/upgradecomponent/index.html @@ -1 +1 @@ - upgradecomponent - Django-Components upgradecomponent - Django-Components" > upgradecomponent - Django-Components" >

    upgradecomponent ¤

    \ No newline at end of file + upgradecomponent - Django-Components upgradecomponent - Django-Components" > upgradecomponent - Django-Components" >

    upgradecomponent ¤

    \ No newline at end of file diff --git a/dev/reference/django_components/management/index.html b/dev/reference/django_components/management/index.html index 222e9171..ae997dca 100644 --- a/dev/reference/django_components/management/index.html +++ b/dev/reference/django_components/management/index.html @@ -1 +1 @@ - Index - Django-Components
    \ No newline at end of file + Index - Django-Components
    \ No newline at end of file diff --git a/dev/reference/django_components/middleware/index.html b/dev/reference/django_components/middleware/index.html index 543c9369..dcfd67db 100644 --- a/dev/reference/django_components/middleware/index.html +++ b/dev/reference/django_components/middleware/index.html @@ -1,4 +1,4 @@ - middleware - Django-Components middleware - Django-Components" > middleware - Django-Components" >

    middleware ¤

    ComponentDependencyMiddleware ¤

    ComponentDependencyMiddleware(get_response: Callable[[HttpRequest], HttpResponse])
    + middleware - Django-Components middleware - Django-Components" >  middleware - Django-Components" >       

    middleware ¤

    Classes:

    • ComponentDependencyMiddleware

      Middleware that inserts CSS/JS dependencies for all rendered components at points marked with template tags.

    • DependencyReplacer

      Replacer for use in re.sub that replaces the first placeholder CSS and JS

    Functions:

    • join_media

      Return combined media object for iterable of components.

    ComponentDependencyMiddleware ¤

    ComponentDependencyMiddleware(get_response: Callable[[HttpRequest], HttpResponse])
     

    Middleware that inserts CSS/JS dependencies for all rendered components at points marked with template tags.

    Source code in src/django_components/middleware.py
    36
     37
     38
    diff --git a/dev/reference/django_components/node/index.html b/dev/reference/django_components/node/index.html
    index 95291370..bb227dc8 100644
    --- a/dev/reference/django_components/node/index.html
    +++ b/dev/reference/django_components/node/index.html
    @@ -1,4 +1,4 @@
    - node - Django-Components node - Django-Components" >  node - Django-Components" >       

    node ¤

    BaseNode ¤

    BaseNode(
    + node - Django-Components node - Django-Components" >  node - Django-Components" >       

    node ¤

    Classes:

    • BaseNode

      Shared behavior for our subclasses of Django's Node

    Functions:

    BaseNode ¤

    BaseNode(
         nodelist: Optional[NodeList] = None,
         node_id: Optional[str] = None,
         args: Optional[List[Expression]] = None,
    diff --git a/dev/reference/django_components/provide/index.html b/dev/reference/django_components/provide/index.html
    index 0ff10a9e..39ac5ed0 100644
    --- a/dev/reference/django_components/provide/index.html
    +++ b/dev/reference/django_components/provide/index.html
    @@ -1,4 +1,4 @@
    - provide - Django-Components provide - Django-Components" >  provide - Django-Components" >       

    provide ¤

    ProvideNode ¤

    ProvideNode(nodelist: NodeList, trace_id: str, node_id: Optional[str] = None, kwargs: Optional[RuntimeKwargs] = None)
    + provide - Django-Components provide - Django-Components" >  provide - Django-Components" >       

    provide ¤

    Classes:

    • ProvideNode

      Implementation of the {% provide %} tag.

    ProvideNode ¤

    ProvideNode(nodelist: NodeList, trace_id: str, node_id: Optional[str] = None, kwargs: Optional[RuntimeKwargs] = None)
     

    Bases: BaseNode

    Implementation of the {% provide %} tag. For more info see Component.inject.

    Source code in src/django_components/provide.py
    22
     23
     24
    diff --git a/dev/reference/django_components/slots/index.html b/dev/reference/django_components/slots/index.html
    index 0b9f3c58..39878c71 100644
    --- a/dev/reference/django_components/slots/index.html
    +++ b/dev/reference/django_components/slots/index.html
    @@ -1,4 +1,4 @@
    - slots - Django-Components slots - Django-Components" >  slots - Django-Components" >       

    slots ¤

    FillContent dataclass ¤

    FillContent(content_func: SlotFunc[TSlotData], slot_default_var: Optional[SlotDefaultName], slot_data_var: Optional[SlotDataName])
    + slots - Django-Components slots - Django-Components" >  slots - Django-Components" >       

    slots ¤

    Classes:

    • FillContent

      This represents content set with the {% fill %} tag, e.g.:

    • FillNode

      Set when a component tag pair is passed template content that

    • Slot

      This represents content set with the {% slot %} tag, e.g.:

    • SlotFill

      SlotFill describes what WILL be rendered.

    • SlotNode
    • SlotRef

      SlotRef allows to treat a slot as a variable. The slot is rendered only once

    Functions:

    FillContent dataclass ¤

    FillContent(content_func: SlotFunc[TSlotData], slot_default_var: Optional[SlotDefaultName], slot_data_var: Optional[SlotDataName])
     

    Bases: Generic[TSlotData]

    This represents content set with the {% fill %} tag, e.g.:

    {% component "my_comp" %}
         {% fill "first_slot" %} <--- This
             hi
    diff --git a/dev/reference/django_components/tag_formatter/index.html b/dev/reference/django_components/tag_formatter/index.html
    index 339a45bd..a02bd02a 100644
    --- a/dev/reference/django_components/tag_formatter/index.html
    +++ b/dev/reference/django_components/tag_formatter/index.html
    @@ -1,4 +1,4 @@
    - tag_formatter - Django-Components tag_formatter - Django-Components" >  tag_formatter - Django-Components" >       

    tag_formatter ¤

    ComponentFormatter ¤

    ComponentFormatter(tag: str)
    + tag_formatter - Django-Components tag_formatter - Django-Components" >  tag_formatter - Django-Components" >       

    tag_formatter ¤

    Classes:

    Functions:

    • get_tag_formatter

      Returns an instance of the currently configured component tag formatter.

    ComponentFormatter ¤

    ComponentFormatter(tag: str)
     

    Bases: TagFormatterABC

    The original django_component's component tag formatter, it uses the component and endcomponent tags, and the component name is gives as the first positional arg.

    Example as block:

    {% component "mycomp" abc=123 %}
         {% fill "myfill" %}
             ...
    @@ -18,7 +18,7 @@
         {% endfill %}
     {% endmycomp %}
     

    Example as inlined tag:

    {% mycomp abc=123 / %}
    -

    TagFormatterABC ¤

    Bases: ABC

    end_tag abstractmethod ¤

    end_tag(name: str) -> str
    +

    TagFormatterABC ¤

    Bases: ABC

    Methods:

    • end_tag

      Formats the end tag of a block component.

    • parse

      Given the tokens (words) of a component start tag, this function extracts

    • start_tag

      Formats the start tag of a component.

    end_tag abstractmethod ¤

    end_tag(name: str) -> str
     

    Formats the end tag of a block component.

    Source code in src/django_components/tag_formatter.py
    34
     35
     36
    @@ -86,7 +86,7 @@
     def start_tag(self, name: str) -> str:
         """Formats the start tag of a component."""
         ...
    -

    TagResult ¤

    Bases: NamedTuple

    The return value from TagFormatter.parse()

    component_name instance-attribute ¤

    component_name: str
    +

    TagResult ¤

    Bases: NamedTuple

    The return value from TagFormatter.parse()

    Attributes:

    • component_name (str) –

      Component name extracted from the template tag

    • tokens (List[str]) –

      Remaining tokens (words) that were passed to the tag, with component name removed

    component_name instance-attribute ¤

    component_name: str
     

    Component name extracted from the template tag

    tokens instance-attribute ¤

    tokens: List[str]
     

    Remaining tokens (words) that were passed to the tag, with component name removed

    get_tag_formatter ¤

    get_tag_formatter(registry: ComponentRegistry) -> InternalTagFormatter
     

    Returns an instance of the currently configured component tag formatter.

    Source code in src/django_components/tag_formatter.py
    207
    diff --git a/dev/reference/django_components/template/index.html b/dev/reference/django_components/template/index.html
    index 6ff91364..445d94fa 100644
    --- a/dev/reference/django_components/template/index.html
    +++ b/dev/reference/django_components/template/index.html
    @@ -1,4 +1,4 @@
    - template - Django-Components template - Django-Components" >  template - Django-Components" >       

    template ¤

    cached_template ¤

    cached_template(
    + template - Django-Components template - Django-Components" >  template - Django-Components" >       

    template ¤

    Functions:

    • cached_template

      Create a Template instance that will be cached as per the TEMPLATE_CACHE_SIZE setting.

    cached_template ¤

    cached_template(
         template_string: str,
         template_cls: Optional[Type[Template]] = None,
         origin: Optional[Origin] = None,
    diff --git a/dev/reference/django_components/template_loader/index.html b/dev/reference/django_components/template_loader/index.html
    index 62d1158d..149fde93 100644
    --- a/dev/reference/django_components/template_loader/index.html
    +++ b/dev/reference/django_components/template_loader/index.html
    @@ -1,4 +1,4 @@
    - template_loader - Django-Components template_loader - Django-Components" >  template_loader - Django-Components" >       

    template_loader ¤

    Template loader that loads templates from each Django app's "components" directory.

    Loader ¤

    Bases: Loader

    get_dirs ¤

    get_dirs(include_apps: bool = True) -> List[Path]
    + template_loader - Django-Components template_loader - Django-Components" >  template_loader - Django-Components" >       

    template_loader ¤

    Template loader that loads templates from each Django app's "components" directory.

    Classes:

    Functions:

    • get_dirs

      Helper for using django_component's FilesystemLoader class to obtain a list

    Loader ¤

    Bases: Loader

    Methods:

    • get_dirs

      Prepare directories that may contain component files:

    get_dirs ¤

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

    Prepare directories that may contain component files:

    Searches for dirs set in COMPONENTS.dirs settings. If none set, defaults to searching for a "components" app. The dirs in COMPONENTS.dirs must be absolute paths.

    In addition to that, also all apps are checked for [app]/components dirs.

    Paths are accepted only if they resolve to a directory. E.g. /path/to/django_project/my_app/components/.

    BASE_DIR setting is required.

    Source code in src/django_components/template_loader.py
    21
     22
     23
    diff --git a/dev/reference/django_components/template_parser/index.html b/dev/reference/django_components/template_parser/index.html
    index 495ac8b6..886101a3 100644
    --- a/dev/reference/django_components/template_parser/index.html
    +++ b/dev/reference/django_components/template_parser/index.html
    @@ -1,4 +1,4 @@
    - template_parser - Django-Components template_parser - Django-Components" >  template_parser - Django-Components" >       

    template_parser ¤

    Overrides for the Django Template system to allow finer control over template parsing.

    Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py

    parse_bits ¤

    parse_bits(
    + template_parser - Django-Components template_parser - Django-Components" >  template_parser - Django-Components" >       

    template_parser ¤

    Overrides for the Django Template system to allow finer control over template parsing.

    Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py

    Functions:

    • parse_bits

      Parse bits for template tag helpers simple_tag and inclusion_tag, in

    • token_kwargs

      Parse token keyword arguments and return a dictionary of the arguments

    parse_bits ¤

    parse_bits(
         parser: Parser, bits: List[str], params: List[str], name: str
     ) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]
     

    Parse bits for template tag helpers simple_tag and inclusion_tag, in particular by detecting syntax errors and by extracting positional and keyword arguments.

    This is a simplified version of django.template.library.parse_bits where we use custom regex to handle special characters in keyword names.

    Furthermore, our version allows duplicate keys, and instead of return kwargs as a dict, we return it as a list of key-value pairs. So it is up to the user of this function to decide whether they support duplicate keys or not.

    Source code in src/django_components/template_parser.py
    155
    diff --git a/dev/reference/django_components/templatetags/component_tags/index.html b/dev/reference/django_components/templatetags/component_tags/index.html
    index b2f70acc..c9b176a8 100644
    --- a/dev/reference/django_components/templatetags/component_tags/index.html
    +++ b/dev/reference/django_components/templatetags/component_tags/index.html
    @@ -1,4 +1,4 @@
    - component_tags - Django-Components component_tags - Django-Components" >  component_tags - Django-Components" >       

    component_tags ¤

    component ¤

    component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode
    + component_tags - Django-Components component_tags - Django-Components" >  component_tags - Django-Components" >       

    component_tags ¤

    Functions:

    component ¤

    component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode
     
    To give the component access to the template context

    {% component "name" positional_arg keyword_arg=value ... %}

    To render the component in an isolated context

    {% component "name" positional_arg keyword_arg=value ... only %}

    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 or, if there are no positional arguments, passed as 'name'.

    Source code in src/django_components/templatetags/component_tags.py
    206
     207
     208
    diff --git a/dev/reference/django_components/templatetags/index.html b/dev/reference/django_components/templatetags/index.html
    index 72b6a641..59078592 100644
    --- a/dev/reference/django_components/templatetags/index.html
    +++ b/dev/reference/django_components/templatetags/index.html
    @@ -1,4 +1,4 @@
    - Index - Django-Components      

    templatetags ¤

    component_tags ¤

    component ¤

    component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode
    + Index - Django-Components      

    templatetags ¤

    Modules:

    component_tags ¤

    Functions:

    component ¤

    component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode
     
    To give the component access to the template context

    {% component "name" positional_arg keyword_arg=value ... %}

    To render the component in an isolated context

    {% component "name" positional_arg keyword_arg=value ... only %}

    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 or, if there are no positional arguments, passed as 'name'.

    Source code in src/django_components/templatetags/component_tags.py
    206
     207
     208
    diff --git a/dev/reference/django_components/types/index.html b/dev/reference/django_components/types/index.html
    index fcbb8d5b..72a49ad0 100644
    --- a/dev/reference/django_components/types/index.html
    +++ b/dev/reference/django_components/types/index.html
    @@ -1 +1 @@
    - types - Django-Components types - Django-Components" >  types - Django-Components" >       

    types ¤

    Helper types for IDEs.

    \ No newline at end of file + types - Django-Components types - Django-Components" > types - Django-Components" >

    types ¤

    Helper types for IDEs.

    \ No newline at end of file diff --git a/dev/reference/django_components/utils/index.html b/dev/reference/django_components/utils/index.html index 4bdd2a01..302c0017 100644 --- a/dev/reference/django_components/utils/index.html +++ b/dev/reference/django_components/utils/index.html @@ -1,4 +1,4 @@ - utils - Django-Components utils - Django-Components" > utils - Django-Components" >

    utils ¤

    gen_id ¤

    gen_id(length: int = 5) -> str
    + utils - Django-Components utils - Django-Components" >  utils - Django-Components" >       

    utils ¤

    Functions:

    • gen_id

      Generate a unique ID that can be associated with a Node

    • lazy_cache

      Decorator that caches the given function similarly to functools.lru_cache.

    gen_id ¤

    gen_id(length: int = 5) -> str
     

    Generate a unique ID that can be associated with a Node

    Source code in src/django_components/utils.py
    14
     15
     16
    diff --git a/dev/reference/django_components_js/build/index.html b/dev/reference/django_components_js/build/index.html
    index 42b160f3..a84c1cd7 100644
    --- a/dev/reference/django_components_js/build/index.html
    +++ b/dev/reference/django_components_js/build/index.html
    @@ -1 +1 @@
    - build - Django-Components build - Django-Components" >  build - Django-Components" >       
    \ No newline at end of file + build - Django-Components build - Django-Components" > build - Django-Components" >
    \ No newline at end of file diff --git a/dev/search/search_index.json b/dev/search/search_index.json index ce2998ef..fdfbfbf2 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":"Index","text":"

    Docs (Work in progress)

    Django-components is a package that introduces component-based architecture to Django's server-side rendering. It aims to combine Django's templating system with the modularity seen in modern frontend frameworks.

    "},{"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":"#summary","title":"Summary","text":"

    It lets you create \"template components\", that contains both the template, the Javascript and the CSS needed to generate the front end code you need for a modern app. Use components like this:

    {% component \"calendar\" date=\"2015-06-19\" %}{% endcomponent %}\n

    And this is what gets rendered (plus the CSS and Javascript you've specified):

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

    See the example project or read on to learn about the details!

    "},{"location":"#table-of-contents","title":"Table of Contents","text":"
    • Release notes
    • Security notes \ud83d\udea8
    • Installation
    • Compatibility
    • Create your first component
    • Using single-file components
    • Use components in templates
    • Use components outside of templates
    • Use components as views
    • Typing and validating components
    • Pre-defined components
    • Registering components
    • Autodiscovery
    • Using slots in templates
    • Accessing data passed to the component
    • Rendering HTML attributes
    • Template tag syntax
    • Prop drilling and dependency injection (provide / inject)
    • Component hooks
    • Component context and scope
    • Pre-defined template variables
    • Customizing component tags with TagFormatter
    • Defining HTML/JS/CSS files
    • Rendering JS/CSS dependencies
    • Available settings
    • Running with development server
    • Logging and debugging
    • Management Command
    • Writing and sharing component libraries
    • Community examples
    • Running django-components project locally
    • Development guides
    "},{"location":"#release-notes","title":"Release notes","text":"

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

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

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

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

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

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

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

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

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

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

    {# Before #}\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`:\n```django\n{% component \"button\" href=\"...\" disabled %}\n    Click me!\n{% endcomponent %}\n```\n\nWhile `django_components.shorthand_component_formatter` allows you to write components like so:\n\n```django\n{% button href=\"...\" disabled %}\n    Click me!\n{% endbutton %}\n

    \ud83d\udea8\ud83d\udce2 Version 0.85 Autodiscovery module resolution changed. Following undocumented behavior was removed:

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

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

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

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

    \ud83d\udea8\ud83d\udce2 Version 0.79

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

    \ud83d\udea8\ud83d\udce2 Version 0.77 CHANGED the syntax for accessing default slot content.

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

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

    \ud83d\udea8\ud83d\udce2 Version 0.70

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

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

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

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

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

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

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

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

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

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

    "},{"location":"#security-notes","title":"Security notes \ud83d\udea8","text":"

    It is strongly recommended to read this section before using django-components in production.

    "},{"location":"#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":"#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 older version of django-components, your alternatives are a) passing --ignore <pattern> options to the collecstatic CLI command, or 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.

    "},{"location":"#installation","title":"Installation","text":"
    1. Install django_components into your environment:

    pip install django_components

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

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

    2. Remove 'APP_DIRS': True,

      • NOTE: Instead of APP_DIRS, for the same effect, we will use django.template.loaders.app_directories.Loader
    3. Add loaders to OPTIONS list and set it to following value:
    TEMPLATES = [\n   {\n      ...,\n      'OPTIONS': {\n            'context_processors': [\n               ...\n            ],\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
    1. Lastly, be able to serve the component JS and CSS files as static files, modify STATICFILES_FINDERS section of settings.py as follows:
    STATICFILES_FINDERS = [\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
    "},{"location":"#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            'context_processors': [\n                ...\n            ],\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":"#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 3.11 4.2, 5.0 3.12 4.2, 5.0"},{"location":"#create-your-first-component","title":"Create your first component","text":"

    A component in django-components is the combination of four things: CSS, Javascript, a Django template, and some Python code to put them all together.

        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       \u251c\u2500\u2500 script.js       \ud83c\udd95\n    \u2502       \u251c\u2500\u2500 style.css       \ud83c\udd95\n    \u2502       \u2514\u2500\u2500 template.html   \ud83c\udd95\n    \u251c\u2500\u2500 sampleproject/\n    \u251c\u2500\u2500 manage.py\n    \u2514\u2500\u2500 requirements.txt\n

    Start by creating empty files in the structure above.

    First, you need a CSS file. Be sure to prefix all rules with a unique class so they don't clash with other rules.

    [project root]/components/calendar/style.css
    /* In a file called [project root]/components/calendar/style.css */\n.calendar-component {\n  width: 200px;\n  background: pink;\n}\n.calendar-component span {\n  font-weight: bold;\n}\n

    Then you need a javascript file that specifies how you interact with this component. You are free to use any javascript framework you want. A good way to make sure this component doesn't clash with other components is to define all code inside an anonymous function that calls itself. This makes all variables defined only be defined inside this component and not affect other components.

    [project root]/components/calendar/script.js
    /* In a file called [project root]/components/calendar/script.js */\n(function () {\n  if (document.querySelector(\".calendar-component\")) {\n    document.querySelector(\".calendar-component\").onclick = function () {\n      alert(\"Clicked calendar!\");\n    };\n  }\n})();\n

    Now you need a Django template for your component. Feel free to define more variables like date in this example. When creating an instance of this component we will send in the values for these variables. The template will be rendered with whatever template backend you've specified in your Django settings file.

    [project root]/components/calendar/calendar.html
    {# In a file called [project root]/components/calendar/template.html #}\n<div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n

    Finally, we use django-components to tie this together. Start by creating a file called calendar.py in your component calendar directory. It will be auto-detected and loaded by the app.

    Inside this file we create a Component by inheriting from the Component class and specifying the context method. We also register the global component registry so that we easily can render it anywhere in our templates.

    [project root]/components/calendar/calendar.py
    # In a file called [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    # Templates inside `[your apps]/components` dir and `[project root]/components` dir\n    # will be automatically found.\n    #\n    # `template_name` can be relative to dir where `calendar.py` is, or relative to COMPONENTS.dirs\n    template_name = \"template.html\"\n    # Or\n    def get_template_name(context):\n        return f\"template-{context['name']}.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\n    # Both `css` and `js` can be relative to dir where `calendar.py` is, or relative to COMPONENTS.dirs\n    class Media:\n        css = \"style.css\"\n        js = \"script.js\"\n

    And voil\u00e1!! We've created our first component.

    "},{"location":"#using-single-file-components","title":"Using single-file components","text":"

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

    [project root]/components/calendar.py
    # In a file called [project root]/components/calendar.py\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

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

    "},{"location":"#syntax-highlight-and-code-assistance","title":"Syntax highlight and code assistance","text":""},{"location":"#vscode","title":"VSCode","text":"

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

    "},{"location":"#pycharm-or-other-jetbrains-ides","title":"Pycharm (or other Jetbrains IDEs)","text":"

    If you're a Pycharm user (or any other editor from Jetbrains), you can have coding assistance as well:

    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

    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.

    "},{"location":"#use-components-in-templates","title":"Use components in templates","text":"

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

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

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

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

    The output from the above template will be:

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

    "},{"location":"#use-components-outside-of-templates","title":"Use components outside of templates","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":"#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.
    "},{"location":"#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":"#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":"#use-components-as-views","title":"Use 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":"#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":"#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":"#typing-and-validating-components","title":"Typing and validating components","text":""},{"location":"#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, Data, Slots]):\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, Data, Slots]):\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":"#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":"#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:

    ```py\n# Tuple of one member of list of strings\nArgs = Tuple[List[str]]\n```\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":"#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, Data, Slots]):\n    ...\n
    "},{"location":"#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, Data, Slots]):\n    ...\n

    Same applies to kwargs, data, and slots.

    "},{"location":"#pre-defined-components","title":"Pre-defined components","text":""},{"location":"#dynamic-components","title":"Dynamic components","text":"

    If you are writing something like a form component, you may design it such that users give you the component names, and your component renders it.

    While you can handle this with a series of if / else statements, this is not an extensible solution.

    Instead, you can use dynamic components. Dynamic components are used in place of normal components.

    {% load component_tags %}\n{% component \"dynamic\" is=component_name title=\"Cat Museum\" %}\n    {% fill \"content\" %}\n        HELLO_FROM_SLOT_1\n    {% endfill %}\n    {% fill \"sidebar\" %}\n        HELLO_FROM_SLOT_2\n    {% endfill %}\n{% endcomponent %}\n

    These behave same way as regular components. You pass it the same args, kwargs, and slots as you would to the component that you want to render.

    The only exception is that also you supply 1-2 additional inputs: - is - Required - The component name or a component class to render - registry - Optional - The ComponentRegistry that will be searched if is is a component name. If omitted, ALL registries are searched.

    By default, the dynamic component is registered under the name \"dynamic\". In case of a conflict, you can change the name used for the dynamic components by defining the COMPONENTS.dynamic_component_name setting.

    If you need to use the dynamic components in Python, you can also import it from django_components:

    from django_components import DynamicComponent\n\ncomp = SimpleTableComp if is_readonly else TableComp\n\noutput = DynamicComponent.render(\n    kwargs={\n        \"is\": comp,\n        # Other kwargs...\n    },\n    # args: [...],\n    # slots: {...},\n)\n

    "},{"location":"#registering-components","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_name = \"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":"#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":"#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":"#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":"#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":"#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 (or app-level [app]/components/) are auto-imported in order to auto-register the components.

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

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

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

    Autodiscovery can be disabled in the settings.

    "},{"location":"#manually-trigger-autodiscovery","title":"Manually trigger autodiscovery","text":"

    Autodiscovery can be also triggered manually as a function call. This is useful if you want to run autodiscovery at a custom point of the lifecycle:

    from django_components import autodiscover\n\nautodiscover()\n
    "},{"location":"#using-slots-in-templates","title":"Using slots in templates","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\" %}Can you believe it's already <span>{{ date }}</span>??{% 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":"#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 end of 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 compiled.

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

    By contrast, it is permitted to use fill tags in nested components, e.g.:

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

    This is fine too:

    {% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"header\" %}\n        {% component \"calendar-header\" %}\n            Super Special Calendar Header\n        {% endcomponent %}\n    {% endfill %}\n{% endcomponent %}\n
    "},{"location":"#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":"#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 ONLY ONE of the identical slots.

    We recommend to mark the first occurence for consistency, 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\" %}Image here{% endslot %}\n    </div>\n</div>\n

    Which you can then use are regular default slot:

    {% component \"calendar\" date=\"2020-06-06\" %}\n    <img src=\"...\" />\n{% endcomponent %}\n
    "},{"location":"#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
    "},{"location":"#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\nHere's our example with more complex branching.\n\n```htmldjango\n<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":"#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___.

    "},{"location":"#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":"#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":"#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=\"data\" %}\n        {{ 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=\"data\" %}\n        {{ 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":"#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":"#accessing-data-passed-to-the-component","title":"Accessing data passed to the component","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

    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
    "},{"location":"#rendering-html-attributes","title":"Rendering 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":"#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":"#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":"#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":"#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":"#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":"#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":"#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":"#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":"#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":"#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":"#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":"#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":"#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":"#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":"#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\n  value={ isEnabled ? inputValue : null }\n/>\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":"#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":"#multi-line-tags","title":"Multi-line 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":"#prop-drilling-and-dependency-injection-provide-inject","title":"Prop drilling and dependency injection (provide / inject)","text":"

    New in version 0.80:

    Django components supports dependency injection with the combination of:

    1. {% provide %} tag
    2. inject() method of the Component class
    "},{"location":"#what-is-dependency-injection-and-prop-drilling","title":"What is \"dependency injection\" and \"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, AKA dependency injection.

    With dependency injection, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.

    This feature is inspired by Vue's Provide / Inject and React's Context / useContext.

    "},{"location":"#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":"#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":"#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":"#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":"#component-hooks","title":"Component hooks","text":"

    New in version 0.96

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

    "},{"location":"#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.\n\nYou can use this hook to access or modify the context or the template:\n\n```py\ndef 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```\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.\nIt receives the rendered output as the last argument.\n\nYou can use this hook to access the context or the template, but modifying\nthem won't have any effect.\n\nTo override the content that gets rendered, you can return a string or SafeString from this hook:\n\n```py\ndef on_render_after(self, context, template, content):\n    # Prepend text to the rendered content\n    return \"Chocolate cookie recipe: \" + content\n```\n
    "},{"location":"#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":"#component-context-and-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":"#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":"#pre-defined-template-variables","title":"Pre-defined template variables","text":"

    Here is a list of all variables that are automatically available from within the component's template and on_render_before / on_render_after hooks.

    • component_vars.is_filled

      New in version 0.70

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

      Example:

      {% if component_vars.is_filled.my_slot %}\n    {% slot \"my_slot\" / %}\n{% endif %}\n
    "},{"location":"#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.shorthand_component_formatter, the components will use their name as the template tags:

    {% button href=\"...\" disabled %}\n  Click me!\n{% endbutton %}\n\n{# or #}\n\n{% button href=\"...\" disabled / %}\n
    "},{"location":"#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.shorthand_component_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":"#writing-your-own-tagformatter","title":"Writing your own TagFormatter","text":""},{"location":"#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:\n```django\n{% component \"button\" href=\"...\" disabled %}\n{% endcomponent %}\n```\n\nThen `TagFormatter.parse()` will receive a following input:\n```py\n[\"component\", '\"button\"', 'href=\"...\"', 'disabled']\n```\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
      5. The tag handler resumes, using the tokens returned from TagFormatter.

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

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

    "},{"location":"#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":"#defining-htmljscss-files","title":"Defining HTML/JS/CSS files","text":"

    django_component's management of files builds on top of Django's Media class.

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

    • How to manage static files (e.g. images, JavaScript, CSS)
    "},{"location":"#defining-file-paths-relative-to-component-or-static-dirs","title":"Defining file paths relative to component or static dirs","text":"

    As seen in the getting started example, to associate HTML/JS/CSS files with a component, you set them as template_name, Media.js and Media.css respectively:

    # In a file [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_name = \"template.html\"\n\n    class Media:\n        css = \"style.css\"\n        js = \"script.js\"\n

    In the example above, the files are defined relative to the directory where component.py is.

    Alternatively, you can specify the file paths relative to the directories set in COMPONENTS.dirs or COMPONENTS.app_dirs.

    Assuming that COMPONENTS.dirs contains path [project root]/components, we can rewrite the example as:

    # In a file [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_name = \"calendar/template.html\"\n\n    class Media:\n        css = \"calendar/style.css\"\n        js = \"calendar/script.js\"\n

    NOTE: In case of conflict, the preference goes to resolving the files relative to the component's directory.

    "},{"location":"#defining-multiple-paths","title":"Defining multiple paths","text":"

    Each component can have only a single template. However, you can define as many JS or CSS files as you want using a list.

    class MyComponent(Component):\n    class Media:\n        js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n        css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n
    "},{"location":"#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\",\n        }\n
    class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": [\"path/to/style1.css\", \"path/to/style2.css\"],\n            \"print\": [\"path/to/style3.css\", \"path/to/style4.css\"],\n        }\n

    NOTE: When you define CSS as a string or a list, the all media type is implied.

    "},{"location":"#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__)
    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/style.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/script.js\"></script>'),\n            Path(\"calendar/script1.js\"),\n            \"calendar/script2.js\",\n            b\"calendar/script3.js\",\n            lambda: \"calendar/script4.js\",\n        ]\n
    "},{"location":"#path-as-objects","title":"Path as objects","text":"

    In the example above, you could see that when we used 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:

    class LazyJsPath:\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_name = \"calendar/template.html\"\n\n    def get_context_data(self, date):\n        return {\n            \"date\": date,\n        }\n\n    class Media:\n        css = \"calendar/style.css\"\n        js = [\n            # <script> tag constructed by Media class\n            \"calendar/script1.js\",\n            # Custom <script> tag\n            LazyJsPath(\"calendar/script2.js\"),\n        ]\n
    "},{"location":"#customize-how-paths-are-rendered-into-html-tags-with-media_class","title":"Customize how paths are rendered into HTML tags with media_class","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_name = \"calendar/template.html\"\n\n    class Media:\n        css = \"calendar/style.css\"\n        js = \"calendar/script.js\"\n\n    # Override the behavior of Media class\n    media_class = MyMedia\n

    NOTE: The instance of the Media class (or it's subclass) is available under Component.media after the class creation (__new__).

    "},{"location":"#rendering-jscss-dependencies","title":"Rendering JS/CSS dependencies","text":"

    The JS and CSS files included in components are not automatically rendered. Instead, use the following tags to specify where to render the dependencies:

    • component_dependencies - Renders both JS and CSS
    • component_js_dependencies - Renders only JS
    • component_css_dependencies - Reneders only CSS

    JS files are rendered as <script> tags. CSS files are rendered as <style> tags.

    "},{"location":"#setting-up-componentdependencymiddleware","title":"Setting Up ComponentDependencyMiddleware","text":"

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

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

    MIDDLEWARE = [\n    # ... other middleware classes ...\n    'django_components.middleware.ComponentDependencyMiddleware'\n    # ... other middleware classes ...\n]\n

    Then, enable RENDER_DEPENDENCIES in setting.py:

    COMPONENTS = {\n    \"RENDER_DEPENDENCIES\": True,\n    # ... other component settings ...\n}\n
    "},{"location":"#available-settings","title":"Available settings","text":"

    All library settings are handled from a global COMPONENTS variable that is read from settings.py. By default you don't need it set, there are resonable defaults.

    Here's overview of all available settings and their defaults:

    COMPONENTS = {\n    \"autodiscover\": True,\n    \"context_behavior\": \"django\",  # \"django\" | \"isolated\"\n    \"dirs\": [BASE_DIR / \"components\"],  # Root-level \"components\" dirs, e.g. `/path/to/proj/components/`\n    \"app_dirs\": [\"components\"],  # App-level \"components\" dirs, e.g. `[app]/components/`\n    \"dynamic_component_name\": \"dynamic\",\n    \"libraries\": [],  # [\"mysite.components.forms\", ...]\n    \"multiline_tags\": True,\n    \"reload_on_template_change\": False,\n    \"static_files_allowed\": [\n        \".css\",\n        \".js\",\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        \".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":"#libraries-load-component-modules","title":"libraries - Load component modules","text":"

    Configure the locations where components are loaded. To do this, add a COMPONENTS variable to you settings.py with a list of python paths to load. This allows you to build a structure of components that are independent from your apps.

    COMPONENTS = {\n    \"libraries\": [\n        \"mysite.components.forms\",\n        \"mysite.components.buttons\",\n        \"mysite.components.cards\",\n    ],\n}\n

    Where mysite/components/forms.py may look like this:

    @register(\"form_simple\")\nclass FormSimple(Component):\n    template = \"\"\"\n        <form>\n            ...\n        </form>\n    \"\"\"\n\n@register(\"form_other\")\nclass FormOther(Component):\n    template = \"\"\"\n        <form>\n            ...\n        </form>\n    \"\"\"\n

    In the rare cases when you need to manually trigger the import of libraries, you can use the import_libraries function:

    from django_components import import_libraries\n\nimport_libraries()\n
    "},{"location":"#autodiscover-toggle-autodiscovery","title":"autodiscover - Toggle autodiscovery","text":"

    If you specify all the component locations with the setting above and have a lot of apps, you can (very) slightly speed things up by disabling autodiscovery.

    COMPONENTS = {\n    \"autodiscover\": False,\n}\n
    "},{"location":"#dirs","title":"dirs","text":"

    Specify the directories that contain your components.

    Directories must be full paths, same as with STATICFILES_DIRS.

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

    COMPONENTS = {\n    \"dirs\": [BASE_DIR / \"components\"],\n}\n
    "},{"location":"#app_dirs","title":"app_dirs","text":"

    Specify the app-level directories that contain your components.

    Directories must be relative to app, e.g.:

    COMPONENTS = {\n    \"app_dirs\": [\"my_comps\"],  # To search for [app]/my_comps\n}\n

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

    Each app will be searched for these directories.

    Set to empty list to disable app-level components:

    COMPONENTS = {\n    \"app_dirs\": [],\n}\n
    "},{"location":"#dynamic_component_name","title":"dynamic_component_name","text":"

    By default, the dynamic component is registered under the name \"dynamic\". In case of a conflict, use this setting to change the name used for the dynamic components.

    COMPONENTS = {\n    \"dynamic_component_name\": \"new_dynamic\",\n}\n
    "},{"location":"#multiline_tags-enabledisable-multiline-support","title":"multiline_tags - Enable/Disable multiline support","text":"

    If True, template tags can span multiple lines. Default: True

    COMPONENTS = {\n    \"multiline_tags\": True,\n}\n
    "},{"location":"#static_files_allowed","title":"static_files_allowed","text":"

    A list of regex patterns (as strings) that define which files within COMPONENTS.dirs and COMPONENTS.app_dirs are treated as static files.

    If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running collectstatic, and can be accessed under the static file endpoint.

    You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

    By default, JS, CSS, and common image and font file formats are considered static files:

    COMPONENTS = {\n    \"static_files_allowed\": [\n            \"css\",\n            \"js\",\n            # Images\n            \".apng\", \".png\",\n            \".avif\",\n            \".gif\",\n            \".jpg\", \".jpeg\", \".jfif\", \".pjpeg\", \".pjp\",  # JPEG\n            \".svg\",\n            \".webp\", \".bmp\",\n            \".ico\", \".cur\",  # ICO\n            \".tif\", \".tiff\",\n            # Fonts\n            \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n    ],\n}\n
    "},{"location":"#static_files_forbidden","title":"static_files_forbidden","text":"

    A list of suffixes that define which files within COMPONENTS.dirs and 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 COMPONENTS.static_files_allowed.

    Use this setting together with COMPONENTS.static_files_allowed for a fine control over what files 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 = {\n    \"static_files_forbidden\": [\n        \".html\", \".django\", \".dj\", \".tpl\", \".py\", \".pyc\",\n    ],\n}\n
    "},{"location":"#template_cache_size-tune-the-template-cache","title":"template_cache_size - Tune the template cache","text":"

    Each time a template is rendered it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.

    By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are using the template method of a component to render lots of dynamic templates, you can increase this number. To remove the cache limit altogether and cache everything, set template_cache_size to None.

    COMPONENTS = {\n    \"template_cache_size\": 256,\n}\n

    If you want 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":"#context_behavior-make-components-isolated-or-not","title":"context_behavior - Make components isolated (or not)","text":"

    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.

    You can configure what variables are available inside the {% fill %} tags. See Component context and scope.

    This has two modes:

    • \"django\" - Default - 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 loops or with tag
    • Data returned from get_context_data() of the component that wraps 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:

    • get_context_data() of the component which defined the template (AKA the \"root\" component)
    • Any loops ({% for ... %}) that the {% fill %} tag is part of.
    COMPONENTS = {\n    \"context_behavior\": \"isolated\",\n}\n
    "},{"location":"#example-django","title":"Example \"django\"","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    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 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":"#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    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.

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

    "},{"location":"#reload_on_template_change-reload-dev-server-on-component-file-changes","title":"reload_on_template_change - Reload dev server on component file changes","text":"

    If True, configures Django to reload on component files. See Reload dev server on component file changes.

    NOTE: This setting should be enabled only for the dev environment!

    "},{"location":"#tag_formatter-change-how-components-are-used-in-templates","title":"tag_formatter - Change how components are used in templates","text":"

    Sets the TagFormatter instance. See the section Customizing component tags with TagFormatter.

    Can be set either as direct reference, or as an import string;

    COMPONENTS = {\n    \"tag_formatter\": \"django_components.component_formatter\"\n}\n

    Or

    from django_components import component_formatter\n\nCOMPONENTS = {\n    \"tag_formatter\": component_formatter\n}\n
    "},{"location":"#running-with-development-server","title":"Running with development server","text":""},{"location":"#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 separate 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 comoponent 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_template_change to True. This configures Django to watch for component files too.

    NOTE: This setting should be enabled only for the dev environment!

    "},{"location":"#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":"#management-command","title":"Management Command","text":"

    You can use the built-in management command startcomponent to create a django component. The command accepts the following arguments and options:

    • name: The name of the component to create. This is a required argument.

    • --path: The path to the components directory. This is an optional argument. If not provided, the command will use the BASE_DIR setting from your Django settings.

    • --js: The name of the JavaScript file. This is an optional argument. The default value is script.js.

    • --css: The name of the CSS file. This is an optional argument. The default value is style.css.

    • --template: The name of the template file. This is an optional argument. The default value is template.html.

    • --force: This option allows you to overwrite existing files if they exist. This is an optional argument.

    • --verbose: This option allows the command to print additional information during component creation. This is an optional argument.

    • --dry-run: This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False.

    "},{"location":"#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":"#management-command-examples","title":"Management Command Examples","text":"

    Here are some examples of how you can use the command:

    "},{"location":"#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":"#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":"#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":"#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":"#writing-and-sharing-component-libraries","title":"Writing and sharing component libraries","text":"

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

    "},{"location":"#writing-component-libraries","title":"Writing component libraries","text":"
    1. Create a Django project with the following 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 settingt 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]):\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":"#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: - The user of the package NEEDS to have installed and configured django_components. - If you use components where the HTML / CSS / JS files are separate, you may need to define MANIFEST.in to include those files with the distribution (see user guide).

    "},{"location":"#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\n
    2. Add the package to INSTALLED_APPS

      INSTALLED_APPS = [\n    ...\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            'context_processors': [\n                ...\n            ],\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":"#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":""},{"location":"#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 local 3.8 3.9 3.10 3.11 3.12\ntox -p\n
    "},{"location":"#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":"#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
    1. Install dependencies from the requirements.txt file:
    pip install -r requirements.txt\n
    1. Link to your local version of django-components:
    pip install -e ..\n

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

    1. Start Django server
      python manage.py runserver\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":"#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
    1. Install the JS dependencies
    npm install\n
    1. 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":"#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":"#development-guides","title":"Development guides","text":"
    • Slot rendering flot
    • Slots and blocks
    "},{"location":"CHANGELOG/","title":"Release notes","text":"

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

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

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

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

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

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

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

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

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

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

    {# Before #}\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`:\n```django\n{% component \"button\" href=\"...\" disabled %}\n    Click me!\n{% endcomponent %}\n```\n\nWhile `django_components.shorthand_component_formatter` allows you to write components like so:\n\n```django\n{% button href=\"...\" disabled %}\n    Click me!\n{% endbutton %}\n

    \ud83d\udea8\ud83d\udce2 Version 0.85 Autodiscovery module resolution changed. Following undocumented behavior was removed:

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

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

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

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

    \ud83d\udea8\ud83d\udce2 Version 0.79

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

    \ud83d\udea8\ud83d\udce2 Version 0.77 CHANGED the syntax for accessing default slot content.

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

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

    \ud83d\udea8\ud83d\udce2 Version 0.70

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

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

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

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

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

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

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

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

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

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

    Static files

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

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

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

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

    "},{"location":"CHANGELOG/#installation","title":"Installation","text":"
    1. Install django_components into your environment:

    pip install django_components

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

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

    2. Remove 'APP_DIRS': True,

      • NOTE: Instead of APP_DIRS, for the same effect, we will use django.template.loaders.app_directories.Loader
    3. Add loaders to OPTIONS list and set it to following value:
    TEMPLATES = [\n   {\n      ...,\n      'OPTIONS': {\n            'context_processors': [\n               ...\n            ],\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
    1. Lastly, be able to serve the component JS and CSS files as static files, modify STATICFILES_FINDERS section of settings.py as follows:
    STATICFILES_FINDERS = [\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
    "},{"location":"CHANGELOG/#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 3.11 4.2, 5.0 3.12 4.2, 5.0

    Using single-file components

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

    [project root]/components/calendar.py
    ## In a file called [project root]/components/calendar.py\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

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

    "},{"location":"CHANGELOG/#vscode","title":"VSCode","text":"

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

    "},{"location":"CHANGELOG/#use-components-in-templates","title":"Use components in templates","text":"

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

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

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

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

    The output from the above template will be:

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

    Inputs of render and render_to_response

    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.
    "},{"location":"CHANGELOG/#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

    Component as view example

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

    ## In a file called [project root]/components/calendar.py\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":"CHANGELOG/#typing-and-validating-components","title":"Typing and validating components","text":""},{"location":"CHANGELOG/#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":"CHANGELOG/#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, Data, Slots]):\n    ...\n
    "},{"location":"CHANGELOG/#pre-defined-components","title":"Pre-defined components","text":""},{"location":"CHANGELOG/#registering-components","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_name = \"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":"CHANGELOG/#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":"CHANGELOG/#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.

    Manually trigger autodiscovery

    Autodiscovery can be also triggered manually as a function call. This is useful if you want to run autodiscovery at a custom point of the lifecycle:

    from django_components import autodiscover\n\nautodiscover()\n

    Default slot

    Added in version 0.28

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

    It can become tedious to use fill tags everywhere, especially when you're using a component that declares only one slot. To make things easier, slot tags can be marked with an optional keyword: default. When added to the end of the tag (as shown below), this option lets you pass filling content directly in the body of a component tag pair \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 compiled.

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

    By contrast, it is permitted to use fill tags in nested components, e.g.:

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

    This is fine too:

    {% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"header\" %}\n        {% component \"calendar-header\" %}\n            Super Special Calendar Header\n        {% endcomponent %}\n    {% endfill %}\n{% endcomponent %}\n
    "},{"location":"CHANGELOG/#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 ONLY ONE of the identical slots.

    We recommend to mark the first occurence for consistency, 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\" %}Image here{% endslot %}\n    </div>\n</div>\n

    Which you can then use are regular default slot:

    {% component \"calendar\" date=\"2020-06-06\" %}\n    <img src=\"...\" />\n{% endcomponent %}\n
    "},{"location":"CHANGELOG/#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\nHere's our example with more complex branching.\n\n```htmldjango\n<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":"CHANGELOG/#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":"CHANGELOG/#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=\"data\" %}\n        {{ 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=\"data\" %}\n        {{ 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":"CHANGELOG/#accessing-data-passed-to-the-component","title":"Accessing data passed to the component","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

    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

    Removing atttributes

    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":"CHANGELOG/#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":"CHANGELOG/#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":"CHANGELOG/#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":"CHANGELOG/#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":"CHANGELOG/#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":"CHANGELOG/#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":"CHANGELOG/#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\n  value={ isEnabled ? inputValue : null }\n/>\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":"CHANGELOG/#multi-line-tags","title":"Multi-line 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

    What is \"dependency injection\" and \"prop drilling\"?

    Prop drilling refers to a scenario in UI development where you need to pass data through many layers of a component tree to reach the nested components that actually need the data.

    Normally, you'd use props to send data from a parent component to its children. However, this straightforward method becomes cumbersome and inefficient if the data has to travel through many levels or if several components scattered at different depths all need the same piece of information.

    This results in a situation where the intermediate components, which don't need the data for their own functioning, end up having to manage and pass along these props. This clutters the component tree and makes the code verbose and harder to manage.

    A neat solution to avoid prop drilling is using the \"provide and inject\" technique, AKA dependency injection.

    With dependency injection, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.

    This feature is inspired by Vue's Provide / Inject and React's Context / useContext.

    "},{"location":"CHANGELOG/#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":"CHANGELOG/#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

    Available hooks

    • 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.\n\nYou can use this hook to access or modify the context or the template:\n\n```py\ndef 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```\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.\nIt receives the rendered output as the last argument.\n\nYou can use this hook to access the context or the template, but modifying\nthem won't have any effect.\n\nTo override the content that gets rendered, you can return a string or SafeString from this hook:\n\n```py\ndef on_render_after(self, context, template, content):\n    # Prepend text to the rendered content\n    return \"Chocolate cookie recipe: \" + content\n```\n
    "},{"location":"CHANGELOG/#component-context-and-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":"CHANGELOG/#pre-defined-template-variables","title":"Pre-defined template variables","text":"

    Here is a list of all variables that are automatically available from within the component's template and on_render_before / on_render_after hooks.

    • component_vars.is_filled

      New in version 0.70

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

      Example:

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

    Available TagFormatters

    django_components provides following predefined TagFormatters:

    • ComponentFormatter (django_components.component_formatter)

      Default

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

      Example as block:

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

      Example as inlined tag:

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

    • ShorthandComponentFormatter (django_components.shorthand_component_formatter)

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

      Example as block:

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

      Example as inlined tag:

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

    "},{"location":"CHANGELOG/#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:\n```django\n{% component \"button\" href=\"...\" disabled %}\n{% endcomponent %}\n```\n\nThen `TagFormatter.parse()` will receive a following input:\n```py\n[\"component\", '\"button\"', 'href=\"...\"', 'disabled']\n```\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
      5. The tag handler resumes, using the tokens returned from TagFormatter.

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

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

    "},{"location":"CHANGELOG/#defining-htmljscss-files","title":"Defining HTML/JS/CSS files","text":"

    django_component's management of files builds on top of Django's Media class.

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

    • How to manage static files (e.g. images, JavaScript, CSS)
    "},{"location":"CHANGELOG/#defining-multiple-paths","title":"Defining multiple paths","text":"

    Each component can have only a single template. However, you can define as many JS or CSS files as you want using a list.

    class MyComponent(Component):\n    class Media:\n        js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n        css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n
    "},{"location":"CHANGELOG/#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__)
    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/style.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/script.js\"></script>'),\n            Path(\"calendar/script1.js\"),\n            \"calendar/script2.js\",\n            b\"calendar/script3.js\",\n            lambda: \"calendar/script4.js\",\n        ]\n
    "},{"location":"CHANGELOG/#customize-how-paths-are-rendered-into-html-tags-with-media_class","title":"Customize how paths are rendered into HTML tags with media_class","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_name = \"calendar/template.html\"\n\n    class Media:\n        css = \"calendar/style.css\"\n        js = \"calendar/script.js\"\n\n    # Override the behavior of Media class\n    media_class = MyMedia\n

    NOTE: The instance of the Media class (or it's subclass) is available under Component.media after the class creation (__new__).

    Setting Up ComponentDependencyMiddleware

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

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

    MIDDLEWARE = [\n    # ... other middleware classes ...\n    'django_components.middleware.ComponentDependencyMiddleware'\n    # ... other middleware classes ...\n]\n

    Then, enable RENDER_DEPENDENCIES in setting.py:

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

    libraries - Load component modules

    Configure the locations where components are loaded. To do this, add a COMPONENTS variable to you settings.py with a list of python paths to load. This allows you to build a structure of components that are independent from your apps.

    COMPONENTS = {\n    \"libraries\": [\n        \"mysite.components.forms\",\n        \"mysite.components.buttons\",\n        \"mysite.components.cards\",\n    ],\n}\n

    Where mysite/components/forms.py may look like this:

    @register(\"form_simple\")\nclass FormSimple(Component):\n    template = \"\"\"\n        <form>\n            ...\n        </form>\n    \"\"\"\n\n@register(\"form_other\")\nclass FormOther(Component):\n    template = \"\"\"\n        <form>\n            ...\n        </form>\n    \"\"\"\n

    In the rare cases when you need to manually trigger the import of libraries, you can use the import_libraries function:

    from django_components import import_libraries\n\nimport_libraries()\n
    "},{"location":"CHANGELOG/#dirs","title":"dirs","text":"

    Specify the directories that contain your components.

    Directories must be full paths, same as with STATICFILES_DIRS.

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

    COMPONENTS = {\n    \"dirs\": [BASE_DIR / \"components\"],\n}\n
    "},{"location":"CHANGELOG/#dynamic_component_name","title":"dynamic_component_name","text":"

    By default, the dynamic component is registered under the name \"dynamic\". In case of a conflict, use this setting to change the name used for the dynamic components.

    COMPONENTS = {\n    \"dynamic_component_name\": \"new_dynamic\",\n}\n
    "},{"location":"CHANGELOG/#static_files_allowed","title":"static_files_allowed","text":"

    A list of regex patterns (as strings) that define which files within COMPONENTS.dirs and COMPONENTS.app_dirs are treated as static files.

    If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running collectstatic, and can be accessed under the static file endpoint.

    You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

    By default, JS, CSS, and common image and font file formats are considered static files:

    COMPONENTS = {\n    \"static_files_allowed\": [\n            \"css\",\n            \"js\",\n            # Images\n            \".apng\", \".png\",\n            \".avif\",\n            \".gif\",\n            \".jpg\", \".jpeg\", \".jfif\", \".pjpeg\", \".pjp\",  # JPEG\n            \".svg\",\n            \".webp\", \".bmp\",\n            \".ico\", \".cur\",  # ICO\n            \".tif\", \".tiff\",\n            # Fonts\n            \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n    ],\n}\n
    "},{"location":"CHANGELOG/#template_cache_size-tune-the-template-cache","title":"template_cache_size - Tune the template cache","text":"

    Each time a template is rendered it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.

    By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are using the template method of a component to render lots of dynamic templates, you can increase this number. To remove the cache limit altogether and cache everything, set template_cache_size to None.

    COMPONENTS = {\n    \"template_cache_size\": 256,\n}\n

    If you want 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":"CHANGELOG/#example-django","title":"Example \"django\"","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    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 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":"CHANGELOG/#reload_on_template_change-reload-dev-server-on-component-file-changes","title":"reload_on_template_change - Reload dev server on component file changes","text":"

    If True, configures Django to reload on component files. See Reload dev server on component file changes.

    NOTE: This setting should be enabled only for the dev environment!

    "},{"location":"CHANGELOG/#running-with-development-server","title":"Running with development server","text":""},{"location":"CHANGELOG/#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

    Management Command Usage

    To use the command, run the following command in your terminal:

    python manage.py startcomponent <name> --path <path> --js <js_filename> --css <css_filename> --template <template_filename> --force --verbose --dry-run\n

    Replace <name>, <path>, <js_filename>, <css_filename>, and <template_filename> with your desired values.

    "},{"location":"CHANGELOG/#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":"CHANGELOG/#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":"CHANGELOG/#writing-and-sharing-component-libraries","title":"Writing and sharing component libraries","text":"

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

    "},{"location":"CHANGELOG/#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: - The user of the package NEEDS to have installed and configured django_components. - If you use components where the HTML / CSS / JS files are separate, you may need to define MANIFEST.in to include those files with the distribution (see user guide).

    "},{"location":"CHANGELOG/#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.

    Install locally and run the tests

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

    git clone https://github.com/<your GitHub username>/django-components.git\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 local 3.8 3.9 3.10 3.11 3.12\ntox -p\n
    "},{"location":"CHANGELOG/#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
    1. Install dependencies from the requirements.txt file:
    pip install -r requirements.txt\n
    1. Link to your local version of django-components:
    pip install -e ..\n

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

    1. Start Django server
      python manage.py runserver\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":"CHANGELOG/#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":"CHANGELOG/#_1","title":"Changelog","text":""},{"location":"CODE_OF_CONDUCT/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"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":"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":"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":"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":"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":"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":"SUMMARY/","title":"SUMMARY","text":"
    • README
    • Changelog
    • Code of Conduct
    • License
    • Reference
    • API Reference
    "},{"location":"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":"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":"slot_rendering/","title":"Slot rendering","text":"

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

    "},{"location":"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. I want to render the slots with {% fill %} tag that were defined OUTSIDE of this template. How do I do that?

    7. Traverse the template to collect ALL slots

      • NOTE: I will also look inside {% slot %} and {% fill %} tags, since they are all still defined within the same TEMPLATE.

      I should end up with a list like this:

      - Name: \"myslot\"\n   ID 0001\n   Content:\n   | ----- DEF {{ my_var }}\n   | ----- {% slot \"myslot_inner\" %}\n   | -------- GHI {{ my_var }}\n   | ----- {% endslot %}\n- Name: \"myslot_inner\"\n   ID 0002\n   Content:\n   | -------- GHI {{ my_var }}\n- Name: \"myslot\"\n   ID 0003\n   Content:\n   | ------- JKL {{ my_var }}\n   | ------- {% slot \"myslot_inner\" %}\n   | ---------- MNO {{ my_var }}\n   | ------- {% endslot %}\n- Name: \"myslot_inner\"\n   ID 0004\n   Content:\n   | ---------- MNO {{ my_var }}\n- Name: \"myslot2\"\n   ID 0005\n   Content:\n   | ---- PQR {{ my_var }}\n

    8. Note the relationships - which slot is nested in which one

      I should end up with a graph-like data like:

      - 0001: [0002]\n- 0002: []\n- 0003: [0004]\n- 0004: []\n- 0005: []\n

      In other words, the data tells us that slot ID 0001 is PARENT of slot 0002.

      This is important, because, IF parent template provides slot fill for slot 0001, then we DON'T NEED TO render it's children, AKA slot 0002.

    9. Find roots of the slot relationships

      The data from previous step can be understood also as a collection of directled acyclig graphs (DAG), e.g.:

      0001 --> 0002\n0003 --> 0004\n0005\n

      So we find the roots (0001, 0003, 0005), AKA slots that are NOT nested in other slots. We do so by going over ALL entries from previous step. Those IDs which are NOT mentioned in ANY of the lists are the roots.

      Because of the nature of nested structures, there cannot be any cycles.

    10. Recursively render slots, starting from roots.

      1. First we take each of the roots.

      2. Then we check if there is a slot fill for given slot name.

      3. If YES we replace the slot node with the fill node.

        • Note: We assume slot fills are ALREADY RENDERED!
          | ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n
          becomes
          | ----- Bla bla\n| -------- Some Other Content\n| ----- ...\n
          We don't continue further, because inner slots have been overriden!
      4. If NO, then we will replace slot nodes with their children, e.g.:

        | ---- {% slot \"myslot\" %} ---\n| ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n| ---- {% endslot %} ---\n
        Becomes
        | ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n

      5. We check if the slot includes any children {% slot %} tags. If YES, then continue with step 4. for them, and wait until they finish.

    11. At this point, ALL slots should be rendered and we should have something like this:

      | -- {{ my_var }} --\n| -- ABC\n| ----- DEF {{ my_var }}\n| -------- GHI {{ my_var }}\n| ------\n| -- {% component \"mycomp\" %} ---\n| ------- JKL {{ my_var }}\n| ---- {% component \"mycomp\" %} ---\n| ---------- MNO {{ my_var }}\n| ---- {% endcomponent %} ---\n| -- {% endcomponent %} ---\n| ----\n| -- {% component \"mycomp2\" %} ---\n| ---- PQR {{ my_var }}\n| -- {% endcomponent %} ---\n| ----\n

      • NOTE: Inserting fills into {% slots %} should NOT introduce new {% slots %}, as the fills should be already rendered!
    "},{"location":"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":"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_name = \"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_name = \"\"\"\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_name = \"\"\"\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":"reference/SUMMARY/","title":"SUMMARY","text":"
    • django_components
    • app_settings
    • apps
    • attributes
    • autodiscover
    • component
    • component_media
    • component_registry
    • components
      • dynamic
    • context
    • expression
    • finders
    • library
    • logger
    • management
      • commands
      • startcomponent
      • upgradecomponent
    • middleware
    • node
    • provide
    • slots
    • tag_formatter
    • template
    • template_loader
    • template_parser
    • templatetags
      • component_tags
    • types
    • utils
    • django_components_js
    • build
    "},{"location":"reference/django_components/","title":"Index","text":""},{"location":"reference/django_components/#django_components","title":"django_components","text":"

    Main package for Django Components.

    "},{"location":"reference/django_components/#django_components.app_settings","title":"app_settings","text":""},{"location":"reference/django_components/#django_components.app_settings.ContextBehavior","title":"ContextBehavior","text":"

    Bases: str, Enum

    "},{"location":"reference/django_components/#django_components.app_settings.ContextBehavior.DJANGO","title":"DJANGO class-attribute instance-attribute","text":"
    DJANGO = 'django'\n

    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 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 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/django_components/#django_components.app_settings.ContextBehavior.ISOLATED","title":"ISOLATED class-attribute instance-attribute","text":"
    ISOLATED = 'isolated'\n

    This setting makes the component fills behave similar to Vue or React, where the fills use EXCLUSIVELY the context variables defined in 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/django_components/#django_components.attributes","title":"attributes","text":""},{"location":"reference/django_components/#django_components.attributes.append_attributes","title":"append_attributes","text":"
    append_attributes(*args: Tuple[str, Any]) -> Dict\n

    Merges the key-value pairs and returns a new dictionary.

    If a key is present multiple times, its values are concatenated with a space character as separator in the final dictionary.

    Source code in src/django_components/attributes.py
    def append_attributes(*args: Tuple[str, Any]) -> Dict:\n    \"\"\"\n    Merges the key-value pairs and returns a new dictionary.\n\n    If a key is present multiple times, its values are concatenated with a space\n    character as separator in the final dictionary.\n    \"\"\"\n    result: Dict = {}\n\n    for key, value in args:\n        if key in result:\n            result[key] += \" \" + value\n        else:\n            result[key] = value\n\n    return result\n
    "},{"location":"reference/django_components/#django_components.attributes.attributes_to_string","title":"attributes_to_string","text":"
    attributes_to_string(attributes: Mapping[str, Any]) -> str\n

    Convert a dict of attributes to a string.

    Source code in src/django_components/attributes.py
    def attributes_to_string(attributes: Mapping[str, Any]) -> str:\n    \"\"\"Convert a dict of attributes to a string.\"\"\"\n    attr_list = []\n\n    for key, value in attributes.items():\n        if value is None or value is False:\n            continue\n        if value is True:\n            attr_list.append(conditional_escape(key))\n        else:\n            attr_list.append(format_html('{}=\"{}\"', key, value))\n\n    return mark_safe(SafeString(\" \").join(attr_list))\n
    "},{"location":"reference/django_components/#django_components.autodiscover","title":"autodiscover","text":""},{"location":"reference/django_components/#django_components.autodiscover.autodiscover","title":"autodiscover","text":"
    autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n

    Search for component files and import them. Returns a list of module paths of imported files.

    Autodiscover searches in the locations as defined by Loader.get_dirs.

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

    Source code in src/django_components/autodiscover.py
    def autodiscover(\n    map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n    \"\"\"\n    Search for component files and import them. Returns a list of module\n    paths of imported files.\n\n    Autodiscover searches in the locations as defined by `Loader.get_dirs`.\n\n    You can map the module paths with `map_module` function. This serves\n    as an escape hatch for when you need to use this function in tests.\n    \"\"\"\n    dirs = get_dirs(include_apps=False)\n    component_filepaths = search_dirs(dirs, \"**/*.py\")\n    logger.debug(f\"Autodiscover found {len(component_filepaths)} files in component directories.\")\n\n    if hasattr(settings, \"BASE_DIR\") and settings.BASE_DIR:\n        project_root = str(settings.BASE_DIR)\n    else:\n        # Fallback for getting the root dir, see https://stackoverflow.com/a/16413955/9788634\n        project_root = os.path.abspath(os.path.dirname(__name__))\n\n    modules: List[str] = []\n\n    # We handle dirs from `COMPONENTS.dirs` and from individual apps separately.\n    #\n    # Because for dirs in `COMPONENTS.dirs`, we assume they will be nested under `BASE_DIR`,\n    # and that `BASE_DIR` is the current working dir (CWD). So the path relatively to `BASE_DIR`\n    # is ALSO the python import path.\n    for filepath in component_filepaths:\n        module_path = _filepath_to_python_module(filepath, project_root, None)\n        # Ignore files starting with dot `.` or files in dirs that start with dot.\n        #\n        # If any of the parts of the path start with a dot, e.g. the filesystem path\n        # is `./abc/.def`, then this gets converted to python module as `abc..def`\n        #\n        # NOTE: This approach also ignores files:\n        #   - with two dots in the middle (ab..cd.py)\n        #   - an extra dot at the end (abcd..py)\n        #   - files outside of the parent component (../abcd.py).\n        # But all these are NOT valid python modules so that's fine.\n        if \"..\" in module_path:\n            continue\n\n        modules.append(module_path)\n\n    # For for apps, the directories may be outside of the project, e.g. in case of third party\n    # apps. So we have to resolve the python import path relative to the package name / the root\n    # import path for the app.\n    # See https://github.com/EmilStenstrom/django-components/issues/669\n    for conf in apps.get_app_configs():\n        for app_dir in app_settings.APP_DIRS:\n            comps_path = Path(conf.path).joinpath(app_dir)\n            if not comps_path.exists():\n                continue\n            app_component_filepaths = search_dirs([comps_path], \"**/*.py\")\n            for filepath in app_component_filepaths:\n                app_component_module = _filepath_to_python_module(filepath, conf.path, conf.name)\n                modules.append(app_component_module)\n\n    return _import_modules(modules, map_module)\n
    "},{"location":"reference/django_components/#django_components.autodiscover.import_libraries","title":"import_libraries","text":"
    import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n

    Import modules set in COMPONENTS.libraries setting.

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

    Source code in src/django_components/autodiscover.py
    def import_libraries(\n    map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n    \"\"\"\n    Import modules set in `COMPONENTS.libraries` setting.\n\n    You can map the module paths with `map_module` function. This serves\n    as an escape hatch for when you need to use this function in tests.\n    \"\"\"\n    from django_components.app_settings import app_settings\n\n    return _import_modules(app_settings.LIBRARIES, map_module)\n
    "},{"location":"reference/django_components/#django_components.autodiscover.search_dirs","title":"search_dirs","text":"
    search_dirs(dirs: List[Path], search_glob: str) -> List[Path]\n

    Search the directories for the given glob pattern. Glob search results are returned as a flattened list.

    Source code in src/django_components/autodiscover.py
    def search_dirs(dirs: List[Path], search_glob: str) -> List[Path]:\n    \"\"\"\n    Search the directories for the given glob pattern. Glob search results are returned\n    as a flattened list.\n    \"\"\"\n    matched_files: List[Path] = []\n    for directory in dirs:\n        for path in glob.iglob(str(Path(directory) / search_glob), recursive=True):\n            matched_files.append(Path(path))\n\n    return matched_files\n
    "},{"location":"reference/django_components/#django_components.component","title":"component","text":""},{"location":"reference/django_components/#django_components.component.Component","title":"Component","text":"
    Component(\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,\n)\n

    Bases: Generic[ArgsType, KwargsType, DataType, SlotsType]

    Source code in src/django_components/component.py
    def __init__(\n    self,\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,  # noqa F811\n):\n    # When user first instantiates the component class before calling\n    # `render` or `render_to_response`, then we want to allow the render\n    # function to make use of the instantiated object.\n    #\n    # So while `MyComp.render()` creates a new instance of MyComp internally,\n    # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n    # already-instantiated object.\n    #\n    # To achieve that, we want to re-assign the class methods as instance methods.\n    # For that we have to \"unwrap\" the class methods via __func__.\n    # See https://stackoverflow.com/a/76706399/9788634\n    self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self)  # type: ignore\n    self.render = types.MethodType(self.__class__.render.__func__, self)  # type: ignore\n    self.as_view = types.MethodType(self.__class__.as_view.__func__, self)  # type: ignore\n\n    self.registered_name: Optional[str] = registered_name\n    self.outer_context: Context = outer_context or Context()\n    self.fill_content = fill_content or {}\n    self.component_id = component_id or gen_id()\n    self.registry = registry or registry_\n    self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n    # None == uninitialized, False == No types, Tuple == types\n    self._types: Optional[Union[Tuple[Any, Any, Any, Any], Literal[False]]] = None\n
    "},{"location":"reference/django_components/#django_components.component.Component.Media","title":"Media class-attribute instance-attribute","text":"
    Media = ComponentMediaInput\n

    Defines JS and CSS media files associated with this component.

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

    Inlined CSS associated with this component.

    "},{"location":"reference/django_components/#django_components.component.Component.input","title":"input property","text":"
    input: RenderInput[ArgsType, KwargsType, SlotsType]\n

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

    "},{"location":"reference/django_components/#django_components.component.Component.is_filled","title":"is_filled property","text":"
    is_filled: Dict[str, bool]\n

    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/django_components/#django_components.component.Component.js","title":"js class-attribute instance-attribute","text":"
    js: Optional[str] = None\n

    Inlined JS associated with this component.

    "},{"location":"reference/django_components/#django_components.component.Component.media","title":"media instance-attribute","text":"
    media: Media\n

    Normalized definition of JS and CSS media files associated with this component.

    NOTE: This field is generated from Component.Media class.

    "},{"location":"reference/django_components/#django_components.component.Component.response_class","title":"response_class class-attribute instance-attribute","text":"
    response_class = HttpResponse\n

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

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

    Inlined Django template associated with this component. Can be a plain string or a Template instance.

    Only one of template_name, get_template_name, template or get_template must be defined.

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

    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_name, get_template_name, template or get_template must be defined.

    "},{"location":"reference/django_components/#django_components.component.Component.as_view","title":"as_view classmethod","text":"
    as_view(**initkwargs: Any) -> ViewFn\n

    Shortcut for calling Component.View.as_view and passing component instance to it.

    Source code in src/django_components/component.py
    @classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n    \"\"\"\n    Shortcut for calling `Component.View.as_view` and passing component instance to it.\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    # Allow the View class to access this component via `self.component`\n    return comp.View.as_view(**initkwargs, component=comp)\n
    "},{"location":"reference/django_components/#django_components.component.Component.get_template","title":"get_template","text":"
    get_template(context: Context) -> Optional[Union[str, Template]]\n

    Inlined Django template associated with this component. Can be a plain string or a Template instance.

    Only one of template_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n    \"\"\"\n    Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/#django_components.component.Component.get_template_name","title":"get_template_name","text":"
    get_template_name(context: Context) -> Optional[str]\n

    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_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template_name(self, context: Context) -> Optional[str]:\n    \"\"\"\n    Filepath to the Django template associated with this component.\n\n    The filepath must be relative to either the file where the component class was defined,\n    or one of the roots of `STATIFILES_DIRS`.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/#django_components.component.Component.inject","title":"inject","text":"
    inject(key: str, default: Optional[Any] = None) -> Any\n

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

    Source code in src/django_components/component.py
    def inject(self, key: str, default: Optional[Any] = None) -> Any:\n    \"\"\"\n    Use this method to retrieve the data that was passed to a `{% provide %}` tag\n    with the corresponding key.\n\n    To retrieve the data, `inject()` must be called inside a component that's\n    inside the `{% provide %}` tag.\n\n    You may also pass a default that will be used if the `provide` tag with given\n    key was NOT found.\n\n    This method mut be used inside the `get_context_data()` method and raises\n    an error if called elsewhere.\n\n    Example:\n\n    Given this template:\n    ```django\n    {% provide \"provider\" hello=\"world\" %}\n        {% component \"my_comp\" %}\n        {% endcomponent %}\n    {% endprovide %}\n    ```\n\n    And given this definition of \"my_comp\" component:\n    ```py\n    from django_components import Component, register\n\n    @register(\"my_comp\")\n    class MyComp(Component):\n        template = \"hi {{ data.hello }}!\"\n        def get_context_data(self):\n            data = self.inject(\"provider\")\n            return {\"data\": data}\n    ```\n\n    This renders into:\n    ```\n    hi world!\n    ```\n\n    As the `{{ data.hello }}` is taken from the \"provider\".\n    \"\"\"\n    if self.input is None:\n        raise RuntimeError(\n            f\"Method 'inject()' of component '{self.name}' was called outside of 'get_context_data()'\"\n        )\n\n    return get_injected_context_var(self.name, self.input.context, key, default)\n
    "},{"location":"reference/django_components/#django_components.component.Component.on_render_after","title":"on_render_after","text":"
    on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\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.

    Source code in src/django_components/component.py
    def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n    \"\"\"\n    Hook that runs just after the component's template was rendered.\n    It receives the rendered output as the last argument.\n\n    You can use this hook to access the context or the template, but modifying\n    them won't have any effect.\n\n    To override the content that gets rendered, you can return a string or SafeString\n    from this hook.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/#django_components.component.Component.on_render_before","title":"on_render_before","text":"
    on_render_before(context: Context, template: Template) -> 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.

    Source code in src/django_components/component.py
    def on_render_before(self, context: Context, template: Template) -> None:\n    \"\"\"\n    Hook that runs just before the component's template is rendered.\n\n    You can use this hook to access or modify the context or the template.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/#django_components.component.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) -> str\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render(\n    cls,\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) -> str:\n    \"\"\"\n    Render the component into a string.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    return comp._render(context, args, kwargs, slots, escape_slots_content)\n
    "},{"location":"reference/django_components/#django_components.component.Component.render_css_dependencies","title":"render_css_dependencies","text":"
    render_css_dependencies() -> SafeString\n

    Render only CSS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_css_dependencies(self) -> SafeString:\n    \"\"\"Render only CSS dependencies available in the media class or provided as a string.\"\"\"\n    if self.css is not None:\n        return mark_safe(f\"<style>{self.css}</style>\")\n    return mark_safe(\"\\n\".join(self.media.render_css()))\n
    "},{"location":"reference/django_components/#django_components.component.Component.render_dependencies","title":"render_dependencies","text":"
    render_dependencies() -> SafeString\n

    Helper function to render all dependencies for a component.

    Source code in src/django_components/component.py
    def render_dependencies(self) -> SafeString:\n    \"\"\"Helper function to render all dependencies for a component.\"\"\"\n    dependencies = []\n\n    css_deps = self.render_css_dependencies()\n    if css_deps:\n        dependencies.append(css_deps)\n\n    js_deps = self.render_js_dependencies()\n    if js_deps:\n        dependencies.append(js_deps)\n\n    return mark_safe(\"\\n\".join(dependencies))\n
    "},{"location":"reference/django_components/#django_components.component.Component.render_js_dependencies","title":"render_js_dependencies","text":"
    render_js_dependencies() -> SafeString\n

    Render only JS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_js_dependencies(self) -> SafeString:\n    \"\"\"Render only JS dependencies available in the media class or provided as a string.\"\"\"\n    if self.js is not None:\n        return mark_safe(f\"<script>{self.js}</script>\")\n    return mark_safe(\"\\n\".join(self.media.render_js()))\n
    "},{"location":"reference/django_components/#django_components.component.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    *response_args: Any,\n    **response_kwargs: Any\n) -> HttpResponse\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render_to_response(\n    cls,\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    slots: Optional[SlotsType] = None,\n    escape_slots_content: bool = True,\n    args: Optional[ArgsType] = None,\n    kwargs: Optional[KwargsType] = None,\n    *response_args: Any,\n    **response_kwargs: Any,\n) -> HttpResponse:\n    \"\"\"\n    Render the component and wrap the content in the response class.\n\n    The response class is taken from `Component.response_class`. Defaults to `django.http.HttpResponse`.\n\n    This is the interface for the `django.views.View` class which allows us to\n    use components as Django views with `component.as_view()`.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Any additional args and kwargs are passed to the `response_class`.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    content = cls.render(\n        args=args,\n        kwargs=kwargs,\n        context=context,\n        slots=slots,\n        escape_slots_content=escape_slots_content,\n    )\n    return cls.response_class(content, *response_args, **response_kwargs)\n
    "},{"location":"reference/django_components/#django_components.component.ComponentNode","title":"ComponentNode","text":"
    ComponentNode(\n    name: str,\n    args: List[Expression],\n    kwargs: RuntimeKwargs,\n    registry: ComponentRegistry,\n    isolated_context: bool = False,\n    fill_nodes: Optional[List[FillNode]] = None,\n    node_id: Optional[str] = None,\n)\n

    Bases: BaseNode

    Django.template.Node subclass that renders a django-components component

    Source code in src/django_components/component.py
    def __init__(\n    self,\n    name: str,\n    args: List[Expression],\n    kwargs: RuntimeKwargs,\n    registry: ComponentRegistry,  # noqa F811\n    isolated_context: bool = False,\n    fill_nodes: Optional[List[FillNode]] = None,\n    node_id: Optional[str] = None,\n) -> None:\n    super().__init__(nodelist=NodeList(fill_nodes), args=args, kwargs=kwargs, node_id=node_id)\n\n    self.name = name\n    self.isolated_context = isolated_context\n    self.fill_nodes = fill_nodes or []\n    self.registry = registry\n
    "},{"location":"reference/django_components/#django_components.component.ComponentView","title":"ComponentView","text":"
    ComponentView(component: Component, **kwargs: Any)\n

    Bases: View

    Subclass of django.views.View where the Component instance is available via self.component.

    Source code in src/django_components/component.py
    def __init__(self, component: \"Component\", **kwargs: Any) -> None:\n    super().__init__(**kwargs)\n    self.component = component\n
    "},{"location":"reference/django_components/#django_components.component_media","title":"component_media","text":""},{"location":"reference/django_components/#django_components.component_media.ComponentMediaInput","title":"ComponentMediaInput","text":"

    Defines JS and CSS media files associated with this component.

    "},{"location":"reference/django_components/#django_components.component_media.MediaMeta","title":"MediaMeta","text":"

    Bases: MediaDefiningClass

    Metaclass for handling media files for components.

    Similar to MediaDefiningClass, this class supports the use of Media attribute to define associated JS/CSS files, which are then available under media attribute as a instance of Media class.

    This subclass has following changes:

    "},{"location":"reference/django_components/#django_components.component_media.MediaMeta--1-support-for-multiple-interfaces-of-jscss","title":"1. Support for multiple interfaces of JS/CSS","text":"
    1. As plain strings

      class MyComponent(Component):\n    class Media:\n        js = \"path/to/script.js\"\n        css = \"path/to/style.css\"\n

    2. As lists

      class MyComponent(Component):\n    class Media:\n        js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n        css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n

    3. [CSS ONLY] Dicts of strings

      class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": \"path/to/style1.css\",\n            \"print\": \"path/to/style2.css\",\n        }\n

    4. [CSS ONLY] Dicts of lists

      class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": [\"path/to/style1.css\"],\n            \"print\": [\"path/to/style2.css\"],\n        }\n

    "},{"location":"reference/django_components/#django_components.component_media.MediaMeta--2-media-are-first-resolved-relative-to-class-definition-file","title":"2. Media are first resolved relative to class definition file","text":"

    E.g. if in a directory my_comp you have script.js and my_comp.py, and my_comp.py looks like this:

    class MyComponent(Component):\n    class Media:\n        js = \"script.js\"\n

    Then script.js will be resolved as my_comp/script.js.

    "},{"location":"reference/django_components/#django_components.component_media.MediaMeta--3-media-can-be-defined-as-str-bytes-pathlike-safestring-or-function-of-thereof","title":"3. Media can be defined as str, bytes, PathLike, SafeString, or function of thereof","text":"

    E.g.:

    def lazy_eval_css():\n    # do something\n    return path\n\nclass MyComponent(Component):\n    class Media:\n        js = b\"script.js\"\n        css = lazy_eval_css\n
    "},{"location":"reference/django_components/#django_components.component_media.MediaMeta--4-subclass-media-class-with-media_class","title":"4. Subclass Media class with media_class","text":"

    Normal MediaDefiningClass creates an instance of Media class under the media attribute. This class allows to override which class will be instantiated with media_class attribute:

    class MyMedia(Media):\n    def render_js(self):\n        ...\n\nclass MyComponent(Component):\n    media_class = MyMedia\n    def get_context_data(self):\n        assert isinstance(self.media, MyMedia)\n
    "},{"location":"reference/django_components/#django_components.component_registry","title":"component_registry","text":""},{"location":"reference/django_components/#django_components.component_registry.registry","title":"registry module-attribute","text":"
    registry: ComponentRegistry = ComponentRegistry()\n

    The default and global component registry. Use this instance to directly register or remove components:

    # Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Get single\nregistry.get(\"button\")\n# Get all\nregistry.all()\n# Unregister single\nregistry.unregister(\"button\")\n# Unregister all\nregistry.clear()\n
    "},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry","title":"ComponentRegistry","text":"
    ComponentRegistry(\n    library: Optional[Library] = None, settings: Optional[Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]] = None\n)\n

    Manages which components can be used in the template tags.

    Each ComponentRegistry instance is associated with an instance of Django's Library. So when you register or unregister a component to/from a component registry, behind the scenes the registry automatically adds/removes the component's template tag to/from the Library.

    The Library instance can be set at instantiation. If omitted, then the default Library instance from django_components is used. The Library instance can be accessed under library attribute.

    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
    Source code in src/django_components/component_registry.py
    def __init__(\n    self,\n    library: Optional[Library] = None,\n    settings: Optional[Union[RegistrySettings, Callable[[\"ComponentRegistry\"], RegistrySettings]]] = None,\n) -> None:\n    self._registry: Dict[str, ComponentRegistryEntry] = {}  # component name -> component_entry mapping\n    self._tags: Dict[str, Set[str]] = {}  # tag -> list[component names]\n    self._library = library\n    self._settings_input = settings\n    self._settings: Optional[Callable[[], InternalRegistrySettings]] = None\n\n    all_registries.append(self)\n
    "},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.library","title":"library property","text":"
    library: Library\n

    The template tag library with which the component registry is associated.

    "},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.all","title":"all","text":"
    all() -> Dict[str, Type[Component]]\n

    Retrieve all registered 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
    Source code in src/django_components/component_registry.py
    def all(self) -> Dict[str, Type[\"Component\"]]:\n    \"\"\"\n    Retrieve all registered component classes.\n\n    Example:\n\n    ```py\n    # First register components\n    registry.register(\"button\", ButtonComponent)\n    registry.register(\"card\", CardComponent)\n    # Then get all\n    registry.all()\n    # > {\n    # >   \"button\": ButtonComponent,\n    # >   \"card\": CardComponent,\n    # > }\n    ```\n    \"\"\"\n    comps = {key: entry.cls for key, entry in self._registry.items()}\n    return comps\n
    "},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.clear","title":"clear","text":"
    clear() -> None\n

    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
    Source code in src/django_components/component_registry.py
    def clear(self) -> None:\n    \"\"\"\n    Clears the registry, unregistering all components.\n\n    Example:\n\n    ```py\n    # First register components\n    registry.register(\"button\", ButtonComponent)\n    registry.register(\"card\", CardComponent)\n    # Then clear\n    registry.clear()\n    # Then get all\n    registry.all()\n    # > {}\n    ```\n    \"\"\"\n    all_comp_names = list(self._registry.keys())\n    for comp_name in all_comp_names:\n        self.unregister(comp_name)\n\n    self._registry = {}\n    self._tags = {}\n
    "},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.get","title":"get","text":"
    get(name: str) -> Type[Component]\n

    Retrieve a 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
    Source code in src/django_components/component_registry.py
    def get(self, name: str) -> Type[\"Component\"]:\n    \"\"\"\n    Retrieve a component class registered under the given name.\n\n    Raises `NotRegistered` if the given name is not registered.\n\n    Example:\n\n    ```py\n    # First register component\n    registry.register(\"button\", ButtonComponent)\n    # Then get\n    registry.get(\"button\")\n    # > ButtonComponent\n    ```\n    \"\"\"\n    if name not in self._registry:\n        raise NotRegistered('The component \"%s\" is not registered' % name)\n\n    return self._registry[name].cls\n
    "},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.register","title":"register","text":"
    register(name: str, component: Type[Component]) -> None\n

    Register a component 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\" %}{% endcomponent %}\n

    Raises AlreadyRegistered if a different component was already registered under the same name.

    Example:

    registry.register(\"button\", ButtonComponent)\n
    Source code in src/django_components/component_registry.py
    def register(self, name: str, component: Type[\"Component\"]) -> None:\n    \"\"\"\n    Register a component with this registry under the given name.\n\n    A component MUST be registered before it can be used in a template such as:\n    ```django\n    {% component \"my_comp\" %}{% endcomponent %}\n    ```\n\n    Raises `AlreadyRegistered` if a different component was already registered\n    under the same name.\n\n    Example:\n\n    ```py\n    registry.register(\"button\", ButtonComponent)\n    ```\n    \"\"\"\n    existing_component = self._registry.get(name)\n    if existing_component and existing_component.cls._class_hash != component._class_hash:\n        raise AlreadyRegistered('The component \"%s\" has already been registered' % name)\n\n    entry = self._register_to_library(name, component)\n\n    # Keep track of which components use which tags, because multiple components may\n    # use the same tag.\n    tag = entry.tag\n    if tag not in self._tags:\n        self._tags[tag] = set()\n    self._tags[tag].add(name)\n\n    self._registry[name] = entry\n
    "},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.unregister","title":"unregister","text":"
    unregister(name: str) -> None\n

    Unlinks a previously-registered component from the registry under the given name.

    Once a component is unregistered, it CANNOT be used in a template anymore. Following would raise an error:

    {% component \"my_comp\" %}{% endcomponent %}\n

    Raises NotRegistered if the given name is not registered.

    Example:

    # First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
    Source code in src/django_components/component_registry.py
    def unregister(self, name: str) -> None:\n    \"\"\"\n    Unlinks a previously-registered component from the registry under the given name.\n\n    Once a component is unregistered, it CANNOT be used in a template anymore.\n    Following would raise an error:\n    ```django\n    {% component \"my_comp\" %}{% endcomponent %}\n    ```\n\n    Raises `NotRegistered` if the given name is not registered.\n\n    Example:\n\n    ```py\n    # First register component\n    registry.register(\"button\", ButtonComponent)\n    # Then unregister\n    registry.unregister(\"button\")\n    ```\n    \"\"\"\n    # Validate\n    self.get(name)\n\n    entry = self._registry[name]\n    tag = entry.tag\n\n    # Unregister the tag from library if this was the last component using this tag\n    # Unlink component from tag\n    self._tags[tag].remove(name)\n\n    # Cleanup\n    is_tag_empty = not len(self._tags[tag])\n    if is_tag_empty:\n        del self._tags[tag]\n\n    # Only unregister a tag if it's NOT protected\n    is_protected = is_tag_protected(self.library, tag)\n    if not is_protected:\n        # Unregister the tag from library if this was the last component using this tag\n        if is_tag_empty and tag in self.library.tags:\n            del self.library.tags[tag]\n\n    del self._registry[name]\n
    "},{"location":"reference/django_components/#django_components.component_registry.register","title":"register","text":"
    register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]\n

    Class decorator to register a component.

    Usage:

    @register(\"my_component\")\nclass MyComponent(Component):\n    ...\n

    Optionally specify which ComponentRegistry the component should be registered to by setting the registry kwarg:

    my_lib = django.template.Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n    ...\n
    Source code in src/django_components/component_registry.py
    def register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]:\n    \"\"\"\n    Class decorator to register a component.\n\n    Usage:\n\n    ```py\n    @register(\"my_component\")\n    class MyComponent(Component):\n        ...\n    ```\n\n    Optionally specify which `ComponentRegistry` the component should be registered to by\n    setting the `registry` kwarg:\n\n    ```py\n    my_lib = django.template.Library()\n    my_reg = ComponentRegistry(library=my_lib)\n\n    @register(\"my_component\", registry=my_reg)\n    class MyComponent(Component):\n        ...\n    ```\n    \"\"\"\n    if registry is None:\n        registry = _the_registry\n\n    def decorator(component: _TComp) -> _TComp:\n        registry.register(name=name, component=component)\n        return component\n\n    return decorator\n
    "},{"location":"reference/django_components/#django_components.components","title":"components","text":""},{"location":"reference/django_components/#django_components.components.dynamic","title":"dynamic","text":""},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent","title":"DynamicComponent","text":"
    DynamicComponent(\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,\n)\n

    Bases: Component

    Dynamic component - This component takes inputs and renders the outputs depending on the is and registry arguments.

    • is - required - The component class or registered name of the component that will be rendered in this place.

    • registry - optional - Specify the registry to search for the registered name. If omitted, all registries are searched.

    Source code in src/django_components/component.py
    def __init__(\n    self,\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,  # noqa F811\n):\n    # When user first instantiates the component class before calling\n    # `render` or `render_to_response`, then we want to allow the render\n    # function to make use of the instantiated object.\n    #\n    # So while `MyComp.render()` creates a new instance of MyComp internally,\n    # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n    # already-instantiated object.\n    #\n    # To achieve that, we want to re-assign the class methods as instance methods.\n    # For that we have to \"unwrap\" the class methods via __func__.\n    # See https://stackoverflow.com/a/76706399/9788634\n    self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self)  # type: ignore\n    self.render = types.MethodType(self.__class__.render.__func__, self)  # type: ignore\n    self.as_view = types.MethodType(self.__class__.as_view.__func__, self)  # type: ignore\n\n    self.registered_name: Optional[str] = registered_name\n    self.outer_context: Context = outer_context or Context()\n    self.fill_content = fill_content or {}\n    self.component_id = component_id or gen_id()\n    self.registry = registry or registry_\n    self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n    # None == uninitialized, False == No types, Tuple == types\n    self._types: Optional[Union[Tuple[Any, Any, Any, Any], Literal[False]]] = None\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.Media","title":"Media class-attribute instance-attribute","text":"
    Media = ComponentMediaInput\n

    Defines JS and CSS media files associated with this component.

    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.css","title":"css class-attribute instance-attribute","text":"
    css: Optional[str] = None\n

    Inlined CSS associated with this component.

    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.input","title":"input property","text":"
    input: RenderInput[ArgsType, KwargsType, SlotsType]\n

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

    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.is_filled","title":"is_filled property","text":"
    is_filled: Dict[str, bool]\n

    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/django_components/#django_components.components.dynamic.DynamicComponent.js","title":"js class-attribute instance-attribute","text":"
    js: Optional[str] = None\n

    Inlined JS associated with this component.

    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.media","title":"media instance-attribute","text":"
    media: Media\n

    Normalized definition of JS and CSS media files associated with this component.

    NOTE: This field is generated from Component.Media class.

    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.response_class","title":"response_class class-attribute instance-attribute","text":"
    response_class = HttpResponse\n

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

    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.template_name","title":"template_name class-attribute instance-attribute","text":"
    template_name: Optional[str] = None\n

    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_name, get_template_name, template or get_template must be defined.

    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.as_view","title":"as_view classmethod","text":"
    as_view(**initkwargs: Any) -> ViewFn\n

    Shortcut for calling Component.View.as_view and passing component instance to it.

    Source code in src/django_components/component.py
    @classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n    \"\"\"\n    Shortcut for calling `Component.View.as_view` and passing component instance to it.\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    # Allow the View class to access this component via `self.component`\n    return comp.View.as_view(**initkwargs, component=comp)\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.get_template","title":"get_template","text":"
    get_template(context: Context) -> Optional[Union[str, Template]]\n

    Inlined Django template associated with this component. Can be a plain string or a Template instance.

    Only one of template_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n    \"\"\"\n    Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.get_template_name","title":"get_template_name","text":"
    get_template_name(context: Context) -> Optional[str]\n

    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_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template_name(self, context: Context) -> Optional[str]:\n    \"\"\"\n    Filepath to the Django template associated with this component.\n\n    The filepath must be relative to either the file where the component class was defined,\n    or one of the roots of `STATIFILES_DIRS`.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.inject","title":"inject","text":"
    inject(key: str, default: Optional[Any] = None) -> Any\n

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

    Source code in src/django_components/component.py
    def inject(self, key: str, default: Optional[Any] = None) -> Any:\n    \"\"\"\n    Use this method to retrieve the data that was passed to a `{% provide %}` tag\n    with the corresponding key.\n\n    To retrieve the data, `inject()` must be called inside a component that's\n    inside the `{% provide %}` tag.\n\n    You may also pass a default that will be used if the `provide` tag with given\n    key was NOT found.\n\n    This method mut be used inside the `get_context_data()` method and raises\n    an error if called elsewhere.\n\n    Example:\n\n    Given this template:\n    ```django\n    {% provide \"provider\" hello=\"world\" %}\n        {% component \"my_comp\" %}\n        {% endcomponent %}\n    {% endprovide %}\n    ```\n\n    And given this definition of \"my_comp\" component:\n    ```py\n    from django_components import Component, register\n\n    @register(\"my_comp\")\n    class MyComp(Component):\n        template = \"hi {{ data.hello }}!\"\n        def get_context_data(self):\n            data = self.inject(\"provider\")\n            return {\"data\": data}\n    ```\n\n    This renders into:\n    ```\n    hi world!\n    ```\n\n    As the `{{ data.hello }}` is taken from the \"provider\".\n    \"\"\"\n    if self.input is None:\n        raise RuntimeError(\n            f\"Method 'inject()' of component '{self.name}' was called outside of 'get_context_data()'\"\n        )\n\n    return get_injected_context_var(self.name, self.input.context, key, default)\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.on_render_after","title":"on_render_after","text":"
    on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\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.

    Source code in src/django_components/component.py
    def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n    \"\"\"\n    Hook that runs just after the component's template was rendered.\n    It receives the rendered output as the last argument.\n\n    You can use this hook to access the context or the template, but modifying\n    them won't have any effect.\n\n    To override the content that gets rendered, you can return a string or SafeString\n    from this hook.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.on_render_before","title":"on_render_before","text":"
    on_render_before(context: Context, template: Template) -> 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.

    Source code in src/django_components/component.py
    def on_render_before(self, context: Context, template: Template) -> None:\n    \"\"\"\n    Hook that runs just before the component's template is rendered.\n\n    You can use this hook to access or modify the context or the template.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.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) -> str\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render(\n    cls,\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) -> str:\n    \"\"\"\n    Render the component into a string.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    return comp._render(context, args, kwargs, slots, escape_slots_content)\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.render_css_dependencies","title":"render_css_dependencies","text":"
    render_css_dependencies() -> SafeString\n

    Render only CSS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_css_dependencies(self) -> SafeString:\n    \"\"\"Render only CSS dependencies available in the media class or provided as a string.\"\"\"\n    if self.css is not None:\n        return mark_safe(f\"<style>{self.css}</style>\")\n    return mark_safe(\"\\n\".join(self.media.render_css()))\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.render_dependencies","title":"render_dependencies","text":"
    render_dependencies() -> SafeString\n

    Helper function to render all dependencies for a component.

    Source code in src/django_components/component.py
    def render_dependencies(self) -> SafeString:\n    \"\"\"Helper function to render all dependencies for a component.\"\"\"\n    dependencies = []\n\n    css_deps = self.render_css_dependencies()\n    if css_deps:\n        dependencies.append(css_deps)\n\n    js_deps = self.render_js_dependencies()\n    if js_deps:\n        dependencies.append(js_deps)\n\n    return mark_safe(\"\\n\".join(dependencies))\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.render_js_dependencies","title":"render_js_dependencies","text":"
    render_js_dependencies() -> SafeString\n

    Render only JS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_js_dependencies(self) -> SafeString:\n    \"\"\"Render only JS dependencies available in the media class or provided as a string.\"\"\"\n    if self.js is not None:\n        return mark_safe(f\"<script>{self.js}</script>\")\n    return mark_safe(\"\\n\".join(self.media.render_js()))\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.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    *response_args: Any,\n    **response_kwargs: Any\n) -> HttpResponse\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render_to_response(\n    cls,\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    slots: Optional[SlotsType] = None,\n    escape_slots_content: bool = True,\n    args: Optional[ArgsType] = None,\n    kwargs: Optional[KwargsType] = None,\n    *response_args: Any,\n    **response_kwargs: Any,\n) -> HttpResponse:\n    \"\"\"\n    Render the component and wrap the content in the response class.\n\n    The response class is taken from `Component.response_class`. Defaults to `django.http.HttpResponse`.\n\n    This is the interface for the `django.views.View` class which allows us to\n    use components as Django views with `component.as_view()`.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Any additional args and kwargs are passed to the `response_class`.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    content = cls.render(\n        args=args,\n        kwargs=kwargs,\n        context=context,\n        slots=slots,\n        escape_slots_content=escape_slots_content,\n    )\n    return cls.response_class(content, *response_args, **response_kwargs)\n
    "},{"location":"reference/django_components/#django_components.context","title":"context","text":"

    This file centralizes various ways we use Django's Context class pass data across components, nodes, slots, and contexts.

    You can think of the Context as our storage system.

    "},{"location":"reference/django_components/#django_components.context.copy_forloop_context","title":"copy_forloop_context","text":"
    copy_forloop_context(from_context: Context, to_context: Context) -> None\n

    Forward the info about the current loop

    Source code in src/django_components/context.py
    def copy_forloop_context(from_context: Context, to_context: Context) -> None:\n    \"\"\"Forward the info about the current loop\"\"\"\n    # Note that the ForNode (which implements for loop behavior) does not\n    # only add the `forloop` key, but also keys corresponding to the loop elements\n    # So if the loop syntax is `{% for my_val in my_lists %}`, then ForNode also\n    # sets a `my_val` key.\n    # For this reason, instead of copying individual keys, we copy the whole stack layer\n    # set by ForNode.\n    if \"forloop\" in from_context:\n        forloop_dict_index = find_last_index(from_context.dicts, lambda d: \"forloop\" in d)\n        to_context.update(from_context.dicts[forloop_dict_index])\n
    "},{"location":"reference/django_components/#django_components.context.get_injected_context_var","title":"get_injected_context_var","text":"
    get_injected_context_var(component_name: str, context: Context, key: str, default: Optional[Any] = None) -> Any\n

    Retrieve a 'provided' field. The field MUST have been previously 'provided' by the component's ancestors using the {% provide %} template tag.

    Source code in src/django_components/context.py
    def get_injected_context_var(\n    component_name: str,\n    context: Context,\n    key: str,\n    default: Optional[Any] = None,\n) -> Any:\n    \"\"\"\n    Retrieve a 'provided' field. The field MUST have been previously 'provided'\n    by the component's ancestors using the `{% provide %}` template tag.\n    \"\"\"\n    # NOTE: For simplicity, we keep the provided values directly on the context.\n    # This plays nicely with Django's Context, which behaves like a stack, so \"newer\"\n    # values overshadow the \"older\" ones.\n    internal_key = _INJECT_CONTEXT_KEY_PREFIX + key\n\n    # Return provided value if found\n    if internal_key in context:\n        return context[internal_key]\n\n    # If a default was given, return that\n    if default is not None:\n        return default\n\n    # Otherwise raise error\n    raise KeyError(\n        f\"Component '{component_name}' tried to inject a variable '{key}' before it was provided.\"\n        f\" To fix this, make sure that at least one ancestor of component '{component_name}' has\"\n        f\" the variable '{key}' in their 'provide' attribute.\"\n    )\n
    "},{"location":"reference/django_components/#django_components.context.prepare_context","title":"prepare_context","text":"
    prepare_context(context: Context, component_id: str) -> None\n

    Initialize the internal context state.

    Source code in src/django_components/context.py
    def prepare_context(\n    context: Context,\n    component_id: str,\n) -> None:\n    \"\"\"Initialize the internal context state.\"\"\"\n    # Initialize mapping dicts within this rendering run.\n    # This is shared across the whole render chain, thus we set it only once.\n    if _FILLED_SLOTS_CONTENT_CONTEXT_KEY not in context:\n        context[_FILLED_SLOTS_CONTENT_CONTEXT_KEY] = {}\n\n    set_component_id(context, component_id)\n
    "},{"location":"reference/django_components/#django_components.context.set_component_id","title":"set_component_id","text":"
    set_component_id(context: Context, component_id: str) -> None\n

    We use the Context object to pass down info on inside of which component we are currently rendering.

    Source code in src/django_components/context.py
    def set_component_id(context: Context, component_id: str) -> None:\n    \"\"\"\n    We use the Context object to pass down info on inside of which component\n    we are currently rendering.\n    \"\"\"\n    context[_CURRENT_COMP_CONTEXT_KEY] = component_id\n
    "},{"location":"reference/django_components/#django_components.context.set_provided_context_var","title":"set_provided_context_var","text":"
    set_provided_context_var(context: Context, key: str, provided_kwargs: Dict[str, Any]) -> None\n

    'Provide' given data under given key. In other words, this data can be retrieved using self.inject(key) inside of get_context_data() method of components that are nested inside the {% provide %} tag.

    Source code in src/django_components/context.py
    def set_provided_context_var(\n    context: Context,\n    key: str,\n    provided_kwargs: Dict[str, Any],\n) -> None:\n    \"\"\"\n    'Provide' given data under given key. In other words, this data can be retrieved\n    using `self.inject(key)` inside of `get_context_data()` method of components that\n    are nested inside the `{% provide %}` tag.\n    \"\"\"\n    # NOTE: We raise TemplateSyntaxError since this func should be called only from\n    # within template.\n    if not key:\n        raise TemplateSyntaxError(\n            \"Provide tag received an empty string. Key must be non-empty and a valid identifier.\"\n        )\n    if not key.isidentifier():\n        raise TemplateSyntaxError(\n            \"Provide tag received a non-identifier string. Key must be non-empty and a valid identifier.\"\n        )\n\n    # We turn the kwargs into a NamedTuple so that the object that's \"provided\"\n    # is immutable. This ensures that the data returned from `inject` will always\n    # have all the keys that were passed to the `provide` tag.\n    tpl_cls = namedtuple(\"DepInject\", provided_kwargs.keys())  # type: ignore[misc]\n    payload = tpl_cls(**provided_kwargs)\n\n    internal_key = _INJECT_CONTEXT_KEY_PREFIX + key\n    context[internal_key] = payload\n
    "},{"location":"reference/django_components/#django_components.expression","title":"expression","text":""},{"location":"reference/django_components/#django_components.expression.Operator","title":"Operator","text":"

    Bases: ABC

    Operator describes something that somehow changes the inputs to template tags (the {% %}).

    For example, a SpreadOperator inserts one or more kwargs at the specified location.

    "},{"location":"reference/django_components/#django_components.expression.SpreadOperator","title":"SpreadOperator","text":"
    SpreadOperator(expr: Expression)\n

    Bases: Operator

    Operator that inserts one or more kwargs at the specified location.

    Source code in src/django_components/expression.py
    def __init__(self, expr: Expression) -> None:\n    self.expr = expr\n
    "},{"location":"reference/django_components/#django_components.expression.process_aggregate_kwargs","title":"process_aggregate_kwargs","text":"
    process_aggregate_kwargs(kwargs: Mapping[str, Any]) -> Dict[str, Any]\n

    This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs start with some prefix delimited with : (e.g. attrs:).

    Example:

    process_component_kwargs({\"abc:one\": 1, \"abc:two\": 2, \"def:three\": 3, \"four\": 4})\n# {\"abc\": {\"one\": 1, \"two\": 2}, \"def\": {\"three\": 3}, \"four\": 4}\n

    We want to support a use case similar to Vue's fallthrough attributes. In other words, where a component author can designate a prop (input) which is a dict and which will be rendered as HTML attributes.

    This is useful for allowing component users to tweak styling or add event handling to the underlying HTML. E.g.:

    class=\"pa-4 d-flex text-black\" or @click.stop=\"alert('clicked!')\"

    So if the prop is attrs, and the component is called like so:

    {% component \"my_comp\" attrs=attrs %}\n

    then, if attrs is:

    {\"class\": \"text-red pa-4\", \"@click\": \"dispatch('my_event', 123)\"}\n

    and the component template is:

    <div {% html_attrs attrs add:class=\"extra-class\" %}></div>\n

    Then this renders:

    <div class=\"text-red pa-4 extra-class\" @click=\"dispatch('my_event', 123)\" ></div>\n

    However, this way it is difficult for the component user to define the attrs variable, especially if they want to combine static and dynamic values. Because they will need to pre-process the attrs dict.

    So, instead, we allow to \"aggregate\" props into a dict. So all props that start with attrs:, like attrs:class=\"text-red\", will be collected into a dict at key attrs.

    This provides sufficient flexiblity to make it easy for component users to provide \"fallthrough attributes\", and sufficiently easy for component authors to process that input while still being able to provide their own keys.

    Source code in src/django_components/expression.py
    def process_aggregate_kwargs(kwargs: Mapping[str, Any]) -> Dict[str, Any]:\n    \"\"\"\n    This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs\n    start with some prefix delimited with `:` (e.g. `attrs:`).\n\n    Example:\n    ```py\n    process_component_kwargs({\"abc:one\": 1, \"abc:two\": 2, \"def:three\": 3, \"four\": 4})\n    # {\"abc\": {\"one\": 1, \"two\": 2}, \"def\": {\"three\": 3}, \"four\": 4}\n    ```\n\n    ---\n\n    We want to support a use case similar to Vue's fallthrough attributes.\n    In other words, where a component author can designate a prop (input)\n    which is a dict and which will be rendered as HTML attributes.\n\n    This is useful for allowing component users to tweak styling or add\n    event handling to the underlying HTML. E.g.:\n\n    `class=\"pa-4 d-flex text-black\"` or `@click.stop=\"alert('clicked!')\"`\n\n    So if the prop is `attrs`, and the component is called like so:\n    ```django\n    {% component \"my_comp\" attrs=attrs %}\n    ```\n\n    then, if `attrs` is:\n    ```py\n    {\"class\": \"text-red pa-4\", \"@click\": \"dispatch('my_event', 123)\"}\n    ```\n\n    and the component template is:\n    ```django\n    <div {% html_attrs attrs add:class=\"extra-class\" %}></div>\n    ```\n\n    Then this renders:\n    ```html\n    <div class=\"text-red pa-4 extra-class\" @click=\"dispatch('my_event', 123)\" ></div>\n    ```\n\n    However, this way it is difficult for the component user to define the `attrs`\n    variable, especially if they want to combine static and dynamic values. Because\n    they will need to pre-process the `attrs` dict.\n\n    So, instead, we allow to \"aggregate\" props into a dict. So all props that start\n    with `attrs:`, like `attrs:class=\"text-red\"`, will be collected into a dict\n    at key `attrs`.\n\n    This provides sufficient flexiblity to make it easy for component users to provide\n    \"fallthrough attributes\", and sufficiently easy for component authors to process\n    that input while still being able to provide their own keys.\n    \"\"\"\n    processed_kwargs = {}\n    nested_kwargs: Dict[str, Dict[str, Any]] = {}\n    for key, val in kwargs.items():\n        if not is_aggregate_key(key):\n            processed_kwargs[key] = val\n            continue\n\n        # NOTE: Trim off the prefix from keys\n        prefix, sub_key = key.split(\":\", 1)\n        if prefix not in nested_kwargs:\n            nested_kwargs[prefix] = {}\n        nested_kwargs[prefix][sub_key] = val\n\n    # Assign aggregated values into normal input\n    for key, val in nested_kwargs.items():\n        if key in processed_kwargs:\n            raise TemplateSyntaxError(\n                f\"Received argument '{key}' both as a regular input ({key}=...)\"\n                f\" and as an aggregate dict ('{key}:key=...'). Must be only one of the two\"\n            )\n        processed_kwargs[key] = val\n\n    return processed_kwargs\n
    "},{"location":"reference/django_components/#django_components.finders","title":"finders","text":""},{"location":"reference/django_components/#django_components.finders.ComponentsFileSystemFinder","title":"ComponentsFileSystemFinder","text":"
    ComponentsFileSystemFinder(app_names: Any = None, *args: Any, **kwargs: Any)\n

    Bases: BaseFinder

    A static files finder based on FileSystemFinder.

    Differences: - This finder uses COMPONENTS.dirs setting to locate files instead of STATICFILES_DIRS. - Whether a file within COMPONENTS.dirs is considered a STATIC file is configured by COMPONENTS.static_files_allowed and COMPONENTS.forbidden_static_files. - If COMPONENTS.dirs is not set, defaults to settings.BASE_DIR / \"components\"

    Source code in src/django_components/finders.py
    def __init__(self, app_names: Any = None, *args: Any, **kwargs: Any) -> None:\n    component_dirs = [str(p) for p in get_dirs()]\n\n    # NOTE: The rest of the __init__ is the same as `django.contrib.staticfiles.finders.FileSystemFinder`,\n    # but using our locations instead of STATICFILES_DIRS.\n\n    # List of locations with static files\n    self.locations: List[Tuple[str, str]] = []\n\n    # Maps dir paths to an appropriate storage instance\n    self.storages: Dict[str, FileSystemStorage] = {}\n    for root in component_dirs:\n        if isinstance(root, (list, tuple)):\n            prefix, root = root\n        else:\n            prefix = \"\"\n        if (prefix, root) not in self.locations:\n            self.locations.append((prefix, root))\n    for prefix, root in self.locations:\n        filesystem_storage = FileSystemStorage(location=root)\n        filesystem_storage.prefix = prefix\n        self.storages[root] = filesystem_storage\n\n    super().__init__(*args, **kwargs)\n
    "},{"location":"reference/django_components/#django_components.finders.ComponentsFileSystemFinder.find","title":"find","text":"
    find(path: str, all: bool = False) -> Union[List[str], str]\n

    Look for files in the extra locations as defined in COMPONENTS.dirs.

    Source code in src/django_components/finders.py
    def find(self, path: str, all: bool = False) -> Union[List[str], str]:\n    \"\"\"\n    Look for files in the extra locations as defined in COMPONENTS.dirs.\n    \"\"\"\n    matches: List[str] = []\n    for prefix, root in self.locations:\n        if root not in searched_locations:\n            searched_locations.append(root)\n        matched_path = self.find_location(root, path, prefix)\n        if matched_path:\n            if not all:\n                return matched_path\n            matches.append(matched_path)\n    return matches\n
    "},{"location":"reference/django_components/#django_components.finders.ComponentsFileSystemFinder.find_location","title":"find_location","text":"
    find_location(root: str, path: str, prefix: Optional[str] = None) -> Optional[str]\n

    Find a requested static file in a location and return the found absolute path (or None if no match).

    Source code in src/django_components/finders.py
    def find_location(self, root: str, path: str, prefix: Optional[str] = None) -> Optional[str]:\n    \"\"\"\n    Find a requested static file in a location and return the found\n    absolute path (or ``None`` if no match).\n    \"\"\"\n    if prefix:\n        prefix = \"%s%s\" % (prefix, os.sep)\n        if not path.startswith(prefix):\n            return None\n        path = path.removeprefix(prefix)\n    path = safe_join(root, path)\n\n    if os.path.exists(path) and self._is_path_valid(path):\n        return path\n    return None\n
    "},{"location":"reference/django_components/#django_components.finders.ComponentsFileSystemFinder.list","title":"list","text":"
    list(ignore_patterns: List[str]) -> Iterable[Tuple[str, FileSystemStorage]]\n

    List all files in all locations.

    Source code in src/django_components/finders.py
    def list(self, ignore_patterns: List[str]) -> Iterable[Tuple[str, FileSystemStorage]]:\n    \"\"\"\n    List all files in all locations.\n    \"\"\"\n    for prefix, root in self.locations:\n        # Skip nonexistent directories.\n        if os.path.isdir(root):\n            storage = self.storages[root]\n            for path in get_files(storage, ignore_patterns):\n                if self._is_path_valid(path):\n                    yield path, storage\n
    "},{"location":"reference/django_components/#django_components.library","title":"library","text":"

    Module for interfacing with Django's Library (django.template.library)

    "},{"location":"reference/django_components/#django_components.library.PROTECTED_TAGS","title":"PROTECTED_TAGS module-attribute","text":"
    PROTECTED_TAGS = [\n    \"component_dependencies\",\n    \"component_css_dependencies\",\n    \"component_js_dependencies\",\n    \"fill\",\n    \"html_attrs\",\n    \"provide\",\n    \"slot\",\n]\n

    These are the names that users cannot choose for their components, as they would conflict with other tags in the Library.

    "},{"location":"reference/django_components/#django_components.logger","title":"logger","text":""},{"location":"reference/django_components/#django_components.logger.trace","title":"trace","text":"
    trace(logger: Logger, message: str, *args: Any, **kwargs: Any) -> None\n

    TRACE level logger.

    To display TRACE logs, set the logging level to 5.

    Example:

    LOGGING = {\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\": 5,\n            \"handlers\": [\"console\"],\n        },\n    },\n}\n

    Source code in src/django_components/logger.py
    def trace(logger: logging.Logger, message: str, *args: Any, **kwargs: Any) -> None:\n    \"\"\"\n    TRACE level logger.\n\n    To display TRACE logs, set the logging level to 5.\n\n    Example:\n    ```py\n    LOGGING = {\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\": 5,\n                \"handlers\": [\"console\"],\n            },\n        },\n    }\n    ```\n    \"\"\"\n    if actual_trace_level_num == -1:\n        setup_logging()\n    if logger.isEnabledFor(actual_trace_level_num):\n        logger.log(actual_trace_level_num, message, *args, **kwargs)\n
    "},{"location":"reference/django_components/#django_components.logger.trace_msg","title":"trace_msg","text":"
    trace_msg(\n    action: Literal[\"PARSE\", \"ASSOC\", \"RENDR\", \"GET\", \"SET\"],\n    node_type: Literal[\"COMP\", \"FILL\", \"SLOT\", \"PROVIDE\", \"N/A\"],\n    node_name: str,\n    node_id: str,\n    msg: str = \"\",\n    component_id: Optional[str] = None,\n) -> None\n

    TRACE level logger with opinionated format for tracing interaction of components, nodes, and slots. Formats messages like so:

    \"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"

    Source code in src/django_components/logger.py
    def trace_msg(\n    action: Literal[\"PARSE\", \"ASSOC\", \"RENDR\", \"GET\", \"SET\"],\n    node_type: Literal[\"COMP\", \"FILL\", \"SLOT\", \"PROVIDE\", \"N/A\"],\n    node_name: str,\n    node_id: str,\n    msg: str = \"\",\n    component_id: Optional[str] = None,\n) -> None:\n    \"\"\"\n    TRACE level logger with opinionated format for tracing interaction of components,\n    nodes, and slots. Formats messages like so:\n\n    `\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"`\n    \"\"\"\n    msg_prefix = \"\"\n    if action == \"ASSOC\":\n        if not component_id:\n            raise ValueError(\"component_id must be set for the ASSOC action\")\n        msg_prefix = f\"TO COMP {component_id}\"\n    elif action == \"RENDR\" and node_type == \"FILL\":\n        if not component_id:\n            raise ValueError(\"component_id must be set for the RENDER action\")\n        msg_prefix = f\"FOR COMP {component_id}\"\n\n    msg_parts = [f\"{action} {node_type} {node_name} ID {node_id}\", *([msg_prefix] if msg_prefix else []), msg]\n    full_msg = \" \".join(msg_parts)\n\n    # NOTE: When debugging tests during development, it may be easier to change\n    # this to `print()`\n    trace(logger, full_msg)\n
    "},{"location":"reference/django_components/#django_components.middleware","title":"middleware","text":""},{"location":"reference/django_components/#django_components.middleware.ComponentDependencyMiddleware","title":"ComponentDependencyMiddleware","text":"
    ComponentDependencyMiddleware(get_response: Callable[[HttpRequest], HttpResponse])\n

    Middleware that inserts CSS/JS dependencies for all rendered components at points marked with template tags.

    Source code in src/django_components/middleware.py
    def __init__(self, get_response: \"Callable[[HttpRequest], HttpResponse]\") -> None:\n    self.get_response = get_response\n\n    if iscoroutinefunction(self.get_response):\n        markcoroutinefunction(self)\n
    "},{"location":"reference/django_components/#django_components.middleware.DependencyReplacer","title":"DependencyReplacer","text":"
    DependencyReplacer(css_string: bytes, js_string: bytes)\n

    Replacer for use in re.sub that replaces the first placeholder CSS and JS tags it encounters and removes any subsequent ones.

    Source code in src/django_components/middleware.py
    def __init__(self, css_string: bytes, js_string: bytes) -> None:\n    self.js_string = js_string\n    self.css_string = css_string\n
    "},{"location":"reference/django_components/#django_components.middleware.join_media","title":"join_media","text":"
    join_media(components: Iterable[Component]) -> Media\n

    Return combined media object for iterable of components.

    Source code in src/django_components/middleware.py
    def join_media(components: Iterable[\"Component\"]) -> Media:\n    \"\"\"Return combined media object for iterable of components.\"\"\"\n\n    return sum([component.media for component in components], Media())\n
    "},{"location":"reference/django_components/#django_components.node","title":"node","text":""},{"location":"reference/django_components/#django_components.node.BaseNode","title":"BaseNode","text":"
    BaseNode(\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    args: Optional[List[Expression]] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n)\n

    Bases: Node

    Shared behavior for our subclasses of Django's Node

    Source code in src/django_components/node.py
    def __init__(\n    self,\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    args: Optional[List[Expression]] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n):\n    self.nodelist = nodelist or NodeList()\n    self.node_id = node_id or gen_id()\n    self.args = args or []\n    self.kwargs = kwargs or RuntimeKwargs({})\n
    "},{"location":"reference/django_components/#django_components.node.get_node_children","title":"get_node_children","text":"
    get_node_children(node: Node, context: Optional[Context] = None) -> NodeList\n

    Get child Nodes from Node's nodelist atribute.

    This function is taken from get_nodes_by_type method of django.template.base.Node.

    Source code in src/django_components/node.py
    def get_node_children(node: Node, context: Optional[Context] = None) -> NodeList:\n    \"\"\"\n    Get child Nodes from Node's nodelist atribute.\n\n    This function is taken from `get_nodes_by_type` method of `django.template.base.Node`.\n    \"\"\"\n    # Special case - {% extends %} tag - Load the template and go deeper\n    if isinstance(node, ExtendsNode):\n        # NOTE: When {% extends %} node is being parsed, it collects all remaining template\n        # under node.nodelist.\n        # Hence, when we come across ExtendsNode in the template, we:\n        # 1. Go over all nodes in the template using `node.nodelist`\n        # 2. Go over all nodes in the \"parent\" template, via `node.get_parent`\n        nodes = NodeList()\n        nodes.extend(node.nodelist)\n        template = node.get_parent(context)\n        nodes.extend(template.nodelist)\n        return nodes\n\n    # Special case - {% include %} tag - Load the template and go deeper\n    elif isinstance(node, IncludeNode):\n        template = get_template_for_include_node(node, context)\n        return template.nodelist\n\n    nodes = NodeList()\n    for attr in node.child_nodelists:\n        nodelist = getattr(node, attr, [])\n        if nodelist:\n            nodes.extend(nodelist)\n    return nodes\n
    "},{"location":"reference/django_components/#django_components.node.get_template_for_include_node","title":"get_template_for_include_node","text":"
    get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template\n

    This snippet is taken directly from IncludeNode.render(). Unfortunately the render logic doesn't separate out template loading logic from rendering, so we have to copy the method.

    Source code in src/django_components/node.py
    def get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template:\n    \"\"\"\n    This snippet is taken directly from `IncludeNode.render()`. Unfortunately the\n    render logic doesn't separate out template loading logic from rendering, so we\n    have to copy the method.\n    \"\"\"\n    template = include_node.template.resolve(context)\n    # Does this quack like a Template?\n    if not callable(getattr(template, \"render\", None)):\n        # If not, try the cache and select_template().\n        template_name = template or ()\n        if isinstance(template_name, str):\n            template_name = (\n                construct_relative_path(\n                    include_node.origin.template_name,\n                    template_name,\n                ),\n            )\n        else:\n            template_name = tuple(template_name)\n        cache = context.render_context.dicts[0].setdefault(include_node, {})\n        template = cache.get(template_name)\n        if template is None:\n            template = context.template.engine.select_template(template_name)\n            cache[template_name] = template\n    # Use the base.Template of a backends.django.Template.\n    elif hasattr(template, \"template\"):\n        template = template.template\n    return template\n
    "},{"location":"reference/django_components/#django_components.node.walk_nodelist","title":"walk_nodelist","text":"
    walk_nodelist(nodes: NodeList, callback: Callable[[Node], Optional[str]], context: Optional[Context] = None) -> None\n

    Recursively walk a NodeList, calling callback for each Node.

    Source code in src/django_components/node.py
    def walk_nodelist(\n    nodes: NodeList,\n    callback: Callable[[Node], Optional[str]],\n    context: Optional[Context] = None,\n) -> None:\n    \"\"\"Recursively walk a NodeList, calling `callback` for each Node.\"\"\"\n    node_queue: List[NodeTraverse] = [NodeTraverse(node=node, parent=None) for node in nodes]\n    while len(node_queue):\n        traverse = node_queue.pop()\n        callback(traverse)\n        child_nodes = get_node_children(traverse.node, context)\n        child_traverses = [NodeTraverse(node=child_node, parent=traverse) for child_node in child_nodes]\n        node_queue.extend(child_traverses)\n
    "},{"location":"reference/django_components/#django_components.provide","title":"provide","text":""},{"location":"reference/django_components/#django_components.provide.ProvideNode","title":"ProvideNode","text":"
    ProvideNode(nodelist: NodeList, trace_id: str, node_id: Optional[str] = None, kwargs: Optional[RuntimeKwargs] = None)\n

    Bases: BaseNode

    Implementation of the {% provide %} tag. For more info see Component.inject.

    Source code in src/django_components/provide.py
    def __init__(\n    self,\n    nodelist: NodeList,\n    trace_id: str,\n    node_id: Optional[str] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n):\n    super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n    self.nodelist = nodelist\n    self.node_id = node_id or gen_id()\n    self.trace_id = trace_id\n    self.kwargs = kwargs or RuntimeKwargs({})\n
    "},{"location":"reference/django_components/#django_components.slots","title":"slots","text":""},{"location":"reference/django_components/#django_components.slots.FillContent","title":"FillContent dataclass","text":"
    FillContent(content_func: SlotFunc[TSlotData], slot_default_var: Optional[SlotDefaultName], slot_data_var: Optional[SlotDataName])\n

    Bases: Generic[TSlotData]

    This represents content set with the {% fill %} tag, e.g.:

    {% component \"my_comp\" %}\n    {% fill \"first_slot\" %} <--- This\n        hi\n        {{ my_var }}\n        hello\n    {% endfill %}\n{% endcomponent %}\n
    "},{"location":"reference/django_components/#django_components.slots.FillNode","title":"FillNode","text":"
    FillNode(nodelist: NodeList, kwargs: RuntimeKwargs, trace_id: str, node_id: Optional[str] = None, is_implicit: bool = False)\n

    Bases: BaseNode

    Set when a component tag pair is passed template content that excludes fill tags. Nodes of this type contribute their nodelists to slots marked as 'default'.

    Source code in src/django_components/slots.py
    def __init__(\n    self,\n    nodelist: NodeList,\n    kwargs: RuntimeKwargs,\n    trace_id: str,\n    node_id: Optional[str] = None,\n    is_implicit: bool = False,\n):\n    super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n    self.is_implicit = is_implicit\n    self.trace_id = trace_id\n    self.component_id: Optional[str] = None\n
    "},{"location":"reference/django_components/#django_components.slots.Slot","title":"Slot","text":"

    Bases: NamedTuple

    This represents content set with the {% slot %} tag, e.g.:

    {% slot \"my_comp\" default %} <--- This\n    hi\n    {{ my_var }}\n    hello\n{% endslot %}\n
    "},{"location":"reference/django_components/#django_components.slots.SlotFill","title":"SlotFill dataclass","text":"
    SlotFill(\n    name: str,\n    escaped_name: str,\n    is_filled: bool,\n    content_func: SlotFunc[TSlotData],\n    slot_default_var: Optional[SlotDefaultName],\n    slot_data_var: Optional[SlotDataName],\n)\n

    Bases: Generic[TSlotData]

    SlotFill describes what WILL be rendered.

    It is a Slot that has been resolved against FillContents passed to a Component.

    "},{"location":"reference/django_components/#django_components.slots.SlotNode","title":"SlotNode","text":"
    SlotNode(\n    nodelist: NodeList,\n    trace_id: str,\n    node_id: Optional[str] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n    is_required: bool = False,\n    is_default: bool = False,\n)\n

    Bases: BaseNode

    Source code in src/django_components/slots.py
    def __init__(\n    self,\n    nodelist: NodeList,\n    trace_id: str,\n    node_id: Optional[str] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n    is_required: bool = False,\n    is_default: bool = False,\n):\n    super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n    self.is_required = is_required\n    self.is_default = is_default\n    self.trace_id = trace_id\n
    "},{"location":"reference/django_components/#django_components.slots.SlotRef","title":"SlotRef","text":"
    SlotRef(slot: SlotNode, context: Context)\n

    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.

    Source code in src/django_components/slots.py
    def __init__(self, slot: \"SlotNode\", context: Context):\n    self._slot = slot\n    self._context = context\n
    "},{"location":"reference/django_components/#django_components.slots.parse_slot_fill_nodes_from_component_nodelist","title":"parse_slot_fill_nodes_from_component_nodelist","text":"
    parse_slot_fill_nodes_from_component_nodelist(nodes: Tuple[Node, ...], ignored_nodes: Tuple[Type[Node]]) -> List[FillNode]\n

    Given a component body (django.template.NodeList), find all slot fills, whether defined explicitly with {% fill %} or implicitly.

    So if we have a component body:

    {% component \"mycomponent\" %}\n    {% fill \"first_fill\" %}\n        Hello!\n    {% endfill %}\n    {% fill \"second_fill\" %}\n        Hello too!\n    {% endfill %}\n{% endcomponent %}\n
    Then this function returns the nodes (django.template.Node) for fill \"first_fill\" and fill \"second_fill\".

    Source code in src/django_components/slots.py
    @lazy_cache(lambda: lru_cache(maxsize=app_settings.TEMPLATE_CACHE_SIZE))\ndef parse_slot_fill_nodes_from_component_nodelist(\n    nodes: Tuple[Node, ...],\n    ignored_nodes: Tuple[Type[Node]],\n) -> List[FillNode]:\n    \"\"\"\n    Given a component body (`django.template.NodeList`), find all slot fills,\n    whether defined explicitly with `{% fill %}` or implicitly.\n\n    So if we have a component body:\n    ```django\n    {% component \"mycomponent\" %}\n        {% fill \"first_fill\" %}\n            Hello!\n        {% endfill %}\n        {% fill \"second_fill\" %}\n            Hello too!\n        {% endfill %}\n    {% endcomponent %}\n    ```\n    Then this function returns the nodes (`django.template.Node`) for `fill \"first_fill\"`\n    and `fill \"second_fill\"`.\n    \"\"\"\n    fill_nodes: List[FillNode] = []\n    if nodelist_has_content(nodes):\n        for parse_fn in (\n            _try_parse_as_default_fill,\n            _try_parse_as_named_fill_tag_set,\n        ):\n            curr_fill_nodes = parse_fn(nodes, ignored_nodes)\n            if curr_fill_nodes:\n                fill_nodes = curr_fill_nodes\n                break\n        else:\n            raise TemplateSyntaxError(\n                \"Illegal content passed to 'component' tag pair. \"\n                \"Possible causes: 1) Explicit 'fill' tags cannot occur alongside other \"\n                \"tags except comment tags; 2) Default (default slot-targeting) content \"\n                \"is mixed with explict 'fill' tags.\"\n            )\n    return fill_nodes\n
    "},{"location":"reference/django_components/#django_components.slots.resolve_slots","title":"resolve_slots","text":"
    resolve_slots(\n    context: Context,\n    template: Template,\n    component_name: Optional[str],\n    fill_content: Dict[SlotName, FillContent],\n    is_dynamic_component: bool = False,\n) -> Tuple[Dict[SlotId, Slot], Dict[SlotId, SlotFill]]\n

    Search the template for all SlotNodes, and associate the slots with the given fills.

    Returns tuple of: - Slots defined in the component's Template with {% slot %} tag - SlotFills (AKA slots matched with fills) describing what will be rendered for each slot.

    Source code in src/django_components/slots.py
    def resolve_slots(\n    context: Context,\n    template: Template,\n    component_name: Optional[str],\n    fill_content: Dict[SlotName, FillContent],\n    is_dynamic_component: bool = False,\n) -> Tuple[Dict[SlotId, Slot], Dict[SlotId, SlotFill]]:\n    \"\"\"\n    Search the template for all SlotNodes, and associate the slots\n    with the given fills.\n\n    Returns tuple of:\n    - Slots defined in the component's Template with `{% slot %}` tag\n    - SlotFills (AKA slots matched with fills) describing what will be rendered for each slot.\n    \"\"\"\n    slot_fills = {\n        name: SlotFill(\n            name=name,\n            escaped_name=_escape_slot_name(name),\n            is_filled=True,\n            content_func=fill.content_func,\n            slot_default_var=fill.slot_default_var,\n            slot_data_var=fill.slot_data_var,\n        )\n        for name, fill in fill_content.items()\n    }\n\n    slots: Dict[SlotId, Slot] = {}\n    # This holds info on which slot (key) has which slots nested in it (value list)\n    slot_children: Dict[SlotId, List[SlotId]] = {}\n    all_nested_slots: Set[SlotId] = set()\n\n    def on_node(entry: NodeTraverse) -> None:\n        node = entry.node\n        if not isinstance(node, SlotNode):\n            return\n\n        slot_name, _ = node.resolve_kwargs(context, component_name)\n\n        # 1. Collect slots\n        # Basically we take all the important info form the SlotNode, so the logic is\n        # less coupled to Django's Template/Node. Plain tuples should also help with\n        # troubleshooting.\n        slot = Slot(\n            id=node.node_id,\n            name=slot_name,\n            nodelist=node.nodelist,\n            is_default=node.is_default,\n            is_required=node.is_required,\n        )\n        slots[node.node_id] = slot\n\n        # 2. Figure out which Slots are nested in other Slots, so we can render\n        # them from outside-inwards, so we can skip inner Slots if fills are provided.\n        # We should end up with a graph-like data like:\n        # - 0001: [0002]\n        # - 0002: []\n        # - 0003: [0004]\n        # In other words, the data tells us that slot ID 0001 is PARENT of slot 0002.\n        parent_slot_entry = entry.parent\n        while parent_slot_entry is not None:\n            if not isinstance(parent_slot_entry.node, SlotNode):\n                parent_slot_entry = parent_slot_entry.parent\n                continue\n\n            parent_slot_id = parent_slot_entry.node.node_id\n            if parent_slot_id not in slot_children:\n                slot_children[parent_slot_id] = []\n            slot_children[parent_slot_id].append(node.node_id)\n            all_nested_slots.add(node.node_id)\n            break\n\n    walk_nodelist(template.nodelist, on_node, context)\n\n    # 3. Figure out which slot the default/implicit fill belongs to\n    slot_fills = _resolve_default_slot(\n        template_name=template.name,\n        component_name=component_name,\n        slots=slots,\n        slot_fills=slot_fills,\n        is_dynamic_component=is_dynamic_component,\n    )\n\n    # 4. Detect any errors with slots/fills\n    # NOTE: We ignore errors for the dynamic component, as the underlying component\n    # will deal with it\n    if not is_dynamic_component:\n        _report_slot_errors(slots, slot_fills, component_name)\n\n    # 5. Find roots of the slot relationships\n    top_level_slot_ids: List[SlotId] = [node_id for node_id in slots.keys() if node_id not in all_nested_slots]\n\n    # 6. Walk from out-most slots inwards, and decide whether and how\n    # we will render each slot.\n    resolved_slots: Dict[SlotId, SlotFill] = {}\n    slot_ids_queue = deque([*top_level_slot_ids])\n    while len(slot_ids_queue):\n        slot_id = slot_ids_queue.pop()\n        slot = slots[slot_id]\n\n        # Check if there is a slot fill for given slot name\n        if slot.name in slot_fills:\n            # If yes, we remember which slot we want to replace with already-rendered fills\n            resolved_slots[slot_id] = slot_fills[slot.name]\n            # Since the fill cannot include other slots, we can leave this path\n            continue\n        else:\n            # If no, then the slot is NOT filled, and we will render the slot's default (what's\n            # between the slot tags)\n            resolved_slots[slot_id] = SlotFill(\n                name=slot.name,\n                escaped_name=_escape_slot_name(slot.name),\n                is_filled=False,\n                content_func=_nodelist_to_slot_render_func(slot.nodelist),\n                slot_default_var=None,\n                slot_data_var=None,\n            )\n            # Since the slot's default CAN include other slots (because it's defined in\n            # the same template), we need to enqueue the slot's children\n            if slot_id in slot_children and slot_children[slot_id]:\n                slot_ids_queue.extend(slot_children[slot_id])\n\n    # By the time we get here, we should know, for each slot, how it will be rendered\n    # -> Whether it will be replaced with a fill, or whether we render slot's defaults.\n    return slots, resolved_slots\n
    "},{"location":"reference/django_components/#django_components.tag_formatter","title":"tag_formatter","text":""},{"location":"reference/django_components/#django_components.tag_formatter.ComponentFormatter","title":"ComponentFormatter","text":"
    ComponentFormatter(tag: str)\n

    Bases: TagFormatterABC

    The original django_component's component tag formatter, it uses the component and endcomponent tags, and the component name is gives 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

    Source code in src/django_components/tag_formatter.py
    def __init__(self, tag: str):\n    self.tag = tag\n
    "},{"location":"reference/django_components/#django_components.tag_formatter.InternalTagFormatter","title":"InternalTagFormatter","text":"
    InternalTagFormatter(tag_formatter: TagFormatterABC)\n

    Internal wrapper around user-provided TagFormatters, so that we validate the outputs.

    Source code in src/django_components/tag_formatter.py
    def __init__(self, tag_formatter: TagFormatterABC):\n    self.tag_formatter = tag_formatter\n
    "},{"location":"reference/django_components/#django_components.tag_formatter.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":"

    Bases: TagFormatterABC

    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/django_components/#django_components.tag_formatter.TagFormatterABC","title":"TagFormatterABC","text":"

    Bases: ABC

    "},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC.end_tag","title":"end_tag abstractmethod","text":"
    end_tag(name: str) -> str\n

    Formats the end tag of a block component.

    Source code in src/django_components/tag_formatter.py
    @abc.abstractmethod\ndef end_tag(self, name: str) -> str:\n    \"\"\"Formats the end tag of a block component.\"\"\"\n    ...\n
    "},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC.parse","title":"parse abstractmethod","text":"
    parse(tokens: List[str]) -> TagResult\n

    Given the tokens (words) of 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).

    Example:

    Given a component declarations:

    {% component \"my_comp\" key=val key2=val2 %}

    This function receives a list of tokens

    ['component', '\"my_comp\"', 'key=val', 'key2=val2']

    component is the tag name, which we drop. \"my_comp\" is the component name, but we must remove the extra quotes. And we pass remaining tokens unmodified, as that's the input to the component.

    So in the end, we return a tuple:

    ('my_comp', ['key=val', 'key2=val2'])

    Source code in src/django_components/tag_formatter.py
    @abc.abstractmethod\ndef parse(self, tokens: List[str]) -> TagResult:\n    \"\"\"\n    Given the tokens (words) of a component start tag, this function extracts\n    the component name from the tokens list, and returns `TagResult`, which\n    is a tuple of `(component_name, remaining_tokens)`.\n\n    Example:\n\n    Given a component declarations:\n\n    `{% component \"my_comp\" key=val key2=val2 %}`\n\n    This function receives a list of tokens\n\n    `['component', '\"my_comp\"', 'key=val', 'key2=val2']`\n\n    `component` is the tag name, which we drop. `\"my_comp\"` is the component name,\n    but we must remove the extra quotes. And we pass remaining tokens unmodified,\n    as that's the input to the component.\n\n    So in the end, we return a tuple:\n\n    `('my_comp', ['key=val', 'key2=val2'])`\n    \"\"\"\n    ...\n
    "},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC.start_tag","title":"start_tag abstractmethod","text":"
    start_tag(name: str) -> str\n

    Formats the start tag of a component.

    Source code in src/django_components/tag_formatter.py
    @abc.abstractmethod\ndef start_tag(self, name: str) -> str:\n    \"\"\"Formats the start tag of a component.\"\"\"\n    ...\n
    "},{"location":"reference/django_components/#django_components.tag_formatter.TagResult","title":"TagResult","text":"

    Bases: NamedTuple

    The return value from TagFormatter.parse()

    "},{"location":"reference/django_components/#django_components.tag_formatter.TagResult.component_name","title":"component_name instance-attribute","text":"
    component_name: str\n

    Component name extracted from the template tag

    "},{"location":"reference/django_components/#django_components.tag_formatter.TagResult.tokens","title":"tokens instance-attribute","text":"
    tokens: List[str]\n

    Remaining tokens (words) that were passed to the tag, with component name removed

    "},{"location":"reference/django_components/#django_components.tag_formatter.get_tag_formatter","title":"get_tag_formatter","text":"
    get_tag_formatter(registry: ComponentRegistry) -> InternalTagFormatter\n

    Returns an instance of the currently configured component tag formatter.

    Source code in src/django_components/tag_formatter.py
    def get_tag_formatter(registry: \"ComponentRegistry\") -> InternalTagFormatter:\n    \"\"\"Returns an instance of the currently configured component tag formatter.\"\"\"\n    # Allow users to configure the component TagFormatter\n    formatter_cls_or_str = registry.settings.TAG_FORMATTER\n\n    if isinstance(formatter_cls_or_str, str):\n        tag_formatter: TagFormatterABC = import_string(formatter_cls_or_str)\n    else:\n        tag_formatter = formatter_cls_or_str\n\n    return InternalTagFormatter(tag_formatter)\n
    "},{"location":"reference/django_components/#django_components.template","title":"template","text":""},{"location":"reference/django_components/#django_components.template.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

    Create a Template instance that will be cached as per the TEMPLATE_CACHE_SIZE setting.

    Source code in src/django_components/template.py
    def 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    \"\"\"Create a Template instance that will be cached as per the `TEMPLATE_CACHE_SIZE` setting.\"\"\"\n    template = _create_template(template_cls or Template, template_string, engine)\n\n    # Assign the origin and name separately, so the caching doesn't depend on them\n    # Since we might be accessing a template from cache, we want to define these only once\n    if not getattr(template, \"_dc_cached\", False):\n        template.origin = origin or Origin(UNKNOWN_SOURCE)\n        template.name = name\n        template._dc_cached = True\n\n    return template\n
    "},{"location":"reference/django_components/#django_components.template_loader","title":"template_loader","text":"

    Template loader that loads templates from each Django app's \"components\" directory.

    "},{"location":"reference/django_components/#django_components.template_loader.Loader","title":"Loader","text":"

    Bases: Loader

    "},{"location":"reference/django_components/#django_components.template_loader.Loader.get_dirs","title":"get_dirs","text":"
    get_dirs(include_apps: bool = True) -> List[Path]\n

    Prepare directories that may contain component files:

    Searches for dirs set in COMPONENTS.dirs settings. If none set, defaults to searching for a \"components\" app. The dirs in COMPONENTS.dirs must be absolute paths.

    In addition to that, also all apps are checked for [app]/components dirs.

    Paths are accepted only if they resolve to a directory. E.g. /path/to/django_project/my_app/components/.

    BASE_DIR setting is required.

    Source code in src/django_components/template_loader.py
    def get_dirs(self, include_apps: bool = True) -> List[Path]:\n    \"\"\"\n    Prepare directories that may contain component files:\n\n    Searches for dirs set in `COMPONENTS.dirs` settings. If none set, defaults to searching\n    for a \"components\" app. The dirs in `COMPONENTS.dirs` must be absolute paths.\n\n    In addition to that, also all apps are checked for `[app]/components` dirs.\n\n    Paths are accepted only if they resolve to a directory.\n    E.g. `/path/to/django_project/my_app/components/`.\n\n    `BASE_DIR` setting is required.\n    \"\"\"\n    # Allow to configure from settings which dirs should be checked for components\n    component_dirs = app_settings.DIRS\n\n    # TODO_REMOVE_IN_V1\n    is_legacy_paths = (\n        # Use value of `STATICFILES_DIRS` ONLY if `COMPONENT.dirs` not set\n        not getattr(settings, \"COMPONENTS\", {}).get(\"dirs\", None) is not None\n        and hasattr(settings, \"STATICFILES_DIRS\")\n        and settings.STATICFILES_DIRS\n    )\n    if is_legacy_paths:\n        # NOTE: For STATICFILES_DIRS, we use the defaults even for empty list.\n        # We don't do this for COMPONENTS.dirs, so user can explicitly specify \"NO dirs\".\n        component_dirs = settings.STATICFILES_DIRS or [settings.BASE_DIR / \"components\"]\n    source = \"STATICFILES_DIRS\" if is_legacy_paths else \"COMPONENTS.dirs\"\n\n    logger.debug(\n        \"Template loader will search for valid template dirs from following options:\\n\"\n        + \"\\n\".join([f\" - {str(d)}\" for d in component_dirs])\n    )\n\n    # Add `[app]/[APP_DIR]` to the directories. This is, by default `[app]/components`\n    app_paths: List[Path] = []\n    if include_apps:\n        for conf in apps.get_app_configs():\n            for app_dir in app_settings.APP_DIRS:\n                comps_path = Path(conf.path).joinpath(app_dir)\n                if comps_path.exists():\n                    app_paths.append(comps_path)\n\n    directories: Set[Path] = set(app_paths)\n\n    # Validate and add other values from the config\n    for component_dir in component_dirs:\n        # Consider tuples for STATICFILES_DIRS (See #489)\n        # See https://docs.djangoproject.com/en/5.0/ref/settings/#prefixes-optional\n        if isinstance(component_dir, (tuple, list)):\n            component_dir = component_dir[1]\n        try:\n            Path(component_dir)\n        except TypeError:\n            logger.warning(\n                f\"{source} expected str, bytes or os.PathLike object, or tuple/list of length 2. \"\n                f\"See Django documentation for STATICFILES_DIRS. Got {type(component_dir)} : {component_dir}\"\n            )\n            continue\n\n        if not Path(component_dir).is_absolute():\n            raise ValueError(f\"{source} must contain absolute paths, got '{component_dir}'\")\n        else:\n            directories.add(Path(component_dir).resolve())\n\n    logger.debug(\n        \"Template loader matched following template dirs:\\n\" + \"\\n\".join([f\" - {str(d)}\" for d in directories])\n    )\n    return list(directories)\n
    "},{"location":"reference/django_components/#django_components.template_loader.get_dirs","title":"get_dirs","text":"
    get_dirs(include_apps: bool = True, engine: Optional[Engine] = None) -> List[Path]\n

    Helper for using django_component's FilesystemLoader class to obtain a list of directories where component python files may be defined.

    Source code in src/django_components/template_loader.py
    def get_dirs(include_apps: bool = True, engine: Optional[Engine] = None) -> List[Path]:\n    \"\"\"\n    Helper for using django_component's FilesystemLoader class to obtain a list\n    of directories where component python files may be defined.\n    \"\"\"\n    current_engine = engine\n    if current_engine is None:\n        current_engine = Engine.get_default()\n\n    loader = Loader(current_engine)\n    return loader.get_dirs(include_apps)\n
    "},{"location":"reference/django_components/#django_components.template_parser","title":"template_parser","text":"

    Overrides for the Django Template system to allow finer control over template parsing.

    Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py

    "},{"location":"reference/django_components/#django_components.template_parser.parse_bits","title":"parse_bits","text":"
    parse_bits(\n    parser: Parser, bits: List[str], params: List[str], name: str\n) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]\n

    Parse bits for template tag helpers simple_tag and inclusion_tag, in particular by detecting syntax errors and by extracting positional and keyword arguments.

    This is a simplified version of django.template.library.parse_bits where we use custom regex to handle special characters in keyword names.

    Furthermore, our version allows duplicate keys, and instead of return kwargs as a dict, we return it as a list of key-value pairs. So it is up to the user of this function to decide whether they support duplicate keys or not.

    Source code in src/django_components/template_parser.py
    def parse_bits(\n    parser: Parser,\n    bits: List[str],\n    params: List[str],\n    name: str,\n) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]:\n    \"\"\"\n    Parse bits for template tag helpers simple_tag and inclusion_tag, in\n    particular by detecting syntax errors and by extracting positional and\n    keyword arguments.\n\n    This is a simplified version of `django.template.library.parse_bits`\n    where we use custom regex to handle special characters in keyword names.\n\n    Furthermore, our version allows duplicate keys, and instead of return kwargs\n    as a dict, we return it as a list of key-value pairs. So it is up to the\n    user of this function to decide whether they support duplicate keys or not.\n    \"\"\"\n    args: List[FilterExpression] = []\n    kwargs: List[Tuple[str, FilterExpression]] = []\n    unhandled_params = list(params)\n    for bit in bits:\n        # First we try to extract a potential kwarg from the bit\n        kwarg = token_kwargs([bit], parser)\n        if kwarg:\n            # The kwarg was successfully extracted\n            param, value = kwarg.popitem()\n            # All good, record the keyword argument\n            kwargs.append((str(param), value))\n            if param in unhandled_params:\n                # If using the keyword syntax for a positional arg, then\n                # consume it.\n                unhandled_params.remove(param)\n        else:\n            if kwargs:\n                raise TemplateSyntaxError(\n                    \"'%s' received some positional argument(s) after some \" \"keyword argument(s)\" % name\n                )\n            else:\n                # Record the positional argument\n                args.append(parser.compile_filter(bit))\n                try:\n                    # Consume from the list of expected positional arguments\n                    unhandled_params.pop(0)\n                except IndexError:\n                    pass\n    if unhandled_params:\n        # Some positional arguments were not supplied\n        raise TemplateSyntaxError(\n            \"'%s' did not receive value(s) for the argument(s): %s\"\n            % (name, \", \".join(\"'%s'\" % p for p in unhandled_params))\n        )\n    return args, kwargs\n
    "},{"location":"reference/django_components/#django_components.template_parser.token_kwargs","title":"token_kwargs","text":"
    token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]\n

    Parse token keyword arguments and return a dictionary of the arguments retrieved from the bits token list.

    bits is a list containing the remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments are removed from this list.

    There is no requirement for all remaining token bits to be keyword arguments, so return the dictionary as soon as an invalid argument format is reached.

    Source code in src/django_components/template_parser.py
    def token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]:\n    \"\"\"\n    Parse token keyword arguments and return a dictionary of the arguments\n    retrieved from the ``bits`` token list.\n\n    `bits` is a list containing the remainder of the token (split by spaces)\n    that is to be checked for arguments. Valid arguments are removed from this\n    list.\n\n    There is no requirement for all remaining token ``bits`` to be keyword\n    arguments, so return the dictionary as soon as an invalid argument format\n    is reached.\n    \"\"\"\n    if not bits:\n        return {}\n    match = kwarg_re.match(bits[0])\n    kwarg_format = match and match[1]\n    if not kwarg_format:\n        return {}\n\n    kwargs: Dict[str, FilterExpression] = {}\n    while bits:\n        if kwarg_format:\n            match = kwarg_re.match(bits[0])\n            if not match or not match[1]:\n                return kwargs\n            key, value = match.groups()\n            del bits[:1]\n        else:\n            if len(bits) < 3 or bits[1] != \"as\":\n                return kwargs\n            key, value = bits[2], bits[0]\n            del bits[:3]\n\n        # This is the only difference from the original token_kwargs. We use\n        # the ComponentsFilterExpression instead of the original FilterExpression.\n        kwargs[key] = ComponentsFilterExpression(value, parser)\n        if bits and not kwarg_format:\n            if bits[0] != \"and\":\n                return kwargs\n            del bits[:1]\n    return kwargs\n
    "},{"location":"reference/django_components/#django_components.templatetags","title":"templatetags","text":""},{"location":"reference/django_components/#django_components.templatetags.component_tags","title":"component_tags","text":""},{"location":"reference/django_components/#django_components.templatetags.component_tags.component","title":"component","text":"
    component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode\n
    To give the component access to the template context

    {% component \"name\" positional_arg keyword_arg=value ... %}

    To render the component in an isolated context

    {% component \"name\" positional_arg keyword_arg=value ... only %}

    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 or, if there are no positional arguments, passed as 'name'.

    Source code in src/django_components/templatetags/component_tags.py
    def component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode:\n    \"\"\"\n    To give the component access to the template context:\n        ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... %}```\n\n    To render the component in an isolated context:\n        ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... only %}```\n\n    Positional and keyword arguments can be literals or template variables.\n    The component name must be a single- or double-quotes string and must\n    be either the first positional argument or, if there are no positional\n    arguments, passed as 'name'.\n    \"\"\"\n    _fix_nested_tags(parser, token)\n    bits = token.split_contents()\n\n    # Let the TagFormatter pre-process the tokens\n    formatter = get_tag_formatter(registry)\n    result = formatter.parse([*bits])\n    end_tag = formatter.end_tag(result.component_name)\n\n    # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n    bits = [bits[0], *result.tokens]\n    token.contents = \" \".join(bits)\n\n    tag = _parse_tag(\n        tag_name,\n        parser,\n        token,\n        params=[],\n        extra_params=True,  # Allow many args\n        flags=[COMP_ONLY_FLAG],\n        keywordonly_kwargs=True,\n        repeatable_kwargs=False,\n        end_tag=end_tag,\n    )\n\n    # Check for isolated context keyword\n    isolated_context = tag.flags[COMP_ONLY_FLAG]\n\n    trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n    body = tag.parse_body()\n    fill_nodes = parse_slot_fill_nodes_from_component_nodelist(tuple(body), ignored_nodes=(ComponentNode,))\n\n    # Tag all fill nodes as children of this particular component instance\n    for node in fill_nodes:\n        trace_msg(\"ASSOC\", \"FILL\", node.trace_id, node.node_id, component_id=tag.id)\n        node.component_id = tag.id\n\n    component_node = ComponentNode(\n        name=result.component_name,\n        args=tag.args,\n        kwargs=tag.kwargs,\n        isolated_context=isolated_context,\n        fill_nodes=fill_nodes,\n        node_id=tag.id,\n        registry=registry,\n    )\n\n    trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n    return component_node\n
    "},{"location":"reference/django_components/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"
    component_css_dependencies(preload: str = '') -> SafeString\n

    Marks location where CSS link tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_css_dependencies\")\ndef component_css_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where CSS link tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_css_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/#django_components.templatetags.component_tags.component_dependencies","title":"component_dependencies","text":"
    component_dependencies(preload: str = '') -> SafeString\n

    Marks location where CSS link and JS script tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_dependencies\")\ndef component_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where CSS link and JS script tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER + JS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"
    component_js_dependencies(preload: str = '') -> SafeString\n

    Marks location where JS script tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_js_dependencies\")\ndef component_js_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where JS script tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + JS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_js_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/#django_components.templatetags.component_tags.fill","title":"fill","text":"
    fill(parser: Parser, token: Token) -> FillNode\n

    Block tag whose contents 'fill' (are inserted into) an identically named 'slot'-block in the component template referred to by a parent component. It exists to make component nesting easier.

    This tag is available only within a {% component %}..{% endcomponent %} block. Runtime checks should prohibit other usages.

    Source code in src/django_components/templatetags/component_tags.py
    @register.tag(\"fill\")\ndef fill(parser: Parser, token: Token) -> FillNode:\n    \"\"\"\n    Block tag whose contents 'fill' (are inserted into) an identically named\n    'slot'-block in the component template referred to by a parent component.\n    It exists to make component nesting easier.\n\n    This tag is available only within a {% component %}..{% endcomponent %} block.\n    Runtime checks should prohibit other usages.\n    \"\"\"\n    tag = _parse_tag(\n        \"fill\",\n        parser,\n        token,\n        params=[SLOT_NAME_KWARG],\n        optional_params=[SLOT_NAME_KWARG],\n        keywordonly_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n        repeatable_kwargs=False,\n        end_tag=\"endfill\",\n    )\n\n    fill_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n    trace_id = f\"fill-id-{tag.id} ({fill_name_kwarg})\" if fill_name_kwarg else f\"fill-id-{tag.id}\"\n\n    trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id)\n\n    body = tag.parse_body()\n    fill_node = FillNode(\n        nodelist=body,\n        node_id=tag.id,\n        kwargs=tag.kwargs,\n        trace_id=trace_id,\n    )\n\n    trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id, \"...Done!\")\n    return fill_node\n
    "},{"location":"reference/django_components/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"
    html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode\n

    This tag takes: - Optional dictionary of attributes (attrs) - Optional dictionary of defaults (defaults) - Additional kwargs that are appended to the former two

    The inputs are merged and resulting dict is rendered as HTML attributes (key=\"value\").

    Rules: 1. Both attrs and defaults can be passed as positional args or as kwargs 2. Both attrs and defaults are optional (can be omitted) 3. 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. 4. All other kwargs (key=value) are appended and can be repeated.

    Normal kwargs (key=value) are concatenated to existing keys. So if e.g. key \"class\" is supplied with value \"my-class\", then adding class=\"extra-class\" will result in `class=\"my-class extra-class\".

    Example:

    {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n

    Source code in src/django_components/templatetags/component_tags.py
    @register.tag(\"html_attrs\")\ndef html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode:\n    \"\"\"\n    This tag takes:\n    - Optional dictionary of attributes (`attrs`)\n    - Optional dictionary of defaults (`defaults`)\n    - Additional kwargs that are appended to the former two\n\n    The inputs are merged and resulting dict is rendered as HTML attributes\n    (`key=\"value\"`).\n\n    Rules:\n    1. Both `attrs` and `defaults` can be passed as positional args or as kwargs\n    2. Both `attrs` and `defaults` are optional (can be omitted)\n    3. Both `attrs` and `defaults` are dictionaries, and we can define them the same way\n       we define dictionaries for the `component` tag. So either as `attrs=attrs` or\n       `attrs:key=value`.\n    4. All other kwargs (`key=value`) are appended and can be repeated.\n\n    Normal kwargs (`key=value`) are concatenated to existing keys. So if e.g. key\n    \"class\" is supplied with value \"my-class\", then adding `class=\"extra-class\"`\n    will result in `class=\"my-class extra-class\".\n\n    Example:\n    ```htmldjango\n    {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n    ```\n    \"\"\"\n    tag = _parse_tag(\n        \"html_attrs\",\n        parser,\n        token,\n        params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n        optional_params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n        flags=[],\n        keywordonly_kwargs=True,\n        repeatable_kwargs=True,\n    )\n\n    return HtmlAttrsNode(\n        kwargs=tag.kwargs,\n        kwarg_pairs=tag.kwarg_pairs,\n    )\n
    "},{"location":"reference/django_components/#django_components.types","title":"types","text":"

    Helper types for IDEs.

    "},{"location":"reference/django_components/#django_components.utils","title":"utils","text":""},{"location":"reference/django_components/#django_components.utils.gen_id","title":"gen_id","text":"
    gen_id(length: int = 5) -> str\n

    Generate a unique ID that can be associated with a Node

    Source code in src/django_components/utils.py
    def gen_id(length: int = 5) -> str:\n    \"\"\"Generate a unique ID that can be associated with a Node\"\"\"\n    # Global counter to avoid conflicts\n    global _id\n    _id += 1\n\n    # Pad the ID with `0`s up to 4 digits, e.g. `0007`\n    return f\"{_id:04}\"\n
    "},{"location":"reference/django_components/#django_components.utils.lazy_cache","title":"lazy_cache","text":"
    lazy_cache(make_cache: Callable[[], Callable[[Callable], Callable]]) -> Callable[[TFunc], TFunc]\n

    Decorator that caches the given function similarly to functools.lru_cache. But the cache is instantiated only at first invocation.

    cache argument is a function that generates the cache function, e.g. functools.lru_cache().

    Source code in src/django_components/utils.py
    def lazy_cache(\n    make_cache: Callable[[], Callable[[Callable], Callable]],\n) -> Callable[[TFunc], TFunc]:\n    \"\"\"\n    Decorator that caches the given function similarly to `functools.lru_cache`.\n    But the cache is instantiated only at first invocation.\n\n    `cache` argument is a function that generates the cache function,\n    e.g. `functools.lru_cache()`.\n    \"\"\"\n    _cached_fn = None\n\n    def decorator(fn: TFunc) -> TFunc:\n        @functools.wraps(fn)\n        def wrapper(*args: Any, **kwargs: Any) -> Any:\n            # Lazily initialize the cache\n            nonlocal _cached_fn\n            if not _cached_fn:\n                # E.g. `lambda: functools.lru_cache(maxsize=app_settings.TEMPLATE_CACHE_SIZE)`\n                cache = make_cache()\n                _cached_fn = cache(fn)\n\n            return _cached_fn(*args, **kwargs)\n\n        # Allow to access the LRU cache methods\n        # See https://stackoverflow.com/a/37654201/9788634\n        wrapper.cache_info = lambda: _cached_fn.cache_info()  # type: ignore\n        wrapper.cache_clear = lambda: _cached_fn.cache_clear()  # type: ignore\n\n        # And allow to remove the cache instance (mostly for tests)\n        def cache_remove() -> None:\n            nonlocal _cached_fn\n            _cached_fn = None\n\n        wrapper.cache_remove = cache_remove  # type: ignore\n\n        return cast(TFunc, wrapper)\n\n    return decorator\n
    "},{"location":"reference/django_components/app_settings/","title":" app_settings","text":""},{"location":"reference/django_components/app_settings/#django_components.app_settings","title":"app_settings","text":""},{"location":"reference/django_components/app_settings/#django_components.app_settings.ContextBehavior","title":"ContextBehavior","text":"

    Bases: str, Enum

    "},{"location":"reference/django_components/app_settings/#django_components.app_settings.ContextBehavior.DJANGO","title":"DJANGO class-attribute instance-attribute","text":"
    DJANGO = 'django'\n

    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 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 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/django_components/app_settings/#django_components.app_settings.ContextBehavior.ISOLATED","title":"ISOLATED class-attribute instance-attribute","text":"
    ISOLATED = 'isolated'\n

    This setting makes the component fills behave similar to Vue or React, where the fills use EXCLUSIVELY the context variables defined in 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/django_components/apps/","title":" apps","text":""},{"location":"reference/django_components/apps/#django_components.apps","title":"apps","text":""},{"location":"reference/django_components/attributes/","title":" attributes","text":""},{"location":"reference/django_components/attributes/#django_components.attributes","title":"attributes","text":""},{"location":"reference/django_components/attributes/#django_components.attributes.append_attributes","title":"append_attributes","text":"
    append_attributes(*args: Tuple[str, Any]) -> Dict\n

    Merges the key-value pairs and returns a new dictionary.

    If a key is present multiple times, its values are concatenated with a space character as separator in the final dictionary.

    Source code in src/django_components/attributes.py
    def append_attributes(*args: Tuple[str, Any]) -> Dict:\n    \"\"\"\n    Merges the key-value pairs and returns a new dictionary.\n\n    If a key is present multiple times, its values are concatenated with a space\n    character as separator in the final dictionary.\n    \"\"\"\n    result: Dict = {}\n\n    for key, value in args:\n        if key in result:\n            result[key] += \" \" + value\n        else:\n            result[key] = value\n\n    return result\n
    "},{"location":"reference/django_components/attributes/#django_components.attributes.attributes_to_string","title":"attributes_to_string","text":"
    attributes_to_string(attributes: Mapping[str, Any]) -> str\n

    Convert a dict of attributes to a string.

    Source code in src/django_components/attributes.py
    def attributes_to_string(attributes: Mapping[str, Any]) -> str:\n    \"\"\"Convert a dict of attributes to a string.\"\"\"\n    attr_list = []\n\n    for key, value in attributes.items():\n        if value is None or value is False:\n            continue\n        if value is True:\n            attr_list.append(conditional_escape(key))\n        else:\n            attr_list.append(format_html('{}=\"{}\"', key, value))\n\n    return mark_safe(SafeString(\" \").join(attr_list))\n
    "},{"location":"reference/django_components/autodiscover/","title":" autodiscover","text":""},{"location":"reference/django_components/autodiscover/#django_components.autodiscover","title":"autodiscover","text":""},{"location":"reference/django_components/autodiscover/#django_components.autodiscover.autodiscover","title":"autodiscover","text":"
    autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n

    Search for component files and import them. Returns a list of module paths of imported files.

    Autodiscover searches in the locations as defined by Loader.get_dirs.

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

    Source code in src/django_components/autodiscover.py
    def autodiscover(\n    map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n    \"\"\"\n    Search for component files and import them. Returns a list of module\n    paths of imported files.\n\n    Autodiscover searches in the locations as defined by `Loader.get_dirs`.\n\n    You can map the module paths with `map_module` function. This serves\n    as an escape hatch for when you need to use this function in tests.\n    \"\"\"\n    dirs = get_dirs(include_apps=False)\n    component_filepaths = search_dirs(dirs, \"**/*.py\")\n    logger.debug(f\"Autodiscover found {len(component_filepaths)} files in component directories.\")\n\n    if hasattr(settings, \"BASE_DIR\") and settings.BASE_DIR:\n        project_root = str(settings.BASE_DIR)\n    else:\n        # Fallback for getting the root dir, see https://stackoverflow.com/a/16413955/9788634\n        project_root = os.path.abspath(os.path.dirname(__name__))\n\n    modules: List[str] = []\n\n    # We handle dirs from `COMPONENTS.dirs` and from individual apps separately.\n    #\n    # Because for dirs in `COMPONENTS.dirs`, we assume they will be nested under `BASE_DIR`,\n    # and that `BASE_DIR` is the current working dir (CWD). So the path relatively to `BASE_DIR`\n    # is ALSO the python import path.\n    for filepath in component_filepaths:\n        module_path = _filepath_to_python_module(filepath, project_root, None)\n        # Ignore files starting with dot `.` or files in dirs that start with dot.\n        #\n        # If any of the parts of the path start with a dot, e.g. the filesystem path\n        # is `./abc/.def`, then this gets converted to python module as `abc..def`\n        #\n        # NOTE: This approach also ignores files:\n        #   - with two dots in the middle (ab..cd.py)\n        #   - an extra dot at the end (abcd..py)\n        #   - files outside of the parent component (../abcd.py).\n        # But all these are NOT valid python modules so that's fine.\n        if \"..\" in module_path:\n            continue\n\n        modules.append(module_path)\n\n    # For for apps, the directories may be outside of the project, e.g. in case of third party\n    # apps. So we have to resolve the python import path relative to the package name / the root\n    # import path for the app.\n    # See https://github.com/EmilStenstrom/django-components/issues/669\n    for conf in apps.get_app_configs():\n        for app_dir in app_settings.APP_DIRS:\n            comps_path = Path(conf.path).joinpath(app_dir)\n            if not comps_path.exists():\n                continue\n            app_component_filepaths = search_dirs([comps_path], \"**/*.py\")\n            for filepath in app_component_filepaths:\n                app_component_module = _filepath_to_python_module(filepath, conf.path, conf.name)\n                modules.append(app_component_module)\n\n    return _import_modules(modules, map_module)\n
    "},{"location":"reference/django_components/autodiscover/#django_components.autodiscover.import_libraries","title":"import_libraries","text":"
    import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n

    Import modules set in COMPONENTS.libraries setting.

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

    Source code in src/django_components/autodiscover.py
    def import_libraries(\n    map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n    \"\"\"\n    Import modules set in `COMPONENTS.libraries` setting.\n\n    You can map the module paths with `map_module` function. This serves\n    as an escape hatch for when you need to use this function in tests.\n    \"\"\"\n    from django_components.app_settings import app_settings\n\n    return _import_modules(app_settings.LIBRARIES, map_module)\n
    "},{"location":"reference/django_components/autodiscover/#django_components.autodiscover.search_dirs","title":"search_dirs","text":"
    search_dirs(dirs: List[Path], search_glob: str) -> List[Path]\n

    Search the directories for the given glob pattern. Glob search results are returned as a flattened list.

    Source code in src/django_components/autodiscover.py
    def search_dirs(dirs: List[Path], search_glob: str) -> List[Path]:\n    \"\"\"\n    Search the directories for the given glob pattern. Glob search results are returned\n    as a flattened list.\n    \"\"\"\n    matched_files: List[Path] = []\n    for directory in dirs:\n        for path in glob.iglob(str(Path(directory) / search_glob), recursive=True):\n            matched_files.append(Path(path))\n\n    return matched_files\n
    "},{"location":"reference/django_components/component/","title":" component","text":""},{"location":"reference/django_components/component/#django_components.component","title":"component","text":""},{"location":"reference/django_components/component/#django_components.component.Component","title":"Component","text":"
    Component(\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,\n)\n

    Bases: Generic[ArgsType, KwargsType, DataType, SlotsType]

    Source code in src/django_components/component.py
    def __init__(\n    self,\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,  # noqa F811\n):\n    # When user first instantiates the component class before calling\n    # `render` or `render_to_response`, then we want to allow the render\n    # function to make use of the instantiated object.\n    #\n    # So while `MyComp.render()` creates a new instance of MyComp internally,\n    # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n    # already-instantiated object.\n    #\n    # To achieve that, we want to re-assign the class methods as instance methods.\n    # For that we have to \"unwrap\" the class methods via __func__.\n    # See https://stackoverflow.com/a/76706399/9788634\n    self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self)  # type: ignore\n    self.render = types.MethodType(self.__class__.render.__func__, self)  # type: ignore\n    self.as_view = types.MethodType(self.__class__.as_view.__func__, self)  # type: ignore\n\n    self.registered_name: Optional[str] = registered_name\n    self.outer_context: Context = outer_context or Context()\n    self.fill_content = fill_content or {}\n    self.component_id = component_id or gen_id()\n    self.registry = registry or registry_\n    self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n    # None == uninitialized, False == No types, Tuple == types\n    self._types: Optional[Union[Tuple[Any, Any, Any, Any], Literal[False]]] = None\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.Media","title":"Media class-attribute instance-attribute","text":"
    Media = ComponentMediaInput\n

    Defines JS and CSS media files associated with this component.

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

    Inlined CSS associated with this component.

    "},{"location":"reference/django_components/component/#django_components.component.Component.input","title":"input property","text":"
    input: RenderInput[ArgsType, KwargsType, SlotsType]\n

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

    "},{"location":"reference/django_components/component/#django_components.component.Component.is_filled","title":"is_filled property","text":"
    is_filled: Dict[str, bool]\n

    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/django_components/component/#django_components.component.Component.js","title":"js class-attribute instance-attribute","text":"
    js: Optional[str] = None\n

    Inlined JS associated with this component.

    "},{"location":"reference/django_components/component/#django_components.component.Component.media","title":"media instance-attribute","text":"
    media: Media\n

    Normalized definition of JS and CSS media files associated with this component.

    NOTE: This field is generated from Component.Media class.

    "},{"location":"reference/django_components/component/#django_components.component.Component.response_class","title":"response_class class-attribute instance-attribute","text":"
    response_class = HttpResponse\n

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

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

    Inlined Django template associated with this component. Can be a plain string or a Template instance.

    Only one of template_name, get_template_name, template or get_template must be defined.

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

    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_name, get_template_name, template or get_template must be defined.

    "},{"location":"reference/django_components/component/#django_components.component.Component.as_view","title":"as_view classmethod","text":"
    as_view(**initkwargs: Any) -> ViewFn\n

    Shortcut for calling Component.View.as_view and passing component instance to it.

    Source code in src/django_components/component.py
    @classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n    \"\"\"\n    Shortcut for calling `Component.View.as_view` and passing component instance to it.\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    # Allow the View class to access this component via `self.component`\n    return comp.View.as_view(**initkwargs, component=comp)\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.get_template","title":"get_template","text":"
    get_template(context: Context) -> Optional[Union[str, Template]]\n

    Inlined Django template associated with this component. Can be a plain string or a Template instance.

    Only one of template_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n    \"\"\"\n    Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.get_template_name","title":"get_template_name","text":"
    get_template_name(context: Context) -> Optional[str]\n

    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_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template_name(self, context: Context) -> Optional[str]:\n    \"\"\"\n    Filepath to the Django template associated with this component.\n\n    The filepath must be relative to either the file where the component class was defined,\n    or one of the roots of `STATIFILES_DIRS`.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.inject","title":"inject","text":"
    inject(key: str, default: Optional[Any] = None) -> Any\n

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

    Source code in src/django_components/component.py
    def inject(self, key: str, default: Optional[Any] = None) -> Any:\n    \"\"\"\n    Use this method to retrieve the data that was passed to a `{% provide %}` tag\n    with the corresponding key.\n\n    To retrieve the data, `inject()` must be called inside a component that's\n    inside the `{% provide %}` tag.\n\n    You may also pass a default that will be used if the `provide` tag with given\n    key was NOT found.\n\n    This method mut be used inside the `get_context_data()` method and raises\n    an error if called elsewhere.\n\n    Example:\n\n    Given this template:\n    ```django\n    {% provide \"provider\" hello=\"world\" %}\n        {% component \"my_comp\" %}\n        {% endcomponent %}\n    {% endprovide %}\n    ```\n\n    And given this definition of \"my_comp\" component:\n    ```py\n    from django_components import Component, register\n\n    @register(\"my_comp\")\n    class MyComp(Component):\n        template = \"hi {{ data.hello }}!\"\n        def get_context_data(self):\n            data = self.inject(\"provider\")\n            return {\"data\": data}\n    ```\n\n    This renders into:\n    ```\n    hi world!\n    ```\n\n    As the `{{ data.hello }}` is taken from the \"provider\".\n    \"\"\"\n    if self.input is None:\n        raise RuntimeError(\n            f\"Method 'inject()' of component '{self.name}' was called outside of 'get_context_data()'\"\n        )\n\n    return get_injected_context_var(self.name, self.input.context, key, default)\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.on_render_after","title":"on_render_after","text":"
    on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\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.

    Source code in src/django_components/component.py
    def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n    \"\"\"\n    Hook that runs just after the component's template was rendered.\n    It receives the rendered output as the last argument.\n\n    You can use this hook to access the context or the template, but modifying\n    them won't have any effect.\n\n    To override the content that gets rendered, you can return a string or SafeString\n    from this hook.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.on_render_before","title":"on_render_before","text":"
    on_render_before(context: Context, template: Template) -> 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.

    Source code in src/django_components/component.py
    def on_render_before(self, context: Context, template: Template) -> None:\n    \"\"\"\n    Hook that runs just before the component's template is rendered.\n\n    You can use this hook to access or modify the context or the template.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/component/#django_components.component.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) -> str\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render(\n    cls,\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) -> str:\n    \"\"\"\n    Render the component into a string.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    return comp._render(context, args, kwargs, slots, escape_slots_content)\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.render_css_dependencies","title":"render_css_dependencies","text":"
    render_css_dependencies() -> SafeString\n

    Render only CSS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_css_dependencies(self) -> SafeString:\n    \"\"\"Render only CSS dependencies available in the media class or provided as a string.\"\"\"\n    if self.css is not None:\n        return mark_safe(f\"<style>{self.css}</style>\")\n    return mark_safe(\"\\n\".join(self.media.render_css()))\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.render_dependencies","title":"render_dependencies","text":"
    render_dependencies() -> SafeString\n

    Helper function to render all dependencies for a component.

    Source code in src/django_components/component.py
    def render_dependencies(self) -> SafeString:\n    \"\"\"Helper function to render all dependencies for a component.\"\"\"\n    dependencies = []\n\n    css_deps = self.render_css_dependencies()\n    if css_deps:\n        dependencies.append(css_deps)\n\n    js_deps = self.render_js_dependencies()\n    if js_deps:\n        dependencies.append(js_deps)\n\n    return mark_safe(\"\\n\".join(dependencies))\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.render_js_dependencies","title":"render_js_dependencies","text":"
    render_js_dependencies() -> SafeString\n

    Render only JS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_js_dependencies(self) -> SafeString:\n    \"\"\"Render only JS dependencies available in the media class or provided as a string.\"\"\"\n    if self.js is not None:\n        return mark_safe(f\"<script>{self.js}</script>\")\n    return mark_safe(\"\\n\".join(self.media.render_js()))\n
    "},{"location":"reference/django_components/component/#django_components.component.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    *response_args: Any,\n    **response_kwargs: Any\n) -> HttpResponse\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render_to_response(\n    cls,\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    slots: Optional[SlotsType] = None,\n    escape_slots_content: bool = True,\n    args: Optional[ArgsType] = None,\n    kwargs: Optional[KwargsType] = None,\n    *response_args: Any,\n    **response_kwargs: Any,\n) -> HttpResponse:\n    \"\"\"\n    Render the component and wrap the content in the response class.\n\n    The response class is taken from `Component.response_class`. Defaults to `django.http.HttpResponse`.\n\n    This is the interface for the `django.views.View` class which allows us to\n    use components as Django views with `component.as_view()`.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Any additional args and kwargs are passed to the `response_class`.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    content = cls.render(\n        args=args,\n        kwargs=kwargs,\n        context=context,\n        slots=slots,\n        escape_slots_content=escape_slots_content,\n    )\n    return cls.response_class(content, *response_args, **response_kwargs)\n
    "},{"location":"reference/django_components/component/#django_components.component.ComponentNode","title":"ComponentNode","text":"
    ComponentNode(\n    name: str,\n    args: List[Expression],\n    kwargs: RuntimeKwargs,\n    registry: ComponentRegistry,\n    isolated_context: bool = False,\n    fill_nodes: Optional[List[FillNode]] = None,\n    node_id: Optional[str] = None,\n)\n

    Bases: BaseNode

    Django.template.Node subclass that renders a django-components component

    Source code in src/django_components/component.py
    def __init__(\n    self,\n    name: str,\n    args: List[Expression],\n    kwargs: RuntimeKwargs,\n    registry: ComponentRegistry,  # noqa F811\n    isolated_context: bool = False,\n    fill_nodes: Optional[List[FillNode]] = None,\n    node_id: Optional[str] = None,\n) -> None:\n    super().__init__(nodelist=NodeList(fill_nodes), args=args, kwargs=kwargs, node_id=node_id)\n\n    self.name = name\n    self.isolated_context = isolated_context\n    self.fill_nodes = fill_nodes or []\n    self.registry = registry\n
    "},{"location":"reference/django_components/component/#django_components.component.ComponentView","title":"ComponentView","text":"
    ComponentView(component: Component, **kwargs: Any)\n

    Bases: View

    Subclass of django.views.View where the Component instance is available via self.component.

    Source code in src/django_components/component.py
    def __init__(self, component: \"Component\", **kwargs: Any) -> None:\n    super().__init__(**kwargs)\n    self.component = component\n
    "},{"location":"reference/django_components/component_media/","title":" component_media","text":""},{"location":"reference/django_components/component_media/#django_components.component_media","title":"component_media","text":""},{"location":"reference/django_components/component_media/#django_components.component_media.ComponentMediaInput","title":"ComponentMediaInput","text":"

    Defines JS and CSS media files associated with this component.

    "},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta","title":"MediaMeta","text":"

    Bases: MediaDefiningClass

    Metaclass for handling media files for components.

    Similar to MediaDefiningClass, this class supports the use of Media attribute to define associated JS/CSS files, which are then available under media attribute as a instance of Media class.

    This subclass has following changes:

    "},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--1-support-for-multiple-interfaces-of-jscss","title":"1. Support for multiple interfaces of JS/CSS","text":"
    1. As plain strings

      class MyComponent(Component):\n    class Media:\n        js = \"path/to/script.js\"\n        css = \"path/to/style.css\"\n

    2. As lists

      class MyComponent(Component):\n    class Media:\n        js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n        css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n

    3. [CSS ONLY] Dicts of strings

      class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": \"path/to/style1.css\",\n            \"print\": \"path/to/style2.css\",\n        }\n

    4. [CSS ONLY] Dicts of lists

      class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": [\"path/to/style1.css\"],\n            \"print\": [\"path/to/style2.css\"],\n        }\n

    "},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--2-media-are-first-resolved-relative-to-class-definition-file","title":"2. Media are first resolved relative to class definition file","text":"

    E.g. if in a directory my_comp you have script.js and my_comp.py, and my_comp.py looks like this:

    class MyComponent(Component):\n    class Media:\n        js = \"script.js\"\n

    Then script.js will be resolved as my_comp/script.js.

    "},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--3-media-can-be-defined-as-str-bytes-pathlike-safestring-or-function-of-thereof","title":"3. Media can be defined as str, bytes, PathLike, SafeString, or function of thereof","text":"

    E.g.:

    def lazy_eval_css():\n    # do something\n    return path\n\nclass MyComponent(Component):\n    class Media:\n        js = b\"script.js\"\n        css = lazy_eval_css\n
    "},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--4-subclass-media-class-with-media_class","title":"4. Subclass Media class with media_class","text":"

    Normal MediaDefiningClass creates an instance of Media class under the media attribute. This class allows to override which class will be instantiated with media_class attribute:

    class MyMedia(Media):\n    def render_js(self):\n        ...\n\nclass MyComponent(Component):\n    media_class = MyMedia\n    def get_context_data(self):\n        assert isinstance(self.media, MyMedia)\n
    "},{"location":"reference/django_components/component_registry/","title":" component_registry","text":""},{"location":"reference/django_components/component_registry/#django_components.component_registry","title":"component_registry","text":""},{"location":"reference/django_components/component_registry/#django_components.component_registry.registry","title":"registry module-attribute","text":"
    registry: ComponentRegistry = ComponentRegistry()\n

    The default and global component registry. Use this instance to directly register or remove components:

    # Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Get single\nregistry.get(\"button\")\n# Get all\nregistry.all()\n# Unregister single\nregistry.unregister(\"button\")\n# Unregister all\nregistry.clear()\n
    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry","title":"ComponentRegistry","text":"
    ComponentRegistry(\n    library: Optional[Library] = None, settings: Optional[Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]] = None\n)\n

    Manages which components can be used in the template tags.

    Each ComponentRegistry instance is associated with an instance of Django's Library. So when you register or unregister a component to/from a component registry, behind the scenes the registry automatically adds/removes the component's template tag to/from the Library.

    The Library instance can be set at instantiation. If omitted, then the default Library instance from django_components is used. The Library instance can be accessed under library attribute.

    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
    Source code in src/django_components/component_registry.py
    def __init__(\n    self,\n    library: Optional[Library] = None,\n    settings: Optional[Union[RegistrySettings, Callable[[\"ComponentRegistry\"], RegistrySettings]]] = None,\n) -> None:\n    self._registry: Dict[str, ComponentRegistryEntry] = {}  # component name -> component_entry mapping\n    self._tags: Dict[str, Set[str]] = {}  # tag -> list[component names]\n    self._library = library\n    self._settings_input = settings\n    self._settings: Optional[Callable[[], InternalRegistrySettings]] = None\n\n    all_registries.append(self)\n
    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.library","title":"library property","text":"
    library: Library\n

    The template tag library with which the component registry is associated.

    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.all","title":"all","text":"
    all() -> Dict[str, Type[Component]]\n

    Retrieve all registered 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
    Source code in src/django_components/component_registry.py
    def all(self) -> Dict[str, Type[\"Component\"]]:\n    \"\"\"\n    Retrieve all registered component classes.\n\n    Example:\n\n    ```py\n    # First register components\n    registry.register(\"button\", ButtonComponent)\n    registry.register(\"card\", CardComponent)\n    # Then get all\n    registry.all()\n    # > {\n    # >   \"button\": ButtonComponent,\n    # >   \"card\": CardComponent,\n    # > }\n    ```\n    \"\"\"\n    comps = {key: entry.cls for key, entry in self._registry.items()}\n    return comps\n
    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.clear","title":"clear","text":"
    clear() -> None\n

    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
    Source code in src/django_components/component_registry.py
    def clear(self) -> None:\n    \"\"\"\n    Clears the registry, unregistering all components.\n\n    Example:\n\n    ```py\n    # First register components\n    registry.register(\"button\", ButtonComponent)\n    registry.register(\"card\", CardComponent)\n    # Then clear\n    registry.clear()\n    # Then get all\n    registry.all()\n    # > {}\n    ```\n    \"\"\"\n    all_comp_names = list(self._registry.keys())\n    for comp_name in all_comp_names:\n        self.unregister(comp_name)\n\n    self._registry = {}\n    self._tags = {}\n
    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.get","title":"get","text":"
    get(name: str) -> Type[Component]\n

    Retrieve a 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
    Source code in src/django_components/component_registry.py
    def get(self, name: str) -> Type[\"Component\"]:\n    \"\"\"\n    Retrieve a component class registered under the given name.\n\n    Raises `NotRegistered` if the given name is not registered.\n\n    Example:\n\n    ```py\n    # First register component\n    registry.register(\"button\", ButtonComponent)\n    # Then get\n    registry.get(\"button\")\n    # > ButtonComponent\n    ```\n    \"\"\"\n    if name not in self._registry:\n        raise NotRegistered('The component \"%s\" is not registered' % name)\n\n    return self._registry[name].cls\n
    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.register","title":"register","text":"
    register(name: str, component: Type[Component]) -> None\n

    Register a component 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\" %}{% endcomponent %}\n

    Raises AlreadyRegistered if a different component was already registered under the same name.

    Example:

    registry.register(\"button\", ButtonComponent)\n
    Source code in src/django_components/component_registry.py
    def register(self, name: str, component: Type[\"Component\"]) -> None:\n    \"\"\"\n    Register a component with this registry under the given name.\n\n    A component MUST be registered before it can be used in a template such as:\n    ```django\n    {% component \"my_comp\" %}{% endcomponent %}\n    ```\n\n    Raises `AlreadyRegistered` if a different component was already registered\n    under the same name.\n\n    Example:\n\n    ```py\n    registry.register(\"button\", ButtonComponent)\n    ```\n    \"\"\"\n    existing_component = self._registry.get(name)\n    if existing_component and existing_component.cls._class_hash != component._class_hash:\n        raise AlreadyRegistered('The component \"%s\" has already been registered' % name)\n\n    entry = self._register_to_library(name, component)\n\n    # Keep track of which components use which tags, because multiple components may\n    # use the same tag.\n    tag = entry.tag\n    if tag not in self._tags:\n        self._tags[tag] = set()\n    self._tags[tag].add(name)\n\n    self._registry[name] = entry\n
    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.unregister","title":"unregister","text":"
    unregister(name: str) -> None\n

    Unlinks a previously-registered component from the registry under the given name.

    Once a component is unregistered, it CANNOT be used in a template anymore. Following would raise an error:

    {% component \"my_comp\" %}{% endcomponent %}\n

    Raises NotRegistered if the given name is not registered.

    Example:

    # First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
    Source code in src/django_components/component_registry.py
    def unregister(self, name: str) -> None:\n    \"\"\"\n    Unlinks a previously-registered component from the registry under the given name.\n\n    Once a component is unregistered, it CANNOT be used in a template anymore.\n    Following would raise an error:\n    ```django\n    {% component \"my_comp\" %}{% endcomponent %}\n    ```\n\n    Raises `NotRegistered` if the given name is not registered.\n\n    Example:\n\n    ```py\n    # First register component\n    registry.register(\"button\", ButtonComponent)\n    # Then unregister\n    registry.unregister(\"button\")\n    ```\n    \"\"\"\n    # Validate\n    self.get(name)\n\n    entry = self._registry[name]\n    tag = entry.tag\n\n    # Unregister the tag from library if this was the last component using this tag\n    # Unlink component from tag\n    self._tags[tag].remove(name)\n\n    # Cleanup\n    is_tag_empty = not len(self._tags[tag])\n    if is_tag_empty:\n        del self._tags[tag]\n\n    # Only unregister a tag if it's NOT protected\n    is_protected = is_tag_protected(self.library, tag)\n    if not is_protected:\n        # Unregister the tag from library if this was the last component using this tag\n        if is_tag_empty and tag in self.library.tags:\n            del self.library.tags[tag]\n\n    del self._registry[name]\n
    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.register","title":"register","text":"
    register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]\n

    Class decorator to register a component.

    Usage:

    @register(\"my_component\")\nclass MyComponent(Component):\n    ...\n

    Optionally specify which ComponentRegistry the component should be registered to by setting the registry kwarg:

    my_lib = django.template.Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n    ...\n
    Source code in src/django_components/component_registry.py
    def register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]:\n    \"\"\"\n    Class decorator to register a component.\n\n    Usage:\n\n    ```py\n    @register(\"my_component\")\n    class MyComponent(Component):\n        ...\n    ```\n\n    Optionally specify which `ComponentRegistry` the component should be registered to by\n    setting the `registry` kwarg:\n\n    ```py\n    my_lib = django.template.Library()\n    my_reg = ComponentRegistry(library=my_lib)\n\n    @register(\"my_component\", registry=my_reg)\n    class MyComponent(Component):\n        ...\n    ```\n    \"\"\"\n    if registry is None:\n        registry = _the_registry\n\n    def decorator(component: _TComp) -> _TComp:\n        registry.register(name=name, component=component)\n        return component\n\n    return decorator\n
    "},{"location":"reference/django_components/components/","title":"Index","text":""},{"location":"reference/django_components/components/#django_components.components","title":"components","text":""},{"location":"reference/django_components/components/#django_components.components.dynamic","title":"dynamic","text":""},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent","title":"DynamicComponent","text":"
    DynamicComponent(\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,\n)\n

    Bases: Component

    Dynamic component - This component takes inputs and renders the outputs depending on the is and registry arguments.

    • is - required - The component class or registered name of the component that will be rendered in this place.

    • registry - optional - Specify the registry to search for the registered name. If omitted, all registries are searched.

    Source code in src/django_components/component.py
    def __init__(\n    self,\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,  # noqa F811\n):\n    # When user first instantiates the component class before calling\n    # `render` or `render_to_response`, then we want to allow the render\n    # function to make use of the instantiated object.\n    #\n    # So while `MyComp.render()` creates a new instance of MyComp internally,\n    # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n    # already-instantiated object.\n    #\n    # To achieve that, we want to re-assign the class methods as instance methods.\n    # For that we have to \"unwrap\" the class methods via __func__.\n    # See https://stackoverflow.com/a/76706399/9788634\n    self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self)  # type: ignore\n    self.render = types.MethodType(self.__class__.render.__func__, self)  # type: ignore\n    self.as_view = types.MethodType(self.__class__.as_view.__func__, self)  # type: ignore\n\n    self.registered_name: Optional[str] = registered_name\n    self.outer_context: Context = outer_context or Context()\n    self.fill_content = fill_content or {}\n    self.component_id = component_id or gen_id()\n    self.registry = registry or registry_\n    self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n    # None == uninitialized, False == No types, Tuple == types\n    self._types: Optional[Union[Tuple[Any, Any, Any, Any], Literal[False]]] = None\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.Media","title":"Media class-attribute instance-attribute","text":"
    Media = ComponentMediaInput\n

    Defines JS and CSS media files associated with this component.

    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.css","title":"css class-attribute instance-attribute","text":"
    css: Optional[str] = None\n

    Inlined CSS associated with this component.

    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.input","title":"input property","text":"
    input: RenderInput[ArgsType, KwargsType, SlotsType]\n

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

    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.is_filled","title":"is_filled property","text":"
    is_filled: Dict[str, bool]\n

    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/django_components/components/#django_components.components.dynamic.DynamicComponent.js","title":"js class-attribute instance-attribute","text":"
    js: Optional[str] = None\n

    Inlined JS associated with this component.

    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.media","title":"media instance-attribute","text":"
    media: Media\n

    Normalized definition of JS and CSS media files associated with this component.

    NOTE: This field is generated from Component.Media class.

    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.response_class","title":"response_class class-attribute instance-attribute","text":"
    response_class = HttpResponse\n

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

    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.template_name","title":"template_name class-attribute instance-attribute","text":"
    template_name: Optional[str] = None\n

    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_name, get_template_name, template or get_template must be defined.

    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.as_view","title":"as_view classmethod","text":"
    as_view(**initkwargs: Any) -> ViewFn\n

    Shortcut for calling Component.View.as_view and passing component instance to it.

    Source code in src/django_components/component.py
    @classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n    \"\"\"\n    Shortcut for calling `Component.View.as_view` and passing component instance to it.\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    # Allow the View class to access this component via `self.component`\n    return comp.View.as_view(**initkwargs, component=comp)\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.get_template","title":"get_template","text":"
    get_template(context: Context) -> Optional[Union[str, Template]]\n

    Inlined Django template associated with this component. Can be a plain string or a Template instance.

    Only one of template_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n    \"\"\"\n    Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.get_template_name","title":"get_template_name","text":"
    get_template_name(context: Context) -> Optional[str]\n

    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_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template_name(self, context: Context) -> Optional[str]:\n    \"\"\"\n    Filepath to the Django template associated with this component.\n\n    The filepath must be relative to either the file where the component class was defined,\n    or one of the roots of `STATIFILES_DIRS`.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.inject","title":"inject","text":"
    inject(key: str, default: Optional[Any] = None) -> Any\n

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

    Source code in src/django_components/component.py
    def inject(self, key: str, default: Optional[Any] = None) -> Any:\n    \"\"\"\n    Use this method to retrieve the data that was passed to a `{% provide %}` tag\n    with the corresponding key.\n\n    To retrieve the data, `inject()` must be called inside a component that's\n    inside the `{% provide %}` tag.\n\n    You may also pass a default that will be used if the `provide` tag with given\n    key was NOT found.\n\n    This method mut be used inside the `get_context_data()` method and raises\n    an error if called elsewhere.\n\n    Example:\n\n    Given this template:\n    ```django\n    {% provide \"provider\" hello=\"world\" %}\n        {% component \"my_comp\" %}\n        {% endcomponent %}\n    {% endprovide %}\n    ```\n\n    And given this definition of \"my_comp\" component:\n    ```py\n    from django_components import Component, register\n\n    @register(\"my_comp\")\n    class MyComp(Component):\n        template = \"hi {{ data.hello }}!\"\n        def get_context_data(self):\n            data = self.inject(\"provider\")\n            return {\"data\": data}\n    ```\n\n    This renders into:\n    ```\n    hi world!\n    ```\n\n    As the `{{ data.hello }}` is taken from the \"provider\".\n    \"\"\"\n    if self.input is None:\n        raise RuntimeError(\n            f\"Method 'inject()' of component '{self.name}' was called outside of 'get_context_data()'\"\n        )\n\n    return get_injected_context_var(self.name, self.input.context, key, default)\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.on_render_after","title":"on_render_after","text":"
    on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\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.

    Source code in src/django_components/component.py
    def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n    \"\"\"\n    Hook that runs just after the component's template was rendered.\n    It receives the rendered output as the last argument.\n\n    You can use this hook to access the context or the template, but modifying\n    them won't have any effect.\n\n    To override the content that gets rendered, you can return a string or SafeString\n    from this hook.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.on_render_before","title":"on_render_before","text":"
    on_render_before(context: Context, template: Template) -> 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.

    Source code in src/django_components/component.py
    def on_render_before(self, context: Context, template: Template) -> None:\n    \"\"\"\n    Hook that runs just before the component's template is rendered.\n\n    You can use this hook to access or modify the context or the template.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.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) -> str\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render(\n    cls,\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) -> str:\n    \"\"\"\n    Render the component into a string.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    return comp._render(context, args, kwargs, slots, escape_slots_content)\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.render_css_dependencies","title":"render_css_dependencies","text":"
    render_css_dependencies() -> SafeString\n

    Render only CSS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_css_dependencies(self) -> SafeString:\n    \"\"\"Render only CSS dependencies available in the media class or provided as a string.\"\"\"\n    if self.css is not None:\n        return mark_safe(f\"<style>{self.css}</style>\")\n    return mark_safe(\"\\n\".join(self.media.render_css()))\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.render_dependencies","title":"render_dependencies","text":"
    render_dependencies() -> SafeString\n

    Helper function to render all dependencies for a component.

    Source code in src/django_components/component.py
    def render_dependencies(self) -> SafeString:\n    \"\"\"Helper function to render all dependencies for a component.\"\"\"\n    dependencies = []\n\n    css_deps = self.render_css_dependencies()\n    if css_deps:\n        dependencies.append(css_deps)\n\n    js_deps = self.render_js_dependencies()\n    if js_deps:\n        dependencies.append(js_deps)\n\n    return mark_safe(\"\\n\".join(dependencies))\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.render_js_dependencies","title":"render_js_dependencies","text":"
    render_js_dependencies() -> SafeString\n

    Render only JS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_js_dependencies(self) -> SafeString:\n    \"\"\"Render only JS dependencies available in the media class or provided as a string.\"\"\"\n    if self.js is not None:\n        return mark_safe(f\"<script>{self.js}</script>\")\n    return mark_safe(\"\\n\".join(self.media.render_js()))\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.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    *response_args: Any,\n    **response_kwargs: Any\n) -> HttpResponse\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render_to_response(\n    cls,\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    slots: Optional[SlotsType] = None,\n    escape_slots_content: bool = True,\n    args: Optional[ArgsType] = None,\n    kwargs: Optional[KwargsType] = None,\n    *response_args: Any,\n    **response_kwargs: Any,\n) -> HttpResponse:\n    \"\"\"\n    Render the component and wrap the content in the response class.\n\n    The response class is taken from `Component.response_class`. Defaults to `django.http.HttpResponse`.\n\n    This is the interface for the `django.views.View` class which allows us to\n    use components as Django views with `component.as_view()`.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Any additional args and kwargs are passed to the `response_class`.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    content = cls.render(\n        args=args,\n        kwargs=kwargs,\n        context=context,\n        slots=slots,\n        escape_slots_content=escape_slots_content,\n    )\n    return cls.response_class(content, *response_args, **response_kwargs)\n
    "},{"location":"reference/django_components/components/dynamic/","title":" dynamic","text":""},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic","title":"dynamic","text":""},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent","title":"DynamicComponent","text":"
    DynamicComponent(\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,\n)\n

    Bases: Component

    Dynamic component - This component takes inputs and renders the outputs depending on the is and registry arguments.

    • is - required - The component class or registered name of the component that will be rendered in this place.

    • registry - optional - Specify the registry to search for the registered name. If omitted, all registries are searched.

    Source code in src/django_components/component.py
    def __init__(\n    self,\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,  # noqa F811\n):\n    # When user first instantiates the component class before calling\n    # `render` or `render_to_response`, then we want to allow the render\n    # function to make use of the instantiated object.\n    #\n    # So while `MyComp.render()` creates a new instance of MyComp internally,\n    # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n    # already-instantiated object.\n    #\n    # To achieve that, we want to re-assign the class methods as instance methods.\n    # For that we have to \"unwrap\" the class methods via __func__.\n    # See https://stackoverflow.com/a/76706399/9788634\n    self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self)  # type: ignore\n    self.render = types.MethodType(self.__class__.render.__func__, self)  # type: ignore\n    self.as_view = types.MethodType(self.__class__.as_view.__func__, self)  # type: ignore\n\n    self.registered_name: Optional[str] = registered_name\n    self.outer_context: Context = outer_context or Context()\n    self.fill_content = fill_content or {}\n    self.component_id = component_id or gen_id()\n    self.registry = registry or registry_\n    self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n    # None == uninitialized, False == No types, Tuple == types\n    self._types: Optional[Union[Tuple[Any, Any, Any, Any], Literal[False]]] = None\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.Media","title":"Media class-attribute instance-attribute","text":"
    Media = ComponentMediaInput\n

    Defines JS and CSS media files associated with this component.

    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.css","title":"css class-attribute instance-attribute","text":"
    css: Optional[str] = None\n

    Inlined CSS associated with this component.

    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.input","title":"input property","text":"
    input: RenderInput[ArgsType, KwargsType, SlotsType]\n

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

    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.is_filled","title":"is_filled property","text":"
    is_filled: Dict[str, bool]\n

    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/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.js","title":"js class-attribute instance-attribute","text":"
    js: Optional[str] = None\n

    Inlined JS associated with this component.

    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.media","title":"media instance-attribute","text":"
    media: Media\n

    Normalized definition of JS and CSS media files associated with this component.

    NOTE: This field is generated from Component.Media class.

    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.response_class","title":"response_class class-attribute instance-attribute","text":"
    response_class = HttpResponse\n

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

    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.template_name","title":"template_name class-attribute instance-attribute","text":"
    template_name: Optional[str] = None\n

    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_name, get_template_name, template or get_template must be defined.

    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.as_view","title":"as_view classmethod","text":"
    as_view(**initkwargs: Any) -> ViewFn\n

    Shortcut for calling Component.View.as_view and passing component instance to it.

    Source code in src/django_components/component.py
    @classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n    \"\"\"\n    Shortcut for calling `Component.View.as_view` and passing component instance to it.\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    # Allow the View class to access this component via `self.component`\n    return comp.View.as_view(**initkwargs, component=comp)\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.get_template","title":"get_template","text":"
    get_template(context: Context) -> Optional[Union[str, Template]]\n

    Inlined Django template associated with this component. Can be a plain string or a Template instance.

    Only one of template_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n    \"\"\"\n    Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.get_template_name","title":"get_template_name","text":"
    get_template_name(context: Context) -> Optional[str]\n

    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_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template_name(self, context: Context) -> Optional[str]:\n    \"\"\"\n    Filepath to the Django template associated with this component.\n\n    The filepath must be relative to either the file where the component class was defined,\n    or one of the roots of `STATIFILES_DIRS`.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.inject","title":"inject","text":"
    inject(key: str, default: Optional[Any] = None) -> Any\n

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

    Source code in src/django_components/component.py
    def inject(self, key: str, default: Optional[Any] = None) -> Any:\n    \"\"\"\n    Use this method to retrieve the data that was passed to a `{% provide %}` tag\n    with the corresponding key.\n\n    To retrieve the data, `inject()` must be called inside a component that's\n    inside the `{% provide %}` tag.\n\n    You may also pass a default that will be used if the `provide` tag with given\n    key was NOT found.\n\n    This method mut be used inside the `get_context_data()` method and raises\n    an error if called elsewhere.\n\n    Example:\n\n    Given this template:\n    ```django\n    {% provide \"provider\" hello=\"world\" %}\n        {% component \"my_comp\" %}\n        {% endcomponent %}\n    {% endprovide %}\n    ```\n\n    And given this definition of \"my_comp\" component:\n    ```py\n    from django_components import Component, register\n\n    @register(\"my_comp\")\n    class MyComp(Component):\n        template = \"hi {{ data.hello }}!\"\n        def get_context_data(self):\n            data = self.inject(\"provider\")\n            return {\"data\": data}\n    ```\n\n    This renders into:\n    ```\n    hi world!\n    ```\n\n    As the `{{ data.hello }}` is taken from the \"provider\".\n    \"\"\"\n    if self.input is None:\n        raise RuntimeError(\n            f\"Method 'inject()' of component '{self.name}' was called outside of 'get_context_data()'\"\n        )\n\n    return get_injected_context_var(self.name, self.input.context, key, default)\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.on_render_after","title":"on_render_after","text":"
    on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\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.

    Source code in src/django_components/component.py
    def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n    \"\"\"\n    Hook that runs just after the component's template was rendered.\n    It receives the rendered output as the last argument.\n\n    You can use this hook to access the context or the template, but modifying\n    them won't have any effect.\n\n    To override the content that gets rendered, you can return a string or SafeString\n    from this hook.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.on_render_before","title":"on_render_before","text":"
    on_render_before(context: Context, template: Template) -> 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.

    Source code in src/django_components/component.py
    def on_render_before(self, context: Context, template: Template) -> None:\n    \"\"\"\n    Hook that runs just before the component's template is rendered.\n\n    You can use this hook to access or modify the context or the template.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.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) -> str\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render(\n    cls,\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) -> str:\n    \"\"\"\n    Render the component into a string.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    return comp._render(context, args, kwargs, slots, escape_slots_content)\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.render_css_dependencies","title":"render_css_dependencies","text":"
    render_css_dependencies() -> SafeString\n

    Render only CSS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_css_dependencies(self) -> SafeString:\n    \"\"\"Render only CSS dependencies available in the media class or provided as a string.\"\"\"\n    if self.css is not None:\n        return mark_safe(f\"<style>{self.css}</style>\")\n    return mark_safe(\"\\n\".join(self.media.render_css()))\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.render_dependencies","title":"render_dependencies","text":"
    render_dependencies() -> SafeString\n

    Helper function to render all dependencies for a component.

    Source code in src/django_components/component.py
    def render_dependencies(self) -> SafeString:\n    \"\"\"Helper function to render all dependencies for a component.\"\"\"\n    dependencies = []\n\n    css_deps = self.render_css_dependencies()\n    if css_deps:\n        dependencies.append(css_deps)\n\n    js_deps = self.render_js_dependencies()\n    if js_deps:\n        dependencies.append(js_deps)\n\n    return mark_safe(\"\\n\".join(dependencies))\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.render_js_dependencies","title":"render_js_dependencies","text":"
    render_js_dependencies() -> SafeString\n

    Render only JS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_js_dependencies(self) -> SafeString:\n    \"\"\"Render only JS dependencies available in the media class or provided as a string.\"\"\"\n    if self.js is not None:\n        return mark_safe(f\"<script>{self.js}</script>\")\n    return mark_safe(\"\\n\".join(self.media.render_js()))\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.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    *response_args: Any,\n    **response_kwargs: Any\n) -> HttpResponse\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render_to_response(\n    cls,\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    slots: Optional[SlotsType] = None,\n    escape_slots_content: bool = True,\n    args: Optional[ArgsType] = None,\n    kwargs: Optional[KwargsType] = None,\n    *response_args: Any,\n    **response_kwargs: Any,\n) -> HttpResponse:\n    \"\"\"\n    Render the component and wrap the content in the response class.\n\n    The response class is taken from `Component.response_class`. Defaults to `django.http.HttpResponse`.\n\n    This is the interface for the `django.views.View` class which allows us to\n    use components as Django views with `component.as_view()`.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Any additional args and kwargs are passed to the `response_class`.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    content = cls.render(\n        args=args,\n        kwargs=kwargs,\n        context=context,\n        slots=slots,\n        escape_slots_content=escape_slots_content,\n    )\n    return cls.response_class(content, *response_args, **response_kwargs)\n
    "},{"location":"reference/django_components/context/","title":" context","text":""},{"location":"reference/django_components/context/#django_components.context","title":"context","text":"

    This file centralizes various ways we use Django's Context class pass data across components, nodes, slots, and contexts.

    You can think of the Context as our storage system.

    "},{"location":"reference/django_components/context/#django_components.context.copy_forloop_context","title":"copy_forloop_context","text":"
    copy_forloop_context(from_context: Context, to_context: Context) -> None\n

    Forward the info about the current loop

    Source code in src/django_components/context.py
    def copy_forloop_context(from_context: Context, to_context: Context) -> None:\n    \"\"\"Forward the info about the current loop\"\"\"\n    # Note that the ForNode (which implements for loop behavior) does not\n    # only add the `forloop` key, but also keys corresponding to the loop elements\n    # So if the loop syntax is `{% for my_val in my_lists %}`, then ForNode also\n    # sets a `my_val` key.\n    # For this reason, instead of copying individual keys, we copy the whole stack layer\n    # set by ForNode.\n    if \"forloop\" in from_context:\n        forloop_dict_index = find_last_index(from_context.dicts, lambda d: \"forloop\" in d)\n        to_context.update(from_context.dicts[forloop_dict_index])\n
    "},{"location":"reference/django_components/context/#django_components.context.get_injected_context_var","title":"get_injected_context_var","text":"
    get_injected_context_var(component_name: str, context: Context, key: str, default: Optional[Any] = None) -> Any\n

    Retrieve a 'provided' field. The field MUST have been previously 'provided' by the component's ancestors using the {% provide %} template tag.

    Source code in src/django_components/context.py
    def get_injected_context_var(\n    component_name: str,\n    context: Context,\n    key: str,\n    default: Optional[Any] = None,\n) -> Any:\n    \"\"\"\n    Retrieve a 'provided' field. The field MUST have been previously 'provided'\n    by the component's ancestors using the `{% provide %}` template tag.\n    \"\"\"\n    # NOTE: For simplicity, we keep the provided values directly on the context.\n    # This plays nicely with Django's Context, which behaves like a stack, so \"newer\"\n    # values overshadow the \"older\" ones.\n    internal_key = _INJECT_CONTEXT_KEY_PREFIX + key\n\n    # Return provided value if found\n    if internal_key in context:\n        return context[internal_key]\n\n    # If a default was given, return that\n    if default is not None:\n        return default\n\n    # Otherwise raise error\n    raise KeyError(\n        f\"Component '{component_name}' tried to inject a variable '{key}' before it was provided.\"\n        f\" To fix this, make sure that at least one ancestor of component '{component_name}' has\"\n        f\" the variable '{key}' in their 'provide' attribute.\"\n    )\n
    "},{"location":"reference/django_components/context/#django_components.context.prepare_context","title":"prepare_context","text":"
    prepare_context(context: Context, component_id: str) -> None\n

    Initialize the internal context state.

    Source code in src/django_components/context.py
    def prepare_context(\n    context: Context,\n    component_id: str,\n) -> None:\n    \"\"\"Initialize the internal context state.\"\"\"\n    # Initialize mapping dicts within this rendering run.\n    # This is shared across the whole render chain, thus we set it only once.\n    if _FILLED_SLOTS_CONTENT_CONTEXT_KEY not in context:\n        context[_FILLED_SLOTS_CONTENT_CONTEXT_KEY] = {}\n\n    set_component_id(context, component_id)\n
    "},{"location":"reference/django_components/context/#django_components.context.set_component_id","title":"set_component_id","text":"
    set_component_id(context: Context, component_id: str) -> None\n

    We use the Context object to pass down info on inside of which component we are currently rendering.

    Source code in src/django_components/context.py
    def set_component_id(context: Context, component_id: str) -> None:\n    \"\"\"\n    We use the Context object to pass down info on inside of which component\n    we are currently rendering.\n    \"\"\"\n    context[_CURRENT_COMP_CONTEXT_KEY] = component_id\n
    "},{"location":"reference/django_components/context/#django_components.context.set_provided_context_var","title":"set_provided_context_var","text":"
    set_provided_context_var(context: Context, key: str, provided_kwargs: Dict[str, Any]) -> None\n

    'Provide' given data under given key. In other words, this data can be retrieved using self.inject(key) inside of get_context_data() method of components that are nested inside the {% provide %} tag.

    Source code in src/django_components/context.py
    def set_provided_context_var(\n    context: Context,\n    key: str,\n    provided_kwargs: Dict[str, Any],\n) -> None:\n    \"\"\"\n    'Provide' given data under given key. In other words, this data can be retrieved\n    using `self.inject(key)` inside of `get_context_data()` method of components that\n    are nested inside the `{% provide %}` tag.\n    \"\"\"\n    # NOTE: We raise TemplateSyntaxError since this func should be called only from\n    # within template.\n    if not key:\n        raise TemplateSyntaxError(\n            \"Provide tag received an empty string. Key must be non-empty and a valid identifier.\"\n        )\n    if not key.isidentifier():\n        raise TemplateSyntaxError(\n            \"Provide tag received a non-identifier string. Key must be non-empty and a valid identifier.\"\n        )\n\n    # We turn the kwargs into a NamedTuple so that the object that's \"provided\"\n    # is immutable. This ensures that the data returned from `inject` will always\n    # have all the keys that were passed to the `provide` tag.\n    tpl_cls = namedtuple(\"DepInject\", provided_kwargs.keys())  # type: ignore[misc]\n    payload = tpl_cls(**provided_kwargs)\n\n    internal_key = _INJECT_CONTEXT_KEY_PREFIX + key\n    context[internal_key] = payload\n
    "},{"location":"reference/django_components/expression/","title":" expression","text":""},{"location":"reference/django_components/expression/#django_components.expression","title":"expression","text":""},{"location":"reference/django_components/expression/#django_components.expression.Operator","title":"Operator","text":"

    Bases: ABC

    Operator describes something that somehow changes the inputs to template tags (the {% %}).

    For example, a SpreadOperator inserts one or more kwargs at the specified location.

    "},{"location":"reference/django_components/expression/#django_components.expression.SpreadOperator","title":"SpreadOperator","text":"
    SpreadOperator(expr: Expression)\n

    Bases: Operator

    Operator that inserts one or more kwargs at the specified location.

    Source code in src/django_components/expression.py
    def __init__(self, expr: Expression) -> None:\n    self.expr = expr\n
    "},{"location":"reference/django_components/expression/#django_components.expression.process_aggregate_kwargs","title":"process_aggregate_kwargs","text":"
    process_aggregate_kwargs(kwargs: Mapping[str, Any]) -> Dict[str, Any]\n

    This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs start with some prefix delimited with : (e.g. attrs:).

    Example:

    process_component_kwargs({\"abc:one\": 1, \"abc:two\": 2, \"def:three\": 3, \"four\": 4})\n# {\"abc\": {\"one\": 1, \"two\": 2}, \"def\": {\"three\": 3}, \"four\": 4}\n

    We want to support a use case similar to Vue's fallthrough attributes. In other words, where a component author can designate a prop (input) which is a dict and which will be rendered as HTML attributes.

    This is useful for allowing component users to tweak styling or add event handling to the underlying HTML. E.g.:

    class=\"pa-4 d-flex text-black\" or @click.stop=\"alert('clicked!')\"

    So if the prop is attrs, and the component is called like so:

    {% component \"my_comp\" attrs=attrs %}\n

    then, if attrs is:

    {\"class\": \"text-red pa-4\", \"@click\": \"dispatch('my_event', 123)\"}\n

    and the component template is:

    <div {% html_attrs attrs add:class=\"extra-class\" %}></div>\n

    Then this renders:

    <div class=\"text-red pa-4 extra-class\" @click=\"dispatch('my_event', 123)\" ></div>\n

    However, this way it is difficult for the component user to define the attrs variable, especially if they want to combine static and dynamic values. Because they will need to pre-process the attrs dict.

    So, instead, we allow to \"aggregate\" props into a dict. So all props that start with attrs:, like attrs:class=\"text-red\", will be collected into a dict at key attrs.

    This provides sufficient flexiblity to make it easy for component users to provide \"fallthrough attributes\", and sufficiently easy for component authors to process that input while still being able to provide their own keys.

    Source code in src/django_components/expression.py
    def process_aggregate_kwargs(kwargs: Mapping[str, Any]) -> Dict[str, Any]:\n    \"\"\"\n    This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs\n    start with some prefix delimited with `:` (e.g. `attrs:`).\n\n    Example:\n    ```py\n    process_component_kwargs({\"abc:one\": 1, \"abc:two\": 2, \"def:three\": 3, \"four\": 4})\n    # {\"abc\": {\"one\": 1, \"two\": 2}, \"def\": {\"three\": 3}, \"four\": 4}\n    ```\n\n    ---\n\n    We want to support a use case similar to Vue's fallthrough attributes.\n    In other words, where a component author can designate a prop (input)\n    which is a dict and which will be rendered as HTML attributes.\n\n    This is useful for allowing component users to tweak styling or add\n    event handling to the underlying HTML. E.g.:\n\n    `class=\"pa-4 d-flex text-black\"` or `@click.stop=\"alert('clicked!')\"`\n\n    So if the prop is `attrs`, and the component is called like so:\n    ```django\n    {% component \"my_comp\" attrs=attrs %}\n    ```\n\n    then, if `attrs` is:\n    ```py\n    {\"class\": \"text-red pa-4\", \"@click\": \"dispatch('my_event', 123)\"}\n    ```\n\n    and the component template is:\n    ```django\n    <div {% html_attrs attrs add:class=\"extra-class\" %}></div>\n    ```\n\n    Then this renders:\n    ```html\n    <div class=\"text-red pa-4 extra-class\" @click=\"dispatch('my_event', 123)\" ></div>\n    ```\n\n    However, this way it is difficult for the component user to define the `attrs`\n    variable, especially if they want to combine static and dynamic values. Because\n    they will need to pre-process the `attrs` dict.\n\n    So, instead, we allow to \"aggregate\" props into a dict. So all props that start\n    with `attrs:`, like `attrs:class=\"text-red\"`, will be collected into a dict\n    at key `attrs`.\n\n    This provides sufficient flexiblity to make it easy for component users to provide\n    \"fallthrough attributes\", and sufficiently easy for component authors to process\n    that input while still being able to provide their own keys.\n    \"\"\"\n    processed_kwargs = {}\n    nested_kwargs: Dict[str, Dict[str, Any]] = {}\n    for key, val in kwargs.items():\n        if not is_aggregate_key(key):\n            processed_kwargs[key] = val\n            continue\n\n        # NOTE: Trim off the prefix from keys\n        prefix, sub_key = key.split(\":\", 1)\n        if prefix not in nested_kwargs:\n            nested_kwargs[prefix] = {}\n        nested_kwargs[prefix][sub_key] = val\n\n    # Assign aggregated values into normal input\n    for key, val in nested_kwargs.items():\n        if key in processed_kwargs:\n            raise TemplateSyntaxError(\n                f\"Received argument '{key}' both as a regular input ({key}=...)\"\n                f\" and as an aggregate dict ('{key}:key=...'). Must be only one of the two\"\n            )\n        processed_kwargs[key] = val\n\n    return processed_kwargs\n
    "},{"location":"reference/django_components/finders/","title":" finders","text":""},{"location":"reference/django_components/finders/#django_components.finders","title":"finders","text":""},{"location":"reference/django_components/finders/#django_components.finders.ComponentsFileSystemFinder","title":"ComponentsFileSystemFinder","text":"
    ComponentsFileSystemFinder(app_names: Any = None, *args: Any, **kwargs: Any)\n

    Bases: BaseFinder

    A static files finder based on FileSystemFinder.

    Differences: - This finder uses COMPONENTS.dirs setting to locate files instead of STATICFILES_DIRS. - Whether a file within COMPONENTS.dirs is considered a STATIC file is configured by COMPONENTS.static_files_allowed and COMPONENTS.forbidden_static_files. - If COMPONENTS.dirs is not set, defaults to settings.BASE_DIR / \"components\"

    Source code in src/django_components/finders.py
    def __init__(self, app_names: Any = None, *args: Any, **kwargs: Any) -> None:\n    component_dirs = [str(p) for p in get_dirs()]\n\n    # NOTE: The rest of the __init__ is the same as `django.contrib.staticfiles.finders.FileSystemFinder`,\n    # but using our locations instead of STATICFILES_DIRS.\n\n    # List of locations with static files\n    self.locations: List[Tuple[str, str]] = []\n\n    # Maps dir paths to an appropriate storage instance\n    self.storages: Dict[str, FileSystemStorage] = {}\n    for root in component_dirs:\n        if isinstance(root, (list, tuple)):\n            prefix, root = root\n        else:\n            prefix = \"\"\n        if (prefix, root) not in self.locations:\n            self.locations.append((prefix, root))\n    for prefix, root in self.locations:\n        filesystem_storage = FileSystemStorage(location=root)\n        filesystem_storage.prefix = prefix\n        self.storages[root] = filesystem_storage\n\n    super().__init__(*args, **kwargs)\n
    "},{"location":"reference/django_components/finders/#django_components.finders.ComponentsFileSystemFinder.find","title":"find","text":"
    find(path: str, all: bool = False) -> Union[List[str], str]\n

    Look for files in the extra locations as defined in COMPONENTS.dirs.

    Source code in src/django_components/finders.py
    def find(self, path: str, all: bool = False) -> Union[List[str], str]:\n    \"\"\"\n    Look for files in the extra locations as defined in COMPONENTS.dirs.\n    \"\"\"\n    matches: List[str] = []\n    for prefix, root in self.locations:\n        if root not in searched_locations:\n            searched_locations.append(root)\n        matched_path = self.find_location(root, path, prefix)\n        if matched_path:\n            if not all:\n                return matched_path\n            matches.append(matched_path)\n    return matches\n
    "},{"location":"reference/django_components/finders/#django_components.finders.ComponentsFileSystemFinder.find_location","title":"find_location","text":"
    find_location(root: str, path: str, prefix: Optional[str] = None) -> Optional[str]\n

    Find a requested static file in a location and return the found absolute path (or None if no match).

    Source code in src/django_components/finders.py
    def find_location(self, root: str, path: str, prefix: Optional[str] = None) -> Optional[str]:\n    \"\"\"\n    Find a requested static file in a location and return the found\n    absolute path (or ``None`` if no match).\n    \"\"\"\n    if prefix:\n        prefix = \"%s%s\" % (prefix, os.sep)\n        if not path.startswith(prefix):\n            return None\n        path = path.removeprefix(prefix)\n    path = safe_join(root, path)\n\n    if os.path.exists(path) and self._is_path_valid(path):\n        return path\n    return None\n
    "},{"location":"reference/django_components/finders/#django_components.finders.ComponentsFileSystemFinder.list","title":"list","text":"
    list(ignore_patterns: List[str]) -> Iterable[Tuple[str, FileSystemStorage]]\n

    List all files in all locations.

    Source code in src/django_components/finders.py
    def list(self, ignore_patterns: List[str]) -> Iterable[Tuple[str, FileSystemStorage]]:\n    \"\"\"\n    List all files in all locations.\n    \"\"\"\n    for prefix, root in self.locations:\n        # Skip nonexistent directories.\n        if os.path.isdir(root):\n            storage = self.storages[root]\n            for path in get_files(storage, ignore_patterns):\n                if self._is_path_valid(path):\n                    yield path, storage\n
    "},{"location":"reference/django_components/library/","title":" library","text":""},{"location":"reference/django_components/library/#django_components.library","title":"library","text":"

    Module for interfacing with Django's Library (django.template.library)

    "},{"location":"reference/django_components/library/#django_components.library.PROTECTED_TAGS","title":"PROTECTED_TAGS module-attribute","text":"
    PROTECTED_TAGS = [\n    \"component_dependencies\",\n    \"component_css_dependencies\",\n    \"component_js_dependencies\",\n    \"fill\",\n    \"html_attrs\",\n    \"provide\",\n    \"slot\",\n]\n

    These are the names that users cannot choose for their components, as they would conflict with other tags in the Library.

    "},{"location":"reference/django_components/logger/","title":" logger","text":""},{"location":"reference/django_components/logger/#django_components.logger","title":"logger","text":""},{"location":"reference/django_components/logger/#django_components.logger.trace","title":"trace","text":"
    trace(logger: Logger, message: str, *args: Any, **kwargs: Any) -> None\n

    TRACE level logger.

    To display TRACE logs, set the logging level to 5.

    Example:

    LOGGING = {\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\": 5,\n            \"handlers\": [\"console\"],\n        },\n    },\n}\n

    Source code in src/django_components/logger.py
    def trace(logger: logging.Logger, message: str, *args: Any, **kwargs: Any) -> None:\n    \"\"\"\n    TRACE level logger.\n\n    To display TRACE logs, set the logging level to 5.\n\n    Example:\n    ```py\n    LOGGING = {\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\": 5,\n                \"handlers\": [\"console\"],\n            },\n        },\n    }\n    ```\n    \"\"\"\n    if actual_trace_level_num == -1:\n        setup_logging()\n    if logger.isEnabledFor(actual_trace_level_num):\n        logger.log(actual_trace_level_num, message, *args, **kwargs)\n
    "},{"location":"reference/django_components/logger/#django_components.logger.trace_msg","title":"trace_msg","text":"
    trace_msg(\n    action: Literal[\"PARSE\", \"ASSOC\", \"RENDR\", \"GET\", \"SET\"],\n    node_type: Literal[\"COMP\", \"FILL\", \"SLOT\", \"PROVIDE\", \"N/A\"],\n    node_name: str,\n    node_id: str,\n    msg: str = \"\",\n    component_id: Optional[str] = None,\n) -> None\n

    TRACE level logger with opinionated format for tracing interaction of components, nodes, and slots. Formats messages like so:

    \"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"

    Source code in src/django_components/logger.py
    def trace_msg(\n    action: Literal[\"PARSE\", \"ASSOC\", \"RENDR\", \"GET\", \"SET\"],\n    node_type: Literal[\"COMP\", \"FILL\", \"SLOT\", \"PROVIDE\", \"N/A\"],\n    node_name: str,\n    node_id: str,\n    msg: str = \"\",\n    component_id: Optional[str] = None,\n) -> None:\n    \"\"\"\n    TRACE level logger with opinionated format for tracing interaction of components,\n    nodes, and slots. Formats messages like so:\n\n    `\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"`\n    \"\"\"\n    msg_prefix = \"\"\n    if action == \"ASSOC\":\n        if not component_id:\n            raise ValueError(\"component_id must be set for the ASSOC action\")\n        msg_prefix = f\"TO COMP {component_id}\"\n    elif action == \"RENDR\" and node_type == \"FILL\":\n        if not component_id:\n            raise ValueError(\"component_id must be set for the RENDER action\")\n        msg_prefix = f\"FOR COMP {component_id}\"\n\n    msg_parts = [f\"{action} {node_type} {node_name} ID {node_id}\", *([msg_prefix] if msg_prefix else []), msg]\n    full_msg = \" \".join(msg_parts)\n\n    # NOTE: When debugging tests during development, it may be easier to change\n    # this to `print()`\n    trace(logger, full_msg)\n
    "},{"location":"reference/django_components/management/","title":"Index","text":""},{"location":"reference/django_components/management/#django_components.management","title":"management","text":""},{"location":"reference/django_components/management/commands/","title":"Index","text":""},{"location":"reference/django_components/management/commands/#django_components.management.commands","title":"commands","text":""},{"location":"reference/django_components/management/commands/startcomponent/","title":" startcomponent","text":""},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent","title":"startcomponent","text":""},{"location":"reference/django_components/management/commands/upgradecomponent/","title":" upgradecomponent","text":""},{"location":"reference/django_components/management/commands/upgradecomponent/#django_components.management.commands.upgradecomponent","title":"upgradecomponent","text":""},{"location":"reference/django_components/middleware/","title":" middleware","text":""},{"location":"reference/django_components/middleware/#django_components.middleware","title":"middleware","text":""},{"location":"reference/django_components/middleware/#django_components.middleware.ComponentDependencyMiddleware","title":"ComponentDependencyMiddleware","text":"
    ComponentDependencyMiddleware(get_response: Callable[[HttpRequest], HttpResponse])\n

    Middleware that inserts CSS/JS dependencies for all rendered components at points marked with template tags.

    Source code in src/django_components/middleware.py
    def __init__(self, get_response: \"Callable[[HttpRequest], HttpResponse]\") -> None:\n    self.get_response = get_response\n\n    if iscoroutinefunction(self.get_response):\n        markcoroutinefunction(self)\n
    "},{"location":"reference/django_components/middleware/#django_components.middleware.DependencyReplacer","title":"DependencyReplacer","text":"
    DependencyReplacer(css_string: bytes, js_string: bytes)\n

    Replacer for use in re.sub that replaces the first placeholder CSS and JS tags it encounters and removes any subsequent ones.

    Source code in src/django_components/middleware.py
    def __init__(self, css_string: bytes, js_string: bytes) -> None:\n    self.js_string = js_string\n    self.css_string = css_string\n
    "},{"location":"reference/django_components/middleware/#django_components.middleware.join_media","title":"join_media","text":"
    join_media(components: Iterable[Component]) -> Media\n

    Return combined media object for iterable of components.

    Source code in src/django_components/middleware.py
    def join_media(components: Iterable[\"Component\"]) -> Media:\n    \"\"\"Return combined media object for iterable of components.\"\"\"\n\n    return sum([component.media for component in components], Media())\n
    "},{"location":"reference/django_components/node/","title":" node","text":""},{"location":"reference/django_components/node/#django_components.node","title":"node","text":""},{"location":"reference/django_components/node/#django_components.node.BaseNode","title":"BaseNode","text":"
    BaseNode(\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    args: Optional[List[Expression]] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n)\n

    Bases: Node

    Shared behavior for our subclasses of Django's Node

    Source code in src/django_components/node.py
    def __init__(\n    self,\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    args: Optional[List[Expression]] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n):\n    self.nodelist = nodelist or NodeList()\n    self.node_id = node_id or gen_id()\n    self.args = args or []\n    self.kwargs = kwargs or RuntimeKwargs({})\n
    "},{"location":"reference/django_components/node/#django_components.node.get_node_children","title":"get_node_children","text":"
    get_node_children(node: Node, context: Optional[Context] = None) -> NodeList\n

    Get child Nodes from Node's nodelist atribute.

    This function is taken from get_nodes_by_type method of django.template.base.Node.

    Source code in src/django_components/node.py
    def get_node_children(node: Node, context: Optional[Context] = None) -> NodeList:\n    \"\"\"\n    Get child Nodes from Node's nodelist atribute.\n\n    This function is taken from `get_nodes_by_type` method of `django.template.base.Node`.\n    \"\"\"\n    # Special case - {% extends %} tag - Load the template and go deeper\n    if isinstance(node, ExtendsNode):\n        # NOTE: When {% extends %} node is being parsed, it collects all remaining template\n        # under node.nodelist.\n        # Hence, when we come across ExtendsNode in the template, we:\n        # 1. Go over all nodes in the template using `node.nodelist`\n        # 2. Go over all nodes in the \"parent\" template, via `node.get_parent`\n        nodes = NodeList()\n        nodes.extend(node.nodelist)\n        template = node.get_parent(context)\n        nodes.extend(template.nodelist)\n        return nodes\n\n    # Special case - {% include %} tag - Load the template and go deeper\n    elif isinstance(node, IncludeNode):\n        template = get_template_for_include_node(node, context)\n        return template.nodelist\n\n    nodes = NodeList()\n    for attr in node.child_nodelists:\n        nodelist = getattr(node, attr, [])\n        if nodelist:\n            nodes.extend(nodelist)\n    return nodes\n
    "},{"location":"reference/django_components/node/#django_components.node.get_template_for_include_node","title":"get_template_for_include_node","text":"
    get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template\n

    This snippet is taken directly from IncludeNode.render(). Unfortunately the render logic doesn't separate out template loading logic from rendering, so we have to copy the method.

    Source code in src/django_components/node.py
    def get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template:\n    \"\"\"\n    This snippet is taken directly from `IncludeNode.render()`. Unfortunately the\n    render logic doesn't separate out template loading logic from rendering, so we\n    have to copy the method.\n    \"\"\"\n    template = include_node.template.resolve(context)\n    # Does this quack like a Template?\n    if not callable(getattr(template, \"render\", None)):\n        # If not, try the cache and select_template().\n        template_name = template or ()\n        if isinstance(template_name, str):\n            template_name = (\n                construct_relative_path(\n                    include_node.origin.template_name,\n                    template_name,\n                ),\n            )\n        else:\n            template_name = tuple(template_name)\n        cache = context.render_context.dicts[0].setdefault(include_node, {})\n        template = cache.get(template_name)\n        if template is None:\n            template = context.template.engine.select_template(template_name)\n            cache[template_name] = template\n    # Use the base.Template of a backends.django.Template.\n    elif hasattr(template, \"template\"):\n        template = template.template\n    return template\n
    "},{"location":"reference/django_components/node/#django_components.node.walk_nodelist","title":"walk_nodelist","text":"
    walk_nodelist(nodes: NodeList, callback: Callable[[Node], Optional[str]], context: Optional[Context] = None) -> None\n

    Recursively walk a NodeList, calling callback for each Node.

    Source code in src/django_components/node.py
    def walk_nodelist(\n    nodes: NodeList,\n    callback: Callable[[Node], Optional[str]],\n    context: Optional[Context] = None,\n) -> None:\n    \"\"\"Recursively walk a NodeList, calling `callback` for each Node.\"\"\"\n    node_queue: List[NodeTraverse] = [NodeTraverse(node=node, parent=None) for node in nodes]\n    while len(node_queue):\n        traverse = node_queue.pop()\n        callback(traverse)\n        child_nodes = get_node_children(traverse.node, context)\n        child_traverses = [NodeTraverse(node=child_node, parent=traverse) for child_node in child_nodes]\n        node_queue.extend(child_traverses)\n
    "},{"location":"reference/django_components/provide/","title":" provide","text":""},{"location":"reference/django_components/provide/#django_components.provide","title":"provide","text":""},{"location":"reference/django_components/provide/#django_components.provide.ProvideNode","title":"ProvideNode","text":"
    ProvideNode(nodelist: NodeList, trace_id: str, node_id: Optional[str] = None, kwargs: Optional[RuntimeKwargs] = None)\n

    Bases: BaseNode

    Implementation of the {% provide %} tag. For more info see Component.inject.

    Source code in src/django_components/provide.py
    def __init__(\n    self,\n    nodelist: NodeList,\n    trace_id: str,\n    node_id: Optional[str] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n):\n    super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n    self.nodelist = nodelist\n    self.node_id = node_id or gen_id()\n    self.trace_id = trace_id\n    self.kwargs = kwargs or RuntimeKwargs({})\n
    "},{"location":"reference/django_components/slots/","title":" slots","text":""},{"location":"reference/django_components/slots/#django_components.slots","title":"slots","text":""},{"location":"reference/django_components/slots/#django_components.slots.FillContent","title":"FillContent dataclass","text":"
    FillContent(content_func: SlotFunc[TSlotData], slot_default_var: Optional[SlotDefaultName], slot_data_var: Optional[SlotDataName])\n

    Bases: Generic[TSlotData]

    This represents content set with the {% fill %} tag, e.g.:

    {% component \"my_comp\" %}\n    {% fill \"first_slot\" %} <--- This\n        hi\n        {{ my_var }}\n        hello\n    {% endfill %}\n{% endcomponent %}\n
    "},{"location":"reference/django_components/slots/#django_components.slots.FillNode","title":"FillNode","text":"
    FillNode(nodelist: NodeList, kwargs: RuntimeKwargs, trace_id: str, node_id: Optional[str] = None, is_implicit: bool = False)\n

    Bases: BaseNode

    Set when a component tag pair is passed template content that excludes fill tags. Nodes of this type contribute their nodelists to slots marked as 'default'.

    Source code in src/django_components/slots.py
    def __init__(\n    self,\n    nodelist: NodeList,\n    kwargs: RuntimeKwargs,\n    trace_id: str,\n    node_id: Optional[str] = None,\n    is_implicit: bool = False,\n):\n    super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n    self.is_implicit = is_implicit\n    self.trace_id = trace_id\n    self.component_id: Optional[str] = None\n
    "},{"location":"reference/django_components/slots/#django_components.slots.Slot","title":"Slot","text":"

    Bases: NamedTuple

    This represents content set with the {% slot %} tag, e.g.:

    {% slot \"my_comp\" default %} <--- This\n    hi\n    {{ my_var }}\n    hello\n{% endslot %}\n
    "},{"location":"reference/django_components/slots/#django_components.slots.SlotFill","title":"SlotFill dataclass","text":"
    SlotFill(\n    name: str,\n    escaped_name: str,\n    is_filled: bool,\n    content_func: SlotFunc[TSlotData],\n    slot_default_var: Optional[SlotDefaultName],\n    slot_data_var: Optional[SlotDataName],\n)\n

    Bases: Generic[TSlotData]

    SlotFill describes what WILL be rendered.

    It is a Slot that has been resolved against FillContents passed to a Component.

    "},{"location":"reference/django_components/slots/#django_components.slots.SlotNode","title":"SlotNode","text":"
    SlotNode(\n    nodelist: NodeList,\n    trace_id: str,\n    node_id: Optional[str] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n    is_required: bool = False,\n    is_default: bool = False,\n)\n

    Bases: BaseNode

    Source code in src/django_components/slots.py
    def __init__(\n    self,\n    nodelist: NodeList,\n    trace_id: str,\n    node_id: Optional[str] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n    is_required: bool = False,\n    is_default: bool = False,\n):\n    super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n    self.is_required = is_required\n    self.is_default = is_default\n    self.trace_id = trace_id\n
    "},{"location":"reference/django_components/slots/#django_components.slots.SlotRef","title":"SlotRef","text":"
    SlotRef(slot: SlotNode, context: Context)\n

    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.

    Source code in src/django_components/slots.py
    def __init__(self, slot: \"SlotNode\", context: Context):\n    self._slot = slot\n    self._context = context\n
    "},{"location":"reference/django_components/slots/#django_components.slots.parse_slot_fill_nodes_from_component_nodelist","title":"parse_slot_fill_nodes_from_component_nodelist","text":"
    parse_slot_fill_nodes_from_component_nodelist(nodes: Tuple[Node, ...], ignored_nodes: Tuple[Type[Node]]) -> List[FillNode]\n

    Given a component body (django.template.NodeList), find all slot fills, whether defined explicitly with {% fill %} or implicitly.

    So if we have a component body:

    {% component \"mycomponent\" %}\n    {% fill \"first_fill\" %}\n        Hello!\n    {% endfill %}\n    {% fill \"second_fill\" %}\n        Hello too!\n    {% endfill %}\n{% endcomponent %}\n
    Then this function returns the nodes (django.template.Node) for fill \"first_fill\" and fill \"second_fill\".

    Source code in src/django_components/slots.py
    @lazy_cache(lambda: lru_cache(maxsize=app_settings.TEMPLATE_CACHE_SIZE))\ndef parse_slot_fill_nodes_from_component_nodelist(\n    nodes: Tuple[Node, ...],\n    ignored_nodes: Tuple[Type[Node]],\n) -> List[FillNode]:\n    \"\"\"\n    Given a component body (`django.template.NodeList`), find all slot fills,\n    whether defined explicitly with `{% fill %}` or implicitly.\n\n    So if we have a component body:\n    ```django\n    {% component \"mycomponent\" %}\n        {% fill \"first_fill\" %}\n            Hello!\n        {% endfill %}\n        {% fill \"second_fill\" %}\n            Hello too!\n        {% endfill %}\n    {% endcomponent %}\n    ```\n    Then this function returns the nodes (`django.template.Node`) for `fill \"first_fill\"`\n    and `fill \"second_fill\"`.\n    \"\"\"\n    fill_nodes: List[FillNode] = []\n    if nodelist_has_content(nodes):\n        for parse_fn in (\n            _try_parse_as_default_fill,\n            _try_parse_as_named_fill_tag_set,\n        ):\n            curr_fill_nodes = parse_fn(nodes, ignored_nodes)\n            if curr_fill_nodes:\n                fill_nodes = curr_fill_nodes\n                break\n        else:\n            raise TemplateSyntaxError(\n                \"Illegal content passed to 'component' tag pair. \"\n                \"Possible causes: 1) Explicit 'fill' tags cannot occur alongside other \"\n                \"tags except comment tags; 2) Default (default slot-targeting) content \"\n                \"is mixed with explict 'fill' tags.\"\n            )\n    return fill_nodes\n
    "},{"location":"reference/django_components/slots/#django_components.slots.resolve_slots","title":"resolve_slots","text":"
    resolve_slots(\n    context: Context,\n    template: Template,\n    component_name: Optional[str],\n    fill_content: Dict[SlotName, FillContent],\n    is_dynamic_component: bool = False,\n) -> Tuple[Dict[SlotId, Slot], Dict[SlotId, SlotFill]]\n

    Search the template for all SlotNodes, and associate the slots with the given fills.

    Returns tuple of: - Slots defined in the component's Template with {% slot %} tag - SlotFills (AKA slots matched with fills) describing what will be rendered for each slot.

    Source code in src/django_components/slots.py
    def resolve_slots(\n    context: Context,\n    template: Template,\n    component_name: Optional[str],\n    fill_content: Dict[SlotName, FillContent],\n    is_dynamic_component: bool = False,\n) -> Tuple[Dict[SlotId, Slot], Dict[SlotId, SlotFill]]:\n    \"\"\"\n    Search the template for all SlotNodes, and associate the slots\n    with the given fills.\n\n    Returns tuple of:\n    - Slots defined in the component's Template with `{% slot %}` tag\n    - SlotFills (AKA slots matched with fills) describing what will be rendered for each slot.\n    \"\"\"\n    slot_fills = {\n        name: SlotFill(\n            name=name,\n            escaped_name=_escape_slot_name(name),\n            is_filled=True,\n            content_func=fill.content_func,\n            slot_default_var=fill.slot_default_var,\n            slot_data_var=fill.slot_data_var,\n        )\n        for name, fill in fill_content.items()\n    }\n\n    slots: Dict[SlotId, Slot] = {}\n    # This holds info on which slot (key) has which slots nested in it (value list)\n    slot_children: Dict[SlotId, List[SlotId]] = {}\n    all_nested_slots: Set[SlotId] = set()\n\n    def on_node(entry: NodeTraverse) -> None:\n        node = entry.node\n        if not isinstance(node, SlotNode):\n            return\n\n        slot_name, _ = node.resolve_kwargs(context, component_name)\n\n        # 1. Collect slots\n        # Basically we take all the important info form the SlotNode, so the logic is\n        # less coupled to Django's Template/Node. Plain tuples should also help with\n        # troubleshooting.\n        slot = Slot(\n            id=node.node_id,\n            name=slot_name,\n            nodelist=node.nodelist,\n            is_default=node.is_default,\n            is_required=node.is_required,\n        )\n        slots[node.node_id] = slot\n\n        # 2. Figure out which Slots are nested in other Slots, so we can render\n        # them from outside-inwards, so we can skip inner Slots if fills are provided.\n        # We should end up with a graph-like data like:\n        # - 0001: [0002]\n        # - 0002: []\n        # - 0003: [0004]\n        # In other words, the data tells us that slot ID 0001 is PARENT of slot 0002.\n        parent_slot_entry = entry.parent\n        while parent_slot_entry is not None:\n            if not isinstance(parent_slot_entry.node, SlotNode):\n                parent_slot_entry = parent_slot_entry.parent\n                continue\n\n            parent_slot_id = parent_slot_entry.node.node_id\n            if parent_slot_id not in slot_children:\n                slot_children[parent_slot_id] = []\n            slot_children[parent_slot_id].append(node.node_id)\n            all_nested_slots.add(node.node_id)\n            break\n\n    walk_nodelist(template.nodelist, on_node, context)\n\n    # 3. Figure out which slot the default/implicit fill belongs to\n    slot_fills = _resolve_default_slot(\n        template_name=template.name,\n        component_name=component_name,\n        slots=slots,\n        slot_fills=slot_fills,\n        is_dynamic_component=is_dynamic_component,\n    )\n\n    # 4. Detect any errors with slots/fills\n    # NOTE: We ignore errors for the dynamic component, as the underlying component\n    # will deal with it\n    if not is_dynamic_component:\n        _report_slot_errors(slots, slot_fills, component_name)\n\n    # 5. Find roots of the slot relationships\n    top_level_slot_ids: List[SlotId] = [node_id for node_id in slots.keys() if node_id not in all_nested_slots]\n\n    # 6. Walk from out-most slots inwards, and decide whether and how\n    # we will render each slot.\n    resolved_slots: Dict[SlotId, SlotFill] = {}\n    slot_ids_queue = deque([*top_level_slot_ids])\n    while len(slot_ids_queue):\n        slot_id = slot_ids_queue.pop()\n        slot = slots[slot_id]\n\n        # Check if there is a slot fill for given slot name\n        if slot.name in slot_fills:\n            # If yes, we remember which slot we want to replace with already-rendered fills\n            resolved_slots[slot_id] = slot_fills[slot.name]\n            # Since the fill cannot include other slots, we can leave this path\n            continue\n        else:\n            # If no, then the slot is NOT filled, and we will render the slot's default (what's\n            # between the slot tags)\n            resolved_slots[slot_id] = SlotFill(\n                name=slot.name,\n                escaped_name=_escape_slot_name(slot.name),\n                is_filled=False,\n                content_func=_nodelist_to_slot_render_func(slot.nodelist),\n                slot_default_var=None,\n                slot_data_var=None,\n            )\n            # Since the slot's default CAN include other slots (because it's defined in\n            # the same template), we need to enqueue the slot's children\n            if slot_id in slot_children and slot_children[slot_id]:\n                slot_ids_queue.extend(slot_children[slot_id])\n\n    # By the time we get here, we should know, for each slot, how it will be rendered\n    # -> Whether it will be replaced with a fill, or whether we render slot's defaults.\n    return slots, resolved_slots\n
    "},{"location":"reference/django_components/tag_formatter/","title":" tag_formatter","text":""},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter","title":"tag_formatter","text":""},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.ComponentFormatter","title":"ComponentFormatter","text":"
    ComponentFormatter(tag: str)\n

    Bases: TagFormatterABC

    The original django_component's component tag formatter, it uses the component and endcomponent tags, and the component name is gives 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

    Source code in src/django_components/tag_formatter.py
    def __init__(self, tag: str):\n    self.tag = tag\n
    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.InternalTagFormatter","title":"InternalTagFormatter","text":"
    InternalTagFormatter(tag_formatter: TagFormatterABC)\n

    Internal wrapper around user-provided TagFormatters, so that we validate the outputs.

    Source code in src/django_components/tag_formatter.py
    def __init__(self, tag_formatter: TagFormatterABC):\n    self.tag_formatter = tag_formatter\n
    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":"

    Bases: TagFormatterABC

    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/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC","title":"TagFormatterABC","text":"

    Bases: ABC

    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC.end_tag","title":"end_tag abstractmethod","text":"
    end_tag(name: str) -> str\n

    Formats the end tag of a block component.

    Source code in src/django_components/tag_formatter.py
    @abc.abstractmethod\ndef end_tag(self, name: str) -> str:\n    \"\"\"Formats the end tag of a block component.\"\"\"\n    ...\n
    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC.parse","title":"parse abstractmethod","text":"
    parse(tokens: List[str]) -> TagResult\n

    Given the tokens (words) of 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).

    Example:

    Given a component declarations:

    {% component \"my_comp\" key=val key2=val2 %}

    This function receives a list of tokens

    ['component', '\"my_comp\"', 'key=val', 'key2=val2']

    component is the tag name, which we drop. \"my_comp\" is the component name, but we must remove the extra quotes. And we pass remaining tokens unmodified, as that's the input to the component.

    So in the end, we return a tuple:

    ('my_comp', ['key=val', 'key2=val2'])

    Source code in src/django_components/tag_formatter.py
    @abc.abstractmethod\ndef parse(self, tokens: List[str]) -> TagResult:\n    \"\"\"\n    Given the tokens (words) of a component start tag, this function extracts\n    the component name from the tokens list, and returns `TagResult`, which\n    is a tuple of `(component_name, remaining_tokens)`.\n\n    Example:\n\n    Given a component declarations:\n\n    `{% component \"my_comp\" key=val key2=val2 %}`\n\n    This function receives a list of tokens\n\n    `['component', '\"my_comp\"', 'key=val', 'key2=val2']`\n\n    `component` is the tag name, which we drop. `\"my_comp\"` is the component name,\n    but we must remove the extra quotes. And we pass remaining tokens unmodified,\n    as that's the input to the component.\n\n    So in the end, we return a tuple:\n\n    `('my_comp', ['key=val', 'key2=val2'])`\n    \"\"\"\n    ...\n
    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC.start_tag","title":"start_tag abstractmethod","text":"
    start_tag(name: str) -> str\n

    Formats the start tag of a component.

    Source code in src/django_components/tag_formatter.py
    @abc.abstractmethod\ndef start_tag(self, name: str) -> str:\n    \"\"\"Formats the start tag of a component.\"\"\"\n    ...\n
    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagResult","title":"TagResult","text":"

    Bases: NamedTuple

    The return value from TagFormatter.parse()

    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagResult.component_name","title":"component_name instance-attribute","text":"
    component_name: str\n

    Component name extracted from the template tag

    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagResult.tokens","title":"tokens instance-attribute","text":"
    tokens: List[str]\n

    Remaining tokens (words) that were passed to the tag, with component name removed

    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.get_tag_formatter","title":"get_tag_formatter","text":"
    get_tag_formatter(registry: ComponentRegistry) -> InternalTagFormatter\n

    Returns an instance of the currently configured component tag formatter.

    Source code in src/django_components/tag_formatter.py
    def get_tag_formatter(registry: \"ComponentRegistry\") -> InternalTagFormatter:\n    \"\"\"Returns an instance of the currently configured component tag formatter.\"\"\"\n    # Allow users to configure the component TagFormatter\n    formatter_cls_or_str = registry.settings.TAG_FORMATTER\n\n    if isinstance(formatter_cls_or_str, str):\n        tag_formatter: TagFormatterABC = import_string(formatter_cls_or_str)\n    else:\n        tag_formatter = formatter_cls_or_str\n\n    return InternalTagFormatter(tag_formatter)\n
    "},{"location":"reference/django_components/template/","title":" template","text":""},{"location":"reference/django_components/template/#django_components.template","title":"template","text":""},{"location":"reference/django_components/template/#django_components.template.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

    Create a Template instance that will be cached as per the TEMPLATE_CACHE_SIZE setting.

    Source code in src/django_components/template.py
    def 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    \"\"\"Create a Template instance that will be cached as per the `TEMPLATE_CACHE_SIZE` setting.\"\"\"\n    template = _create_template(template_cls or Template, template_string, engine)\n\n    # Assign the origin and name separately, so the caching doesn't depend on them\n    # Since we might be accessing a template from cache, we want to define these only once\n    if not getattr(template, \"_dc_cached\", False):\n        template.origin = origin or Origin(UNKNOWN_SOURCE)\n        template.name = name\n        template._dc_cached = True\n\n    return template\n
    "},{"location":"reference/django_components/template_loader/","title":" template_loader","text":""},{"location":"reference/django_components/template_loader/#django_components.template_loader","title":"template_loader","text":"

    Template loader that loads templates from each Django app's \"components\" directory.

    "},{"location":"reference/django_components/template_loader/#django_components.template_loader.Loader","title":"Loader","text":"

    Bases: Loader

    "},{"location":"reference/django_components/template_loader/#django_components.template_loader.Loader.get_dirs","title":"get_dirs","text":"
    get_dirs(include_apps: bool = True) -> List[Path]\n

    Prepare directories that may contain component files:

    Searches for dirs set in COMPONENTS.dirs settings. If none set, defaults to searching for a \"components\" app. The dirs in COMPONENTS.dirs must be absolute paths.

    In addition to that, also all apps are checked for [app]/components dirs.

    Paths are accepted only if they resolve to a directory. E.g. /path/to/django_project/my_app/components/.

    BASE_DIR setting is required.

    Source code in src/django_components/template_loader.py
    def get_dirs(self, include_apps: bool = True) -> List[Path]:\n    \"\"\"\n    Prepare directories that may contain component files:\n\n    Searches for dirs set in `COMPONENTS.dirs` settings. If none set, defaults to searching\n    for a \"components\" app. The dirs in `COMPONENTS.dirs` must be absolute paths.\n\n    In addition to that, also all apps are checked for `[app]/components` dirs.\n\n    Paths are accepted only if they resolve to a directory.\n    E.g. `/path/to/django_project/my_app/components/`.\n\n    `BASE_DIR` setting is required.\n    \"\"\"\n    # Allow to configure from settings which dirs should be checked for components\n    component_dirs = app_settings.DIRS\n\n    # TODO_REMOVE_IN_V1\n    is_legacy_paths = (\n        # Use value of `STATICFILES_DIRS` ONLY if `COMPONENT.dirs` not set\n        not getattr(settings, \"COMPONENTS\", {}).get(\"dirs\", None) is not None\n        and hasattr(settings, \"STATICFILES_DIRS\")\n        and settings.STATICFILES_DIRS\n    )\n    if is_legacy_paths:\n        # NOTE: For STATICFILES_DIRS, we use the defaults even for empty list.\n        # We don't do this for COMPONENTS.dirs, so user can explicitly specify \"NO dirs\".\n        component_dirs = settings.STATICFILES_DIRS or [settings.BASE_DIR / \"components\"]\n    source = \"STATICFILES_DIRS\" if is_legacy_paths else \"COMPONENTS.dirs\"\n\n    logger.debug(\n        \"Template loader will search for valid template dirs from following options:\\n\"\n        + \"\\n\".join([f\" - {str(d)}\" for d in component_dirs])\n    )\n\n    # Add `[app]/[APP_DIR]` to the directories. This is, by default `[app]/components`\n    app_paths: List[Path] = []\n    if include_apps:\n        for conf in apps.get_app_configs():\n            for app_dir in app_settings.APP_DIRS:\n                comps_path = Path(conf.path).joinpath(app_dir)\n                if comps_path.exists():\n                    app_paths.append(comps_path)\n\n    directories: Set[Path] = set(app_paths)\n\n    # Validate and add other values from the config\n    for component_dir in component_dirs:\n        # Consider tuples for STATICFILES_DIRS (See #489)\n        # See https://docs.djangoproject.com/en/5.0/ref/settings/#prefixes-optional\n        if isinstance(component_dir, (tuple, list)):\n            component_dir = component_dir[1]\n        try:\n            Path(component_dir)\n        except TypeError:\n            logger.warning(\n                f\"{source} expected str, bytes or os.PathLike object, or tuple/list of length 2. \"\n                f\"See Django documentation for STATICFILES_DIRS. Got {type(component_dir)} : {component_dir}\"\n            )\n            continue\n\n        if not Path(component_dir).is_absolute():\n            raise ValueError(f\"{source} must contain absolute paths, got '{component_dir}'\")\n        else:\n            directories.add(Path(component_dir).resolve())\n\n    logger.debug(\n        \"Template loader matched following template dirs:\\n\" + \"\\n\".join([f\" - {str(d)}\" for d in directories])\n    )\n    return list(directories)\n
    "},{"location":"reference/django_components/template_loader/#django_components.template_loader.get_dirs","title":"get_dirs","text":"
    get_dirs(include_apps: bool = True, engine: Optional[Engine] = None) -> List[Path]\n

    Helper for using django_component's FilesystemLoader class to obtain a list of directories where component python files may be defined.

    Source code in src/django_components/template_loader.py
    def get_dirs(include_apps: bool = True, engine: Optional[Engine] = None) -> List[Path]:\n    \"\"\"\n    Helper for using django_component's FilesystemLoader class to obtain a list\n    of directories where component python files may be defined.\n    \"\"\"\n    current_engine = engine\n    if current_engine is None:\n        current_engine = Engine.get_default()\n\n    loader = Loader(current_engine)\n    return loader.get_dirs(include_apps)\n
    "},{"location":"reference/django_components/template_parser/","title":" template_parser","text":""},{"location":"reference/django_components/template_parser/#django_components.template_parser","title":"template_parser","text":"

    Overrides for the Django Template system to allow finer control over template parsing.

    Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py

    "},{"location":"reference/django_components/template_parser/#django_components.template_parser.parse_bits","title":"parse_bits","text":"
    parse_bits(\n    parser: Parser, bits: List[str], params: List[str], name: str\n) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]\n

    Parse bits for template tag helpers simple_tag and inclusion_tag, in particular by detecting syntax errors and by extracting positional and keyword arguments.

    This is a simplified version of django.template.library.parse_bits where we use custom regex to handle special characters in keyword names.

    Furthermore, our version allows duplicate keys, and instead of return kwargs as a dict, we return it as a list of key-value pairs. So it is up to the user of this function to decide whether they support duplicate keys or not.

    Source code in src/django_components/template_parser.py
    def parse_bits(\n    parser: Parser,\n    bits: List[str],\n    params: List[str],\n    name: str,\n) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]:\n    \"\"\"\n    Parse bits for template tag helpers simple_tag and inclusion_tag, in\n    particular by detecting syntax errors and by extracting positional and\n    keyword arguments.\n\n    This is a simplified version of `django.template.library.parse_bits`\n    where we use custom regex to handle special characters in keyword names.\n\n    Furthermore, our version allows duplicate keys, and instead of return kwargs\n    as a dict, we return it as a list of key-value pairs. So it is up to the\n    user of this function to decide whether they support duplicate keys or not.\n    \"\"\"\n    args: List[FilterExpression] = []\n    kwargs: List[Tuple[str, FilterExpression]] = []\n    unhandled_params = list(params)\n    for bit in bits:\n        # First we try to extract a potential kwarg from the bit\n        kwarg = token_kwargs([bit], parser)\n        if kwarg:\n            # The kwarg was successfully extracted\n            param, value = kwarg.popitem()\n            # All good, record the keyword argument\n            kwargs.append((str(param), value))\n            if param in unhandled_params:\n                # If using the keyword syntax for a positional arg, then\n                # consume it.\n                unhandled_params.remove(param)\n        else:\n            if kwargs:\n                raise TemplateSyntaxError(\n                    \"'%s' received some positional argument(s) after some \" \"keyword argument(s)\" % name\n                )\n            else:\n                # Record the positional argument\n                args.append(parser.compile_filter(bit))\n                try:\n                    # Consume from the list of expected positional arguments\n                    unhandled_params.pop(0)\n                except IndexError:\n                    pass\n    if unhandled_params:\n        # Some positional arguments were not supplied\n        raise TemplateSyntaxError(\n            \"'%s' did not receive value(s) for the argument(s): %s\"\n            % (name, \", \".join(\"'%s'\" % p for p in unhandled_params))\n        )\n    return args, kwargs\n
    "},{"location":"reference/django_components/template_parser/#django_components.template_parser.token_kwargs","title":"token_kwargs","text":"
    token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]\n

    Parse token keyword arguments and return a dictionary of the arguments retrieved from the bits token list.

    bits is a list containing the remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments are removed from this list.

    There is no requirement for all remaining token bits to be keyword arguments, so return the dictionary as soon as an invalid argument format is reached.

    Source code in src/django_components/template_parser.py
    def token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]:\n    \"\"\"\n    Parse token keyword arguments and return a dictionary of the arguments\n    retrieved from the ``bits`` token list.\n\n    `bits` is a list containing the remainder of the token (split by spaces)\n    that is to be checked for arguments. Valid arguments are removed from this\n    list.\n\n    There is no requirement for all remaining token ``bits`` to be keyword\n    arguments, so return the dictionary as soon as an invalid argument format\n    is reached.\n    \"\"\"\n    if not bits:\n        return {}\n    match = kwarg_re.match(bits[0])\n    kwarg_format = match and match[1]\n    if not kwarg_format:\n        return {}\n\n    kwargs: Dict[str, FilterExpression] = {}\n    while bits:\n        if kwarg_format:\n            match = kwarg_re.match(bits[0])\n            if not match or not match[1]:\n                return kwargs\n            key, value = match.groups()\n            del bits[:1]\n        else:\n            if len(bits) < 3 or bits[1] != \"as\":\n                return kwargs\n            key, value = bits[2], bits[0]\n            del bits[:3]\n\n        # This is the only difference from the original token_kwargs. We use\n        # the ComponentsFilterExpression instead of the original FilterExpression.\n        kwargs[key] = ComponentsFilterExpression(value, parser)\n        if bits and not kwarg_format:\n            if bits[0] != \"and\":\n                return kwargs\n            del bits[:1]\n    return kwargs\n
    "},{"location":"reference/django_components/templatetags/","title":"Index","text":""},{"location":"reference/django_components/templatetags/#django_components.templatetags","title":"templatetags","text":""},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags","title":"component_tags","text":""},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component","title":"component","text":"
    component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode\n
    To give the component access to the template context

    {% component \"name\" positional_arg keyword_arg=value ... %}

    To render the component in an isolated context

    {% component \"name\" positional_arg keyword_arg=value ... only %}

    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 or, if there are no positional arguments, passed as 'name'.

    Source code in src/django_components/templatetags/component_tags.py
    def component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode:\n    \"\"\"\n    To give the component access to the template context:\n        ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... %}```\n\n    To render the component in an isolated context:\n        ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... only %}```\n\n    Positional and keyword arguments can be literals or template variables.\n    The component name must be a single- or double-quotes string and must\n    be either the first positional argument or, if there are no positional\n    arguments, passed as 'name'.\n    \"\"\"\n    _fix_nested_tags(parser, token)\n    bits = token.split_contents()\n\n    # Let the TagFormatter pre-process the tokens\n    formatter = get_tag_formatter(registry)\n    result = formatter.parse([*bits])\n    end_tag = formatter.end_tag(result.component_name)\n\n    # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n    bits = [bits[0], *result.tokens]\n    token.contents = \" \".join(bits)\n\n    tag = _parse_tag(\n        tag_name,\n        parser,\n        token,\n        params=[],\n        extra_params=True,  # Allow many args\n        flags=[COMP_ONLY_FLAG],\n        keywordonly_kwargs=True,\n        repeatable_kwargs=False,\n        end_tag=end_tag,\n    )\n\n    # Check for isolated context keyword\n    isolated_context = tag.flags[COMP_ONLY_FLAG]\n\n    trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n    body = tag.parse_body()\n    fill_nodes = parse_slot_fill_nodes_from_component_nodelist(tuple(body), ignored_nodes=(ComponentNode,))\n\n    # Tag all fill nodes as children of this particular component instance\n    for node in fill_nodes:\n        trace_msg(\"ASSOC\", \"FILL\", node.trace_id, node.node_id, component_id=tag.id)\n        node.component_id = tag.id\n\n    component_node = ComponentNode(\n        name=result.component_name,\n        args=tag.args,\n        kwargs=tag.kwargs,\n        isolated_context=isolated_context,\n        fill_nodes=fill_nodes,\n        node_id=tag.id,\n        registry=registry,\n    )\n\n    trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n    return component_node\n
    "},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"
    component_css_dependencies(preload: str = '') -> SafeString\n

    Marks location where CSS link tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_css_dependencies\")\ndef component_css_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where CSS link tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_css_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component_dependencies","title":"component_dependencies","text":"
    component_dependencies(preload: str = '') -> SafeString\n

    Marks location where CSS link and JS script tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_dependencies\")\ndef component_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where CSS link and JS script tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER + JS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"
    component_js_dependencies(preload: str = '') -> SafeString\n

    Marks location where JS script tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_js_dependencies\")\ndef component_js_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where JS script tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + JS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_js_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.fill","title":"fill","text":"
    fill(parser: Parser, token: Token) -> FillNode\n

    Block tag whose contents 'fill' (are inserted into) an identically named 'slot'-block in the component template referred to by a parent component. It exists to make component nesting easier.

    This tag is available only within a {% component %}..{% endcomponent %} block. Runtime checks should prohibit other usages.

    Source code in src/django_components/templatetags/component_tags.py
    @register.tag(\"fill\")\ndef fill(parser: Parser, token: Token) -> FillNode:\n    \"\"\"\n    Block tag whose contents 'fill' (are inserted into) an identically named\n    'slot'-block in the component template referred to by a parent component.\n    It exists to make component nesting easier.\n\n    This tag is available only within a {% component %}..{% endcomponent %} block.\n    Runtime checks should prohibit other usages.\n    \"\"\"\n    tag = _parse_tag(\n        \"fill\",\n        parser,\n        token,\n        params=[SLOT_NAME_KWARG],\n        optional_params=[SLOT_NAME_KWARG],\n        keywordonly_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n        repeatable_kwargs=False,\n        end_tag=\"endfill\",\n    )\n\n    fill_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n    trace_id = f\"fill-id-{tag.id} ({fill_name_kwarg})\" if fill_name_kwarg else f\"fill-id-{tag.id}\"\n\n    trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id)\n\n    body = tag.parse_body()\n    fill_node = FillNode(\n        nodelist=body,\n        node_id=tag.id,\n        kwargs=tag.kwargs,\n        trace_id=trace_id,\n    )\n\n    trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id, \"...Done!\")\n    return fill_node\n
    "},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"
    html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode\n

    This tag takes: - Optional dictionary of attributes (attrs) - Optional dictionary of defaults (defaults) - Additional kwargs that are appended to the former two

    The inputs are merged and resulting dict is rendered as HTML attributes (key=\"value\").

    Rules: 1. Both attrs and defaults can be passed as positional args or as kwargs 2. Both attrs and defaults are optional (can be omitted) 3. 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. 4. All other kwargs (key=value) are appended and can be repeated.

    Normal kwargs (key=value) are concatenated to existing keys. So if e.g. key \"class\" is supplied with value \"my-class\", then adding class=\"extra-class\" will result in `class=\"my-class extra-class\".

    Example:

    {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n

    Source code in src/django_components/templatetags/component_tags.py
    @register.tag(\"html_attrs\")\ndef html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode:\n    \"\"\"\n    This tag takes:\n    - Optional dictionary of attributes (`attrs`)\n    - Optional dictionary of defaults (`defaults`)\n    - Additional kwargs that are appended to the former two\n\n    The inputs are merged and resulting dict is rendered as HTML attributes\n    (`key=\"value\"`).\n\n    Rules:\n    1. Both `attrs` and `defaults` can be passed as positional args or as kwargs\n    2. Both `attrs` and `defaults` are optional (can be omitted)\n    3. Both `attrs` and `defaults` are dictionaries, and we can define them the same way\n       we define dictionaries for the `component` tag. So either as `attrs=attrs` or\n       `attrs:key=value`.\n    4. All other kwargs (`key=value`) are appended and can be repeated.\n\n    Normal kwargs (`key=value`) are concatenated to existing keys. So if e.g. key\n    \"class\" is supplied with value \"my-class\", then adding `class=\"extra-class\"`\n    will result in `class=\"my-class extra-class\".\n\n    Example:\n    ```htmldjango\n    {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n    ```\n    \"\"\"\n    tag = _parse_tag(\n        \"html_attrs\",\n        parser,\n        token,\n        params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n        optional_params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n        flags=[],\n        keywordonly_kwargs=True,\n        repeatable_kwargs=True,\n    )\n\n    return HtmlAttrsNode(\n        kwargs=tag.kwargs,\n        kwarg_pairs=tag.kwarg_pairs,\n    )\n
    "},{"location":"reference/django_components/templatetags/component_tags/","title":" component_tags","text":""},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags","title":"component_tags","text":""},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component","title":"component","text":"
    component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode\n
    To give the component access to the template context

    {% component \"name\" positional_arg keyword_arg=value ... %}

    To render the component in an isolated context

    {% component \"name\" positional_arg keyword_arg=value ... only %}

    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 or, if there are no positional arguments, passed as 'name'.

    Source code in src/django_components/templatetags/component_tags.py
    def component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode:\n    \"\"\"\n    To give the component access to the template context:\n        ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... %}```\n\n    To render the component in an isolated context:\n        ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... only %}```\n\n    Positional and keyword arguments can be literals or template variables.\n    The component name must be a single- or double-quotes string and must\n    be either the first positional argument or, if there are no positional\n    arguments, passed as 'name'.\n    \"\"\"\n    _fix_nested_tags(parser, token)\n    bits = token.split_contents()\n\n    # Let the TagFormatter pre-process the tokens\n    formatter = get_tag_formatter(registry)\n    result = formatter.parse([*bits])\n    end_tag = formatter.end_tag(result.component_name)\n\n    # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n    bits = [bits[0], *result.tokens]\n    token.contents = \" \".join(bits)\n\n    tag = _parse_tag(\n        tag_name,\n        parser,\n        token,\n        params=[],\n        extra_params=True,  # Allow many args\n        flags=[COMP_ONLY_FLAG],\n        keywordonly_kwargs=True,\n        repeatable_kwargs=False,\n        end_tag=end_tag,\n    )\n\n    # Check for isolated context keyword\n    isolated_context = tag.flags[COMP_ONLY_FLAG]\n\n    trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n    body = tag.parse_body()\n    fill_nodes = parse_slot_fill_nodes_from_component_nodelist(tuple(body), ignored_nodes=(ComponentNode,))\n\n    # Tag all fill nodes as children of this particular component instance\n    for node in fill_nodes:\n        trace_msg(\"ASSOC\", \"FILL\", node.trace_id, node.node_id, component_id=tag.id)\n        node.component_id = tag.id\n\n    component_node = ComponentNode(\n        name=result.component_name,\n        args=tag.args,\n        kwargs=tag.kwargs,\n        isolated_context=isolated_context,\n        fill_nodes=fill_nodes,\n        node_id=tag.id,\n        registry=registry,\n    )\n\n    trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n    return component_node\n
    "},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"
    component_css_dependencies(preload: str = '') -> SafeString\n

    Marks location where CSS link tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_css_dependencies\")\ndef component_css_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where CSS link tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_css_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component_dependencies","title":"component_dependencies","text":"
    component_dependencies(preload: str = '') -> SafeString\n

    Marks location where CSS link and JS script tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_dependencies\")\ndef component_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where CSS link and JS script tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER + JS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"
    component_js_dependencies(preload: str = '') -> SafeString\n

    Marks location where JS script tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_js_dependencies\")\ndef component_js_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where JS script tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + JS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_js_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.fill","title":"fill","text":"
    fill(parser: Parser, token: Token) -> FillNode\n

    Block tag whose contents 'fill' (are inserted into) an identically named 'slot'-block in the component template referred to by a parent component. It exists to make component nesting easier.

    This tag is available only within a {% component %}..{% endcomponent %} block. Runtime checks should prohibit other usages.

    Source code in src/django_components/templatetags/component_tags.py
    @register.tag(\"fill\")\ndef fill(parser: Parser, token: Token) -> FillNode:\n    \"\"\"\n    Block tag whose contents 'fill' (are inserted into) an identically named\n    'slot'-block in the component template referred to by a parent component.\n    It exists to make component nesting easier.\n\n    This tag is available only within a {% component %}..{% endcomponent %} block.\n    Runtime checks should prohibit other usages.\n    \"\"\"\n    tag = _parse_tag(\n        \"fill\",\n        parser,\n        token,\n        params=[SLOT_NAME_KWARG],\n        optional_params=[SLOT_NAME_KWARG],\n        keywordonly_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n        repeatable_kwargs=False,\n        end_tag=\"endfill\",\n    )\n\n    fill_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n    trace_id = f\"fill-id-{tag.id} ({fill_name_kwarg})\" if fill_name_kwarg else f\"fill-id-{tag.id}\"\n\n    trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id)\n\n    body = tag.parse_body()\n    fill_node = FillNode(\n        nodelist=body,\n        node_id=tag.id,\n        kwargs=tag.kwargs,\n        trace_id=trace_id,\n    )\n\n    trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id, \"...Done!\")\n    return fill_node\n
    "},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"
    html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode\n

    This tag takes: - Optional dictionary of attributes (attrs) - Optional dictionary of defaults (defaults) - Additional kwargs that are appended to the former two

    The inputs are merged and resulting dict is rendered as HTML attributes (key=\"value\").

    Rules: 1. Both attrs and defaults can be passed as positional args or as kwargs 2. Both attrs and defaults are optional (can be omitted) 3. 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. 4. All other kwargs (key=value) are appended and can be repeated.

    Normal kwargs (key=value) are concatenated to existing keys. So if e.g. key \"class\" is supplied with value \"my-class\", then adding class=\"extra-class\" will result in `class=\"my-class extra-class\".

    Example:

    {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n

    Source code in src/django_components/templatetags/component_tags.py
    @register.tag(\"html_attrs\")\ndef html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode:\n    \"\"\"\n    This tag takes:\n    - Optional dictionary of attributes (`attrs`)\n    - Optional dictionary of defaults (`defaults`)\n    - Additional kwargs that are appended to the former two\n\n    The inputs are merged and resulting dict is rendered as HTML attributes\n    (`key=\"value\"`).\n\n    Rules:\n    1. Both `attrs` and `defaults` can be passed as positional args or as kwargs\n    2. Both `attrs` and `defaults` are optional (can be omitted)\n    3. Both `attrs` and `defaults` are dictionaries, and we can define them the same way\n       we define dictionaries for the `component` tag. So either as `attrs=attrs` or\n       `attrs:key=value`.\n    4. All other kwargs (`key=value`) are appended and can be repeated.\n\n    Normal kwargs (`key=value`) are concatenated to existing keys. So if e.g. key\n    \"class\" is supplied with value \"my-class\", then adding `class=\"extra-class\"`\n    will result in `class=\"my-class extra-class\".\n\n    Example:\n    ```htmldjango\n    {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n    ```\n    \"\"\"\n    tag = _parse_tag(\n        \"html_attrs\",\n        parser,\n        token,\n        params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n        optional_params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n        flags=[],\n        keywordonly_kwargs=True,\n        repeatable_kwargs=True,\n    )\n\n    return HtmlAttrsNode(\n        kwargs=tag.kwargs,\n        kwarg_pairs=tag.kwarg_pairs,\n    )\n
    "},{"location":"reference/django_components/types/","title":" types","text":""},{"location":"reference/django_components/types/#django_components.types","title":"types","text":"

    Helper types for IDEs.

    "},{"location":"reference/django_components/utils/","title":" utils","text":""},{"location":"reference/django_components/utils/#django_components.utils","title":"utils","text":""},{"location":"reference/django_components/utils/#django_components.utils.gen_id","title":"gen_id","text":"
    gen_id(length: int = 5) -> str\n

    Generate a unique ID that can be associated with a Node

    Source code in src/django_components/utils.py
    def gen_id(length: int = 5) -> str:\n    \"\"\"Generate a unique ID that can be associated with a Node\"\"\"\n    # Global counter to avoid conflicts\n    global _id\n    _id += 1\n\n    # Pad the ID with `0`s up to 4 digits, e.g. `0007`\n    return f\"{_id:04}\"\n
    "},{"location":"reference/django_components/utils/#django_components.utils.lazy_cache","title":"lazy_cache","text":"
    lazy_cache(make_cache: Callable[[], Callable[[Callable], Callable]]) -> Callable[[TFunc], TFunc]\n

    Decorator that caches the given function similarly to functools.lru_cache. But the cache is instantiated only at first invocation.

    cache argument is a function that generates the cache function, e.g. functools.lru_cache().

    Source code in src/django_components/utils.py
    def lazy_cache(\n    make_cache: Callable[[], Callable[[Callable], Callable]],\n) -> Callable[[TFunc], TFunc]:\n    \"\"\"\n    Decorator that caches the given function similarly to `functools.lru_cache`.\n    But the cache is instantiated only at first invocation.\n\n    `cache` argument is a function that generates the cache function,\n    e.g. `functools.lru_cache()`.\n    \"\"\"\n    _cached_fn = None\n\n    def decorator(fn: TFunc) -> TFunc:\n        @functools.wraps(fn)\n        def wrapper(*args: Any, **kwargs: Any) -> Any:\n            # Lazily initialize the cache\n            nonlocal _cached_fn\n            if not _cached_fn:\n                # E.g. `lambda: functools.lru_cache(maxsize=app_settings.TEMPLATE_CACHE_SIZE)`\n                cache = make_cache()\n                _cached_fn = cache(fn)\n\n            return _cached_fn(*args, **kwargs)\n\n        # Allow to access the LRU cache methods\n        # See https://stackoverflow.com/a/37654201/9788634\n        wrapper.cache_info = lambda: _cached_fn.cache_info()  # type: ignore\n        wrapper.cache_clear = lambda: _cached_fn.cache_clear()  # type: ignore\n\n        # And allow to remove the cache instance (mostly for tests)\n        def cache_remove() -> None:\n            nonlocal _cached_fn\n            _cached_fn = None\n\n        wrapper.cache_remove = cache_remove  # type: ignore\n\n        return cast(TFunc, wrapper)\n\n    return decorator\n
    "},{"location":"reference/django_components_js/build/","title":" build","text":""},{"location":"reference/django_components_js/build/#django_components_js.build","title":"build","text":""}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Index","text":"

    Docs (Work in progress)

    Django-components is a package that introduces component-based architecture to Django's server-side rendering. It aims to combine Django's templating system with the modularity seen in modern frontend frameworks.

    "},{"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":"#summary","title":"Summary","text":"

    It lets you create \"template components\", that contains both the template, the Javascript and the CSS needed to generate the front end code you need for a modern app. Use components like this:

    {% component \"calendar\" date=\"2015-06-19\" %}{% endcomponent %}\n

    And this is what gets rendered (plus the CSS and Javascript you've specified):

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

    See the example project or read on to learn about the details!

    "},{"location":"#table-of-contents","title":"Table of Contents","text":"
    • Release notes
    • Security notes \ud83d\udea8
    • Installation
    • Compatibility
    • Create your first component
    • Using single-file components
    • Use components in templates
    • Use components outside of templates
    • Use components as views
    • Typing and validating components
    • Pre-defined components
    • Registering components
    • Autodiscovery
    • Using slots in templates
    • Accessing data passed to the component
    • Rendering HTML attributes
    • Template tag syntax
    • Prop drilling and dependency injection (provide / inject)
    • Component hooks
    • Component context and scope
    • Pre-defined template variables
    • Customizing component tags with TagFormatter
    • Defining HTML/JS/CSS files
    • Rendering JS/CSS dependencies
    • Available settings
    • Running with development server
    • Logging and debugging
    • Management Command
    • Writing and sharing component libraries
    • Community examples
    • Running django-components project locally
    • Development guides
    "},{"location":"#release-notes","title":"Release notes","text":"

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

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

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

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

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

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

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

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

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

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

    {# Before #}\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`:\n```django\n{% component \"button\" href=\"...\" disabled %}\n    Click me!\n{% endcomponent %}\n```\n\nWhile `django_components.component_shorthand_formatter` allows you to write components like so:\n\n```django\n{% button href=\"...\" disabled %}\n    Click me!\n{% endbutton %}\n

    \ud83d\udea8\ud83d\udce2 Version 0.85 Autodiscovery module resolution changed. Following undocumented behavior was removed:

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

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

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

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

    \ud83d\udea8\ud83d\udce2 Version 0.79

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

    \ud83d\udea8\ud83d\udce2 Version 0.77 CHANGED the syntax for accessing default slot content.

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

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

    \ud83d\udea8\ud83d\udce2 Version 0.70

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

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

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

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

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

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

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

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

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

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

    "},{"location":"#security-notes","title":"Security notes \ud83d\udea8","text":"

    It is strongly recommended to read this section before using django-components in production.

    "},{"location":"#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":"#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 older version of django-components, your alternatives are a) passing --ignore <pattern> options to the collecstatic CLI command, or 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.

    "},{"location":"#installation","title":"Installation","text":"
    1. Install django_components into your environment:

    pip install django_components

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

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

    2. Remove 'APP_DIRS': True,

      • NOTE: Instead of APP_DIRS, for the same effect, we will use django.template.loaders.app_directories.Loader
    3. Add loaders to OPTIONS list and set it to following value:
    TEMPLATES = [\n   {\n      ...,\n      'OPTIONS': {\n            'context_processors': [\n               ...\n            ],\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
    1. Lastly, be able to serve the component JS and CSS files as static files, modify STATICFILES_FINDERS section of settings.py as follows:
    STATICFILES_FINDERS = [\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
    "},{"location":"#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            'context_processors': [\n                ...\n            ],\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":"#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 3.11 4.2, 5.0 3.12 4.2, 5.0"},{"location":"#create-your-first-component","title":"Create your first component","text":"

    A component in django-components is the combination of four things: CSS, Javascript, a Django template, and some Python code to put them all together.

        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       \u251c\u2500\u2500 script.js       \ud83c\udd95\n    \u2502       \u251c\u2500\u2500 style.css       \ud83c\udd95\n    \u2502       \u2514\u2500\u2500 template.html   \ud83c\udd95\n    \u251c\u2500\u2500 sampleproject/\n    \u251c\u2500\u2500 manage.py\n    \u2514\u2500\u2500 requirements.txt\n

    Start by creating empty files in the structure above.

    First, you need a CSS file. Be sure to prefix all rules with a unique class so they don't clash with other rules.

    [project root]/components/calendar/style.css
    /* In a file called [project root]/components/calendar/style.css */\n.calendar-component {\n  width: 200px;\n  background: pink;\n}\n.calendar-component span {\n  font-weight: bold;\n}\n

    Then you need a javascript file that specifies how you interact with this component. You are free to use any javascript framework you want. A good way to make sure this component doesn't clash with other components is to define all code inside an anonymous function that calls itself. This makes all variables defined only be defined inside this component and not affect other components.

    [project root]/components/calendar/script.js
    /* In a file called [project root]/components/calendar/script.js */\n(function () {\n  if (document.querySelector(\".calendar-component\")) {\n    document.querySelector(\".calendar-component\").onclick = function () {\n      alert(\"Clicked calendar!\");\n    };\n  }\n})();\n

    Now you need a Django template for your component. Feel free to define more variables like date in this example. When creating an instance of this component we will send in the values for these variables. The template will be rendered with whatever template backend you've specified in your Django settings file.

    [project root]/components/calendar/calendar.html
    {# In a file called [project root]/components/calendar/template.html #}\n<div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n

    Finally, we use django-components to tie this together. Start by creating a file called calendar.py in your component calendar directory. It will be auto-detected and loaded by the app.

    Inside this file we create a Component by inheriting from the Component class and specifying the context method. We also register the global component registry so that we easily can render it anywhere in our templates.

    [project root]/components/calendar/calendar.py
    # In a file called [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    # Templates inside `[your apps]/components` dir and `[project root]/components` dir\n    # will be automatically found.\n    #\n    # `template_name` can be relative to dir where `calendar.py` is, or relative to COMPONENTS.dirs\n    template_name = \"template.html\"\n    # Or\n    def get_template_name(context):\n        return f\"template-{context['name']}.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\n    # Both `css` and `js` can be relative to dir where `calendar.py` is, or relative to COMPONENTS.dirs\n    class Media:\n        css = \"style.css\"\n        js = \"script.js\"\n

    And voil\u00e1!! We've created our first component.

    "},{"location":"#using-single-file-components","title":"Using single-file components","text":"

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

    [project root]/components/calendar.py
    # In a file called [project root]/components/calendar.py\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

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

    "},{"location":"#syntax-highlight-and-code-assistance","title":"Syntax highlight and code assistance","text":""},{"location":"#vscode","title":"VSCode","text":"

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

    "},{"location":"#pycharm-or-other-jetbrains-ides","title":"Pycharm (or other Jetbrains IDEs)","text":"

    If you're a Pycharm user (or any other editor from Jetbrains), you can have coding assistance as well:

    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

    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.

    "},{"location":"#use-components-in-templates","title":"Use components in templates","text":"

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

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

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

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

    The output from the above template will be:

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

    "},{"location":"#use-components-outside-of-templates","title":"Use components outside of templates","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":"#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.
    "},{"location":"#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":"#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":"#use-components-as-views","title":"Use 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":"#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":"#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":"#typing-and-validating-components","title":"Typing and validating components","text":""},{"location":"#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, Data, Slots]):\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, Data, Slots]):\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":"#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":"#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:

    ```py\n# Tuple of one member of list of strings\nArgs = Tuple[List[str]]\n```\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":"#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, Data, Slots]):\n    ...\n
    "},{"location":"#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, Data, Slots]):\n    ...\n

    Same applies to kwargs, data, and slots.

    "},{"location":"#pre-defined-components","title":"Pre-defined components","text":""},{"location":"#dynamic-components","title":"Dynamic components","text":"

    If you are writing something like a form component, you may design it such that users give you the component names, and your component renders it.

    While you can handle this with a series of if / else statements, this is not an extensible solution.

    Instead, you can use dynamic components. Dynamic components are used in place of normal components.

    {% load component_tags %}\n{% component \"dynamic\" is=component_name title=\"Cat Museum\" %}\n    {% fill \"content\" %}\n        HELLO_FROM_SLOT_1\n    {% endfill %}\n    {% fill \"sidebar\" %}\n        HELLO_FROM_SLOT_2\n    {% endfill %}\n{% endcomponent %}\n

    These behave same way as regular components. You pass it the same args, kwargs, and slots as you would to the component that you want to render.

    The only exception is that also you supply 1-2 additional inputs: - is - Required - The component name or a component class to render - registry - Optional - The ComponentRegistry that will be searched if is is a component name. If omitted, ALL registries are searched.

    By default, the dynamic component is registered under the name \"dynamic\". In case of a conflict, you can change the name used for the dynamic components by defining the COMPONENTS.dynamic_component_name setting.

    If you need to use the dynamic components in Python, you can also import it from django_components:

    from django_components import DynamicComponent\n\ncomp = SimpleTableComp if is_readonly else TableComp\n\noutput = DynamicComponent.render(\n    kwargs={\n        \"is\": comp,\n        # Other kwargs...\n    },\n    # args: [...],\n    # slots: {...},\n)\n

    "},{"location":"#registering-components","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_name = \"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":"#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":"#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":"#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":"#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":"#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 (or app-level [app]/components/) are auto-imported in order to auto-register the components.

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

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

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

    Autodiscovery can be disabled in the settings.

    "},{"location":"#manually-trigger-autodiscovery","title":"Manually trigger autodiscovery","text":"

    Autodiscovery can be also triggered manually as a function call. This is useful if you want to run autodiscovery at a custom point of the lifecycle:

    from django_components import autodiscover\n\nautodiscover()\n
    "},{"location":"#using-slots-in-templates","title":"Using slots in templates","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\" %}Can you believe it's already <span>{{ date }}</span>??{% 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":"#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 end of 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 compiled.

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

    By contrast, it is permitted to use fill tags in nested components, e.g.:

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

    This is fine too:

    {% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"header\" %}\n        {% component \"calendar-header\" %}\n            Super Special Calendar Header\n        {% endcomponent %}\n    {% endfill %}\n{% endcomponent %}\n
    "},{"location":"#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":"#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 ONLY ONE of the identical slots.

    We recommend to mark the first occurence for consistency, 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\" %}Image here{% endslot %}\n    </div>\n</div>\n

    Which you can then use are regular default slot:

    {% component \"calendar\" date=\"2020-06-06\" %}\n    <img src=\"...\" />\n{% endcomponent %}\n
    "},{"location":"#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
    "},{"location":"#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\nHere's our example with more complex branching.\n\n```htmldjango\n<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":"#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___.

    "},{"location":"#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":"#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":"#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=\"data\" %}\n        {{ 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=\"data\" %}\n        {{ 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":"#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":"#accessing-data-passed-to-the-component","title":"Accessing data passed to the component","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

    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
    "},{"location":"#rendering-html-attributes","title":"Rendering 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":"#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":"#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":"#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":"#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":"#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":"#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":"#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":"#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":"#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":"#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":"#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":"#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":"#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":"#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":"#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\n  value={ isEnabled ? inputValue : null }\n/>\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":"#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":"#multi-line-tags","title":"Multi-line 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":"#prop-drilling-and-dependency-injection-provide-inject","title":"Prop drilling and dependency injection (provide / inject)","text":"

    New in version 0.80:

    Django components supports dependency injection with the combination of:

    1. {% provide %} tag
    2. inject() method of the Component class
    "},{"location":"#what-is-dependency-injection-and-prop-drilling","title":"What is \"dependency injection\" and \"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, AKA dependency injection.

    With dependency injection, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.

    This feature is inspired by Vue's Provide / Inject and React's Context / useContext.

    "},{"location":"#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":"#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":"#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":"#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":"#component-hooks","title":"Component hooks","text":"

    New in version 0.96

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

    "},{"location":"#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.\n\nYou can use this hook to access or modify the context or the template:\n\n```py\ndef 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```\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.\nIt receives the rendered output as the last argument.\n\nYou can use this hook to access the context or the template, but modifying\nthem won't have any effect.\n\nTo override the content that gets rendered, you can return a string or SafeString from this hook:\n\n```py\ndef on_render_after(self, context, template, content):\n    # Prepend text to the rendered content\n    return \"Chocolate cookie recipe: \" + content\n```\n
    "},{"location":"#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":"#component-context-and-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":"#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":"#pre-defined-template-variables","title":"Pre-defined template variables","text":"

    Here is a list of all variables that are automatically available from within the component's template and on_render_before / on_render_after hooks.

    • component_vars.is_filled

      New in version 0.70

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

      Example:

      {% if component_vars.is_filled.my_slot %}\n    {% slot \"my_slot\" / %}\n{% endif %}\n
    "},{"location":"#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, the components will use their name as the template tags:

    {% button href=\"...\" disabled %}\n  Click me!\n{% endbutton %}\n\n{# or #}\n\n{% button href=\"...\" disabled / %}\n
    "},{"location":"#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":"#writing-your-own-tagformatter","title":"Writing your own TagFormatter","text":""},{"location":"#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:\n```django\n{% component \"button\" href=\"...\" disabled %}\n{% endcomponent %}\n```\n\nThen `TagFormatter.parse()` will receive a following input:\n```py\n[\"component\", '\"button\"', 'href=\"...\"', 'disabled']\n```\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
      5. The tag handler resumes, using the tokens returned from TagFormatter.

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

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

    "},{"location":"#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":"#defining-htmljscss-files","title":"Defining HTML/JS/CSS files","text":"

    django_component's management of files builds on top of Django's Media class.

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

    • How to manage static files (e.g. images, JavaScript, CSS)
    "},{"location":"#defining-file-paths-relative-to-component-or-static-dirs","title":"Defining file paths relative to component or static dirs","text":"

    As seen in the getting started example, to associate HTML/JS/CSS files with a component, you set them as template_name, Media.js and Media.css respectively:

    # In a file [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_name = \"template.html\"\n\n    class Media:\n        css = \"style.css\"\n        js = \"script.js\"\n

    In the example above, the files are defined relative to the directory where component.py is.

    Alternatively, you can specify the file paths relative to the directories set in COMPONENTS.dirs or COMPONENTS.app_dirs.

    Assuming that COMPONENTS.dirs contains path [project root]/components, we can rewrite the example as:

    # In a file [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n    template_name = \"calendar/template.html\"\n\n    class Media:\n        css = \"calendar/style.css\"\n        js = \"calendar/script.js\"\n

    NOTE: In case of conflict, the preference goes to resolving the files relative to the component's directory.

    "},{"location":"#defining-multiple-paths","title":"Defining multiple paths","text":"

    Each component can have only a single template. However, you can define as many JS or CSS files as you want using a list.

    class MyComponent(Component):\n    class Media:\n        js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n        css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n
    "},{"location":"#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\",\n        }\n
    class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": [\"path/to/style1.css\", \"path/to/style2.css\"],\n            \"print\": [\"path/to/style3.css\", \"path/to/style4.css\"],\n        }\n

    NOTE: When you define CSS as a string or a list, the all media type is implied.

    "},{"location":"#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__)
    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/style.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/script.js\"></script>'),\n            Path(\"calendar/script1.js\"),\n            \"calendar/script2.js\",\n            b\"calendar/script3.js\",\n            lambda: \"calendar/script4.js\",\n        ]\n
    "},{"location":"#path-as-objects","title":"Path as objects","text":"

    In the example above, you could see that when we used 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:

    class LazyJsPath:\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_name = \"calendar/template.html\"\n\n    def get_context_data(self, date):\n        return {\n            \"date\": date,\n        }\n\n    class Media:\n        css = \"calendar/style.css\"\n        js = [\n            # <script> tag constructed by Media class\n            \"calendar/script1.js\",\n            # Custom <script> tag\n            LazyJsPath(\"calendar/script2.js\"),\n        ]\n
    "},{"location":"#customize-how-paths-are-rendered-into-html-tags-with-media_class","title":"Customize how paths are rendered into HTML tags with media_class","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_name = \"calendar/template.html\"\n\n    class Media:\n        css = \"calendar/style.css\"\n        js = \"calendar/script.js\"\n\n    # Override the behavior of Media class\n    media_class = MyMedia\n

    NOTE: The instance of the Media class (or it's subclass) is available under Component.media after the class creation (__new__).

    "},{"location":"#rendering-jscss-dependencies","title":"Rendering JS/CSS dependencies","text":"

    The JS and CSS files included in components are not automatically rendered. Instead, use the following tags to specify where to render the dependencies:

    • component_dependencies - Renders both JS and CSS
    • component_js_dependencies - Renders only JS
    • component_css_dependencies - Reneders only CSS

    JS files are rendered as <script> tags. CSS files are rendered as <style> tags.

    "},{"location":"#setting-up-componentdependencymiddleware","title":"Setting Up ComponentDependencyMiddleware","text":"

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

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

    MIDDLEWARE = [\n    # ... other middleware classes ...\n    'django_components.middleware.ComponentDependencyMiddleware'\n    # ... other middleware classes ...\n]\n

    Then, enable RENDER_DEPENDENCIES in setting.py:

    COMPONENTS = {\n    \"RENDER_DEPENDENCIES\": True,\n    # ... other component settings ...\n}\n
    "},{"location":"#available-settings","title":"Available settings","text":"

    All library settings are handled from a global COMPONENTS variable that is read from settings.py. By default you don't need it set, there are resonable defaults.

    Here's overview of all available settings and their defaults:

    COMPONENTS = {\n    \"autodiscover\": True,\n    \"context_behavior\": \"django\",  # \"django\" | \"isolated\"\n    \"dirs\": [BASE_DIR / \"components\"],  # Root-level \"components\" dirs, e.g. `/path/to/proj/components/`\n    \"app_dirs\": [\"components\"],  # App-level \"components\" dirs, e.g. `[app]/components/`\n    \"dynamic_component_name\": \"dynamic\",\n    \"libraries\": [],  # [\"mysite.components.forms\", ...]\n    \"multiline_tags\": True,\n    \"reload_on_template_change\": False,\n    \"static_files_allowed\": [\n        \".css\",\n        \".js\",\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        \".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":"#libraries-load-component-modules","title":"libraries - Load component modules","text":"

    Configure the locations where components are loaded. To do this, add a COMPONENTS variable to you settings.py with a list of python paths to load. This allows you to build a structure of components that are independent from your apps.

    COMPONENTS = {\n    \"libraries\": [\n        \"mysite.components.forms\",\n        \"mysite.components.buttons\",\n        \"mysite.components.cards\",\n    ],\n}\n

    Where mysite/components/forms.py may look like this:

    @register(\"form_simple\")\nclass FormSimple(Component):\n    template = \"\"\"\n        <form>\n            ...\n        </form>\n    \"\"\"\n\n@register(\"form_other\")\nclass FormOther(Component):\n    template = \"\"\"\n        <form>\n            ...\n        </form>\n    \"\"\"\n

    In the rare cases when you need to manually trigger the import of libraries, you can use the import_libraries function:

    from django_components import import_libraries\n\nimport_libraries()\n
    "},{"location":"#autodiscover-toggle-autodiscovery","title":"autodiscover - Toggle autodiscovery","text":"

    If you specify all the component locations with the setting above and have a lot of apps, you can (very) slightly speed things up by disabling autodiscovery.

    COMPONENTS = {\n    \"autodiscover\": False,\n}\n
    "},{"location":"#dirs","title":"dirs","text":"

    Specify the directories that contain your components.

    Directories must be full paths, same as with STATICFILES_DIRS.

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

    COMPONENTS = {\n    \"dirs\": [BASE_DIR / \"components\"],\n}\n
    "},{"location":"#app_dirs","title":"app_dirs","text":"

    Specify the app-level directories that contain your components.

    Directories must be relative to app, e.g.:

    COMPONENTS = {\n    \"app_dirs\": [\"my_comps\"],  # To search for [app]/my_comps\n}\n

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

    Each app will be searched for these directories.

    Set to empty list to disable app-level components:

    COMPONENTS = {\n    \"app_dirs\": [],\n}\n
    "},{"location":"#dynamic_component_name","title":"dynamic_component_name","text":"

    By default, the dynamic component is registered under the name \"dynamic\". In case of a conflict, use this setting to change the name used for the dynamic components.

    COMPONENTS = {\n    \"dynamic_component_name\": \"new_dynamic\",\n}\n
    "},{"location":"#multiline_tags-enabledisable-multiline-support","title":"multiline_tags - Enable/Disable multiline support","text":"

    If True, template tags can span multiple lines. Default: True

    COMPONENTS = {\n    \"multiline_tags\": True,\n}\n
    "},{"location":"#static_files_allowed","title":"static_files_allowed","text":"

    A list of regex patterns (as strings) that define which files within COMPONENTS.dirs and COMPONENTS.app_dirs are treated as static files.

    If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running collectstatic, and can be accessed under the static file endpoint.

    You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

    By default, JS, CSS, and common image and font file formats are considered static files:

    COMPONENTS = {\n    \"static_files_allowed\": [\n            \"css\",\n            \"js\",\n            # Images\n            \".apng\", \".png\",\n            \".avif\",\n            \".gif\",\n            \".jpg\", \".jpeg\", \".jfif\", \".pjpeg\", \".pjp\",  # JPEG\n            \".svg\",\n            \".webp\", \".bmp\",\n            \".ico\", \".cur\",  # ICO\n            \".tif\", \".tiff\",\n            # Fonts\n            \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n    ],\n}\n
    "},{"location":"#static_files_forbidden","title":"static_files_forbidden","text":"

    A list of suffixes that define which files within COMPONENTS.dirs and 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 COMPONENTS.static_files_allowed.

    Use this setting together with COMPONENTS.static_files_allowed for a fine control over what files 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 = {\n    \"static_files_forbidden\": [\n        \".html\", \".django\", \".dj\", \".tpl\", \".py\", \".pyc\",\n    ],\n}\n
    "},{"location":"#template_cache_size-tune-the-template-cache","title":"template_cache_size - Tune the template cache","text":"

    Each time a template is rendered it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.

    By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are using the template method of a component to render lots of dynamic templates, you can increase this number. To remove the cache limit altogether and cache everything, set template_cache_size to None.

    COMPONENTS = {\n    \"template_cache_size\": 256,\n}\n

    If you want 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":"#context_behavior-make-components-isolated-or-not","title":"context_behavior - Make components isolated (or not)","text":"

    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.

    You can configure what variables are available inside the {% fill %} tags. See Component context and scope.

    This has two modes:

    • \"django\" - Default - 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 loops or with tag
    • Data returned from get_context_data() of the component that wraps 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:

    • get_context_data() of the component which defined the template (AKA the \"root\" component)
    • Any loops ({% for ... %}) that the {% fill %} tag is part of.
    COMPONENTS = {\n    \"context_behavior\": \"isolated\",\n}\n
    "},{"location":"#example-django","title":"Example \"django\"","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    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 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":"#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    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.

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

    "},{"location":"#reload_on_template_change-reload-dev-server-on-component-file-changes","title":"reload_on_template_change - Reload dev server on component file changes","text":"

    If True, configures Django to reload on component files. See Reload dev server on component file changes.

    NOTE: This setting should be enabled only for the dev environment!

    "},{"location":"#tag_formatter-change-how-components-are-used-in-templates","title":"tag_formatter - Change how components are used in templates","text":"

    Sets the TagFormatter instance. See the section Customizing component tags with TagFormatter.

    Can be set either as direct reference, or as an import string;

    COMPONENTS = {\n    \"tag_formatter\": \"django_components.component_formatter\"\n}\n

    Or

    from django_components import component_formatter\n\nCOMPONENTS = {\n    \"tag_formatter\": component_formatter\n}\n
    "},{"location":"#running-with-development-server","title":"Running with development server","text":""},{"location":"#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 separate 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 comoponent 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_template_change to True. This configures Django to watch for component files too.

    NOTE: This setting should be enabled only for the dev environment!

    "},{"location":"#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":"#management-command","title":"Management Command","text":"

    You can use the built-in management command startcomponent to create a django component. The command accepts the following arguments and options:

    • name: The name of the component to create. This is a required argument.

    • --path: The path to the components directory. This is an optional argument. If not provided, the command will use the BASE_DIR setting from your Django settings.

    • --js: The name of the JavaScript file. This is an optional argument. The default value is script.js.

    • --css: The name of the CSS file. This is an optional argument. The default value is style.css.

    • --template: The name of the template file. This is an optional argument. The default value is template.html.

    • --force: This option allows you to overwrite existing files if they exist. This is an optional argument.

    • --verbose: This option allows the command to print additional information during component creation. This is an optional argument.

    • --dry-run: This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False.

    "},{"location":"#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":"#management-command-examples","title":"Management Command Examples","text":"

    Here are some examples of how you can use the command:

    "},{"location":"#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":"#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":"#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":"#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":"#writing-and-sharing-component-libraries","title":"Writing and sharing component libraries","text":"

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

    "},{"location":"#writing-component-libraries","title":"Writing component libraries","text":"
    1. Create a Django project with the following 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 settingt 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]):\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":"#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: - The user of the package NEEDS to have installed and configured django_components. - If you use components where the HTML / CSS / JS files are separate, you may need to define MANIFEST.in to include those files with the distribution (see user guide).

    "},{"location":"#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\n
    2. Add the package to INSTALLED_APPS

      INSTALLED_APPS = [\n    ...\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            'context_processors': [\n                ...\n            ],\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":"#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":""},{"location":"#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 local 3.8 3.9 3.10 3.11 3.12\ntox -p\n
    "},{"location":"#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":"#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
    1. Install dependencies from the requirements.txt file:
    pip install -r requirements.txt\n
    1. Link to your local version of django-components:
    pip install -e ..\n

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

    1. Start Django server
      python manage.py runserver\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":"#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
    1. Install the JS dependencies
    npm install\n
    1. 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":"#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":"#development-guides","title":"Development guides","text":"
    • Slot rendering flot
    • Slots and blocks
    "},{"location":"CHANGELOG/","title":"Release notes","text":"

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

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

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

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

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

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

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

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

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

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

    {# Before #}\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`:\n```django\n{% component \"button\" href=\"...\" disabled %}\n    Click me!\n{% endcomponent %}\n```\n\nWhile `django_components.component_shorthand_formatter` allows you to write components like so:\n\n```django\n{% button href=\"...\" disabled %}\n    Click me!\n{% endbutton %}\n

    \ud83d\udea8\ud83d\udce2 Version 0.85 Autodiscovery module resolution changed. Following undocumented behavior was removed:

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

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

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

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

    \ud83d\udea8\ud83d\udce2 Version 0.79

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

    \ud83d\udea8\ud83d\udce2 Version 0.77 CHANGED the syntax for accessing default slot content.

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

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

    \ud83d\udea8\ud83d\udce2 Version 0.70

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

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

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

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

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

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

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

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

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

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

    Static files

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

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

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

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

    "},{"location":"CHANGELOG/#installation","title":"Installation","text":"
    1. Install django_components into your environment:

    pip install django_components

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

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

    2. Remove 'APP_DIRS': True,

      • NOTE: Instead of APP_DIRS, for the same effect, we will use django.template.loaders.app_directories.Loader
    3. Add loaders to OPTIONS list and set it to following value:
    TEMPLATES = [\n   {\n      ...,\n      'OPTIONS': {\n            'context_processors': [\n               ...\n            ],\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
    1. Lastly, be able to serve the component JS and CSS files as static files, modify STATICFILES_FINDERS section of settings.py as follows:
    STATICFILES_FINDERS = [\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
    "},{"location":"CHANGELOG/#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 3.11 4.2, 5.0 3.12 4.2, 5.0

    Using single-file components

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

    [project root]/components/calendar.py
    ## In a file called [project root]/components/calendar.py\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

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

    "},{"location":"CHANGELOG/#vscode","title":"VSCode","text":"

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

    "},{"location":"CHANGELOG/#use-components-in-templates","title":"Use components in templates","text":"

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

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

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

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

    The output from the above template will be:

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

    Inputs of render and render_to_response

    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.
    "},{"location":"CHANGELOG/#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

    Component as view example

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

    ## In a file called [project root]/components/calendar.py\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":"CHANGELOG/#typing-and-validating-components","title":"Typing and validating components","text":""},{"location":"CHANGELOG/#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":"CHANGELOG/#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, Data, Slots]):\n    ...\n
    "},{"location":"CHANGELOG/#pre-defined-components","title":"Pre-defined components","text":""},{"location":"CHANGELOG/#registering-components","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_name = \"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":"CHANGELOG/#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":"CHANGELOG/#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.

    Manually trigger autodiscovery

    Autodiscovery can be also triggered manually as a function call. This is useful if you want to run autodiscovery at a custom point of the lifecycle:

    from django_components import autodiscover\n\nautodiscover()\n

    Default slot

    Added in version 0.28

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

    It can become tedious to use fill tags everywhere, especially when you're using a component that declares only one slot. To make things easier, slot tags can be marked with an optional keyword: default. When added to the end of the tag (as shown below), this option lets you pass filling content directly in the body of a component tag pair \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 compiled.

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

    By contrast, it is permitted to use fill tags in nested components, e.g.:

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

    This is fine too:

    {% component \"calendar\" date=\"2020-06-06\" %}\n    {% fill \"header\" %}\n        {% component \"calendar-header\" %}\n            Super Special Calendar Header\n        {% endcomponent %}\n    {% endfill %}\n{% endcomponent %}\n
    "},{"location":"CHANGELOG/#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 ONLY ONE of the identical slots.

    We recommend to mark the first occurence for consistency, 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\" %}Image here{% endslot %}\n    </div>\n</div>\n

    Which you can then use are regular default slot:

    {% component \"calendar\" date=\"2020-06-06\" %}\n    <img src=\"...\" />\n{% endcomponent %}\n
    "},{"location":"CHANGELOG/#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\nHere's our example with more complex branching.\n\n```htmldjango\n<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":"CHANGELOG/#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":"CHANGELOG/#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=\"data\" %}\n        {{ 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=\"data\" %}\n        {{ 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":"CHANGELOG/#accessing-data-passed-to-the-component","title":"Accessing data passed to the component","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

    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

    Removing atttributes

    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":"CHANGELOG/#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":"CHANGELOG/#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":"CHANGELOG/#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":"CHANGELOG/#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":"CHANGELOG/#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":"CHANGELOG/#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":"CHANGELOG/#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\n  value={ isEnabled ? inputValue : null }\n/>\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":"CHANGELOG/#multi-line-tags","title":"Multi-line 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

    What is \"dependency injection\" and \"prop drilling\"?

    Prop drilling refers to a scenario in UI development where you need to pass data through many layers of a component tree to reach the nested components that actually need the data.

    Normally, you'd use props to send data from a parent component to its children. However, this straightforward method becomes cumbersome and inefficient if the data has to travel through many levels or if several components scattered at different depths all need the same piece of information.

    This results in a situation where the intermediate components, which don't need the data for their own functioning, end up having to manage and pass along these props. This clutters the component tree and makes the code verbose and harder to manage.

    A neat solution to avoid prop drilling is using the \"provide and inject\" technique, AKA dependency injection.

    With dependency injection, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.

    This feature is inspired by Vue's Provide / Inject and React's Context / useContext.

    "},{"location":"CHANGELOG/#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":"CHANGELOG/#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

    Available hooks

    • 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.\n\nYou can use this hook to access or modify the context or the template:\n\n```py\ndef 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```\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.\nIt receives the rendered output as the last argument.\n\nYou can use this hook to access the context or the template, but modifying\nthem won't have any effect.\n\nTo override the content that gets rendered, you can return a string or SafeString from this hook:\n\n```py\ndef on_render_after(self, context, template, content):\n    # Prepend text to the rendered content\n    return \"Chocolate cookie recipe: \" + content\n```\n
    "},{"location":"CHANGELOG/#component-context-and-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":"CHANGELOG/#pre-defined-template-variables","title":"Pre-defined template variables","text":"

    Here is a list of all variables that are automatically available from within the component's template and on_render_before / on_render_after hooks.

    • component_vars.is_filled

      New in version 0.70

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

      Example:

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

    Available TagFormatters

    django_components provides following predefined TagFormatters:

    • ComponentFormatter (django_components.component_formatter)

      Default

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

      Example as block:

      {% component \"button\" href=\"...\" %}\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":"CHANGELOG/#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:\n```django\n{% component \"button\" href=\"...\" disabled %}\n{% endcomponent %}\n```\n\nThen `TagFormatter.parse()` will receive a following input:\n```py\n[\"component\", '\"button\"', 'href=\"...\"', 'disabled']\n```\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
      5. The tag handler resumes, using the tokens returned from TagFormatter.

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

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

    "},{"location":"CHANGELOG/#defining-htmljscss-files","title":"Defining HTML/JS/CSS files","text":"

    django_component's management of files builds on top of Django's Media class.

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

    • How to manage static files (e.g. images, JavaScript, CSS)
    "},{"location":"CHANGELOG/#defining-multiple-paths","title":"Defining multiple paths","text":"

    Each component can have only a single template. However, you can define as many JS or CSS files as you want using a list.

    class MyComponent(Component):\n    class Media:\n        js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n        css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n
    "},{"location":"CHANGELOG/#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__)
    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/style.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/script.js\"></script>'),\n            Path(\"calendar/script1.js\"),\n            \"calendar/script2.js\",\n            b\"calendar/script3.js\",\n            lambda: \"calendar/script4.js\",\n        ]\n
    "},{"location":"CHANGELOG/#customize-how-paths-are-rendered-into-html-tags-with-media_class","title":"Customize how paths are rendered into HTML tags with media_class","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_name = \"calendar/template.html\"\n\n    class Media:\n        css = \"calendar/style.css\"\n        js = \"calendar/script.js\"\n\n    # Override the behavior of Media class\n    media_class = MyMedia\n

    NOTE: The instance of the Media class (or it's subclass) is available under Component.media after the class creation (__new__).

    Setting Up ComponentDependencyMiddleware

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

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

    MIDDLEWARE = [\n    # ... other middleware classes ...\n    'django_components.middleware.ComponentDependencyMiddleware'\n    # ... other middleware classes ...\n]\n

    Then, enable RENDER_DEPENDENCIES in setting.py:

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

    libraries - Load component modules

    Configure the locations where components are loaded. To do this, add a COMPONENTS variable to you settings.py with a list of python paths to load. This allows you to build a structure of components that are independent from your apps.

    COMPONENTS = {\n    \"libraries\": [\n        \"mysite.components.forms\",\n        \"mysite.components.buttons\",\n        \"mysite.components.cards\",\n    ],\n}\n

    Where mysite/components/forms.py may look like this:

    @register(\"form_simple\")\nclass FormSimple(Component):\n    template = \"\"\"\n        <form>\n            ...\n        </form>\n    \"\"\"\n\n@register(\"form_other\")\nclass FormOther(Component):\n    template = \"\"\"\n        <form>\n            ...\n        </form>\n    \"\"\"\n

    In the rare cases when you need to manually trigger the import of libraries, you can use the import_libraries function:

    from django_components import import_libraries\n\nimport_libraries()\n
    "},{"location":"CHANGELOG/#dirs","title":"dirs","text":"

    Specify the directories that contain your components.

    Directories must be full paths, same as with STATICFILES_DIRS.

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

    COMPONENTS = {\n    \"dirs\": [BASE_DIR / \"components\"],\n}\n
    "},{"location":"CHANGELOG/#dynamic_component_name","title":"dynamic_component_name","text":"

    By default, the dynamic component is registered under the name \"dynamic\". In case of a conflict, use this setting to change the name used for the dynamic components.

    COMPONENTS = {\n    \"dynamic_component_name\": \"new_dynamic\",\n}\n
    "},{"location":"CHANGELOG/#static_files_allowed","title":"static_files_allowed","text":"

    A list of regex patterns (as strings) that define which files within COMPONENTS.dirs and COMPONENTS.app_dirs are treated as static files.

    If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running collectstatic, and can be accessed under the static file endpoint.

    You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

    By default, JS, CSS, and common image and font file formats are considered static files:

    COMPONENTS = {\n    \"static_files_allowed\": [\n            \"css\",\n            \"js\",\n            # Images\n            \".apng\", \".png\",\n            \".avif\",\n            \".gif\",\n            \".jpg\", \".jpeg\", \".jfif\", \".pjpeg\", \".pjp\",  # JPEG\n            \".svg\",\n            \".webp\", \".bmp\",\n            \".ico\", \".cur\",  # ICO\n            \".tif\", \".tiff\",\n            # Fonts\n            \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n    ],\n}\n
    "},{"location":"CHANGELOG/#template_cache_size-tune-the-template-cache","title":"template_cache_size - Tune the template cache","text":"

    Each time a template is rendered it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.

    By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are using the template method of a component to render lots of dynamic templates, you can increase this number. To remove the cache limit altogether and cache everything, set template_cache_size to None.

    COMPONENTS = {\n    \"template_cache_size\": 256,\n}\n

    If you want 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":"CHANGELOG/#example-django","title":"Example \"django\"","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    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 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":"CHANGELOG/#reload_on_template_change-reload-dev-server-on-component-file-changes","title":"reload_on_template_change - Reload dev server on component file changes","text":"

    If True, configures Django to reload on component files. See Reload dev server on component file changes.

    NOTE: This setting should be enabled only for the dev environment!

    "},{"location":"CHANGELOG/#running-with-development-server","title":"Running with development server","text":""},{"location":"CHANGELOG/#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

    Management Command Usage

    To use the command, run the following command in your terminal:

    python manage.py startcomponent <name> --path <path> --js <js_filename> --css <css_filename> --template <template_filename> --force --verbose --dry-run\n

    Replace <name>, <path>, <js_filename>, <css_filename>, and <template_filename> with your desired values.

    "},{"location":"CHANGELOG/#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":"CHANGELOG/#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":"CHANGELOG/#writing-and-sharing-component-libraries","title":"Writing and sharing component libraries","text":"

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

    "},{"location":"CHANGELOG/#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: - The user of the package NEEDS to have installed and configured django_components. - If you use components where the HTML / CSS / JS files are separate, you may need to define MANIFEST.in to include those files with the distribution (see user guide).

    "},{"location":"CHANGELOG/#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.

    Install locally and run the tests

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

    git clone https://github.com/<your GitHub username>/django-components.git\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 local 3.8 3.9 3.10 3.11 3.12\ntox -p\n
    "},{"location":"CHANGELOG/#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
    1. Install dependencies from the requirements.txt file:
    pip install -r requirements.txt\n
    1. Link to your local version of django-components:
    pip install -e ..\n

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

    1. Start Django server
      python manage.py runserver\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":"CHANGELOG/#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":"CHANGELOG/#_1","title":"Changelog","text":""},{"location":"CODE_OF_CONDUCT/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"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":"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":"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":"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":"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":"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":"SUMMARY/","title":"SUMMARY","text":"
    • README
    • Changelog
    • Code of Conduct
    • License
    • Reference
    • API Reference
    "},{"location":"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":"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":"slot_rendering/","title":"Slot rendering","text":"

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

    "},{"location":"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. I want to render the slots with {% fill %} tag that were defined OUTSIDE of this template. How do I do that?

    7. Traverse the template to collect ALL slots

      • NOTE: I will also look inside {% slot %} and {% fill %} tags, since they are all still defined within the same TEMPLATE.

      I should end up with a list like this:

      - Name: \"myslot\"\n   ID 0001\n   Content:\n   | ----- DEF {{ my_var }}\n   | ----- {% slot \"myslot_inner\" %}\n   | -------- GHI {{ my_var }}\n   | ----- {% endslot %}\n- Name: \"myslot_inner\"\n   ID 0002\n   Content:\n   | -------- GHI {{ my_var }}\n- Name: \"myslot\"\n   ID 0003\n   Content:\n   | ------- JKL {{ my_var }}\n   | ------- {% slot \"myslot_inner\" %}\n   | ---------- MNO {{ my_var }}\n   | ------- {% endslot %}\n- Name: \"myslot_inner\"\n   ID 0004\n   Content:\n   | ---------- MNO {{ my_var }}\n- Name: \"myslot2\"\n   ID 0005\n   Content:\n   | ---- PQR {{ my_var }}\n

    8. Note the relationships - which slot is nested in which one

      I should end up with a graph-like data like:

      - 0001: [0002]\n- 0002: []\n- 0003: [0004]\n- 0004: []\n- 0005: []\n

      In other words, the data tells us that slot ID 0001 is PARENT of slot 0002.

      This is important, because, IF parent template provides slot fill for slot 0001, then we DON'T NEED TO render it's children, AKA slot 0002.

    9. Find roots of the slot relationships

      The data from previous step can be understood also as a collection of directled acyclig graphs (DAG), e.g.:

      0001 --> 0002\n0003 --> 0004\n0005\n

      So we find the roots (0001, 0003, 0005), AKA slots that are NOT nested in other slots. We do so by going over ALL entries from previous step. Those IDs which are NOT mentioned in ANY of the lists are the roots.

      Because of the nature of nested structures, there cannot be any cycles.

    10. Recursively render slots, starting from roots.

      1. First we take each of the roots.

      2. Then we check if there is a slot fill for given slot name.

      3. If YES we replace the slot node with the fill node.

        • Note: We assume slot fills are ALREADY RENDERED!
          | ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n
          becomes
          | ----- Bla bla\n| -------- Some Other Content\n| ----- ...\n
          We don't continue further, because inner slots have been overriden!
      4. If NO, then we will replace slot nodes with their children, e.g.:

        | ---- {% slot \"myslot\" %} ---\n| ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n| ---- {% endslot %} ---\n
        Becomes
        | ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n

      5. We check if the slot includes any children {% slot %} tags. If YES, then continue with step 4. for them, and wait until they finish.

    11. At this point, ALL slots should be rendered and we should have something like this:

      | -- {{ my_var }} --\n| -- ABC\n| ----- DEF {{ my_var }}\n| -------- GHI {{ my_var }}\n| ------\n| -- {% component \"mycomp\" %} ---\n| ------- JKL {{ my_var }}\n| ---- {% component \"mycomp\" %} ---\n| ---------- MNO {{ my_var }}\n| ---- {% endcomponent %} ---\n| -- {% endcomponent %} ---\n| ----\n| -- {% component \"mycomp2\" %} ---\n| ---- PQR {{ my_var }}\n| -- {% endcomponent %} ---\n| ----\n

      • NOTE: Inserting fills into {% slots %} should NOT introduce new {% slots %}, as the fills should be already rendered!
    "},{"location":"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":"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_name = \"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_name = \"\"\"\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_name = \"\"\"\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":"reference/SUMMARY/","title":"SUMMARY","text":"
    • django_components
    • app_settings
    • apps
    • attributes
    • autodiscover
    • component
    • component_media
    • component_registry
    • components
      • dynamic
    • context
    • expression
    • finders
    • library
    • logger
    • management
      • commands
      • startcomponent
      • upgradecomponent
    • middleware
    • node
    • provide
    • slots
    • tag_formatter
    • template
    • template_loader
    • template_parser
    • templatetags
      • component_tags
    • types
    • utils
    • django_components_js
    • build
    "},{"location":"reference/django_components/","title":"Index","text":""},{"location":"reference/django_components/#django_components","title":"django_components","text":"

    Main package for Django Components.

    Modules:

    • app_settings \u2013
    • attributes \u2013
    • autodiscover \u2013
    • component \u2013
    • component_media \u2013
    • component_registry \u2013
    • components \u2013
    • context \u2013

      This file centralizes various ways we use Django's Context class

    • expression \u2013
    • finders \u2013
    • library \u2013

      Module for interfacing with Django's Library (django.template.library)

    • logger \u2013
    • middleware \u2013
    • node \u2013
    • provide \u2013
    • slots \u2013
    • tag_formatter \u2013
    • template \u2013
    • template_loader \u2013

      Template loader that loads templates from each Django app's \"components\" directory.

    • template_parser \u2013

      Overrides for the Django Template system to allow finer control over template parsing.

    • templatetags \u2013
    • types \u2013

      Helper types for IDEs.

    • utils \u2013
    "},{"location":"reference/django_components/#django_components.app_settings","title":"app_settings","text":"

    Classes:

    • ContextBehavior \u2013
    "},{"location":"reference/django_components/#django_components.app_settings.ContextBehavior","title":"ContextBehavior","text":"

    Bases: str, Enum

    Attributes:

    • DJANGO \u2013

      With this setting, component fills behave as usual Django tags.

    • ISOLATED \u2013

      This setting makes the component fills behave similar to Vue or React, where

    "},{"location":"reference/django_components/#django_components.app_settings.ContextBehavior.DJANGO","title":"DJANGO class-attribute instance-attribute","text":"
    DJANGO = 'django'\n

    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 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 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/django_components/#django_components.app_settings.ContextBehavior.ISOLATED","title":"ISOLATED class-attribute instance-attribute","text":"
    ISOLATED = 'isolated'\n

    This setting makes the component fills behave similar to Vue or React, where the fills use EXCLUSIVELY the context variables defined in 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/django_components/#django_components.attributes","title":"attributes","text":"

    Functions:

    • append_attributes \u2013

      Merges the key-value pairs and returns a new dictionary.

    • attributes_to_string \u2013

      Convert a dict of attributes to a string.

    "},{"location":"reference/django_components/#django_components.attributes.append_attributes","title":"append_attributes","text":"
    append_attributes(*args: Tuple[str, Any]) -> Dict\n

    Merges the key-value pairs and returns a new dictionary.

    If a key is present multiple times, its values are concatenated with a space character as separator in the final dictionary.

    Source code in src/django_components/attributes.py
    def append_attributes(*args: Tuple[str, Any]) -> Dict:\n    \"\"\"\n    Merges the key-value pairs and returns a new dictionary.\n\n    If a key is present multiple times, its values are concatenated with a space\n    character as separator in the final dictionary.\n    \"\"\"\n    result: Dict = {}\n\n    for key, value in args:\n        if key in result:\n            result[key] += \" \" + value\n        else:\n            result[key] = value\n\n    return result\n
    "},{"location":"reference/django_components/#django_components.attributes.attributes_to_string","title":"attributes_to_string","text":"
    attributes_to_string(attributes: Mapping[str, Any]) -> str\n

    Convert a dict of attributes to a string.

    Source code in src/django_components/attributes.py
    def attributes_to_string(attributes: Mapping[str, Any]) -> str:\n    \"\"\"Convert a dict of attributes to a string.\"\"\"\n    attr_list = []\n\n    for key, value in attributes.items():\n        if value is None or value is False:\n            continue\n        if value is True:\n            attr_list.append(conditional_escape(key))\n        else:\n            attr_list.append(format_html('{}=\"{}\"', key, value))\n\n    return mark_safe(SafeString(\" \").join(attr_list))\n
    "},{"location":"reference/django_components/#django_components.autodiscover","title":"autodiscover","text":"

    Functions:

    • autodiscover \u2013

      Search for component files and import them. Returns a list of module

    • import_libraries \u2013

      Import modules set in COMPONENTS.libraries setting.

    • search_dirs \u2013

      Search the directories for the given glob pattern. Glob search results are returned

    "},{"location":"reference/django_components/#django_components.autodiscover.autodiscover","title":"autodiscover","text":"
    autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n

    Search for component files and import them. Returns a list of module paths of imported files.

    Autodiscover searches in the locations as defined by Loader.get_dirs.

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

    Source code in src/django_components/autodiscover.py
    def autodiscover(\n    map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n    \"\"\"\n    Search for component files and import them. Returns a list of module\n    paths of imported files.\n\n    Autodiscover searches in the locations as defined by `Loader.get_dirs`.\n\n    You can map the module paths with `map_module` function. This serves\n    as an escape hatch for when you need to use this function in tests.\n    \"\"\"\n    dirs = get_dirs(include_apps=False)\n    component_filepaths = search_dirs(dirs, \"**/*.py\")\n    logger.debug(f\"Autodiscover found {len(component_filepaths)} files in component directories.\")\n\n    if hasattr(settings, \"BASE_DIR\") and settings.BASE_DIR:\n        project_root = str(settings.BASE_DIR)\n    else:\n        # Fallback for getting the root dir, see https://stackoverflow.com/a/16413955/9788634\n        project_root = os.path.abspath(os.path.dirname(__name__))\n\n    modules: List[str] = []\n\n    # We handle dirs from `COMPONENTS.dirs` and from individual apps separately.\n    #\n    # Because for dirs in `COMPONENTS.dirs`, we assume they will be nested under `BASE_DIR`,\n    # and that `BASE_DIR` is the current working dir (CWD). So the path relatively to `BASE_DIR`\n    # is ALSO the python import path.\n    for filepath in component_filepaths:\n        module_path = _filepath_to_python_module(filepath, project_root, None)\n        # Ignore files starting with dot `.` or files in dirs that start with dot.\n        #\n        # If any of the parts of the path start with a dot, e.g. the filesystem path\n        # is `./abc/.def`, then this gets converted to python module as `abc..def`\n        #\n        # NOTE: This approach also ignores files:\n        #   - with two dots in the middle (ab..cd.py)\n        #   - an extra dot at the end (abcd..py)\n        #   - files outside of the parent component (../abcd.py).\n        # But all these are NOT valid python modules so that's fine.\n        if \"..\" in module_path:\n            continue\n\n        modules.append(module_path)\n\n    # For for apps, the directories may be outside of the project, e.g. in case of third party\n    # apps. So we have to resolve the python import path relative to the package name / the root\n    # import path for the app.\n    # See https://github.com/EmilStenstrom/django-components/issues/669\n    for conf in apps.get_app_configs():\n        for app_dir in app_settings.APP_DIRS:\n            comps_path = Path(conf.path).joinpath(app_dir)\n            if not comps_path.exists():\n                continue\n            app_component_filepaths = search_dirs([comps_path], \"**/*.py\")\n            for filepath in app_component_filepaths:\n                app_component_module = _filepath_to_python_module(filepath, conf.path, conf.name)\n                modules.append(app_component_module)\n\n    return _import_modules(modules, map_module)\n
    "},{"location":"reference/django_components/#django_components.autodiscover.import_libraries","title":"import_libraries","text":"
    import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n

    Import modules set in COMPONENTS.libraries setting.

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

    Source code in src/django_components/autodiscover.py
    def import_libraries(\n    map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n    \"\"\"\n    Import modules set in `COMPONENTS.libraries` setting.\n\n    You can map the module paths with `map_module` function. This serves\n    as an escape hatch for when you need to use this function in tests.\n    \"\"\"\n    from django_components.app_settings import app_settings\n\n    return _import_modules(app_settings.LIBRARIES, map_module)\n
    "},{"location":"reference/django_components/#django_components.autodiscover.search_dirs","title":"search_dirs","text":"
    search_dirs(dirs: List[Path], search_glob: str) -> List[Path]\n

    Search the directories for the given glob pattern. Glob search results are returned as a flattened list.

    Source code in src/django_components/autodiscover.py
    def search_dirs(dirs: List[Path], search_glob: str) -> List[Path]:\n    \"\"\"\n    Search the directories for the given glob pattern. Glob search results are returned\n    as a flattened list.\n    \"\"\"\n    matched_files: List[Path] = []\n    for directory in dirs:\n        for path in glob.iglob(str(Path(directory) / search_glob), recursive=True):\n            matched_files.append(Path(path))\n\n    return matched_files\n
    "},{"location":"reference/django_components/#django_components.component","title":"component","text":"

    Classes:

    • Component \u2013
    • ComponentNode \u2013

      Django.template.Node subclass that renders a django-components component

    • ComponentView \u2013

      Subclass of django.views.View where the Component instance is available

    "},{"location":"reference/django_components/#django_components.component.Component","title":"Component","text":"
    Component(\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,\n)\n

    Bases: Generic[ArgsType, KwargsType, DataType, SlotsType]

    Methods:

    • as_view \u2013

      Shortcut for calling Component.View.as_view and passing component instance to it.

    • get_template \u2013

      Inlined Django template associated with this component. Can be a plain string or a Template instance.

    • get_template_name \u2013

      Filepath to the Django template associated with this component.

    • inject \u2013

      Use this method to retrieve the data that was passed to a {% provide %} tag

    • on_render_after \u2013

      Hook that runs just after the component's template was rendered.

    • on_render_before \u2013

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

    • render \u2013

      Render the component into a string.

    • render_css_dependencies \u2013

      Render only CSS dependencies available in the media class or provided as a string.

    • render_dependencies \u2013

      Helper function to render all dependencies for a component.

    • render_js_dependencies \u2013

      Render only JS dependencies available in the media class or provided as a string.

    • render_to_response \u2013

      Render the component and wrap the content in the response class.

    Attributes:

    • Media \u2013

      Defines JS and CSS media files associated with this component.

    • css (Optional[str]) \u2013

      Inlined CSS associated with this component.

    • input (RenderInput[ArgsType, KwargsType, SlotsType]) \u2013

      Input holds the data (like arg, kwargs, slots) that were passsed to

    • is_filled (Dict[str, bool]) \u2013

      Dictionary describing which slots have or have not been filled.

    • js (Optional[str]) \u2013

      Inlined JS associated with this component.

    • media (Media) \u2013

      Normalized definition of JS and CSS media files associated with this component.

    • response_class \u2013

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

    • template (Optional[Union[str, Template]]) \u2013

      Inlined Django template associated with this component. Can be a plain string or a Template instance.

    • template_name (Optional[str]) \u2013

      Filepath to the Django template associated with this component.

    Source code in src/django_components/component.py
    def __init__(\n    self,\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,  # noqa F811\n):\n    # When user first instantiates the component class before calling\n    # `render` or `render_to_response`, then we want to allow the render\n    # function to make use of the instantiated object.\n    #\n    # So while `MyComp.render()` creates a new instance of MyComp internally,\n    # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n    # already-instantiated object.\n    #\n    # To achieve that, we want to re-assign the class methods as instance methods.\n    # For that we have to \"unwrap\" the class methods via __func__.\n    # See https://stackoverflow.com/a/76706399/9788634\n    self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self)  # type: ignore\n    self.render = types.MethodType(self.__class__.render.__func__, self)  # type: ignore\n    self.as_view = types.MethodType(self.__class__.as_view.__func__, self)  # type: ignore\n\n    self.registered_name: Optional[str] = registered_name\n    self.outer_context: Context = outer_context or Context()\n    self.fill_content = fill_content or {}\n    self.component_id = component_id or gen_id()\n    self.registry = registry or registry_\n    self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n    # None == uninitialized, False == No types, Tuple == types\n    self._types: Optional[Union[Tuple[Any, Any, Any, Any], Literal[False]]] = None\n
    "},{"location":"reference/django_components/#django_components.component.Component.Media","title":"Media class-attribute instance-attribute","text":"
    Media = ComponentMediaInput\n

    Defines JS and CSS media files associated with this component.

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

    Inlined CSS associated with this component.

    "},{"location":"reference/django_components/#django_components.component.Component.input","title":"input property","text":"
    input: RenderInput[ArgsType, KwargsType, SlotsType]\n

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

    "},{"location":"reference/django_components/#django_components.component.Component.is_filled","title":"is_filled property","text":"
    is_filled: Dict[str, bool]\n

    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/django_components/#django_components.component.Component.js","title":"js class-attribute instance-attribute","text":"
    js: Optional[str] = None\n

    Inlined JS associated with this component.

    "},{"location":"reference/django_components/#django_components.component.Component.media","title":"media instance-attribute","text":"
    media: Media\n

    Normalized definition of JS and CSS media files associated with this component.

    NOTE: This field is generated from Component.Media class.

    "},{"location":"reference/django_components/#django_components.component.Component.response_class","title":"response_class class-attribute instance-attribute","text":"
    response_class = HttpResponse\n

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

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

    Inlined Django template associated with this component. Can be a plain string or a Template instance.

    Only one of template_name, get_template_name, template or get_template must be defined.

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

    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_name, get_template_name, template or get_template must be defined.

    "},{"location":"reference/django_components/#django_components.component.Component.as_view","title":"as_view classmethod","text":"
    as_view(**initkwargs: Any) -> ViewFn\n

    Shortcut for calling Component.View.as_view and passing component instance to it.

    Source code in src/django_components/component.py
    @classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n    \"\"\"\n    Shortcut for calling `Component.View.as_view` and passing component instance to it.\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    # Allow the View class to access this component via `self.component`\n    return comp.View.as_view(**initkwargs, component=comp)\n
    "},{"location":"reference/django_components/#django_components.component.Component.get_template","title":"get_template","text":"
    get_template(context: Context) -> Optional[Union[str, Template]]\n

    Inlined Django template associated with this component. Can be a plain string or a Template instance.

    Only one of template_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n    \"\"\"\n    Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/#django_components.component.Component.get_template_name","title":"get_template_name","text":"
    get_template_name(context: Context) -> Optional[str]\n

    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_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template_name(self, context: Context) -> Optional[str]:\n    \"\"\"\n    Filepath to the Django template associated with this component.\n\n    The filepath must be relative to either the file where the component class was defined,\n    or one of the roots of `STATIFILES_DIRS`.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/#django_components.component.Component.inject","title":"inject","text":"
    inject(key: str, default: Optional[Any] = None) -> Any\n

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

    Source code in src/django_components/component.py
    def inject(self, key: str, default: Optional[Any] = None) -> Any:\n    \"\"\"\n    Use this method to retrieve the data that was passed to a `{% provide %}` tag\n    with the corresponding key.\n\n    To retrieve the data, `inject()` must be called inside a component that's\n    inside the `{% provide %}` tag.\n\n    You may also pass a default that will be used if the `provide` tag with given\n    key was NOT found.\n\n    This method mut be used inside the `get_context_data()` method and raises\n    an error if called elsewhere.\n\n    Example:\n\n    Given this template:\n    ```django\n    {% provide \"provider\" hello=\"world\" %}\n        {% component \"my_comp\" %}\n        {% endcomponent %}\n    {% endprovide %}\n    ```\n\n    And given this definition of \"my_comp\" component:\n    ```py\n    from django_components import Component, register\n\n    @register(\"my_comp\")\n    class MyComp(Component):\n        template = \"hi {{ data.hello }}!\"\n        def get_context_data(self):\n            data = self.inject(\"provider\")\n            return {\"data\": data}\n    ```\n\n    This renders into:\n    ```\n    hi world!\n    ```\n\n    As the `{{ data.hello }}` is taken from the \"provider\".\n    \"\"\"\n    if self.input is None:\n        raise RuntimeError(\n            f\"Method 'inject()' of component '{self.name}' was called outside of 'get_context_data()'\"\n        )\n\n    return get_injected_context_var(self.name, self.input.context, key, default)\n
    "},{"location":"reference/django_components/#django_components.component.Component.on_render_after","title":"on_render_after","text":"
    on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\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.

    Source code in src/django_components/component.py
    def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n    \"\"\"\n    Hook that runs just after the component's template was rendered.\n    It receives the rendered output as the last argument.\n\n    You can use this hook to access the context or the template, but modifying\n    them won't have any effect.\n\n    To override the content that gets rendered, you can return a string or SafeString\n    from this hook.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/#django_components.component.Component.on_render_before","title":"on_render_before","text":"
    on_render_before(context: Context, template: Template) -> 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.

    Source code in src/django_components/component.py
    def on_render_before(self, context: Context, template: Template) -> None:\n    \"\"\"\n    Hook that runs just before the component's template is rendered.\n\n    You can use this hook to access or modify the context or the template.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/#django_components.component.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) -> str\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render(\n    cls,\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) -> str:\n    \"\"\"\n    Render the component into a string.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    return comp._render(context, args, kwargs, slots, escape_slots_content)\n
    "},{"location":"reference/django_components/#django_components.component.Component.render_css_dependencies","title":"render_css_dependencies","text":"
    render_css_dependencies() -> SafeString\n

    Render only CSS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_css_dependencies(self) -> SafeString:\n    \"\"\"Render only CSS dependencies available in the media class or provided as a string.\"\"\"\n    if self.css is not None:\n        return mark_safe(f\"<style>{self.css}</style>\")\n    return mark_safe(\"\\n\".join(self.media.render_css()))\n
    "},{"location":"reference/django_components/#django_components.component.Component.render_dependencies","title":"render_dependencies","text":"
    render_dependencies() -> SafeString\n

    Helper function to render all dependencies for a component.

    Source code in src/django_components/component.py
    def render_dependencies(self) -> SafeString:\n    \"\"\"Helper function to render all dependencies for a component.\"\"\"\n    dependencies = []\n\n    css_deps = self.render_css_dependencies()\n    if css_deps:\n        dependencies.append(css_deps)\n\n    js_deps = self.render_js_dependencies()\n    if js_deps:\n        dependencies.append(js_deps)\n\n    return mark_safe(\"\\n\".join(dependencies))\n
    "},{"location":"reference/django_components/#django_components.component.Component.render_js_dependencies","title":"render_js_dependencies","text":"
    render_js_dependencies() -> SafeString\n

    Render only JS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_js_dependencies(self) -> SafeString:\n    \"\"\"Render only JS dependencies available in the media class or provided as a string.\"\"\"\n    if self.js is not None:\n        return mark_safe(f\"<script>{self.js}</script>\")\n    return mark_safe(\"\\n\".join(self.media.render_js()))\n
    "},{"location":"reference/django_components/#django_components.component.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    *response_args: Any,\n    **response_kwargs: Any\n) -> HttpResponse\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render_to_response(\n    cls,\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    slots: Optional[SlotsType] = None,\n    escape_slots_content: bool = True,\n    args: Optional[ArgsType] = None,\n    kwargs: Optional[KwargsType] = None,\n    *response_args: Any,\n    **response_kwargs: Any,\n) -> HttpResponse:\n    \"\"\"\n    Render the component and wrap the content in the response class.\n\n    The response class is taken from `Component.response_class`. Defaults to `django.http.HttpResponse`.\n\n    This is the interface for the `django.views.View` class which allows us to\n    use components as Django views with `component.as_view()`.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Any additional args and kwargs are passed to the `response_class`.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    content = cls.render(\n        args=args,\n        kwargs=kwargs,\n        context=context,\n        slots=slots,\n        escape_slots_content=escape_slots_content,\n    )\n    return cls.response_class(content, *response_args, **response_kwargs)\n
    "},{"location":"reference/django_components/#django_components.component.ComponentNode","title":"ComponentNode","text":"
    ComponentNode(\n    name: str,\n    args: List[Expression],\n    kwargs: RuntimeKwargs,\n    registry: ComponentRegistry,\n    isolated_context: bool = False,\n    fill_nodes: Optional[List[FillNode]] = None,\n    node_id: Optional[str] = None,\n)\n

    Bases: BaseNode

    Django.template.Node subclass that renders a django-components component

    Source code in src/django_components/component.py
    def __init__(\n    self,\n    name: str,\n    args: List[Expression],\n    kwargs: RuntimeKwargs,\n    registry: ComponentRegistry,  # noqa F811\n    isolated_context: bool = False,\n    fill_nodes: Optional[List[FillNode]] = None,\n    node_id: Optional[str] = None,\n) -> None:\n    super().__init__(nodelist=NodeList(fill_nodes), args=args, kwargs=kwargs, node_id=node_id)\n\n    self.name = name\n    self.isolated_context = isolated_context\n    self.fill_nodes = fill_nodes or []\n    self.registry = registry\n
    "},{"location":"reference/django_components/#django_components.component.ComponentView","title":"ComponentView","text":"
    ComponentView(component: Component, **kwargs: Any)\n

    Bases: View

    Subclass of django.views.View where the Component instance is available via self.component.

    Source code in src/django_components/component.py
    def __init__(self, component: \"Component\", **kwargs: Any) -> None:\n    super().__init__(**kwargs)\n    self.component = component\n
    "},{"location":"reference/django_components/#django_components.component_media","title":"component_media","text":"

    Classes:

    • ComponentMediaInput \u2013

      Defines JS and CSS media files associated with this component.

    • MediaMeta \u2013

      Metaclass for handling media files for components.

    "},{"location":"reference/django_components/#django_components.component_media.ComponentMediaInput","title":"ComponentMediaInput","text":"

    Defines JS and CSS media files associated with this component.

    "},{"location":"reference/django_components/#django_components.component_media.MediaMeta","title":"MediaMeta","text":"

    Bases: MediaDefiningClass

    Metaclass for handling media files for components.

    Similar to MediaDefiningClass, this class supports the use of Media attribute to define associated JS/CSS files, which are then available under media attribute as a instance of Media class.

    This subclass has following changes:

    "},{"location":"reference/django_components/#django_components.component_media.MediaMeta--1-support-for-multiple-interfaces-of-jscss","title":"1. Support for multiple interfaces of JS/CSS","text":"
    1. As plain strings

      class MyComponent(Component):\n    class Media:\n        js = \"path/to/script.js\"\n        css = \"path/to/style.css\"\n

    2. As lists

      class MyComponent(Component):\n    class Media:\n        js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n        css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n

    3. [CSS ONLY] Dicts of strings

      class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": \"path/to/style1.css\",\n            \"print\": \"path/to/style2.css\",\n        }\n

    4. [CSS ONLY] Dicts of lists

      class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": [\"path/to/style1.css\"],\n            \"print\": [\"path/to/style2.css\"],\n        }\n

    "},{"location":"reference/django_components/#django_components.component_media.MediaMeta--2-media-are-first-resolved-relative-to-class-definition-file","title":"2. Media are first resolved relative to class definition file","text":"

    E.g. if in a directory my_comp you have script.js and my_comp.py, and my_comp.py looks like this:

    class MyComponent(Component):\n    class Media:\n        js = \"script.js\"\n

    Then script.js will be resolved as my_comp/script.js.

    "},{"location":"reference/django_components/#django_components.component_media.MediaMeta--3-media-can-be-defined-as-str-bytes-pathlike-safestring-or-function-of-thereof","title":"3. Media can be defined as str, bytes, PathLike, SafeString, or function of thereof","text":"

    E.g.:

    def lazy_eval_css():\n    # do something\n    return path\n\nclass MyComponent(Component):\n    class Media:\n        js = b\"script.js\"\n        css = lazy_eval_css\n
    "},{"location":"reference/django_components/#django_components.component_media.MediaMeta--4-subclass-media-class-with-media_class","title":"4. Subclass Media class with media_class","text":"

    Normal MediaDefiningClass creates an instance of Media class under the media attribute. This class allows to override which class will be instantiated with media_class attribute:

    class MyMedia(Media):\n    def render_js(self):\n        ...\n\nclass MyComponent(Component):\n    media_class = MyMedia\n    def get_context_data(self):\n        assert isinstance(self.media, MyMedia)\n
    "},{"location":"reference/django_components/#django_components.component_registry","title":"component_registry","text":"

    Classes:

    • ComponentRegistry \u2013

      Manages which components can be used in the template tags.

    Functions:

    • register \u2013

      Class decorator to register a component.

    Attributes:

    • registry (ComponentRegistry) \u2013

      The default and global component registry. Use this instance to directly

    "},{"location":"reference/django_components/#django_components.component_registry.registry","title":"registry module-attribute","text":"
    registry: ComponentRegistry = ComponentRegistry()\n

    The default and global component registry. Use this instance to directly register or remove components:

    # Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Get single\nregistry.get(\"button\")\n# Get all\nregistry.all()\n# Unregister single\nregistry.unregister(\"button\")\n# Unregister all\nregistry.clear()\n
    "},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry","title":"ComponentRegistry","text":"
    ComponentRegistry(\n    library: Optional[Library] = None, settings: Optional[Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]] = None\n)\n

    Manages which components can be used in the template tags.

    Each ComponentRegistry instance is associated with an instance of Django's Library. So when you register or unregister a component to/from a component registry, behind the scenes the registry automatically adds/removes the component's template tag to/from the Library.

    The Library instance can be set at instantiation. If omitted, then the default Library instance from django_components is used. The Library instance can be accessed under library attribute.

    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

    Methods:

    • all \u2013

      Retrieve all registered component classes.

    • clear \u2013

      Clears the registry, unregistering all components.

    • get \u2013

      Retrieve a component class registered under the given name.

    • register \u2013

      Register a component with this registry under the given name.

    • unregister \u2013

      Unlinks a previously-registered component from the registry under the given name.

    Attributes:

    • library (Library) \u2013

      The template tag library with which the component registry is associated.

    Source code in src/django_components/component_registry.py
    def __init__(\n    self,\n    library: Optional[Library] = None,\n    settings: Optional[Union[RegistrySettings, Callable[[\"ComponentRegistry\"], RegistrySettings]]] = None,\n) -> None:\n    self._registry: Dict[str, ComponentRegistryEntry] = {}  # component name -> component_entry mapping\n    self._tags: Dict[str, Set[str]] = {}  # tag -> list[component names]\n    self._library = library\n    self._settings_input = settings\n    self._settings: Optional[Callable[[], InternalRegistrySettings]] = None\n\n    all_registries.append(self)\n
    "},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.library","title":"library property","text":"
    library: Library\n

    The template tag library with which the component registry is associated.

    "},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.all","title":"all","text":"
    all() -> Dict[str, Type[Component]]\n

    Retrieve all registered 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
    Source code in src/django_components/component_registry.py
    def all(self) -> Dict[str, Type[\"Component\"]]:\n    \"\"\"\n    Retrieve all registered component classes.\n\n    Example:\n\n    ```py\n    # First register components\n    registry.register(\"button\", ButtonComponent)\n    registry.register(\"card\", CardComponent)\n    # Then get all\n    registry.all()\n    # > {\n    # >   \"button\": ButtonComponent,\n    # >   \"card\": CardComponent,\n    # > }\n    ```\n    \"\"\"\n    comps = {key: entry.cls for key, entry in self._registry.items()}\n    return comps\n
    "},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.clear","title":"clear","text":"
    clear() -> None\n

    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
    Source code in src/django_components/component_registry.py
    def clear(self) -> None:\n    \"\"\"\n    Clears the registry, unregistering all components.\n\n    Example:\n\n    ```py\n    # First register components\n    registry.register(\"button\", ButtonComponent)\n    registry.register(\"card\", CardComponent)\n    # Then clear\n    registry.clear()\n    # Then get all\n    registry.all()\n    # > {}\n    ```\n    \"\"\"\n    all_comp_names = list(self._registry.keys())\n    for comp_name in all_comp_names:\n        self.unregister(comp_name)\n\n    self._registry = {}\n    self._tags = {}\n
    "},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.get","title":"get","text":"
    get(name: str) -> Type[Component]\n

    Retrieve a 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
    Source code in src/django_components/component_registry.py
    def get(self, name: str) -> Type[\"Component\"]:\n    \"\"\"\n    Retrieve a component class registered under the given name.\n\n    Raises `NotRegistered` if the given name is not registered.\n\n    Example:\n\n    ```py\n    # First register component\n    registry.register(\"button\", ButtonComponent)\n    # Then get\n    registry.get(\"button\")\n    # > ButtonComponent\n    ```\n    \"\"\"\n    if name not in self._registry:\n        raise NotRegistered('The component \"%s\" is not registered' % name)\n\n    return self._registry[name].cls\n
    "},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.register","title":"register","text":"
    register(name: str, component: Type[Component]) -> None\n

    Register a component 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\" %}{% endcomponent %}\n

    Raises AlreadyRegistered if a different component was already registered under the same name.

    Example:

    registry.register(\"button\", ButtonComponent)\n
    Source code in src/django_components/component_registry.py
    def register(self, name: str, component: Type[\"Component\"]) -> None:\n    \"\"\"\n    Register a component with this registry under the given name.\n\n    A component MUST be registered before it can be used in a template such as:\n    ```django\n    {% component \"my_comp\" %}{% endcomponent %}\n    ```\n\n    Raises `AlreadyRegistered` if a different component was already registered\n    under the same name.\n\n    Example:\n\n    ```py\n    registry.register(\"button\", ButtonComponent)\n    ```\n    \"\"\"\n    existing_component = self._registry.get(name)\n    if existing_component and existing_component.cls._class_hash != component._class_hash:\n        raise AlreadyRegistered('The component \"%s\" has already been registered' % name)\n\n    entry = self._register_to_library(name, component)\n\n    # Keep track of which components use which tags, because multiple components may\n    # use the same tag.\n    tag = entry.tag\n    if tag not in self._tags:\n        self._tags[tag] = set()\n    self._tags[tag].add(name)\n\n    self._registry[name] = entry\n
    "},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.unregister","title":"unregister","text":"
    unregister(name: str) -> None\n

    Unlinks a previously-registered component from the registry under the given name.

    Once a component is unregistered, it CANNOT be used in a template anymore. Following would raise an error:

    {% component \"my_comp\" %}{% endcomponent %}\n

    Raises NotRegistered if the given name is not registered.

    Example:

    # First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
    Source code in src/django_components/component_registry.py
    def unregister(self, name: str) -> None:\n    \"\"\"\n    Unlinks a previously-registered component from the registry under the given name.\n\n    Once a component is unregistered, it CANNOT be used in a template anymore.\n    Following would raise an error:\n    ```django\n    {% component \"my_comp\" %}{% endcomponent %}\n    ```\n\n    Raises `NotRegistered` if the given name is not registered.\n\n    Example:\n\n    ```py\n    # First register component\n    registry.register(\"button\", ButtonComponent)\n    # Then unregister\n    registry.unregister(\"button\")\n    ```\n    \"\"\"\n    # Validate\n    self.get(name)\n\n    entry = self._registry[name]\n    tag = entry.tag\n\n    # Unregister the tag from library if this was the last component using this tag\n    # Unlink component from tag\n    self._tags[tag].remove(name)\n\n    # Cleanup\n    is_tag_empty = not len(self._tags[tag])\n    if is_tag_empty:\n        del self._tags[tag]\n\n    # Only unregister a tag if it's NOT protected\n    is_protected = is_tag_protected(self.library, tag)\n    if not is_protected:\n        # Unregister the tag from library if this was the last component using this tag\n        if is_tag_empty and tag in self.library.tags:\n            del self.library.tags[tag]\n\n    del self._registry[name]\n
    "},{"location":"reference/django_components/#django_components.component_registry.register","title":"register","text":"
    register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]\n

    Class decorator to register a component.

    Usage:

    @register(\"my_component\")\nclass MyComponent(Component):\n    ...\n

    Optionally specify which ComponentRegistry the component should be registered to by setting the registry kwarg:

    my_lib = django.template.Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n    ...\n
    Source code in src/django_components/component_registry.py
    def register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]:\n    \"\"\"\n    Class decorator to register a component.\n\n    Usage:\n\n    ```py\n    @register(\"my_component\")\n    class MyComponent(Component):\n        ...\n    ```\n\n    Optionally specify which `ComponentRegistry` the component should be registered to by\n    setting the `registry` kwarg:\n\n    ```py\n    my_lib = django.template.Library()\n    my_reg = ComponentRegistry(library=my_lib)\n\n    @register(\"my_component\", registry=my_reg)\n    class MyComponent(Component):\n        ...\n    ```\n    \"\"\"\n    if registry is None:\n        registry = _the_registry\n\n    def decorator(component: _TComp) -> _TComp:\n        registry.register(name=name, component=component)\n        return component\n\n    return decorator\n
    "},{"location":"reference/django_components/#django_components.components","title":"components","text":"

    Modules:

    • dynamic \u2013
    "},{"location":"reference/django_components/#django_components.components.dynamic","title":"dynamic","text":"

    Modules:

    • types \u2013

      Helper types for IDEs.

    Classes:

    • DynamicComponent \u2013

      Dynamic component - This component takes inputs and renders the outputs depending on the

    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent","title":"DynamicComponent","text":"
    DynamicComponent(\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,\n)\n

    Bases: Component

    Dynamic component - This component takes inputs and renders the outputs depending on the is and registry arguments.

    • is - required - The component class or registered name of the component that will be rendered in this place.

    • registry - optional - Specify the registry to search for the registered name. If omitted, all registries are searched.

    Methods:

    • as_view \u2013

      Shortcut for calling Component.View.as_view and passing component instance to it.

    • get_template \u2013

      Inlined Django template associated with this component. Can be a plain string or a Template instance.

    • get_template_name \u2013

      Filepath to the Django template associated with this component.

    • inject \u2013

      Use this method to retrieve the data that was passed to a {% provide %} tag

    • on_render_after \u2013

      Hook that runs just after the component's template was rendered.

    • on_render_before \u2013

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

    • render \u2013

      Render the component into a string.

    • render_css_dependencies \u2013

      Render only CSS dependencies available in the media class or provided as a string.

    • render_dependencies \u2013

      Helper function to render all dependencies for a component.

    • render_js_dependencies \u2013

      Render only JS dependencies available in the media class or provided as a string.

    • render_to_response \u2013

      Render the component and wrap the content in the response class.

    Attributes:

    • Media \u2013

      Defines JS and CSS media files associated with this component.

    • css (Optional[str]) \u2013

      Inlined CSS associated with this component.

    • input (RenderInput[ArgsType, KwargsType, SlotsType]) \u2013

      Input holds the data (like arg, kwargs, slots) that were passsed to

    • is_filled (Dict[str, bool]) \u2013

      Dictionary describing which slots have or have not been filled.

    • js (Optional[str]) \u2013

      Inlined JS associated with this component.

    • media (Media) \u2013

      Normalized definition of JS and CSS media files associated with this component.

    • response_class \u2013

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

    • template_name (Optional[str]) \u2013

      Filepath to the Django template associated with this component.

    Source code in src/django_components/component.py
    def __init__(\n    self,\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,  # noqa F811\n):\n    # When user first instantiates the component class before calling\n    # `render` or `render_to_response`, then we want to allow the render\n    # function to make use of the instantiated object.\n    #\n    # So while `MyComp.render()` creates a new instance of MyComp internally,\n    # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n    # already-instantiated object.\n    #\n    # To achieve that, we want to re-assign the class methods as instance methods.\n    # For that we have to \"unwrap\" the class methods via __func__.\n    # See https://stackoverflow.com/a/76706399/9788634\n    self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self)  # type: ignore\n    self.render = types.MethodType(self.__class__.render.__func__, self)  # type: ignore\n    self.as_view = types.MethodType(self.__class__.as_view.__func__, self)  # type: ignore\n\n    self.registered_name: Optional[str] = registered_name\n    self.outer_context: Context = outer_context or Context()\n    self.fill_content = fill_content or {}\n    self.component_id = component_id or gen_id()\n    self.registry = registry or registry_\n    self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n    # None == uninitialized, False == No types, Tuple == types\n    self._types: Optional[Union[Tuple[Any, Any, Any, Any], Literal[False]]] = None\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.Media","title":"Media class-attribute instance-attribute","text":"
    Media = ComponentMediaInput\n

    Defines JS and CSS media files associated with this component.

    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.css","title":"css class-attribute instance-attribute","text":"
    css: Optional[str] = None\n

    Inlined CSS associated with this component.

    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.input","title":"input property","text":"
    input: RenderInput[ArgsType, KwargsType, SlotsType]\n

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

    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.is_filled","title":"is_filled property","text":"
    is_filled: Dict[str, bool]\n

    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/django_components/#django_components.components.dynamic.DynamicComponent.js","title":"js class-attribute instance-attribute","text":"
    js: Optional[str] = None\n

    Inlined JS associated with this component.

    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.media","title":"media instance-attribute","text":"
    media: Media\n

    Normalized definition of JS and CSS media files associated with this component.

    NOTE: This field is generated from Component.Media class.

    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.response_class","title":"response_class class-attribute instance-attribute","text":"
    response_class = HttpResponse\n

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

    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.template_name","title":"template_name class-attribute instance-attribute","text":"
    template_name: Optional[str] = None\n

    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_name, get_template_name, template or get_template must be defined.

    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.as_view","title":"as_view classmethod","text":"
    as_view(**initkwargs: Any) -> ViewFn\n

    Shortcut for calling Component.View.as_view and passing component instance to it.

    Source code in src/django_components/component.py
    @classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n    \"\"\"\n    Shortcut for calling `Component.View.as_view` and passing component instance to it.\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    # Allow the View class to access this component via `self.component`\n    return comp.View.as_view(**initkwargs, component=comp)\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.get_template","title":"get_template","text":"
    get_template(context: Context) -> Optional[Union[str, Template]]\n

    Inlined Django template associated with this component. Can be a plain string or a Template instance.

    Only one of template_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n    \"\"\"\n    Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.get_template_name","title":"get_template_name","text":"
    get_template_name(context: Context) -> Optional[str]\n

    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_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template_name(self, context: Context) -> Optional[str]:\n    \"\"\"\n    Filepath to the Django template associated with this component.\n\n    The filepath must be relative to either the file where the component class was defined,\n    or one of the roots of `STATIFILES_DIRS`.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.inject","title":"inject","text":"
    inject(key: str, default: Optional[Any] = None) -> Any\n

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

    Source code in src/django_components/component.py
    def inject(self, key: str, default: Optional[Any] = None) -> Any:\n    \"\"\"\n    Use this method to retrieve the data that was passed to a `{% provide %}` tag\n    with the corresponding key.\n\n    To retrieve the data, `inject()` must be called inside a component that's\n    inside the `{% provide %}` tag.\n\n    You may also pass a default that will be used if the `provide` tag with given\n    key was NOT found.\n\n    This method mut be used inside the `get_context_data()` method and raises\n    an error if called elsewhere.\n\n    Example:\n\n    Given this template:\n    ```django\n    {% provide \"provider\" hello=\"world\" %}\n        {% component \"my_comp\" %}\n        {% endcomponent %}\n    {% endprovide %}\n    ```\n\n    And given this definition of \"my_comp\" component:\n    ```py\n    from django_components import Component, register\n\n    @register(\"my_comp\")\n    class MyComp(Component):\n        template = \"hi {{ data.hello }}!\"\n        def get_context_data(self):\n            data = self.inject(\"provider\")\n            return {\"data\": data}\n    ```\n\n    This renders into:\n    ```\n    hi world!\n    ```\n\n    As the `{{ data.hello }}` is taken from the \"provider\".\n    \"\"\"\n    if self.input is None:\n        raise RuntimeError(\n            f\"Method 'inject()' of component '{self.name}' was called outside of 'get_context_data()'\"\n        )\n\n    return get_injected_context_var(self.name, self.input.context, key, default)\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.on_render_after","title":"on_render_after","text":"
    on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\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.

    Source code in src/django_components/component.py
    def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n    \"\"\"\n    Hook that runs just after the component's template was rendered.\n    It receives the rendered output as the last argument.\n\n    You can use this hook to access the context or the template, but modifying\n    them won't have any effect.\n\n    To override the content that gets rendered, you can return a string or SafeString\n    from this hook.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.on_render_before","title":"on_render_before","text":"
    on_render_before(context: Context, template: Template) -> 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.

    Source code in src/django_components/component.py
    def on_render_before(self, context: Context, template: Template) -> None:\n    \"\"\"\n    Hook that runs just before the component's template is rendered.\n\n    You can use this hook to access or modify the context or the template.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.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) -> str\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render(\n    cls,\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) -> str:\n    \"\"\"\n    Render the component into a string.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    return comp._render(context, args, kwargs, slots, escape_slots_content)\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.render_css_dependencies","title":"render_css_dependencies","text":"
    render_css_dependencies() -> SafeString\n

    Render only CSS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_css_dependencies(self) -> SafeString:\n    \"\"\"Render only CSS dependencies available in the media class or provided as a string.\"\"\"\n    if self.css is not None:\n        return mark_safe(f\"<style>{self.css}</style>\")\n    return mark_safe(\"\\n\".join(self.media.render_css()))\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.render_dependencies","title":"render_dependencies","text":"
    render_dependencies() -> SafeString\n

    Helper function to render all dependencies for a component.

    Source code in src/django_components/component.py
    def render_dependencies(self) -> SafeString:\n    \"\"\"Helper function to render all dependencies for a component.\"\"\"\n    dependencies = []\n\n    css_deps = self.render_css_dependencies()\n    if css_deps:\n        dependencies.append(css_deps)\n\n    js_deps = self.render_js_dependencies()\n    if js_deps:\n        dependencies.append(js_deps)\n\n    return mark_safe(\"\\n\".join(dependencies))\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.render_js_dependencies","title":"render_js_dependencies","text":"
    render_js_dependencies() -> SafeString\n

    Render only JS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_js_dependencies(self) -> SafeString:\n    \"\"\"Render only JS dependencies available in the media class or provided as a string.\"\"\"\n    if self.js is not None:\n        return mark_safe(f\"<script>{self.js}</script>\")\n    return mark_safe(\"\\n\".join(self.media.render_js()))\n
    "},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.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    *response_args: Any,\n    **response_kwargs: Any\n) -> HttpResponse\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render_to_response(\n    cls,\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    slots: Optional[SlotsType] = None,\n    escape_slots_content: bool = True,\n    args: Optional[ArgsType] = None,\n    kwargs: Optional[KwargsType] = None,\n    *response_args: Any,\n    **response_kwargs: Any,\n) -> HttpResponse:\n    \"\"\"\n    Render the component and wrap the content in the response class.\n\n    The response class is taken from `Component.response_class`. Defaults to `django.http.HttpResponse`.\n\n    This is the interface for the `django.views.View` class which allows us to\n    use components as Django views with `component.as_view()`.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Any additional args and kwargs are passed to the `response_class`.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    content = cls.render(\n        args=args,\n        kwargs=kwargs,\n        context=context,\n        slots=slots,\n        escape_slots_content=escape_slots_content,\n    )\n    return cls.response_class(content, *response_args, **response_kwargs)\n
    "},{"location":"reference/django_components/#django_components.context","title":"context","text":"

    This file centralizes various ways we use Django's Context class pass data across components, nodes, slots, and contexts.

    You can think of the Context as our storage system.

    Functions:

    • copy_forloop_context \u2013

      Forward the info about the current loop

    • get_injected_context_var \u2013

      Retrieve a 'provided' field. The field MUST have been previously 'provided'

    • prepare_context \u2013

      Initialize the internal context state.

    • set_component_id \u2013

      We use the Context object to pass down info on inside of which component

    • set_provided_context_var \u2013

      'Provide' given data under given key. In other words, this data can be retrieved

    "},{"location":"reference/django_components/#django_components.context.copy_forloop_context","title":"copy_forloop_context","text":"
    copy_forloop_context(from_context: Context, to_context: Context) -> None\n

    Forward the info about the current loop

    Source code in src/django_components/context.py
    def copy_forloop_context(from_context: Context, to_context: Context) -> None:\n    \"\"\"Forward the info about the current loop\"\"\"\n    # Note that the ForNode (which implements for loop behavior) does not\n    # only add the `forloop` key, but also keys corresponding to the loop elements\n    # So if the loop syntax is `{% for my_val in my_lists %}`, then ForNode also\n    # sets a `my_val` key.\n    # For this reason, instead of copying individual keys, we copy the whole stack layer\n    # set by ForNode.\n    if \"forloop\" in from_context:\n        forloop_dict_index = find_last_index(from_context.dicts, lambda d: \"forloop\" in d)\n        to_context.update(from_context.dicts[forloop_dict_index])\n
    "},{"location":"reference/django_components/#django_components.context.get_injected_context_var","title":"get_injected_context_var","text":"
    get_injected_context_var(component_name: str, context: Context, key: str, default: Optional[Any] = None) -> Any\n

    Retrieve a 'provided' field. The field MUST have been previously 'provided' by the component's ancestors using the {% provide %} template tag.

    Source code in src/django_components/context.py
    def get_injected_context_var(\n    component_name: str,\n    context: Context,\n    key: str,\n    default: Optional[Any] = None,\n) -> Any:\n    \"\"\"\n    Retrieve a 'provided' field. The field MUST have been previously 'provided'\n    by the component's ancestors using the `{% provide %}` template tag.\n    \"\"\"\n    # NOTE: For simplicity, we keep the provided values directly on the context.\n    # This plays nicely with Django's Context, which behaves like a stack, so \"newer\"\n    # values overshadow the \"older\" ones.\n    internal_key = _INJECT_CONTEXT_KEY_PREFIX + key\n\n    # Return provided value if found\n    if internal_key in context:\n        return context[internal_key]\n\n    # If a default was given, return that\n    if default is not None:\n        return default\n\n    # Otherwise raise error\n    raise KeyError(\n        f\"Component '{component_name}' tried to inject a variable '{key}' before it was provided.\"\n        f\" To fix this, make sure that at least one ancestor of component '{component_name}' has\"\n        f\" the variable '{key}' in their 'provide' attribute.\"\n    )\n
    "},{"location":"reference/django_components/#django_components.context.prepare_context","title":"prepare_context","text":"
    prepare_context(context: Context, component_id: str) -> None\n

    Initialize the internal context state.

    Source code in src/django_components/context.py
    def prepare_context(\n    context: Context,\n    component_id: str,\n) -> None:\n    \"\"\"Initialize the internal context state.\"\"\"\n    # Initialize mapping dicts within this rendering run.\n    # This is shared across the whole render chain, thus we set it only once.\n    if _FILLED_SLOTS_CONTENT_CONTEXT_KEY not in context:\n        context[_FILLED_SLOTS_CONTENT_CONTEXT_KEY] = {}\n\n    set_component_id(context, component_id)\n
    "},{"location":"reference/django_components/#django_components.context.set_component_id","title":"set_component_id","text":"
    set_component_id(context: Context, component_id: str) -> None\n

    We use the Context object to pass down info on inside of which component we are currently rendering.

    Source code in src/django_components/context.py
    def set_component_id(context: Context, component_id: str) -> None:\n    \"\"\"\n    We use the Context object to pass down info on inside of which component\n    we are currently rendering.\n    \"\"\"\n    context[_CURRENT_COMP_CONTEXT_KEY] = component_id\n
    "},{"location":"reference/django_components/#django_components.context.set_provided_context_var","title":"set_provided_context_var","text":"
    set_provided_context_var(context: Context, key: str, provided_kwargs: Dict[str, Any]) -> None\n

    'Provide' given data under given key. In other words, this data can be retrieved using self.inject(key) inside of get_context_data() method of components that are nested inside the {% provide %} tag.

    Source code in src/django_components/context.py
    def set_provided_context_var(\n    context: Context,\n    key: str,\n    provided_kwargs: Dict[str, Any],\n) -> None:\n    \"\"\"\n    'Provide' given data under given key. In other words, this data can be retrieved\n    using `self.inject(key)` inside of `get_context_data()` method of components that\n    are nested inside the `{% provide %}` tag.\n    \"\"\"\n    # NOTE: We raise TemplateSyntaxError since this func should be called only from\n    # within template.\n    if not key:\n        raise TemplateSyntaxError(\n            \"Provide tag received an empty string. Key must be non-empty and a valid identifier.\"\n        )\n    if not key.isidentifier():\n        raise TemplateSyntaxError(\n            \"Provide tag received a non-identifier string. Key must be non-empty and a valid identifier.\"\n        )\n\n    # We turn the kwargs into a NamedTuple so that the object that's \"provided\"\n    # is immutable. This ensures that the data returned from `inject` will always\n    # have all the keys that were passed to the `provide` tag.\n    tpl_cls = namedtuple(\"DepInject\", provided_kwargs.keys())  # type: ignore[misc]\n    payload = tpl_cls(**provided_kwargs)\n\n    internal_key = _INJECT_CONTEXT_KEY_PREFIX + key\n    context[internal_key] = payload\n
    "},{"location":"reference/django_components/#django_components.expression","title":"expression","text":"

    Classes:

    • Operator \u2013

      Operator describes something that somehow changes the inputs

    • SpreadOperator \u2013

      Operator that inserts one or more kwargs at the specified location.

    Functions:

    • process_aggregate_kwargs \u2013

      This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs

    "},{"location":"reference/django_components/#django_components.expression.Operator","title":"Operator","text":"

    Bases: ABC

    Operator describes something that somehow changes the inputs to template tags (the {% %}).

    For example, a SpreadOperator inserts one or more kwargs at the specified location.

    "},{"location":"reference/django_components/#django_components.expression.SpreadOperator","title":"SpreadOperator","text":"
    SpreadOperator(expr: Expression)\n

    Bases: Operator

    Operator that inserts one or more kwargs at the specified location.

    Source code in src/django_components/expression.py
    def __init__(self, expr: Expression) -> None:\n    self.expr = expr\n
    "},{"location":"reference/django_components/#django_components.expression.process_aggregate_kwargs","title":"process_aggregate_kwargs","text":"
    process_aggregate_kwargs(kwargs: Mapping[str, Any]) -> Dict[str, Any]\n

    This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs start with some prefix delimited with : (e.g. attrs:).

    Example:

    process_component_kwargs({\"abc:one\": 1, \"abc:two\": 2, \"def:three\": 3, \"four\": 4})\n# {\"abc\": {\"one\": 1, \"two\": 2}, \"def\": {\"three\": 3}, \"four\": 4}\n

    We want to support a use case similar to Vue's fallthrough attributes. In other words, where a component author can designate a prop (input) which is a dict and which will be rendered as HTML attributes.

    This is useful for allowing component users to tweak styling or add event handling to the underlying HTML. E.g.:

    class=\"pa-4 d-flex text-black\" or @click.stop=\"alert('clicked!')\"

    So if the prop is attrs, and the component is called like so:

    {% component \"my_comp\" attrs=attrs %}\n

    then, if attrs is:

    {\"class\": \"text-red pa-4\", \"@click\": \"dispatch('my_event', 123)\"}\n

    and the component template is:

    <div {% html_attrs attrs add:class=\"extra-class\" %}></div>\n

    Then this renders:

    <div class=\"text-red pa-4 extra-class\" @click=\"dispatch('my_event', 123)\" ></div>\n

    However, this way it is difficult for the component user to define the attrs variable, especially if they want to combine static and dynamic values. Because they will need to pre-process the attrs dict.

    So, instead, we allow to \"aggregate\" props into a dict. So all props that start with attrs:, like attrs:class=\"text-red\", will be collected into a dict at key attrs.

    This provides sufficient flexiblity to make it easy for component users to provide \"fallthrough attributes\", and sufficiently easy for component authors to process that input while still being able to provide their own keys.

    Source code in src/django_components/expression.py
    def process_aggregate_kwargs(kwargs: Mapping[str, Any]) -> Dict[str, Any]:\n    \"\"\"\n    This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs\n    start with some prefix delimited with `:` (e.g. `attrs:`).\n\n    Example:\n    ```py\n    process_component_kwargs({\"abc:one\": 1, \"abc:two\": 2, \"def:three\": 3, \"four\": 4})\n    # {\"abc\": {\"one\": 1, \"two\": 2}, \"def\": {\"three\": 3}, \"four\": 4}\n    ```\n\n    ---\n\n    We want to support a use case similar to Vue's fallthrough attributes.\n    In other words, where a component author can designate a prop (input)\n    which is a dict and which will be rendered as HTML attributes.\n\n    This is useful for allowing component users to tweak styling or add\n    event handling to the underlying HTML. E.g.:\n\n    `class=\"pa-4 d-flex text-black\"` or `@click.stop=\"alert('clicked!')\"`\n\n    So if the prop is `attrs`, and the component is called like so:\n    ```django\n    {% component \"my_comp\" attrs=attrs %}\n    ```\n\n    then, if `attrs` is:\n    ```py\n    {\"class\": \"text-red pa-4\", \"@click\": \"dispatch('my_event', 123)\"}\n    ```\n\n    and the component template is:\n    ```django\n    <div {% html_attrs attrs add:class=\"extra-class\" %}></div>\n    ```\n\n    Then this renders:\n    ```html\n    <div class=\"text-red pa-4 extra-class\" @click=\"dispatch('my_event', 123)\" ></div>\n    ```\n\n    However, this way it is difficult for the component user to define the `attrs`\n    variable, especially if they want to combine static and dynamic values. Because\n    they will need to pre-process the `attrs` dict.\n\n    So, instead, we allow to \"aggregate\" props into a dict. So all props that start\n    with `attrs:`, like `attrs:class=\"text-red\"`, will be collected into a dict\n    at key `attrs`.\n\n    This provides sufficient flexiblity to make it easy for component users to provide\n    \"fallthrough attributes\", and sufficiently easy for component authors to process\n    that input while still being able to provide their own keys.\n    \"\"\"\n    processed_kwargs = {}\n    nested_kwargs: Dict[str, Dict[str, Any]] = {}\n    for key, val in kwargs.items():\n        if not is_aggregate_key(key):\n            processed_kwargs[key] = val\n            continue\n\n        # NOTE: Trim off the prefix from keys\n        prefix, sub_key = key.split(\":\", 1)\n        if prefix not in nested_kwargs:\n            nested_kwargs[prefix] = {}\n        nested_kwargs[prefix][sub_key] = val\n\n    # Assign aggregated values into normal input\n    for key, val in nested_kwargs.items():\n        if key in processed_kwargs:\n            raise TemplateSyntaxError(\n                f\"Received argument '{key}' both as a regular input ({key}=...)\"\n                f\" and as an aggregate dict ('{key}:key=...'). Must be only one of the two\"\n            )\n        processed_kwargs[key] = val\n\n    return processed_kwargs\n
    "},{"location":"reference/django_components/#django_components.finders","title":"finders","text":"

    Classes:

    • ComponentsFileSystemFinder \u2013

      A static files finder based on FileSystemFinder.

    "},{"location":"reference/django_components/#django_components.finders.ComponentsFileSystemFinder","title":"ComponentsFileSystemFinder","text":"
    ComponentsFileSystemFinder(app_names: Any = None, *args: Any, **kwargs: Any)\n

    Bases: BaseFinder

    A static files finder based on FileSystemFinder.

    Differences: - This finder uses COMPONENTS.dirs setting to locate files instead of STATICFILES_DIRS. - Whether a file within COMPONENTS.dirs is considered a STATIC file is configured by COMPONENTS.static_files_allowed and COMPONENTS.forbidden_static_files. - If COMPONENTS.dirs is not set, defaults to settings.BASE_DIR / \"components\"

    Methods:

    • find \u2013

      Look for files in the extra locations as defined in COMPONENTS.dirs.

    • find_location \u2013

      Find a requested static file in a location and return the found

    • list \u2013

      List all files in all locations.

    Source code in src/django_components/finders.py
    def __init__(self, app_names: Any = None, *args: Any, **kwargs: Any) -> None:\n    component_dirs = [str(p) for p in get_dirs()]\n\n    # NOTE: The rest of the __init__ is the same as `django.contrib.staticfiles.finders.FileSystemFinder`,\n    # but using our locations instead of STATICFILES_DIRS.\n\n    # List of locations with static files\n    self.locations: List[Tuple[str, str]] = []\n\n    # Maps dir paths to an appropriate storage instance\n    self.storages: Dict[str, FileSystemStorage] = {}\n    for root in component_dirs:\n        if isinstance(root, (list, tuple)):\n            prefix, root = root\n        else:\n            prefix = \"\"\n        if (prefix, root) not in self.locations:\n            self.locations.append((prefix, root))\n    for prefix, root in self.locations:\n        filesystem_storage = FileSystemStorage(location=root)\n        filesystem_storage.prefix = prefix\n        self.storages[root] = filesystem_storage\n\n    super().__init__(*args, **kwargs)\n
    "},{"location":"reference/django_components/#django_components.finders.ComponentsFileSystemFinder.find","title":"find","text":"
    find(path: str, all: bool = False) -> Union[List[str], str]\n

    Look for files in the extra locations as defined in COMPONENTS.dirs.

    Source code in src/django_components/finders.py
    def find(self, path: str, all: bool = False) -> Union[List[str], str]:\n    \"\"\"\n    Look for files in the extra locations as defined in COMPONENTS.dirs.\n    \"\"\"\n    matches: List[str] = []\n    for prefix, root in self.locations:\n        if root not in searched_locations:\n            searched_locations.append(root)\n        matched_path = self.find_location(root, path, prefix)\n        if matched_path:\n            if not all:\n                return matched_path\n            matches.append(matched_path)\n    return matches\n
    "},{"location":"reference/django_components/#django_components.finders.ComponentsFileSystemFinder.find_location","title":"find_location","text":"
    find_location(root: str, path: str, prefix: Optional[str] = None) -> Optional[str]\n

    Find a requested static file in a location and return the found absolute path (or None if no match).

    Source code in src/django_components/finders.py
    def find_location(self, root: str, path: str, prefix: Optional[str] = None) -> Optional[str]:\n    \"\"\"\n    Find a requested static file in a location and return the found\n    absolute path (or ``None`` if no match).\n    \"\"\"\n    if prefix:\n        prefix = \"%s%s\" % (prefix, os.sep)\n        if not path.startswith(prefix):\n            return None\n        path = path.removeprefix(prefix)\n    path = safe_join(root, path)\n\n    if os.path.exists(path) and self._is_path_valid(path):\n        return path\n    return None\n
    "},{"location":"reference/django_components/#django_components.finders.ComponentsFileSystemFinder.list","title":"list","text":"
    list(ignore_patterns: List[str]) -> Iterable[Tuple[str, FileSystemStorage]]\n

    List all files in all locations.

    Source code in src/django_components/finders.py
    def list(self, ignore_patterns: List[str]) -> Iterable[Tuple[str, FileSystemStorage]]:\n    \"\"\"\n    List all files in all locations.\n    \"\"\"\n    for prefix, root in self.locations:\n        # Skip nonexistent directories.\n        if os.path.isdir(root):\n            storage = self.storages[root]\n            for path in get_files(storage, ignore_patterns):\n                if self._is_path_valid(path):\n                    yield path, storage\n
    "},{"location":"reference/django_components/#django_components.library","title":"library","text":"

    Module for interfacing with Django's Library (django.template.library)

    Attributes:

    • PROTECTED_TAGS \u2013

      These are the names that users cannot choose for their components,

    "},{"location":"reference/django_components/#django_components.library.PROTECTED_TAGS","title":"PROTECTED_TAGS module-attribute","text":"
    PROTECTED_TAGS = [\n    \"component_dependencies\",\n    \"component_css_dependencies\",\n    \"component_js_dependencies\",\n    \"fill\",\n    \"html_attrs\",\n    \"provide\",\n    \"slot\",\n]\n

    These are the names that users cannot choose for their components, as they would conflict with other tags in the Library.

    "},{"location":"reference/django_components/#django_components.logger","title":"logger","text":"

    Functions:

    • trace \u2013

      TRACE level logger.

    • trace_msg \u2013

      TRACE level logger with opinionated format for tracing interaction of components,

    "},{"location":"reference/django_components/#django_components.logger.trace","title":"trace","text":"
    trace(logger: Logger, message: str, *args: Any, **kwargs: Any) -> None\n

    TRACE level logger.

    To display TRACE logs, set the logging level to 5.

    Example:

    LOGGING = {\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\": 5,\n            \"handlers\": [\"console\"],\n        },\n    },\n}\n

    Source code in src/django_components/logger.py
    def trace(logger: logging.Logger, message: str, *args: Any, **kwargs: Any) -> None:\n    \"\"\"\n    TRACE level logger.\n\n    To display TRACE logs, set the logging level to 5.\n\n    Example:\n    ```py\n    LOGGING = {\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\": 5,\n                \"handlers\": [\"console\"],\n            },\n        },\n    }\n    ```\n    \"\"\"\n    if actual_trace_level_num == -1:\n        setup_logging()\n    if logger.isEnabledFor(actual_trace_level_num):\n        logger.log(actual_trace_level_num, message, *args, **kwargs)\n
    "},{"location":"reference/django_components/#django_components.logger.trace_msg","title":"trace_msg","text":"
    trace_msg(\n    action: Literal[\"PARSE\", \"ASSOC\", \"RENDR\", \"GET\", \"SET\"],\n    node_type: Literal[\"COMP\", \"FILL\", \"SLOT\", \"PROVIDE\", \"N/A\"],\n    node_name: str,\n    node_id: str,\n    msg: str = \"\",\n    component_id: Optional[str] = None,\n) -> None\n

    TRACE level logger with opinionated format for tracing interaction of components, nodes, and slots. Formats messages like so:

    \"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"

    Source code in src/django_components/logger.py
    def trace_msg(\n    action: Literal[\"PARSE\", \"ASSOC\", \"RENDR\", \"GET\", \"SET\"],\n    node_type: Literal[\"COMP\", \"FILL\", \"SLOT\", \"PROVIDE\", \"N/A\"],\n    node_name: str,\n    node_id: str,\n    msg: str = \"\",\n    component_id: Optional[str] = None,\n) -> None:\n    \"\"\"\n    TRACE level logger with opinionated format for tracing interaction of components,\n    nodes, and slots. Formats messages like so:\n\n    `\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"`\n    \"\"\"\n    msg_prefix = \"\"\n    if action == \"ASSOC\":\n        if not component_id:\n            raise ValueError(\"component_id must be set for the ASSOC action\")\n        msg_prefix = f\"TO COMP {component_id}\"\n    elif action == \"RENDR\" and node_type == \"FILL\":\n        if not component_id:\n            raise ValueError(\"component_id must be set for the RENDER action\")\n        msg_prefix = f\"FOR COMP {component_id}\"\n\n    msg_parts = [f\"{action} {node_type} {node_name} ID {node_id}\", *([msg_prefix] if msg_prefix else []), msg]\n    full_msg = \" \".join(msg_parts)\n\n    # NOTE: When debugging tests during development, it may be easier to change\n    # this to `print()`\n    trace(logger, full_msg)\n
    "},{"location":"reference/django_components/#django_components.middleware","title":"middleware","text":"

    Classes:

    • ComponentDependencyMiddleware \u2013

      Middleware that inserts CSS/JS dependencies for all rendered components at points marked with template tags.

    • DependencyReplacer \u2013

      Replacer for use in re.sub that replaces the first placeholder CSS and JS

    Functions:

    • join_media \u2013

      Return combined media object for iterable of components.

    "},{"location":"reference/django_components/#django_components.middleware.ComponentDependencyMiddleware","title":"ComponentDependencyMiddleware","text":"
    ComponentDependencyMiddleware(get_response: Callable[[HttpRequest], HttpResponse])\n

    Middleware that inserts CSS/JS dependencies for all rendered components at points marked with template tags.

    Source code in src/django_components/middleware.py
    def __init__(self, get_response: \"Callable[[HttpRequest], HttpResponse]\") -> None:\n    self.get_response = get_response\n\n    if iscoroutinefunction(self.get_response):\n        markcoroutinefunction(self)\n
    "},{"location":"reference/django_components/#django_components.middleware.DependencyReplacer","title":"DependencyReplacer","text":"
    DependencyReplacer(css_string: bytes, js_string: bytes)\n

    Replacer for use in re.sub that replaces the first placeholder CSS and JS tags it encounters and removes any subsequent ones.

    Source code in src/django_components/middleware.py
    def __init__(self, css_string: bytes, js_string: bytes) -> None:\n    self.js_string = js_string\n    self.css_string = css_string\n
    "},{"location":"reference/django_components/#django_components.middleware.join_media","title":"join_media","text":"
    join_media(components: Iterable[Component]) -> Media\n

    Return combined media object for iterable of components.

    Source code in src/django_components/middleware.py
    def join_media(components: Iterable[\"Component\"]) -> Media:\n    \"\"\"Return combined media object for iterable of components.\"\"\"\n\n    return sum([component.media for component in components], Media())\n
    "},{"location":"reference/django_components/#django_components.node","title":"node","text":"

    Classes:

    • BaseNode \u2013

      Shared behavior for our subclasses of Django's Node

    Functions:

    • get_node_children \u2013

      Get child Nodes from Node's nodelist atribute.

    • get_template_for_include_node \u2013

      This snippet is taken directly from IncludeNode.render(). Unfortunately the

    • walk_nodelist \u2013

      Recursively walk a NodeList, calling callback for each Node.

    "},{"location":"reference/django_components/#django_components.node.BaseNode","title":"BaseNode","text":"
    BaseNode(\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    args: Optional[List[Expression]] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n)\n

    Bases: Node

    Shared behavior for our subclasses of Django's Node

    Source code in src/django_components/node.py
    def __init__(\n    self,\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    args: Optional[List[Expression]] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n):\n    self.nodelist = nodelist or NodeList()\n    self.node_id = node_id or gen_id()\n    self.args = args or []\n    self.kwargs = kwargs or RuntimeKwargs({})\n
    "},{"location":"reference/django_components/#django_components.node.get_node_children","title":"get_node_children","text":"
    get_node_children(node: Node, context: Optional[Context] = None) -> NodeList\n

    Get child Nodes from Node's nodelist atribute.

    This function is taken from get_nodes_by_type method of django.template.base.Node.

    Source code in src/django_components/node.py
    def get_node_children(node: Node, context: Optional[Context] = None) -> NodeList:\n    \"\"\"\n    Get child Nodes from Node's nodelist atribute.\n\n    This function is taken from `get_nodes_by_type` method of `django.template.base.Node`.\n    \"\"\"\n    # Special case - {% extends %} tag - Load the template and go deeper\n    if isinstance(node, ExtendsNode):\n        # NOTE: When {% extends %} node is being parsed, it collects all remaining template\n        # under node.nodelist.\n        # Hence, when we come across ExtendsNode in the template, we:\n        # 1. Go over all nodes in the template using `node.nodelist`\n        # 2. Go over all nodes in the \"parent\" template, via `node.get_parent`\n        nodes = NodeList()\n        nodes.extend(node.nodelist)\n        template = node.get_parent(context)\n        nodes.extend(template.nodelist)\n        return nodes\n\n    # Special case - {% include %} tag - Load the template and go deeper\n    elif isinstance(node, IncludeNode):\n        template = get_template_for_include_node(node, context)\n        return template.nodelist\n\n    nodes = NodeList()\n    for attr in node.child_nodelists:\n        nodelist = getattr(node, attr, [])\n        if nodelist:\n            nodes.extend(nodelist)\n    return nodes\n
    "},{"location":"reference/django_components/#django_components.node.get_template_for_include_node","title":"get_template_for_include_node","text":"
    get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template\n

    This snippet is taken directly from IncludeNode.render(). Unfortunately the render logic doesn't separate out template loading logic from rendering, so we have to copy the method.

    Source code in src/django_components/node.py
    def get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template:\n    \"\"\"\n    This snippet is taken directly from `IncludeNode.render()`. Unfortunately the\n    render logic doesn't separate out template loading logic from rendering, so we\n    have to copy the method.\n    \"\"\"\n    template = include_node.template.resolve(context)\n    # Does this quack like a Template?\n    if not callable(getattr(template, \"render\", None)):\n        # If not, try the cache and select_template().\n        template_name = template or ()\n        if isinstance(template_name, str):\n            template_name = (\n                construct_relative_path(\n                    include_node.origin.template_name,\n                    template_name,\n                ),\n            )\n        else:\n            template_name = tuple(template_name)\n        cache = context.render_context.dicts[0].setdefault(include_node, {})\n        template = cache.get(template_name)\n        if template is None:\n            template = context.template.engine.select_template(template_name)\n            cache[template_name] = template\n    # Use the base.Template of a backends.django.Template.\n    elif hasattr(template, \"template\"):\n        template = template.template\n    return template\n
    "},{"location":"reference/django_components/#django_components.node.walk_nodelist","title":"walk_nodelist","text":"
    walk_nodelist(nodes: NodeList, callback: Callable[[Node], Optional[str]], context: Optional[Context] = None) -> None\n

    Recursively walk a NodeList, calling callback for each Node.

    Source code in src/django_components/node.py
    def walk_nodelist(\n    nodes: NodeList,\n    callback: Callable[[Node], Optional[str]],\n    context: Optional[Context] = None,\n) -> None:\n    \"\"\"Recursively walk a NodeList, calling `callback` for each Node.\"\"\"\n    node_queue: List[NodeTraverse] = [NodeTraverse(node=node, parent=None) for node in nodes]\n    while len(node_queue):\n        traverse = node_queue.pop()\n        callback(traverse)\n        child_nodes = get_node_children(traverse.node, context)\n        child_traverses = [NodeTraverse(node=child_node, parent=traverse) for child_node in child_nodes]\n        node_queue.extend(child_traverses)\n
    "},{"location":"reference/django_components/#django_components.provide","title":"provide","text":"

    Classes:

    • ProvideNode \u2013

      Implementation of the {% provide %} tag.

    "},{"location":"reference/django_components/#django_components.provide.ProvideNode","title":"ProvideNode","text":"
    ProvideNode(nodelist: NodeList, trace_id: str, node_id: Optional[str] = None, kwargs: Optional[RuntimeKwargs] = None)\n

    Bases: BaseNode

    Implementation of the {% provide %} tag. For more info see Component.inject.

    Source code in src/django_components/provide.py
    def __init__(\n    self,\n    nodelist: NodeList,\n    trace_id: str,\n    node_id: Optional[str] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n):\n    super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n    self.nodelist = nodelist\n    self.node_id = node_id or gen_id()\n    self.trace_id = trace_id\n    self.kwargs = kwargs or RuntimeKwargs({})\n
    "},{"location":"reference/django_components/#django_components.slots","title":"slots","text":"

    Classes:

    • FillContent \u2013

      This represents content set with the {% fill %} tag, e.g.:

    • FillNode \u2013

      Set when a component tag pair is passed template content that

    • Slot \u2013

      This represents content set with the {% slot %} tag, e.g.:

    • SlotFill \u2013

      SlotFill describes what WILL be rendered.

    • SlotNode \u2013
    • SlotRef \u2013

      SlotRef allows to treat a slot as a variable. The slot is rendered only once

    Functions:

    • parse_slot_fill_nodes_from_component_nodelist \u2013

      Given a component body (django.template.NodeList), find all slot fills,

    • resolve_slots \u2013

      Search the template for all SlotNodes, and associate the slots

    "},{"location":"reference/django_components/#django_components.slots.FillContent","title":"FillContent dataclass","text":"
    FillContent(content_func: SlotFunc[TSlotData], slot_default_var: Optional[SlotDefaultName], slot_data_var: Optional[SlotDataName])\n

    Bases: Generic[TSlotData]

    This represents content set with the {% fill %} tag, e.g.:

    {% component \"my_comp\" %}\n    {% fill \"first_slot\" %} <--- This\n        hi\n        {{ my_var }}\n        hello\n    {% endfill %}\n{% endcomponent %}\n
    "},{"location":"reference/django_components/#django_components.slots.FillNode","title":"FillNode","text":"
    FillNode(nodelist: NodeList, kwargs: RuntimeKwargs, trace_id: str, node_id: Optional[str] = None, is_implicit: bool = False)\n

    Bases: BaseNode

    Set when a component tag pair is passed template content that excludes fill tags. Nodes of this type contribute their nodelists to slots marked as 'default'.

    Source code in src/django_components/slots.py
    def __init__(\n    self,\n    nodelist: NodeList,\n    kwargs: RuntimeKwargs,\n    trace_id: str,\n    node_id: Optional[str] = None,\n    is_implicit: bool = False,\n):\n    super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n    self.is_implicit = is_implicit\n    self.trace_id = trace_id\n    self.component_id: Optional[str] = None\n
    "},{"location":"reference/django_components/#django_components.slots.Slot","title":"Slot","text":"

    Bases: NamedTuple

    This represents content set with the {% slot %} tag, e.g.:

    {% slot \"my_comp\" default %} <--- This\n    hi\n    {{ my_var }}\n    hello\n{% endslot %}\n
    "},{"location":"reference/django_components/#django_components.slots.SlotFill","title":"SlotFill dataclass","text":"
    SlotFill(\n    name: str,\n    escaped_name: str,\n    is_filled: bool,\n    content_func: SlotFunc[TSlotData],\n    slot_default_var: Optional[SlotDefaultName],\n    slot_data_var: Optional[SlotDataName],\n)\n

    Bases: Generic[TSlotData]

    SlotFill describes what WILL be rendered.

    It is a Slot that has been resolved against FillContents passed to a Component.

    "},{"location":"reference/django_components/#django_components.slots.SlotNode","title":"SlotNode","text":"
    SlotNode(\n    nodelist: NodeList,\n    trace_id: str,\n    node_id: Optional[str] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n    is_required: bool = False,\n    is_default: bool = False,\n)\n

    Bases: BaseNode

    Source code in src/django_components/slots.py
    def __init__(\n    self,\n    nodelist: NodeList,\n    trace_id: str,\n    node_id: Optional[str] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n    is_required: bool = False,\n    is_default: bool = False,\n):\n    super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n    self.is_required = is_required\n    self.is_default = is_default\n    self.trace_id = trace_id\n
    "},{"location":"reference/django_components/#django_components.slots.SlotRef","title":"SlotRef","text":"
    SlotRef(slot: SlotNode, context: Context)\n

    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.

    Source code in src/django_components/slots.py
    def __init__(self, slot: \"SlotNode\", context: Context):\n    self._slot = slot\n    self._context = context\n
    "},{"location":"reference/django_components/#django_components.slots.parse_slot_fill_nodes_from_component_nodelist","title":"parse_slot_fill_nodes_from_component_nodelist","text":"
    parse_slot_fill_nodes_from_component_nodelist(nodes: Tuple[Node, ...], ignored_nodes: Tuple[Type[Node]]) -> List[FillNode]\n

    Given a component body (django.template.NodeList), find all slot fills, whether defined explicitly with {% fill %} or implicitly.

    So if we have a component body:

    {% component \"mycomponent\" %}\n    {% fill \"first_fill\" %}\n        Hello!\n    {% endfill %}\n    {% fill \"second_fill\" %}\n        Hello too!\n    {% endfill %}\n{% endcomponent %}\n
    Then this function returns the nodes (django.template.Node) for fill \"first_fill\" and fill \"second_fill\".

    Source code in src/django_components/slots.py
    @lazy_cache(lambda: lru_cache(maxsize=app_settings.TEMPLATE_CACHE_SIZE))\ndef parse_slot_fill_nodes_from_component_nodelist(\n    nodes: Tuple[Node, ...],\n    ignored_nodes: Tuple[Type[Node]],\n) -> List[FillNode]:\n    \"\"\"\n    Given a component body (`django.template.NodeList`), find all slot fills,\n    whether defined explicitly with `{% fill %}` or implicitly.\n\n    So if we have a component body:\n    ```django\n    {% component \"mycomponent\" %}\n        {% fill \"first_fill\" %}\n            Hello!\n        {% endfill %}\n        {% fill \"second_fill\" %}\n            Hello too!\n        {% endfill %}\n    {% endcomponent %}\n    ```\n    Then this function returns the nodes (`django.template.Node`) for `fill \"first_fill\"`\n    and `fill \"second_fill\"`.\n    \"\"\"\n    fill_nodes: List[FillNode] = []\n    if nodelist_has_content(nodes):\n        for parse_fn in (\n            _try_parse_as_default_fill,\n            _try_parse_as_named_fill_tag_set,\n        ):\n            curr_fill_nodes = parse_fn(nodes, ignored_nodes)\n            if curr_fill_nodes:\n                fill_nodes = curr_fill_nodes\n                break\n        else:\n            raise TemplateSyntaxError(\n                \"Illegal content passed to 'component' tag pair. \"\n                \"Possible causes: 1) Explicit 'fill' tags cannot occur alongside other \"\n                \"tags except comment tags; 2) Default (default slot-targeting) content \"\n                \"is mixed with explict 'fill' tags.\"\n            )\n    return fill_nodes\n
    "},{"location":"reference/django_components/#django_components.slots.resolve_slots","title":"resolve_slots","text":"
    resolve_slots(\n    context: Context,\n    template: Template,\n    component_name: Optional[str],\n    fill_content: Dict[SlotName, FillContent],\n    is_dynamic_component: bool = False,\n) -> Tuple[Dict[SlotId, Slot], Dict[SlotId, SlotFill]]\n

    Search the template for all SlotNodes, and associate the slots with the given fills.

    Returns tuple of: - Slots defined in the component's Template with {% slot %} tag - SlotFills (AKA slots matched with fills) describing what will be rendered for each slot.

    Source code in src/django_components/slots.py
    def resolve_slots(\n    context: Context,\n    template: Template,\n    component_name: Optional[str],\n    fill_content: Dict[SlotName, FillContent],\n    is_dynamic_component: bool = False,\n) -> Tuple[Dict[SlotId, Slot], Dict[SlotId, SlotFill]]:\n    \"\"\"\n    Search the template for all SlotNodes, and associate the slots\n    with the given fills.\n\n    Returns tuple of:\n    - Slots defined in the component's Template with `{% slot %}` tag\n    - SlotFills (AKA slots matched with fills) describing what will be rendered for each slot.\n    \"\"\"\n    slot_fills = {\n        name: SlotFill(\n            name=name,\n            escaped_name=_escape_slot_name(name),\n            is_filled=True,\n            content_func=fill.content_func,\n            slot_default_var=fill.slot_default_var,\n            slot_data_var=fill.slot_data_var,\n        )\n        for name, fill in fill_content.items()\n    }\n\n    slots: Dict[SlotId, Slot] = {}\n    # This holds info on which slot (key) has which slots nested in it (value list)\n    slot_children: Dict[SlotId, List[SlotId]] = {}\n    all_nested_slots: Set[SlotId] = set()\n\n    def on_node(entry: NodeTraverse) -> None:\n        node = entry.node\n        if not isinstance(node, SlotNode):\n            return\n\n        slot_name, _ = node.resolve_kwargs(context, component_name)\n\n        # 1. Collect slots\n        # Basically we take all the important info form the SlotNode, so the logic is\n        # less coupled to Django's Template/Node. Plain tuples should also help with\n        # troubleshooting.\n        slot = Slot(\n            id=node.node_id,\n            name=slot_name,\n            nodelist=node.nodelist,\n            is_default=node.is_default,\n            is_required=node.is_required,\n        )\n        slots[node.node_id] = slot\n\n        # 2. Figure out which Slots are nested in other Slots, so we can render\n        # them from outside-inwards, so we can skip inner Slots if fills are provided.\n        # We should end up with a graph-like data like:\n        # - 0001: [0002]\n        # - 0002: []\n        # - 0003: [0004]\n        # In other words, the data tells us that slot ID 0001 is PARENT of slot 0002.\n        parent_slot_entry = entry.parent\n        while parent_slot_entry is not None:\n            if not isinstance(parent_slot_entry.node, SlotNode):\n                parent_slot_entry = parent_slot_entry.parent\n                continue\n\n            parent_slot_id = parent_slot_entry.node.node_id\n            if parent_slot_id not in slot_children:\n                slot_children[parent_slot_id] = []\n            slot_children[parent_slot_id].append(node.node_id)\n            all_nested_slots.add(node.node_id)\n            break\n\n    walk_nodelist(template.nodelist, on_node, context)\n\n    # 3. Figure out which slot the default/implicit fill belongs to\n    slot_fills = _resolve_default_slot(\n        template_name=template.name,\n        component_name=component_name,\n        slots=slots,\n        slot_fills=slot_fills,\n        is_dynamic_component=is_dynamic_component,\n    )\n\n    # 4. Detect any errors with slots/fills\n    # NOTE: We ignore errors for the dynamic component, as the underlying component\n    # will deal with it\n    if not is_dynamic_component:\n        _report_slot_errors(slots, slot_fills, component_name)\n\n    # 5. Find roots of the slot relationships\n    top_level_slot_ids: List[SlotId] = [node_id for node_id in slots.keys() if node_id not in all_nested_slots]\n\n    # 6. Walk from out-most slots inwards, and decide whether and how\n    # we will render each slot.\n    resolved_slots: Dict[SlotId, SlotFill] = {}\n    slot_ids_queue = deque([*top_level_slot_ids])\n    while len(slot_ids_queue):\n        slot_id = slot_ids_queue.pop()\n        slot = slots[slot_id]\n\n        # Check if there is a slot fill for given slot name\n        if slot.name in slot_fills:\n            # If yes, we remember which slot we want to replace with already-rendered fills\n            resolved_slots[slot_id] = slot_fills[slot.name]\n            # Since the fill cannot include other slots, we can leave this path\n            continue\n        else:\n            # If no, then the slot is NOT filled, and we will render the slot's default (what's\n            # between the slot tags)\n            resolved_slots[slot_id] = SlotFill(\n                name=slot.name,\n                escaped_name=_escape_slot_name(slot.name),\n                is_filled=False,\n                content_func=_nodelist_to_slot_render_func(slot.nodelist),\n                slot_default_var=None,\n                slot_data_var=None,\n            )\n            # Since the slot's default CAN include other slots (because it's defined in\n            # the same template), we need to enqueue the slot's children\n            if slot_id in slot_children and slot_children[slot_id]:\n                slot_ids_queue.extend(slot_children[slot_id])\n\n    # By the time we get here, we should know, for each slot, how it will be rendered\n    # -> Whether it will be replaced with a fill, or whether we render slot's defaults.\n    return slots, resolved_slots\n
    "},{"location":"reference/django_components/#django_components.tag_formatter","title":"tag_formatter","text":"

    Classes:

    • ComponentFormatter \u2013

      The original django_component's component tag formatter, it uses the component

    • InternalTagFormatter \u2013

      Internal wrapper around user-provided TagFormatters, so that we validate the outputs.

    • ShorthandComponentFormatter \u2013

      The component tag formatter that uses <name> / end<name> tags.

    • TagFormatterABC \u2013
    • TagResult \u2013

      The return value from TagFormatter.parse()

    Functions:

    • get_tag_formatter \u2013

      Returns an instance of the currently configured component tag formatter.

    "},{"location":"reference/django_components/#django_components.tag_formatter.ComponentFormatter","title":"ComponentFormatter","text":"
    ComponentFormatter(tag: str)\n

    Bases: TagFormatterABC

    The original django_component's component tag formatter, it uses the component and endcomponent tags, and the component name is gives 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

    Source code in src/django_components/tag_formatter.py
    def __init__(self, tag: str):\n    self.tag = tag\n
    "},{"location":"reference/django_components/#django_components.tag_formatter.InternalTagFormatter","title":"InternalTagFormatter","text":"
    InternalTagFormatter(tag_formatter: TagFormatterABC)\n

    Internal wrapper around user-provided TagFormatters, so that we validate the outputs.

    Source code in src/django_components/tag_formatter.py
    def __init__(self, tag_formatter: TagFormatterABC):\n    self.tag_formatter = tag_formatter\n
    "},{"location":"reference/django_components/#django_components.tag_formatter.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":"

    Bases: TagFormatterABC

    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/django_components/#django_components.tag_formatter.TagFormatterABC","title":"TagFormatterABC","text":"

    Bases: ABC

    Methods:

    • end_tag \u2013

      Formats the end tag of a block component.

    • parse \u2013

      Given the tokens (words) of a component start tag, this function extracts

    • start_tag \u2013

      Formats the start tag of a component.

    "},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC.end_tag","title":"end_tag abstractmethod","text":"
    end_tag(name: str) -> str\n

    Formats the end tag of a block component.

    Source code in src/django_components/tag_formatter.py
    @abc.abstractmethod\ndef end_tag(self, name: str) -> str:\n    \"\"\"Formats the end tag of a block component.\"\"\"\n    ...\n
    "},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC.parse","title":"parse abstractmethod","text":"
    parse(tokens: List[str]) -> TagResult\n

    Given the tokens (words) of 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).

    Example:

    Given a component declarations:

    {% component \"my_comp\" key=val key2=val2 %}

    This function receives a list of tokens

    ['component', '\"my_comp\"', 'key=val', 'key2=val2']

    component is the tag name, which we drop. \"my_comp\" is the component name, but we must remove the extra quotes. And we pass remaining tokens unmodified, as that's the input to the component.

    So in the end, we return a tuple:

    ('my_comp', ['key=val', 'key2=val2'])

    Source code in src/django_components/tag_formatter.py
    @abc.abstractmethod\ndef parse(self, tokens: List[str]) -> TagResult:\n    \"\"\"\n    Given the tokens (words) of a component start tag, this function extracts\n    the component name from the tokens list, and returns `TagResult`, which\n    is a tuple of `(component_name, remaining_tokens)`.\n\n    Example:\n\n    Given a component declarations:\n\n    `{% component \"my_comp\" key=val key2=val2 %}`\n\n    This function receives a list of tokens\n\n    `['component', '\"my_comp\"', 'key=val', 'key2=val2']`\n\n    `component` is the tag name, which we drop. `\"my_comp\"` is the component name,\n    but we must remove the extra quotes. And we pass remaining tokens unmodified,\n    as that's the input to the component.\n\n    So in the end, we return a tuple:\n\n    `('my_comp', ['key=val', 'key2=val2'])`\n    \"\"\"\n    ...\n
    "},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC.start_tag","title":"start_tag abstractmethod","text":"
    start_tag(name: str) -> str\n

    Formats the start tag of a component.

    Source code in src/django_components/tag_formatter.py
    @abc.abstractmethod\ndef start_tag(self, name: str) -> str:\n    \"\"\"Formats the start tag of a component.\"\"\"\n    ...\n
    "},{"location":"reference/django_components/#django_components.tag_formatter.TagResult","title":"TagResult","text":"

    Bases: NamedTuple

    The return value from TagFormatter.parse()

    Attributes:

    • component_name (str) \u2013

      Component name extracted from the template tag

    • tokens (List[str]) \u2013

      Remaining tokens (words) that were passed to the tag, with component name removed

    "},{"location":"reference/django_components/#django_components.tag_formatter.TagResult.component_name","title":"component_name instance-attribute","text":"
    component_name: str\n

    Component name extracted from the template tag

    "},{"location":"reference/django_components/#django_components.tag_formatter.TagResult.tokens","title":"tokens instance-attribute","text":"
    tokens: List[str]\n

    Remaining tokens (words) that were passed to the tag, with component name removed

    "},{"location":"reference/django_components/#django_components.tag_formatter.get_tag_formatter","title":"get_tag_formatter","text":"
    get_tag_formatter(registry: ComponentRegistry) -> InternalTagFormatter\n

    Returns an instance of the currently configured component tag formatter.

    Source code in src/django_components/tag_formatter.py
    def get_tag_formatter(registry: \"ComponentRegistry\") -> InternalTagFormatter:\n    \"\"\"Returns an instance of the currently configured component tag formatter.\"\"\"\n    # Allow users to configure the component TagFormatter\n    formatter_cls_or_str = registry.settings.TAG_FORMATTER\n\n    if isinstance(formatter_cls_or_str, str):\n        tag_formatter: TagFormatterABC = import_string(formatter_cls_or_str)\n    else:\n        tag_formatter = formatter_cls_or_str\n\n    return InternalTagFormatter(tag_formatter)\n
    "},{"location":"reference/django_components/#django_components.template","title":"template","text":"

    Functions:

    • cached_template \u2013

      Create a Template instance that will be cached as per the TEMPLATE_CACHE_SIZE setting.

    "},{"location":"reference/django_components/#django_components.template.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

    Create a Template instance that will be cached as per the TEMPLATE_CACHE_SIZE setting.

    Source code in src/django_components/template.py
    def 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    \"\"\"Create a Template instance that will be cached as per the `TEMPLATE_CACHE_SIZE` setting.\"\"\"\n    template = _create_template(template_cls or Template, template_string, engine)\n\n    # Assign the origin and name separately, so the caching doesn't depend on them\n    # Since we might be accessing a template from cache, we want to define these only once\n    if not getattr(template, \"_dc_cached\", False):\n        template.origin = origin or Origin(UNKNOWN_SOURCE)\n        template.name = name\n        template._dc_cached = True\n\n    return template\n
    "},{"location":"reference/django_components/#django_components.template_loader","title":"template_loader","text":"

    Template loader that loads templates from each Django app's \"components\" directory.

    Classes:

    • Loader \u2013

    Functions:

    • get_dirs \u2013

      Helper for using django_component's FilesystemLoader class to obtain a list

    "},{"location":"reference/django_components/#django_components.template_loader.Loader","title":"Loader","text":"

    Bases: Loader

    Methods:

    • get_dirs \u2013

      Prepare directories that may contain component files:

    "},{"location":"reference/django_components/#django_components.template_loader.Loader.get_dirs","title":"get_dirs","text":"
    get_dirs(include_apps: bool = True) -> List[Path]\n

    Prepare directories that may contain component files:

    Searches for dirs set in COMPONENTS.dirs settings. If none set, defaults to searching for a \"components\" app. The dirs in COMPONENTS.dirs must be absolute paths.

    In addition to that, also all apps are checked for [app]/components dirs.

    Paths are accepted only if they resolve to a directory. E.g. /path/to/django_project/my_app/components/.

    BASE_DIR setting is required.

    Source code in src/django_components/template_loader.py
    def get_dirs(self, include_apps: bool = True) -> List[Path]:\n    \"\"\"\n    Prepare directories that may contain component files:\n\n    Searches for dirs set in `COMPONENTS.dirs` settings. If none set, defaults to searching\n    for a \"components\" app. The dirs in `COMPONENTS.dirs` must be absolute paths.\n\n    In addition to that, also all apps are checked for `[app]/components` dirs.\n\n    Paths are accepted only if they resolve to a directory.\n    E.g. `/path/to/django_project/my_app/components/`.\n\n    `BASE_DIR` setting is required.\n    \"\"\"\n    # Allow to configure from settings which dirs should be checked for components\n    component_dirs = app_settings.DIRS\n\n    # TODO_REMOVE_IN_V1\n    is_legacy_paths = (\n        # Use value of `STATICFILES_DIRS` ONLY if `COMPONENT.dirs` not set\n        not getattr(settings, \"COMPONENTS\", {}).get(\"dirs\", None) is not None\n        and hasattr(settings, \"STATICFILES_DIRS\")\n        and settings.STATICFILES_DIRS\n    )\n    if is_legacy_paths:\n        # NOTE: For STATICFILES_DIRS, we use the defaults even for empty list.\n        # We don't do this for COMPONENTS.dirs, so user can explicitly specify \"NO dirs\".\n        component_dirs = settings.STATICFILES_DIRS or [settings.BASE_DIR / \"components\"]\n    source = \"STATICFILES_DIRS\" if is_legacy_paths else \"COMPONENTS.dirs\"\n\n    logger.debug(\n        \"Template loader will search for valid template dirs from following options:\\n\"\n        + \"\\n\".join([f\" - {str(d)}\" for d in component_dirs])\n    )\n\n    # Add `[app]/[APP_DIR]` to the directories. This is, by default `[app]/components`\n    app_paths: List[Path] = []\n    if include_apps:\n        for conf in apps.get_app_configs():\n            for app_dir in app_settings.APP_DIRS:\n                comps_path = Path(conf.path).joinpath(app_dir)\n                if comps_path.exists():\n                    app_paths.append(comps_path)\n\n    directories: Set[Path] = set(app_paths)\n\n    # Validate and add other values from the config\n    for component_dir in component_dirs:\n        # Consider tuples for STATICFILES_DIRS (See #489)\n        # See https://docs.djangoproject.com/en/5.0/ref/settings/#prefixes-optional\n        if isinstance(component_dir, (tuple, list)):\n            component_dir = component_dir[1]\n        try:\n            Path(component_dir)\n        except TypeError:\n            logger.warning(\n                f\"{source} expected str, bytes or os.PathLike object, or tuple/list of length 2. \"\n                f\"See Django documentation for STATICFILES_DIRS. Got {type(component_dir)} : {component_dir}\"\n            )\n            continue\n\n        if not Path(component_dir).is_absolute():\n            raise ValueError(f\"{source} must contain absolute paths, got '{component_dir}'\")\n        else:\n            directories.add(Path(component_dir).resolve())\n\n    logger.debug(\n        \"Template loader matched following template dirs:\\n\" + \"\\n\".join([f\" - {str(d)}\" for d in directories])\n    )\n    return list(directories)\n
    "},{"location":"reference/django_components/#django_components.template_loader.get_dirs","title":"get_dirs","text":"
    get_dirs(include_apps: bool = True, engine: Optional[Engine] = None) -> List[Path]\n

    Helper for using django_component's FilesystemLoader class to obtain a list of directories where component python files may be defined.

    Source code in src/django_components/template_loader.py
    def get_dirs(include_apps: bool = True, engine: Optional[Engine] = None) -> List[Path]:\n    \"\"\"\n    Helper for using django_component's FilesystemLoader class to obtain a list\n    of directories where component python files may be defined.\n    \"\"\"\n    current_engine = engine\n    if current_engine is None:\n        current_engine = Engine.get_default()\n\n    loader = Loader(current_engine)\n    return loader.get_dirs(include_apps)\n
    "},{"location":"reference/django_components/#django_components.template_parser","title":"template_parser","text":"

    Overrides for the Django Template system to allow finer control over template parsing.

    Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py

    Functions:

    • parse_bits \u2013

      Parse bits for template tag helpers simple_tag and inclusion_tag, in

    • token_kwargs \u2013

      Parse token keyword arguments and return a dictionary of the arguments

    "},{"location":"reference/django_components/#django_components.template_parser.parse_bits","title":"parse_bits","text":"
    parse_bits(\n    parser: Parser, bits: List[str], params: List[str], name: str\n) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]\n

    Parse bits for template tag helpers simple_tag and inclusion_tag, in particular by detecting syntax errors and by extracting positional and keyword arguments.

    This is a simplified version of django.template.library.parse_bits where we use custom regex to handle special characters in keyword names.

    Furthermore, our version allows duplicate keys, and instead of return kwargs as a dict, we return it as a list of key-value pairs. So it is up to the user of this function to decide whether they support duplicate keys or not.

    Source code in src/django_components/template_parser.py
    def parse_bits(\n    parser: Parser,\n    bits: List[str],\n    params: List[str],\n    name: str,\n) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]:\n    \"\"\"\n    Parse bits for template tag helpers simple_tag and inclusion_tag, in\n    particular by detecting syntax errors and by extracting positional and\n    keyword arguments.\n\n    This is a simplified version of `django.template.library.parse_bits`\n    where we use custom regex to handle special characters in keyword names.\n\n    Furthermore, our version allows duplicate keys, and instead of return kwargs\n    as a dict, we return it as a list of key-value pairs. So it is up to the\n    user of this function to decide whether they support duplicate keys or not.\n    \"\"\"\n    args: List[FilterExpression] = []\n    kwargs: List[Tuple[str, FilterExpression]] = []\n    unhandled_params = list(params)\n    for bit in bits:\n        # First we try to extract a potential kwarg from the bit\n        kwarg = token_kwargs([bit], parser)\n        if kwarg:\n            # The kwarg was successfully extracted\n            param, value = kwarg.popitem()\n            # All good, record the keyword argument\n            kwargs.append((str(param), value))\n            if param in unhandled_params:\n                # If using the keyword syntax for a positional arg, then\n                # consume it.\n                unhandled_params.remove(param)\n        else:\n            if kwargs:\n                raise TemplateSyntaxError(\n                    \"'%s' received some positional argument(s) after some \" \"keyword argument(s)\" % name\n                )\n            else:\n                # Record the positional argument\n                args.append(parser.compile_filter(bit))\n                try:\n                    # Consume from the list of expected positional arguments\n                    unhandled_params.pop(0)\n                except IndexError:\n                    pass\n    if unhandled_params:\n        # Some positional arguments were not supplied\n        raise TemplateSyntaxError(\n            \"'%s' did not receive value(s) for the argument(s): %s\"\n            % (name, \", \".join(\"'%s'\" % p for p in unhandled_params))\n        )\n    return args, kwargs\n
    "},{"location":"reference/django_components/#django_components.template_parser.token_kwargs","title":"token_kwargs","text":"
    token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]\n

    Parse token keyword arguments and return a dictionary of the arguments retrieved from the bits token list.

    bits is a list containing the remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments are removed from this list.

    There is no requirement for all remaining token bits to be keyword arguments, so return the dictionary as soon as an invalid argument format is reached.

    Source code in src/django_components/template_parser.py
    def token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]:\n    \"\"\"\n    Parse token keyword arguments and return a dictionary of the arguments\n    retrieved from the ``bits`` token list.\n\n    `bits` is a list containing the remainder of the token (split by spaces)\n    that is to be checked for arguments. Valid arguments are removed from this\n    list.\n\n    There is no requirement for all remaining token ``bits`` to be keyword\n    arguments, so return the dictionary as soon as an invalid argument format\n    is reached.\n    \"\"\"\n    if not bits:\n        return {}\n    match = kwarg_re.match(bits[0])\n    kwarg_format = match and match[1]\n    if not kwarg_format:\n        return {}\n\n    kwargs: Dict[str, FilterExpression] = {}\n    while bits:\n        if kwarg_format:\n            match = kwarg_re.match(bits[0])\n            if not match or not match[1]:\n                return kwargs\n            key, value = match.groups()\n            del bits[:1]\n        else:\n            if len(bits) < 3 or bits[1] != \"as\":\n                return kwargs\n            key, value = bits[2], bits[0]\n            del bits[:3]\n\n        # This is the only difference from the original token_kwargs. We use\n        # the ComponentsFilterExpression instead of the original FilterExpression.\n        kwargs[key] = ComponentsFilterExpression(value, parser)\n        if bits and not kwarg_format:\n            if bits[0] != \"and\":\n                return kwargs\n            del bits[:1]\n    return kwargs\n
    "},{"location":"reference/django_components/#django_components.templatetags","title":"templatetags","text":"

    Modules:

    • component_tags \u2013
    "},{"location":"reference/django_components/#django_components.templatetags.component_tags","title":"component_tags","text":"

    Functions:

    • component \u2013

      To give the component access to the template context:

    • component_css_dependencies \u2013

      Marks location where CSS link tags should be rendered.

    • component_dependencies \u2013

      Marks location where CSS link and JS script tags should be rendered.

    • component_js_dependencies \u2013

      Marks location where JS script tags should be rendered.

    • fill \u2013

      Block tag whose contents 'fill' (are inserted into) an identically named

    • html_attrs \u2013

      This tag takes:

    "},{"location":"reference/django_components/#django_components.templatetags.component_tags.component","title":"component","text":"
    component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode\n
    To give the component access to the template context

    {% component \"name\" positional_arg keyword_arg=value ... %}

    To render the component in an isolated context

    {% component \"name\" positional_arg keyword_arg=value ... only %}

    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 or, if there are no positional arguments, passed as 'name'.

    Source code in src/django_components/templatetags/component_tags.py
    def component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode:\n    \"\"\"\n    To give the component access to the template context:\n        ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... %}```\n\n    To render the component in an isolated context:\n        ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... only %}```\n\n    Positional and keyword arguments can be literals or template variables.\n    The component name must be a single- or double-quotes string and must\n    be either the first positional argument or, if there are no positional\n    arguments, passed as 'name'.\n    \"\"\"\n    _fix_nested_tags(parser, token)\n    bits = token.split_contents()\n\n    # Let the TagFormatter pre-process the tokens\n    formatter = get_tag_formatter(registry)\n    result = formatter.parse([*bits])\n    end_tag = formatter.end_tag(result.component_name)\n\n    # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n    bits = [bits[0], *result.tokens]\n    token.contents = \" \".join(bits)\n\n    tag = _parse_tag(\n        tag_name,\n        parser,\n        token,\n        params=[],\n        extra_params=True,  # Allow many args\n        flags=[COMP_ONLY_FLAG],\n        keywordonly_kwargs=True,\n        repeatable_kwargs=False,\n        end_tag=end_tag,\n    )\n\n    # Check for isolated context keyword\n    isolated_context = tag.flags[COMP_ONLY_FLAG]\n\n    trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n    body = tag.parse_body()\n    fill_nodes = parse_slot_fill_nodes_from_component_nodelist(tuple(body), ignored_nodes=(ComponentNode,))\n\n    # Tag all fill nodes as children of this particular component instance\n    for node in fill_nodes:\n        trace_msg(\"ASSOC\", \"FILL\", node.trace_id, node.node_id, component_id=tag.id)\n        node.component_id = tag.id\n\n    component_node = ComponentNode(\n        name=result.component_name,\n        args=tag.args,\n        kwargs=tag.kwargs,\n        isolated_context=isolated_context,\n        fill_nodes=fill_nodes,\n        node_id=tag.id,\n        registry=registry,\n    )\n\n    trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n    return component_node\n
    "},{"location":"reference/django_components/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"
    component_css_dependencies(preload: str = '') -> SafeString\n

    Marks location where CSS link tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_css_dependencies\")\ndef component_css_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where CSS link tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_css_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/#django_components.templatetags.component_tags.component_dependencies","title":"component_dependencies","text":"
    component_dependencies(preload: str = '') -> SafeString\n

    Marks location where CSS link and JS script tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_dependencies\")\ndef component_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where CSS link and JS script tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER + JS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"
    component_js_dependencies(preload: str = '') -> SafeString\n

    Marks location where JS script tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_js_dependencies\")\ndef component_js_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where JS script tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + JS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_js_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/#django_components.templatetags.component_tags.fill","title":"fill","text":"
    fill(parser: Parser, token: Token) -> FillNode\n

    Block tag whose contents 'fill' (are inserted into) an identically named 'slot'-block in the component template referred to by a parent component. It exists to make component nesting easier.

    This tag is available only within a {% component %}..{% endcomponent %} block. Runtime checks should prohibit other usages.

    Source code in src/django_components/templatetags/component_tags.py
    @register.tag(\"fill\")\ndef fill(parser: Parser, token: Token) -> FillNode:\n    \"\"\"\n    Block tag whose contents 'fill' (are inserted into) an identically named\n    'slot'-block in the component template referred to by a parent component.\n    It exists to make component nesting easier.\n\n    This tag is available only within a {% component %}..{% endcomponent %} block.\n    Runtime checks should prohibit other usages.\n    \"\"\"\n    tag = _parse_tag(\n        \"fill\",\n        parser,\n        token,\n        params=[SLOT_NAME_KWARG],\n        optional_params=[SLOT_NAME_KWARG],\n        keywordonly_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n        repeatable_kwargs=False,\n        end_tag=\"endfill\",\n    )\n\n    fill_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n    trace_id = f\"fill-id-{tag.id} ({fill_name_kwarg})\" if fill_name_kwarg else f\"fill-id-{tag.id}\"\n\n    trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id)\n\n    body = tag.parse_body()\n    fill_node = FillNode(\n        nodelist=body,\n        node_id=tag.id,\n        kwargs=tag.kwargs,\n        trace_id=trace_id,\n    )\n\n    trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id, \"...Done!\")\n    return fill_node\n
    "},{"location":"reference/django_components/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"
    html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode\n

    This tag takes: - Optional dictionary of attributes (attrs) - Optional dictionary of defaults (defaults) - Additional kwargs that are appended to the former two

    The inputs are merged and resulting dict is rendered as HTML attributes (key=\"value\").

    Rules: 1. Both attrs and defaults can be passed as positional args or as kwargs 2. Both attrs and defaults are optional (can be omitted) 3. 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. 4. All other kwargs (key=value) are appended and can be repeated.

    Normal kwargs (key=value) are concatenated to existing keys. So if e.g. key \"class\" is supplied with value \"my-class\", then adding class=\"extra-class\" will result in `class=\"my-class extra-class\".

    Example:

    {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n

    Source code in src/django_components/templatetags/component_tags.py
    @register.tag(\"html_attrs\")\ndef html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode:\n    \"\"\"\n    This tag takes:\n    - Optional dictionary of attributes (`attrs`)\n    - Optional dictionary of defaults (`defaults`)\n    - Additional kwargs that are appended to the former two\n\n    The inputs are merged and resulting dict is rendered as HTML attributes\n    (`key=\"value\"`).\n\n    Rules:\n    1. Both `attrs` and `defaults` can be passed as positional args or as kwargs\n    2. Both `attrs` and `defaults` are optional (can be omitted)\n    3. Both `attrs` and `defaults` are dictionaries, and we can define them the same way\n       we define dictionaries for the `component` tag. So either as `attrs=attrs` or\n       `attrs:key=value`.\n    4. All other kwargs (`key=value`) are appended and can be repeated.\n\n    Normal kwargs (`key=value`) are concatenated to existing keys. So if e.g. key\n    \"class\" is supplied with value \"my-class\", then adding `class=\"extra-class\"`\n    will result in `class=\"my-class extra-class\".\n\n    Example:\n    ```htmldjango\n    {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n    ```\n    \"\"\"\n    tag = _parse_tag(\n        \"html_attrs\",\n        parser,\n        token,\n        params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n        optional_params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n        flags=[],\n        keywordonly_kwargs=True,\n        repeatable_kwargs=True,\n    )\n\n    return HtmlAttrsNode(\n        kwargs=tag.kwargs,\n        kwarg_pairs=tag.kwarg_pairs,\n    )\n
    "},{"location":"reference/django_components/#django_components.types","title":"types","text":"

    Helper types for IDEs.

    "},{"location":"reference/django_components/#django_components.utils","title":"utils","text":"

    Functions:

    • gen_id \u2013

      Generate a unique ID that can be associated with a Node

    • lazy_cache \u2013

      Decorator that caches the given function similarly to functools.lru_cache.

    "},{"location":"reference/django_components/#django_components.utils.gen_id","title":"gen_id","text":"
    gen_id(length: int = 5) -> str\n

    Generate a unique ID that can be associated with a Node

    Source code in src/django_components/utils.py
    def gen_id(length: int = 5) -> str:\n    \"\"\"Generate a unique ID that can be associated with a Node\"\"\"\n    # Global counter to avoid conflicts\n    global _id\n    _id += 1\n\n    # Pad the ID with `0`s up to 4 digits, e.g. `0007`\n    return f\"{_id:04}\"\n
    "},{"location":"reference/django_components/#django_components.utils.lazy_cache","title":"lazy_cache","text":"
    lazy_cache(make_cache: Callable[[], Callable[[Callable], Callable]]) -> Callable[[TFunc], TFunc]\n

    Decorator that caches the given function similarly to functools.lru_cache. But the cache is instantiated only at first invocation.

    cache argument is a function that generates the cache function, e.g. functools.lru_cache().

    Source code in src/django_components/utils.py
    def lazy_cache(\n    make_cache: Callable[[], Callable[[Callable], Callable]],\n) -> Callable[[TFunc], TFunc]:\n    \"\"\"\n    Decorator that caches the given function similarly to `functools.lru_cache`.\n    But the cache is instantiated only at first invocation.\n\n    `cache` argument is a function that generates the cache function,\n    e.g. `functools.lru_cache()`.\n    \"\"\"\n    _cached_fn = None\n\n    def decorator(fn: TFunc) -> TFunc:\n        @functools.wraps(fn)\n        def wrapper(*args: Any, **kwargs: Any) -> Any:\n            # Lazily initialize the cache\n            nonlocal _cached_fn\n            if not _cached_fn:\n                # E.g. `lambda: functools.lru_cache(maxsize=app_settings.TEMPLATE_CACHE_SIZE)`\n                cache = make_cache()\n                _cached_fn = cache(fn)\n\n            return _cached_fn(*args, **kwargs)\n\n        # Allow to access the LRU cache methods\n        # See https://stackoverflow.com/a/37654201/9788634\n        wrapper.cache_info = lambda: _cached_fn.cache_info()  # type: ignore\n        wrapper.cache_clear = lambda: _cached_fn.cache_clear()  # type: ignore\n\n        # And allow to remove the cache instance (mostly for tests)\n        def cache_remove() -> None:\n            nonlocal _cached_fn\n            _cached_fn = None\n\n        wrapper.cache_remove = cache_remove  # type: ignore\n\n        return cast(TFunc, wrapper)\n\n    return decorator\n
    "},{"location":"reference/django_components/app_settings/","title":" app_settings","text":""},{"location":"reference/django_components/app_settings/#django_components.app_settings","title":"app_settings","text":"

    Classes:

    • ContextBehavior \u2013
    "},{"location":"reference/django_components/app_settings/#django_components.app_settings.ContextBehavior","title":"ContextBehavior","text":"

    Bases: str, Enum

    Attributes:

    • DJANGO \u2013

      With this setting, component fills behave as usual Django tags.

    • ISOLATED \u2013

      This setting makes the component fills behave similar to Vue or React, where

    "},{"location":"reference/django_components/app_settings/#django_components.app_settings.ContextBehavior.DJANGO","title":"DJANGO class-attribute instance-attribute","text":"
    DJANGO = 'django'\n

    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 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 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/django_components/app_settings/#django_components.app_settings.ContextBehavior.ISOLATED","title":"ISOLATED class-attribute instance-attribute","text":"
    ISOLATED = 'isolated'\n

    This setting makes the component fills behave similar to Vue or React, where the fills use EXCLUSIVELY the context variables defined in 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/django_components/apps/","title":" apps","text":""},{"location":"reference/django_components/apps/#django_components.apps","title":"apps","text":""},{"location":"reference/django_components/attributes/","title":" attributes","text":""},{"location":"reference/django_components/attributes/#django_components.attributes","title":"attributes","text":"

    Functions:

    • append_attributes \u2013

      Merges the key-value pairs and returns a new dictionary.

    • attributes_to_string \u2013

      Convert a dict of attributes to a string.

    "},{"location":"reference/django_components/attributes/#django_components.attributes.append_attributes","title":"append_attributes","text":"
    append_attributes(*args: Tuple[str, Any]) -> Dict\n

    Merges the key-value pairs and returns a new dictionary.

    If a key is present multiple times, its values are concatenated with a space character as separator in the final dictionary.

    Source code in src/django_components/attributes.py
    def append_attributes(*args: Tuple[str, Any]) -> Dict:\n    \"\"\"\n    Merges the key-value pairs and returns a new dictionary.\n\n    If a key is present multiple times, its values are concatenated with a space\n    character as separator in the final dictionary.\n    \"\"\"\n    result: Dict = {}\n\n    for key, value in args:\n        if key in result:\n            result[key] += \" \" + value\n        else:\n            result[key] = value\n\n    return result\n
    "},{"location":"reference/django_components/attributes/#django_components.attributes.attributes_to_string","title":"attributes_to_string","text":"
    attributes_to_string(attributes: Mapping[str, Any]) -> str\n

    Convert a dict of attributes to a string.

    Source code in src/django_components/attributes.py
    def attributes_to_string(attributes: Mapping[str, Any]) -> str:\n    \"\"\"Convert a dict of attributes to a string.\"\"\"\n    attr_list = []\n\n    for key, value in attributes.items():\n        if value is None or value is False:\n            continue\n        if value is True:\n            attr_list.append(conditional_escape(key))\n        else:\n            attr_list.append(format_html('{}=\"{}\"', key, value))\n\n    return mark_safe(SafeString(\" \").join(attr_list))\n
    "},{"location":"reference/django_components/autodiscover/","title":" autodiscover","text":""},{"location":"reference/django_components/autodiscover/#django_components.autodiscover","title":"autodiscover","text":"

    Functions:

    • autodiscover \u2013

      Search for component files and import them. Returns a list of module

    • import_libraries \u2013

      Import modules set in COMPONENTS.libraries setting.

    • search_dirs \u2013

      Search the directories for the given glob pattern. Glob search results are returned

    "},{"location":"reference/django_components/autodiscover/#django_components.autodiscover.autodiscover","title":"autodiscover","text":"
    autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n

    Search for component files and import them. Returns a list of module paths of imported files.

    Autodiscover searches in the locations as defined by Loader.get_dirs.

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

    Source code in src/django_components/autodiscover.py
    def autodiscover(\n    map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n    \"\"\"\n    Search for component files and import them. Returns a list of module\n    paths of imported files.\n\n    Autodiscover searches in the locations as defined by `Loader.get_dirs`.\n\n    You can map the module paths with `map_module` function. This serves\n    as an escape hatch for when you need to use this function in tests.\n    \"\"\"\n    dirs = get_dirs(include_apps=False)\n    component_filepaths = search_dirs(dirs, \"**/*.py\")\n    logger.debug(f\"Autodiscover found {len(component_filepaths)} files in component directories.\")\n\n    if hasattr(settings, \"BASE_DIR\") and settings.BASE_DIR:\n        project_root = str(settings.BASE_DIR)\n    else:\n        # Fallback for getting the root dir, see https://stackoverflow.com/a/16413955/9788634\n        project_root = os.path.abspath(os.path.dirname(__name__))\n\n    modules: List[str] = []\n\n    # We handle dirs from `COMPONENTS.dirs` and from individual apps separately.\n    #\n    # Because for dirs in `COMPONENTS.dirs`, we assume they will be nested under `BASE_DIR`,\n    # and that `BASE_DIR` is the current working dir (CWD). So the path relatively to `BASE_DIR`\n    # is ALSO the python import path.\n    for filepath in component_filepaths:\n        module_path = _filepath_to_python_module(filepath, project_root, None)\n        # Ignore files starting with dot `.` or files in dirs that start with dot.\n        #\n        # If any of the parts of the path start with a dot, e.g. the filesystem path\n        # is `./abc/.def`, then this gets converted to python module as `abc..def`\n        #\n        # NOTE: This approach also ignores files:\n        #   - with two dots in the middle (ab..cd.py)\n        #   - an extra dot at the end (abcd..py)\n        #   - files outside of the parent component (../abcd.py).\n        # But all these are NOT valid python modules so that's fine.\n        if \"..\" in module_path:\n            continue\n\n        modules.append(module_path)\n\n    # For for apps, the directories may be outside of the project, e.g. in case of third party\n    # apps. So we have to resolve the python import path relative to the package name / the root\n    # import path for the app.\n    # See https://github.com/EmilStenstrom/django-components/issues/669\n    for conf in apps.get_app_configs():\n        for app_dir in app_settings.APP_DIRS:\n            comps_path = Path(conf.path).joinpath(app_dir)\n            if not comps_path.exists():\n                continue\n            app_component_filepaths = search_dirs([comps_path], \"**/*.py\")\n            for filepath in app_component_filepaths:\n                app_component_module = _filepath_to_python_module(filepath, conf.path, conf.name)\n                modules.append(app_component_module)\n\n    return _import_modules(modules, map_module)\n
    "},{"location":"reference/django_components/autodiscover/#django_components.autodiscover.import_libraries","title":"import_libraries","text":"
    import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n

    Import modules set in COMPONENTS.libraries setting.

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

    Source code in src/django_components/autodiscover.py
    def import_libraries(\n    map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n    \"\"\"\n    Import modules set in `COMPONENTS.libraries` setting.\n\n    You can map the module paths with `map_module` function. This serves\n    as an escape hatch for when you need to use this function in tests.\n    \"\"\"\n    from django_components.app_settings import app_settings\n\n    return _import_modules(app_settings.LIBRARIES, map_module)\n
    "},{"location":"reference/django_components/autodiscover/#django_components.autodiscover.search_dirs","title":"search_dirs","text":"
    search_dirs(dirs: List[Path], search_glob: str) -> List[Path]\n

    Search the directories for the given glob pattern. Glob search results are returned as a flattened list.

    Source code in src/django_components/autodiscover.py
    def search_dirs(dirs: List[Path], search_glob: str) -> List[Path]:\n    \"\"\"\n    Search the directories for the given glob pattern. Glob search results are returned\n    as a flattened list.\n    \"\"\"\n    matched_files: List[Path] = []\n    for directory in dirs:\n        for path in glob.iglob(str(Path(directory) / search_glob), recursive=True):\n            matched_files.append(Path(path))\n\n    return matched_files\n
    "},{"location":"reference/django_components/component/","title":" component","text":""},{"location":"reference/django_components/component/#django_components.component","title":"component","text":"

    Classes:

    • Component \u2013
    • ComponentNode \u2013

      Django.template.Node subclass that renders a django-components component

    • ComponentView \u2013

      Subclass of django.views.View where the Component instance is available

    "},{"location":"reference/django_components/component/#django_components.component.Component","title":"Component","text":"
    Component(\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,\n)\n

    Bases: Generic[ArgsType, KwargsType, DataType, SlotsType]

    Methods:

    • as_view \u2013

      Shortcut for calling Component.View.as_view and passing component instance to it.

    • get_template \u2013

      Inlined Django template associated with this component. Can be a plain string or a Template instance.

    • get_template_name \u2013

      Filepath to the Django template associated with this component.

    • inject \u2013

      Use this method to retrieve the data that was passed to a {% provide %} tag

    • on_render_after \u2013

      Hook that runs just after the component's template was rendered.

    • on_render_before \u2013

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

    • render \u2013

      Render the component into a string.

    • render_css_dependencies \u2013

      Render only CSS dependencies available in the media class or provided as a string.

    • render_dependencies \u2013

      Helper function to render all dependencies for a component.

    • render_js_dependencies \u2013

      Render only JS dependencies available in the media class or provided as a string.

    • render_to_response \u2013

      Render the component and wrap the content in the response class.

    Attributes:

    • Media \u2013

      Defines JS and CSS media files associated with this component.

    • css (Optional[str]) \u2013

      Inlined CSS associated with this component.

    • input (RenderInput[ArgsType, KwargsType, SlotsType]) \u2013

      Input holds the data (like arg, kwargs, slots) that were passsed to

    • is_filled (Dict[str, bool]) \u2013

      Dictionary describing which slots have or have not been filled.

    • js (Optional[str]) \u2013

      Inlined JS associated with this component.

    • media (Media) \u2013

      Normalized definition of JS and CSS media files associated with this component.

    • response_class \u2013

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

    • template (Optional[Union[str, Template]]) \u2013

      Inlined Django template associated with this component. Can be a plain string or a Template instance.

    • template_name (Optional[str]) \u2013

      Filepath to the Django template associated with this component.

    Source code in src/django_components/component.py
    def __init__(\n    self,\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,  # noqa F811\n):\n    # When user first instantiates the component class before calling\n    # `render` or `render_to_response`, then we want to allow the render\n    # function to make use of the instantiated object.\n    #\n    # So while `MyComp.render()` creates a new instance of MyComp internally,\n    # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n    # already-instantiated object.\n    #\n    # To achieve that, we want to re-assign the class methods as instance methods.\n    # For that we have to \"unwrap\" the class methods via __func__.\n    # See https://stackoverflow.com/a/76706399/9788634\n    self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self)  # type: ignore\n    self.render = types.MethodType(self.__class__.render.__func__, self)  # type: ignore\n    self.as_view = types.MethodType(self.__class__.as_view.__func__, self)  # type: ignore\n\n    self.registered_name: Optional[str] = registered_name\n    self.outer_context: Context = outer_context or Context()\n    self.fill_content = fill_content or {}\n    self.component_id = component_id or gen_id()\n    self.registry = registry or registry_\n    self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n    # None == uninitialized, False == No types, Tuple == types\n    self._types: Optional[Union[Tuple[Any, Any, Any, Any], Literal[False]]] = None\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.Media","title":"Media class-attribute instance-attribute","text":"
    Media = ComponentMediaInput\n

    Defines JS and CSS media files associated with this component.

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

    Inlined CSS associated with this component.

    "},{"location":"reference/django_components/component/#django_components.component.Component.input","title":"input property","text":"
    input: RenderInput[ArgsType, KwargsType, SlotsType]\n

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

    "},{"location":"reference/django_components/component/#django_components.component.Component.is_filled","title":"is_filled property","text":"
    is_filled: Dict[str, bool]\n

    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/django_components/component/#django_components.component.Component.js","title":"js class-attribute instance-attribute","text":"
    js: Optional[str] = None\n

    Inlined JS associated with this component.

    "},{"location":"reference/django_components/component/#django_components.component.Component.media","title":"media instance-attribute","text":"
    media: Media\n

    Normalized definition of JS and CSS media files associated with this component.

    NOTE: This field is generated from Component.Media class.

    "},{"location":"reference/django_components/component/#django_components.component.Component.response_class","title":"response_class class-attribute instance-attribute","text":"
    response_class = HttpResponse\n

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

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

    Inlined Django template associated with this component. Can be a plain string or a Template instance.

    Only one of template_name, get_template_name, template or get_template must be defined.

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

    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_name, get_template_name, template or get_template must be defined.

    "},{"location":"reference/django_components/component/#django_components.component.Component.as_view","title":"as_view classmethod","text":"
    as_view(**initkwargs: Any) -> ViewFn\n

    Shortcut for calling Component.View.as_view and passing component instance to it.

    Source code in src/django_components/component.py
    @classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n    \"\"\"\n    Shortcut for calling `Component.View.as_view` and passing component instance to it.\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    # Allow the View class to access this component via `self.component`\n    return comp.View.as_view(**initkwargs, component=comp)\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.get_template","title":"get_template","text":"
    get_template(context: Context) -> Optional[Union[str, Template]]\n

    Inlined Django template associated with this component. Can be a plain string or a Template instance.

    Only one of template_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n    \"\"\"\n    Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.get_template_name","title":"get_template_name","text":"
    get_template_name(context: Context) -> Optional[str]\n

    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_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template_name(self, context: Context) -> Optional[str]:\n    \"\"\"\n    Filepath to the Django template associated with this component.\n\n    The filepath must be relative to either the file where the component class was defined,\n    or one of the roots of `STATIFILES_DIRS`.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.inject","title":"inject","text":"
    inject(key: str, default: Optional[Any] = None) -> Any\n

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

    Source code in src/django_components/component.py
    def inject(self, key: str, default: Optional[Any] = None) -> Any:\n    \"\"\"\n    Use this method to retrieve the data that was passed to a `{% provide %}` tag\n    with the corresponding key.\n\n    To retrieve the data, `inject()` must be called inside a component that's\n    inside the `{% provide %}` tag.\n\n    You may also pass a default that will be used if the `provide` tag with given\n    key was NOT found.\n\n    This method mut be used inside the `get_context_data()` method and raises\n    an error if called elsewhere.\n\n    Example:\n\n    Given this template:\n    ```django\n    {% provide \"provider\" hello=\"world\" %}\n        {% component \"my_comp\" %}\n        {% endcomponent %}\n    {% endprovide %}\n    ```\n\n    And given this definition of \"my_comp\" component:\n    ```py\n    from django_components import Component, register\n\n    @register(\"my_comp\")\n    class MyComp(Component):\n        template = \"hi {{ data.hello }}!\"\n        def get_context_data(self):\n            data = self.inject(\"provider\")\n            return {\"data\": data}\n    ```\n\n    This renders into:\n    ```\n    hi world!\n    ```\n\n    As the `{{ data.hello }}` is taken from the \"provider\".\n    \"\"\"\n    if self.input is None:\n        raise RuntimeError(\n            f\"Method 'inject()' of component '{self.name}' was called outside of 'get_context_data()'\"\n        )\n\n    return get_injected_context_var(self.name, self.input.context, key, default)\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.on_render_after","title":"on_render_after","text":"
    on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\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.

    Source code in src/django_components/component.py
    def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n    \"\"\"\n    Hook that runs just after the component's template was rendered.\n    It receives the rendered output as the last argument.\n\n    You can use this hook to access the context or the template, but modifying\n    them won't have any effect.\n\n    To override the content that gets rendered, you can return a string or SafeString\n    from this hook.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.on_render_before","title":"on_render_before","text":"
    on_render_before(context: Context, template: Template) -> 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.

    Source code in src/django_components/component.py
    def on_render_before(self, context: Context, template: Template) -> None:\n    \"\"\"\n    Hook that runs just before the component's template is rendered.\n\n    You can use this hook to access or modify the context or the template.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/component/#django_components.component.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) -> str\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render(\n    cls,\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) -> str:\n    \"\"\"\n    Render the component into a string.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    return comp._render(context, args, kwargs, slots, escape_slots_content)\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.render_css_dependencies","title":"render_css_dependencies","text":"
    render_css_dependencies() -> SafeString\n

    Render only CSS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_css_dependencies(self) -> SafeString:\n    \"\"\"Render only CSS dependencies available in the media class or provided as a string.\"\"\"\n    if self.css is not None:\n        return mark_safe(f\"<style>{self.css}</style>\")\n    return mark_safe(\"\\n\".join(self.media.render_css()))\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.render_dependencies","title":"render_dependencies","text":"
    render_dependencies() -> SafeString\n

    Helper function to render all dependencies for a component.

    Source code in src/django_components/component.py
    def render_dependencies(self) -> SafeString:\n    \"\"\"Helper function to render all dependencies for a component.\"\"\"\n    dependencies = []\n\n    css_deps = self.render_css_dependencies()\n    if css_deps:\n        dependencies.append(css_deps)\n\n    js_deps = self.render_js_dependencies()\n    if js_deps:\n        dependencies.append(js_deps)\n\n    return mark_safe(\"\\n\".join(dependencies))\n
    "},{"location":"reference/django_components/component/#django_components.component.Component.render_js_dependencies","title":"render_js_dependencies","text":"
    render_js_dependencies() -> SafeString\n

    Render only JS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_js_dependencies(self) -> SafeString:\n    \"\"\"Render only JS dependencies available in the media class or provided as a string.\"\"\"\n    if self.js is not None:\n        return mark_safe(f\"<script>{self.js}</script>\")\n    return mark_safe(\"\\n\".join(self.media.render_js()))\n
    "},{"location":"reference/django_components/component/#django_components.component.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    *response_args: Any,\n    **response_kwargs: Any\n) -> HttpResponse\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render_to_response(\n    cls,\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    slots: Optional[SlotsType] = None,\n    escape_slots_content: bool = True,\n    args: Optional[ArgsType] = None,\n    kwargs: Optional[KwargsType] = None,\n    *response_args: Any,\n    **response_kwargs: Any,\n) -> HttpResponse:\n    \"\"\"\n    Render the component and wrap the content in the response class.\n\n    The response class is taken from `Component.response_class`. Defaults to `django.http.HttpResponse`.\n\n    This is the interface for the `django.views.View` class which allows us to\n    use components as Django views with `component.as_view()`.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Any additional args and kwargs are passed to the `response_class`.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    content = cls.render(\n        args=args,\n        kwargs=kwargs,\n        context=context,\n        slots=slots,\n        escape_slots_content=escape_slots_content,\n    )\n    return cls.response_class(content, *response_args, **response_kwargs)\n
    "},{"location":"reference/django_components/component/#django_components.component.ComponentNode","title":"ComponentNode","text":"
    ComponentNode(\n    name: str,\n    args: List[Expression],\n    kwargs: RuntimeKwargs,\n    registry: ComponentRegistry,\n    isolated_context: bool = False,\n    fill_nodes: Optional[List[FillNode]] = None,\n    node_id: Optional[str] = None,\n)\n

    Bases: BaseNode

    Django.template.Node subclass that renders a django-components component

    Source code in src/django_components/component.py
    def __init__(\n    self,\n    name: str,\n    args: List[Expression],\n    kwargs: RuntimeKwargs,\n    registry: ComponentRegistry,  # noqa F811\n    isolated_context: bool = False,\n    fill_nodes: Optional[List[FillNode]] = None,\n    node_id: Optional[str] = None,\n) -> None:\n    super().__init__(nodelist=NodeList(fill_nodes), args=args, kwargs=kwargs, node_id=node_id)\n\n    self.name = name\n    self.isolated_context = isolated_context\n    self.fill_nodes = fill_nodes or []\n    self.registry = registry\n
    "},{"location":"reference/django_components/component/#django_components.component.ComponentView","title":"ComponentView","text":"
    ComponentView(component: Component, **kwargs: Any)\n

    Bases: View

    Subclass of django.views.View where the Component instance is available via self.component.

    Source code in src/django_components/component.py
    def __init__(self, component: \"Component\", **kwargs: Any) -> None:\n    super().__init__(**kwargs)\n    self.component = component\n
    "},{"location":"reference/django_components/component_media/","title":" component_media","text":""},{"location":"reference/django_components/component_media/#django_components.component_media","title":"component_media","text":"

    Classes:

    • ComponentMediaInput \u2013

      Defines JS and CSS media files associated with this component.

    • MediaMeta \u2013

      Metaclass for handling media files for components.

    "},{"location":"reference/django_components/component_media/#django_components.component_media.ComponentMediaInput","title":"ComponentMediaInput","text":"

    Defines JS and CSS media files associated with this component.

    "},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta","title":"MediaMeta","text":"

    Bases: MediaDefiningClass

    Metaclass for handling media files for components.

    Similar to MediaDefiningClass, this class supports the use of Media attribute to define associated JS/CSS files, which are then available under media attribute as a instance of Media class.

    This subclass has following changes:

    "},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--1-support-for-multiple-interfaces-of-jscss","title":"1. Support for multiple interfaces of JS/CSS","text":"
    1. As plain strings

      class MyComponent(Component):\n    class Media:\n        js = \"path/to/script.js\"\n        css = \"path/to/style.css\"\n

    2. As lists

      class MyComponent(Component):\n    class Media:\n        js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n        css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n

    3. [CSS ONLY] Dicts of strings

      class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": \"path/to/style1.css\",\n            \"print\": \"path/to/style2.css\",\n        }\n

    4. [CSS ONLY] Dicts of lists

      class MyComponent(Component):\n    class Media:\n        css = {\n            \"all\": [\"path/to/style1.css\"],\n            \"print\": [\"path/to/style2.css\"],\n        }\n

    "},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--2-media-are-first-resolved-relative-to-class-definition-file","title":"2. Media are first resolved relative to class definition file","text":"

    E.g. if in a directory my_comp you have script.js and my_comp.py, and my_comp.py looks like this:

    class MyComponent(Component):\n    class Media:\n        js = \"script.js\"\n

    Then script.js will be resolved as my_comp/script.js.

    "},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--3-media-can-be-defined-as-str-bytes-pathlike-safestring-or-function-of-thereof","title":"3. Media can be defined as str, bytes, PathLike, SafeString, or function of thereof","text":"

    E.g.:

    def lazy_eval_css():\n    # do something\n    return path\n\nclass MyComponent(Component):\n    class Media:\n        js = b\"script.js\"\n        css = lazy_eval_css\n
    "},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--4-subclass-media-class-with-media_class","title":"4. Subclass Media class with media_class","text":"

    Normal MediaDefiningClass creates an instance of Media class under the media attribute. This class allows to override which class will be instantiated with media_class attribute:

    class MyMedia(Media):\n    def render_js(self):\n        ...\n\nclass MyComponent(Component):\n    media_class = MyMedia\n    def get_context_data(self):\n        assert isinstance(self.media, MyMedia)\n
    "},{"location":"reference/django_components/component_registry/","title":" component_registry","text":""},{"location":"reference/django_components/component_registry/#django_components.component_registry","title":"component_registry","text":"

    Classes:

    • ComponentRegistry \u2013

      Manages which components can be used in the template tags.

    Functions:

    • register \u2013

      Class decorator to register a component.

    Attributes:

    • registry (ComponentRegistry) \u2013

      The default and global component registry. Use this instance to directly

    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.registry","title":"registry module-attribute","text":"
    registry: ComponentRegistry = ComponentRegistry()\n

    The default and global component registry. Use this instance to directly register or remove components:

    # Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Get single\nregistry.get(\"button\")\n# Get all\nregistry.all()\n# Unregister single\nregistry.unregister(\"button\")\n# Unregister all\nregistry.clear()\n
    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry","title":"ComponentRegistry","text":"
    ComponentRegistry(\n    library: Optional[Library] = None, settings: Optional[Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]] = None\n)\n

    Manages which components can be used in the template tags.

    Each ComponentRegistry instance is associated with an instance of Django's Library. So when you register or unregister a component to/from a component registry, behind the scenes the registry automatically adds/removes the component's template tag to/from the Library.

    The Library instance can be set at instantiation. If omitted, then the default Library instance from django_components is used. The Library instance can be accessed under library attribute.

    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

    Methods:

    • all \u2013

      Retrieve all registered component classes.

    • clear \u2013

      Clears the registry, unregistering all components.

    • get \u2013

      Retrieve a component class registered under the given name.

    • register \u2013

      Register a component with this registry under the given name.

    • unregister \u2013

      Unlinks a previously-registered component from the registry under the given name.

    Attributes:

    • library (Library) \u2013

      The template tag library with which the component registry is associated.

    Source code in src/django_components/component_registry.py
    def __init__(\n    self,\n    library: Optional[Library] = None,\n    settings: Optional[Union[RegistrySettings, Callable[[\"ComponentRegistry\"], RegistrySettings]]] = None,\n) -> None:\n    self._registry: Dict[str, ComponentRegistryEntry] = {}  # component name -> component_entry mapping\n    self._tags: Dict[str, Set[str]] = {}  # tag -> list[component names]\n    self._library = library\n    self._settings_input = settings\n    self._settings: Optional[Callable[[], InternalRegistrySettings]] = None\n\n    all_registries.append(self)\n
    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.library","title":"library property","text":"
    library: Library\n

    The template tag library with which the component registry is associated.

    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.all","title":"all","text":"
    all() -> Dict[str, Type[Component]]\n

    Retrieve all registered 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
    Source code in src/django_components/component_registry.py
    def all(self) -> Dict[str, Type[\"Component\"]]:\n    \"\"\"\n    Retrieve all registered component classes.\n\n    Example:\n\n    ```py\n    # First register components\n    registry.register(\"button\", ButtonComponent)\n    registry.register(\"card\", CardComponent)\n    # Then get all\n    registry.all()\n    # > {\n    # >   \"button\": ButtonComponent,\n    # >   \"card\": CardComponent,\n    # > }\n    ```\n    \"\"\"\n    comps = {key: entry.cls for key, entry in self._registry.items()}\n    return comps\n
    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.clear","title":"clear","text":"
    clear() -> None\n

    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
    Source code in src/django_components/component_registry.py
    def clear(self) -> None:\n    \"\"\"\n    Clears the registry, unregistering all components.\n\n    Example:\n\n    ```py\n    # First register components\n    registry.register(\"button\", ButtonComponent)\n    registry.register(\"card\", CardComponent)\n    # Then clear\n    registry.clear()\n    # Then get all\n    registry.all()\n    # > {}\n    ```\n    \"\"\"\n    all_comp_names = list(self._registry.keys())\n    for comp_name in all_comp_names:\n        self.unregister(comp_name)\n\n    self._registry = {}\n    self._tags = {}\n
    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.get","title":"get","text":"
    get(name: str) -> Type[Component]\n

    Retrieve a 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
    Source code in src/django_components/component_registry.py
    def get(self, name: str) -> Type[\"Component\"]:\n    \"\"\"\n    Retrieve a component class registered under the given name.\n\n    Raises `NotRegistered` if the given name is not registered.\n\n    Example:\n\n    ```py\n    # First register component\n    registry.register(\"button\", ButtonComponent)\n    # Then get\n    registry.get(\"button\")\n    # > ButtonComponent\n    ```\n    \"\"\"\n    if name not in self._registry:\n        raise NotRegistered('The component \"%s\" is not registered' % name)\n\n    return self._registry[name].cls\n
    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.register","title":"register","text":"
    register(name: str, component: Type[Component]) -> None\n

    Register a component 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\" %}{% endcomponent %}\n

    Raises AlreadyRegistered if a different component was already registered under the same name.

    Example:

    registry.register(\"button\", ButtonComponent)\n
    Source code in src/django_components/component_registry.py
    def register(self, name: str, component: Type[\"Component\"]) -> None:\n    \"\"\"\n    Register a component with this registry under the given name.\n\n    A component MUST be registered before it can be used in a template such as:\n    ```django\n    {% component \"my_comp\" %}{% endcomponent %}\n    ```\n\n    Raises `AlreadyRegistered` if a different component was already registered\n    under the same name.\n\n    Example:\n\n    ```py\n    registry.register(\"button\", ButtonComponent)\n    ```\n    \"\"\"\n    existing_component = self._registry.get(name)\n    if existing_component and existing_component.cls._class_hash != component._class_hash:\n        raise AlreadyRegistered('The component \"%s\" has already been registered' % name)\n\n    entry = self._register_to_library(name, component)\n\n    # Keep track of which components use which tags, because multiple components may\n    # use the same tag.\n    tag = entry.tag\n    if tag not in self._tags:\n        self._tags[tag] = set()\n    self._tags[tag].add(name)\n\n    self._registry[name] = entry\n
    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.unregister","title":"unregister","text":"
    unregister(name: str) -> None\n

    Unlinks a previously-registered component from the registry under the given name.

    Once a component is unregistered, it CANNOT be used in a template anymore. Following would raise an error:

    {% component \"my_comp\" %}{% endcomponent %}\n

    Raises NotRegistered if the given name is not registered.

    Example:

    # First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
    Source code in src/django_components/component_registry.py
    def unregister(self, name: str) -> None:\n    \"\"\"\n    Unlinks a previously-registered component from the registry under the given name.\n\n    Once a component is unregistered, it CANNOT be used in a template anymore.\n    Following would raise an error:\n    ```django\n    {% component \"my_comp\" %}{% endcomponent %}\n    ```\n\n    Raises `NotRegistered` if the given name is not registered.\n\n    Example:\n\n    ```py\n    # First register component\n    registry.register(\"button\", ButtonComponent)\n    # Then unregister\n    registry.unregister(\"button\")\n    ```\n    \"\"\"\n    # Validate\n    self.get(name)\n\n    entry = self._registry[name]\n    tag = entry.tag\n\n    # Unregister the tag from library if this was the last component using this tag\n    # Unlink component from tag\n    self._tags[tag].remove(name)\n\n    # Cleanup\n    is_tag_empty = not len(self._tags[tag])\n    if is_tag_empty:\n        del self._tags[tag]\n\n    # Only unregister a tag if it's NOT protected\n    is_protected = is_tag_protected(self.library, tag)\n    if not is_protected:\n        # Unregister the tag from library if this was the last component using this tag\n        if is_tag_empty and tag in self.library.tags:\n            del self.library.tags[tag]\n\n    del self._registry[name]\n
    "},{"location":"reference/django_components/component_registry/#django_components.component_registry.register","title":"register","text":"
    register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]\n

    Class decorator to register a component.

    Usage:

    @register(\"my_component\")\nclass MyComponent(Component):\n    ...\n

    Optionally specify which ComponentRegistry the component should be registered to by setting the registry kwarg:

    my_lib = django.template.Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n    ...\n
    Source code in src/django_components/component_registry.py
    def register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]:\n    \"\"\"\n    Class decorator to register a component.\n\n    Usage:\n\n    ```py\n    @register(\"my_component\")\n    class MyComponent(Component):\n        ...\n    ```\n\n    Optionally specify which `ComponentRegistry` the component should be registered to by\n    setting the `registry` kwarg:\n\n    ```py\n    my_lib = django.template.Library()\n    my_reg = ComponentRegistry(library=my_lib)\n\n    @register(\"my_component\", registry=my_reg)\n    class MyComponent(Component):\n        ...\n    ```\n    \"\"\"\n    if registry is None:\n        registry = _the_registry\n\n    def decorator(component: _TComp) -> _TComp:\n        registry.register(name=name, component=component)\n        return component\n\n    return decorator\n
    "},{"location":"reference/django_components/components/","title":"Index","text":""},{"location":"reference/django_components/components/#django_components.components","title":"components","text":"

    Modules:

    • dynamic \u2013
    "},{"location":"reference/django_components/components/#django_components.components.dynamic","title":"dynamic","text":"

    Modules:

    • types \u2013

      Helper types for IDEs.

    Classes:

    • DynamicComponent \u2013

      Dynamic component - This component takes inputs and renders the outputs depending on the

    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent","title":"DynamicComponent","text":"
    DynamicComponent(\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,\n)\n

    Bases: Component

    Dynamic component - This component takes inputs and renders the outputs depending on the is and registry arguments.

    • is - required - The component class or registered name of the component that will be rendered in this place.

    • registry - optional - Specify the registry to search for the registered name. If omitted, all registries are searched.

    Methods:

    • as_view \u2013

      Shortcut for calling Component.View.as_view and passing component instance to it.

    • get_template \u2013

      Inlined Django template associated with this component. Can be a plain string or a Template instance.

    • get_template_name \u2013

      Filepath to the Django template associated with this component.

    • inject \u2013

      Use this method to retrieve the data that was passed to a {% provide %} tag

    • on_render_after \u2013

      Hook that runs just after the component's template was rendered.

    • on_render_before \u2013

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

    • render \u2013

      Render the component into a string.

    • render_css_dependencies \u2013

      Render only CSS dependencies available in the media class or provided as a string.

    • render_dependencies \u2013

      Helper function to render all dependencies for a component.

    • render_js_dependencies \u2013

      Render only JS dependencies available in the media class or provided as a string.

    • render_to_response \u2013

      Render the component and wrap the content in the response class.

    Attributes:

    • Media \u2013

      Defines JS and CSS media files associated with this component.

    • css (Optional[str]) \u2013

      Inlined CSS associated with this component.

    • input (RenderInput[ArgsType, KwargsType, SlotsType]) \u2013

      Input holds the data (like arg, kwargs, slots) that were passsed to

    • is_filled (Dict[str, bool]) \u2013

      Dictionary describing which slots have or have not been filled.

    • js (Optional[str]) \u2013

      Inlined JS associated with this component.

    • media (Media) \u2013

      Normalized definition of JS and CSS media files associated with this component.

    • response_class \u2013

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

    • template_name (Optional[str]) \u2013

      Filepath to the Django template associated with this component.

    Source code in src/django_components/component.py
    def __init__(\n    self,\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,  # noqa F811\n):\n    # When user first instantiates the component class before calling\n    # `render` or `render_to_response`, then we want to allow the render\n    # function to make use of the instantiated object.\n    #\n    # So while `MyComp.render()` creates a new instance of MyComp internally,\n    # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n    # already-instantiated object.\n    #\n    # To achieve that, we want to re-assign the class methods as instance methods.\n    # For that we have to \"unwrap\" the class methods via __func__.\n    # See https://stackoverflow.com/a/76706399/9788634\n    self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self)  # type: ignore\n    self.render = types.MethodType(self.__class__.render.__func__, self)  # type: ignore\n    self.as_view = types.MethodType(self.__class__.as_view.__func__, self)  # type: ignore\n\n    self.registered_name: Optional[str] = registered_name\n    self.outer_context: Context = outer_context or Context()\n    self.fill_content = fill_content or {}\n    self.component_id = component_id or gen_id()\n    self.registry = registry or registry_\n    self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n    # None == uninitialized, False == No types, Tuple == types\n    self._types: Optional[Union[Tuple[Any, Any, Any, Any], Literal[False]]] = None\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.Media","title":"Media class-attribute instance-attribute","text":"
    Media = ComponentMediaInput\n

    Defines JS and CSS media files associated with this component.

    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.css","title":"css class-attribute instance-attribute","text":"
    css: Optional[str] = None\n

    Inlined CSS associated with this component.

    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.input","title":"input property","text":"
    input: RenderInput[ArgsType, KwargsType, SlotsType]\n

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

    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.is_filled","title":"is_filled property","text":"
    is_filled: Dict[str, bool]\n

    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/django_components/components/#django_components.components.dynamic.DynamicComponent.js","title":"js class-attribute instance-attribute","text":"
    js: Optional[str] = None\n

    Inlined JS associated with this component.

    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.media","title":"media instance-attribute","text":"
    media: Media\n

    Normalized definition of JS and CSS media files associated with this component.

    NOTE: This field is generated from Component.Media class.

    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.response_class","title":"response_class class-attribute instance-attribute","text":"
    response_class = HttpResponse\n

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

    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.template_name","title":"template_name class-attribute instance-attribute","text":"
    template_name: Optional[str] = None\n

    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_name, get_template_name, template or get_template must be defined.

    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.as_view","title":"as_view classmethod","text":"
    as_view(**initkwargs: Any) -> ViewFn\n

    Shortcut for calling Component.View.as_view and passing component instance to it.

    Source code in src/django_components/component.py
    @classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n    \"\"\"\n    Shortcut for calling `Component.View.as_view` and passing component instance to it.\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    # Allow the View class to access this component via `self.component`\n    return comp.View.as_view(**initkwargs, component=comp)\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.get_template","title":"get_template","text":"
    get_template(context: Context) -> Optional[Union[str, Template]]\n

    Inlined Django template associated with this component. Can be a plain string or a Template instance.

    Only one of template_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n    \"\"\"\n    Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.get_template_name","title":"get_template_name","text":"
    get_template_name(context: Context) -> Optional[str]\n

    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_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template_name(self, context: Context) -> Optional[str]:\n    \"\"\"\n    Filepath to the Django template associated with this component.\n\n    The filepath must be relative to either the file where the component class was defined,\n    or one of the roots of `STATIFILES_DIRS`.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.inject","title":"inject","text":"
    inject(key: str, default: Optional[Any] = None) -> Any\n

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

    Source code in src/django_components/component.py
    def inject(self, key: str, default: Optional[Any] = None) -> Any:\n    \"\"\"\n    Use this method to retrieve the data that was passed to a `{% provide %}` tag\n    with the corresponding key.\n\n    To retrieve the data, `inject()` must be called inside a component that's\n    inside the `{% provide %}` tag.\n\n    You may also pass a default that will be used if the `provide` tag with given\n    key was NOT found.\n\n    This method mut be used inside the `get_context_data()` method and raises\n    an error if called elsewhere.\n\n    Example:\n\n    Given this template:\n    ```django\n    {% provide \"provider\" hello=\"world\" %}\n        {% component \"my_comp\" %}\n        {% endcomponent %}\n    {% endprovide %}\n    ```\n\n    And given this definition of \"my_comp\" component:\n    ```py\n    from django_components import Component, register\n\n    @register(\"my_comp\")\n    class MyComp(Component):\n        template = \"hi {{ data.hello }}!\"\n        def get_context_data(self):\n            data = self.inject(\"provider\")\n            return {\"data\": data}\n    ```\n\n    This renders into:\n    ```\n    hi world!\n    ```\n\n    As the `{{ data.hello }}` is taken from the \"provider\".\n    \"\"\"\n    if self.input is None:\n        raise RuntimeError(\n            f\"Method 'inject()' of component '{self.name}' was called outside of 'get_context_data()'\"\n        )\n\n    return get_injected_context_var(self.name, self.input.context, key, default)\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.on_render_after","title":"on_render_after","text":"
    on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\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.

    Source code in src/django_components/component.py
    def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n    \"\"\"\n    Hook that runs just after the component's template was rendered.\n    It receives the rendered output as the last argument.\n\n    You can use this hook to access the context or the template, but modifying\n    them won't have any effect.\n\n    To override the content that gets rendered, you can return a string or SafeString\n    from this hook.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.on_render_before","title":"on_render_before","text":"
    on_render_before(context: Context, template: Template) -> 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.

    Source code in src/django_components/component.py
    def on_render_before(self, context: Context, template: Template) -> None:\n    \"\"\"\n    Hook that runs just before the component's template is rendered.\n\n    You can use this hook to access or modify the context or the template.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.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) -> str\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render(\n    cls,\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) -> str:\n    \"\"\"\n    Render the component into a string.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    return comp._render(context, args, kwargs, slots, escape_slots_content)\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.render_css_dependencies","title":"render_css_dependencies","text":"
    render_css_dependencies() -> SafeString\n

    Render only CSS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_css_dependencies(self) -> SafeString:\n    \"\"\"Render only CSS dependencies available in the media class or provided as a string.\"\"\"\n    if self.css is not None:\n        return mark_safe(f\"<style>{self.css}</style>\")\n    return mark_safe(\"\\n\".join(self.media.render_css()))\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.render_dependencies","title":"render_dependencies","text":"
    render_dependencies() -> SafeString\n

    Helper function to render all dependencies for a component.

    Source code in src/django_components/component.py
    def render_dependencies(self) -> SafeString:\n    \"\"\"Helper function to render all dependencies for a component.\"\"\"\n    dependencies = []\n\n    css_deps = self.render_css_dependencies()\n    if css_deps:\n        dependencies.append(css_deps)\n\n    js_deps = self.render_js_dependencies()\n    if js_deps:\n        dependencies.append(js_deps)\n\n    return mark_safe(\"\\n\".join(dependencies))\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.render_js_dependencies","title":"render_js_dependencies","text":"
    render_js_dependencies() -> SafeString\n

    Render only JS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_js_dependencies(self) -> SafeString:\n    \"\"\"Render only JS dependencies available in the media class or provided as a string.\"\"\"\n    if self.js is not None:\n        return mark_safe(f\"<script>{self.js}</script>\")\n    return mark_safe(\"\\n\".join(self.media.render_js()))\n
    "},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.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    *response_args: Any,\n    **response_kwargs: Any\n) -> HttpResponse\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render_to_response(\n    cls,\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    slots: Optional[SlotsType] = None,\n    escape_slots_content: bool = True,\n    args: Optional[ArgsType] = None,\n    kwargs: Optional[KwargsType] = None,\n    *response_args: Any,\n    **response_kwargs: Any,\n) -> HttpResponse:\n    \"\"\"\n    Render the component and wrap the content in the response class.\n\n    The response class is taken from `Component.response_class`. Defaults to `django.http.HttpResponse`.\n\n    This is the interface for the `django.views.View` class which allows us to\n    use components as Django views with `component.as_view()`.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Any additional args and kwargs are passed to the `response_class`.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    content = cls.render(\n        args=args,\n        kwargs=kwargs,\n        context=context,\n        slots=slots,\n        escape_slots_content=escape_slots_content,\n    )\n    return cls.response_class(content, *response_args, **response_kwargs)\n
    "},{"location":"reference/django_components/components/dynamic/","title":" dynamic","text":""},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic","title":"dynamic","text":"

    Modules:

    • types \u2013

      Helper types for IDEs.

    Classes:

    • DynamicComponent \u2013

      Dynamic component - This component takes inputs and renders the outputs depending on the

    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent","title":"DynamicComponent","text":"
    DynamicComponent(\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,\n)\n

    Bases: Component

    Dynamic component - This component takes inputs and renders the outputs depending on the is and registry arguments.

    • is - required - The component class or registered name of the component that will be rendered in this place.

    • registry - optional - Specify the registry to search for the registered name. If omitted, all registries are searched.

    Methods:

    • as_view \u2013

      Shortcut for calling Component.View.as_view and passing component instance to it.

    • get_template \u2013

      Inlined Django template associated with this component. Can be a plain string or a Template instance.

    • get_template_name \u2013

      Filepath to the Django template associated with this component.

    • inject \u2013

      Use this method to retrieve the data that was passed to a {% provide %} tag

    • on_render_after \u2013

      Hook that runs just after the component's template was rendered.

    • on_render_before \u2013

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

    • render \u2013

      Render the component into a string.

    • render_css_dependencies \u2013

      Render only CSS dependencies available in the media class or provided as a string.

    • render_dependencies \u2013

      Helper function to render all dependencies for a component.

    • render_js_dependencies \u2013

      Render only JS dependencies available in the media class or provided as a string.

    • render_to_response \u2013

      Render the component and wrap the content in the response class.

    Attributes:

    • Media \u2013

      Defines JS and CSS media files associated with this component.

    • css (Optional[str]) \u2013

      Inlined CSS associated with this component.

    • input (RenderInput[ArgsType, KwargsType, SlotsType]) \u2013

      Input holds the data (like arg, kwargs, slots) that were passsed to

    • is_filled (Dict[str, bool]) \u2013

      Dictionary describing which slots have or have not been filled.

    • js (Optional[str]) \u2013

      Inlined JS associated with this component.

    • media (Media) \u2013

      Normalized definition of JS and CSS media files associated with this component.

    • response_class \u2013

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

    • template_name (Optional[str]) \u2013

      Filepath to the Django template associated with this component.

    Source code in src/django_components/component.py
    def __init__(\n    self,\n    registered_name: Optional[str] = None,\n    component_id: Optional[str] = None,\n    outer_context: Optional[Context] = None,\n    fill_content: Optional[Dict[str, FillContent]] = None,\n    registry: Optional[ComponentRegistry] = None,  # noqa F811\n):\n    # When user first instantiates the component class before calling\n    # `render` or `render_to_response`, then we want to allow the render\n    # function to make use of the instantiated object.\n    #\n    # So while `MyComp.render()` creates a new instance of MyComp internally,\n    # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n    # already-instantiated object.\n    #\n    # To achieve that, we want to re-assign the class methods as instance methods.\n    # For that we have to \"unwrap\" the class methods via __func__.\n    # See https://stackoverflow.com/a/76706399/9788634\n    self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self)  # type: ignore\n    self.render = types.MethodType(self.__class__.render.__func__, self)  # type: ignore\n    self.as_view = types.MethodType(self.__class__.as_view.__func__, self)  # type: ignore\n\n    self.registered_name: Optional[str] = registered_name\n    self.outer_context: Context = outer_context or Context()\n    self.fill_content = fill_content or {}\n    self.component_id = component_id or gen_id()\n    self.registry = registry or registry_\n    self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n    # None == uninitialized, False == No types, Tuple == types\n    self._types: Optional[Union[Tuple[Any, Any, Any, Any], Literal[False]]] = None\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.Media","title":"Media class-attribute instance-attribute","text":"
    Media = ComponentMediaInput\n

    Defines JS and CSS media files associated with this component.

    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.css","title":"css class-attribute instance-attribute","text":"
    css: Optional[str] = None\n

    Inlined CSS associated with this component.

    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.input","title":"input property","text":"
    input: RenderInput[ArgsType, KwargsType, SlotsType]\n

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

    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.is_filled","title":"is_filled property","text":"
    is_filled: Dict[str, bool]\n

    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/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.js","title":"js class-attribute instance-attribute","text":"
    js: Optional[str] = None\n

    Inlined JS associated with this component.

    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.media","title":"media instance-attribute","text":"
    media: Media\n

    Normalized definition of JS and CSS media files associated with this component.

    NOTE: This field is generated from Component.Media class.

    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.response_class","title":"response_class class-attribute instance-attribute","text":"
    response_class = HttpResponse\n

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

    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.template_name","title":"template_name class-attribute instance-attribute","text":"
    template_name: Optional[str] = None\n

    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_name, get_template_name, template or get_template must be defined.

    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.as_view","title":"as_view classmethod","text":"
    as_view(**initkwargs: Any) -> ViewFn\n

    Shortcut for calling Component.View.as_view and passing component instance to it.

    Source code in src/django_components/component.py
    @classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n    \"\"\"\n    Shortcut for calling `Component.View.as_view` and passing component instance to it.\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    # Allow the View class to access this component via `self.component`\n    return comp.View.as_view(**initkwargs, component=comp)\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.get_template","title":"get_template","text":"
    get_template(context: Context) -> Optional[Union[str, Template]]\n

    Inlined Django template associated with this component. Can be a plain string or a Template instance.

    Only one of template_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n    \"\"\"\n    Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.get_template_name","title":"get_template_name","text":"
    get_template_name(context: Context) -> Optional[str]\n

    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_name, get_template_name, template or get_template must be defined.

    Source code in src/django_components/component.py
    def get_template_name(self, context: Context) -> Optional[str]:\n    \"\"\"\n    Filepath to the Django template associated with this component.\n\n    The filepath must be relative to either the file where the component class was defined,\n    or one of the roots of `STATIFILES_DIRS`.\n\n    Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n    \"\"\"\n    return None\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.inject","title":"inject","text":"
    inject(key: str, default: Optional[Any] = None) -> Any\n

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

    Source code in src/django_components/component.py
    def inject(self, key: str, default: Optional[Any] = None) -> Any:\n    \"\"\"\n    Use this method to retrieve the data that was passed to a `{% provide %}` tag\n    with the corresponding key.\n\n    To retrieve the data, `inject()` must be called inside a component that's\n    inside the `{% provide %}` tag.\n\n    You may also pass a default that will be used if the `provide` tag with given\n    key was NOT found.\n\n    This method mut be used inside the `get_context_data()` method and raises\n    an error if called elsewhere.\n\n    Example:\n\n    Given this template:\n    ```django\n    {% provide \"provider\" hello=\"world\" %}\n        {% component \"my_comp\" %}\n        {% endcomponent %}\n    {% endprovide %}\n    ```\n\n    And given this definition of \"my_comp\" component:\n    ```py\n    from django_components import Component, register\n\n    @register(\"my_comp\")\n    class MyComp(Component):\n        template = \"hi {{ data.hello }}!\"\n        def get_context_data(self):\n            data = self.inject(\"provider\")\n            return {\"data\": data}\n    ```\n\n    This renders into:\n    ```\n    hi world!\n    ```\n\n    As the `{{ data.hello }}` is taken from the \"provider\".\n    \"\"\"\n    if self.input is None:\n        raise RuntimeError(\n            f\"Method 'inject()' of component '{self.name}' was called outside of 'get_context_data()'\"\n        )\n\n    return get_injected_context_var(self.name, self.input.context, key, default)\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.on_render_after","title":"on_render_after","text":"
    on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\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.

    Source code in src/django_components/component.py
    def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n    \"\"\"\n    Hook that runs just after the component's template was rendered.\n    It receives the rendered output as the last argument.\n\n    You can use this hook to access the context or the template, but modifying\n    them won't have any effect.\n\n    To override the content that gets rendered, you can return a string or SafeString\n    from this hook.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.on_render_before","title":"on_render_before","text":"
    on_render_before(context: Context, template: Template) -> 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.

    Source code in src/django_components/component.py
    def on_render_before(self, context: Context, template: Template) -> None:\n    \"\"\"\n    Hook that runs just before the component's template is rendered.\n\n    You can use this hook to access or modify the context or the template.\n    \"\"\"\n    pass\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.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) -> str\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render(\n    cls,\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) -> str:\n    \"\"\"\n    Render the component into a string.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    # This method may be called as class method or as instance method.\n    # If called as class method, create a new instance.\n    if isinstance(cls, Component):\n        comp: Component = cls\n    else:\n        comp = cls()\n\n    return comp._render(context, args, kwargs, slots, escape_slots_content)\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.render_css_dependencies","title":"render_css_dependencies","text":"
    render_css_dependencies() -> SafeString\n

    Render only CSS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_css_dependencies(self) -> SafeString:\n    \"\"\"Render only CSS dependencies available in the media class or provided as a string.\"\"\"\n    if self.css is not None:\n        return mark_safe(f\"<style>{self.css}</style>\")\n    return mark_safe(\"\\n\".join(self.media.render_css()))\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.render_dependencies","title":"render_dependencies","text":"
    render_dependencies() -> SafeString\n

    Helper function to render all dependencies for a component.

    Source code in src/django_components/component.py
    def render_dependencies(self) -> SafeString:\n    \"\"\"Helper function to render all dependencies for a component.\"\"\"\n    dependencies = []\n\n    css_deps = self.render_css_dependencies()\n    if css_deps:\n        dependencies.append(css_deps)\n\n    js_deps = self.render_js_dependencies()\n    if js_deps:\n        dependencies.append(js_deps)\n\n    return mark_safe(\"\\n\".join(dependencies))\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.render_js_dependencies","title":"render_js_dependencies","text":"
    render_js_dependencies() -> SafeString\n

    Render only JS dependencies available in the media class or provided as a string.

    Source code in src/django_components/component.py
    def render_js_dependencies(self) -> SafeString:\n    \"\"\"Render only JS dependencies available in the media class or provided as a string.\"\"\"\n    if self.js is not None:\n        return mark_safe(f\"<script>{self.js}</script>\")\n    return mark_safe(\"\\n\".join(self.media.render_js()))\n
    "},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.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    *response_args: Any,\n    **response_kwargs: Any\n) -> HttpResponse\n

    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.

    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

    Source code in src/django_components/component.py
    @classmethod\ndef render_to_response(\n    cls,\n    context: Optional[Union[Dict[str, Any], Context]] = None,\n    slots: Optional[SlotsType] = None,\n    escape_slots_content: bool = True,\n    args: Optional[ArgsType] = None,\n    kwargs: Optional[KwargsType] = None,\n    *response_args: Any,\n    **response_kwargs: Any,\n) -> HttpResponse:\n    \"\"\"\n    Render the component and wrap the content in the response class.\n\n    The response class is taken from `Component.response_class`. Defaults to `django.http.HttpResponse`.\n\n    This is the interface for the `django.views.View` class which allows us to\n    use components as Django views with `component.as_view()`.\n\n    Inputs:\n    - `args` - Positional args for the component. This is the same as calling the component\n      as `{% component \"my_comp\" arg1 arg2 ... %}`\n    - `kwargs` - Kwargs for the component. This is the same as calling the component\n      as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n    - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n        Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n        or render function.\n    - `escape_slots_content` - Whether the content from `slots` should be escaped.\n    - `context` - A context (dictionary or Django's Context) within which the component\n      is rendered. The keys on the context can be accessed from within the template.\n        - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n          component's args and kwargs.\n\n    Any additional args and kwargs are passed to the `response_class`.\n\n    Example:\n    ```py\n    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    ```\n    \"\"\"\n    content = cls.render(\n        args=args,\n        kwargs=kwargs,\n        context=context,\n        slots=slots,\n        escape_slots_content=escape_slots_content,\n    )\n    return cls.response_class(content, *response_args, **response_kwargs)\n
    "},{"location":"reference/django_components/context/","title":" context","text":""},{"location":"reference/django_components/context/#django_components.context","title":"context","text":"

    This file centralizes various ways we use Django's Context class pass data across components, nodes, slots, and contexts.

    You can think of the Context as our storage system.

    Functions:

    • copy_forloop_context \u2013

      Forward the info about the current loop

    • get_injected_context_var \u2013

      Retrieve a 'provided' field. The field MUST have been previously 'provided'

    • prepare_context \u2013

      Initialize the internal context state.

    • set_component_id \u2013

      We use the Context object to pass down info on inside of which component

    • set_provided_context_var \u2013

      'Provide' given data under given key. In other words, this data can be retrieved

    "},{"location":"reference/django_components/context/#django_components.context.copy_forloop_context","title":"copy_forloop_context","text":"
    copy_forloop_context(from_context: Context, to_context: Context) -> None\n

    Forward the info about the current loop

    Source code in src/django_components/context.py
    def copy_forloop_context(from_context: Context, to_context: Context) -> None:\n    \"\"\"Forward the info about the current loop\"\"\"\n    # Note that the ForNode (which implements for loop behavior) does not\n    # only add the `forloop` key, but also keys corresponding to the loop elements\n    # So if the loop syntax is `{% for my_val in my_lists %}`, then ForNode also\n    # sets a `my_val` key.\n    # For this reason, instead of copying individual keys, we copy the whole stack layer\n    # set by ForNode.\n    if \"forloop\" in from_context:\n        forloop_dict_index = find_last_index(from_context.dicts, lambda d: \"forloop\" in d)\n        to_context.update(from_context.dicts[forloop_dict_index])\n
    "},{"location":"reference/django_components/context/#django_components.context.get_injected_context_var","title":"get_injected_context_var","text":"
    get_injected_context_var(component_name: str, context: Context, key: str, default: Optional[Any] = None) -> Any\n

    Retrieve a 'provided' field. The field MUST have been previously 'provided' by the component's ancestors using the {% provide %} template tag.

    Source code in src/django_components/context.py
    def get_injected_context_var(\n    component_name: str,\n    context: Context,\n    key: str,\n    default: Optional[Any] = None,\n) -> Any:\n    \"\"\"\n    Retrieve a 'provided' field. The field MUST have been previously 'provided'\n    by the component's ancestors using the `{% provide %}` template tag.\n    \"\"\"\n    # NOTE: For simplicity, we keep the provided values directly on the context.\n    # This plays nicely with Django's Context, which behaves like a stack, so \"newer\"\n    # values overshadow the \"older\" ones.\n    internal_key = _INJECT_CONTEXT_KEY_PREFIX + key\n\n    # Return provided value if found\n    if internal_key in context:\n        return context[internal_key]\n\n    # If a default was given, return that\n    if default is not None:\n        return default\n\n    # Otherwise raise error\n    raise KeyError(\n        f\"Component '{component_name}' tried to inject a variable '{key}' before it was provided.\"\n        f\" To fix this, make sure that at least one ancestor of component '{component_name}' has\"\n        f\" the variable '{key}' in their 'provide' attribute.\"\n    )\n
    "},{"location":"reference/django_components/context/#django_components.context.prepare_context","title":"prepare_context","text":"
    prepare_context(context: Context, component_id: str) -> None\n

    Initialize the internal context state.

    Source code in src/django_components/context.py
    def prepare_context(\n    context: Context,\n    component_id: str,\n) -> None:\n    \"\"\"Initialize the internal context state.\"\"\"\n    # Initialize mapping dicts within this rendering run.\n    # This is shared across the whole render chain, thus we set it only once.\n    if _FILLED_SLOTS_CONTENT_CONTEXT_KEY not in context:\n        context[_FILLED_SLOTS_CONTENT_CONTEXT_KEY] = {}\n\n    set_component_id(context, component_id)\n
    "},{"location":"reference/django_components/context/#django_components.context.set_component_id","title":"set_component_id","text":"
    set_component_id(context: Context, component_id: str) -> None\n

    We use the Context object to pass down info on inside of which component we are currently rendering.

    Source code in src/django_components/context.py
    def set_component_id(context: Context, component_id: str) -> None:\n    \"\"\"\n    We use the Context object to pass down info on inside of which component\n    we are currently rendering.\n    \"\"\"\n    context[_CURRENT_COMP_CONTEXT_KEY] = component_id\n
    "},{"location":"reference/django_components/context/#django_components.context.set_provided_context_var","title":"set_provided_context_var","text":"
    set_provided_context_var(context: Context, key: str, provided_kwargs: Dict[str, Any]) -> None\n

    'Provide' given data under given key. In other words, this data can be retrieved using self.inject(key) inside of get_context_data() method of components that are nested inside the {% provide %} tag.

    Source code in src/django_components/context.py
    def set_provided_context_var(\n    context: Context,\n    key: str,\n    provided_kwargs: Dict[str, Any],\n) -> None:\n    \"\"\"\n    'Provide' given data under given key. In other words, this data can be retrieved\n    using `self.inject(key)` inside of `get_context_data()` method of components that\n    are nested inside the `{% provide %}` tag.\n    \"\"\"\n    # NOTE: We raise TemplateSyntaxError since this func should be called only from\n    # within template.\n    if not key:\n        raise TemplateSyntaxError(\n            \"Provide tag received an empty string. Key must be non-empty and a valid identifier.\"\n        )\n    if not key.isidentifier():\n        raise TemplateSyntaxError(\n            \"Provide tag received a non-identifier string. Key must be non-empty and a valid identifier.\"\n        )\n\n    # We turn the kwargs into a NamedTuple so that the object that's \"provided\"\n    # is immutable. This ensures that the data returned from `inject` will always\n    # have all the keys that were passed to the `provide` tag.\n    tpl_cls = namedtuple(\"DepInject\", provided_kwargs.keys())  # type: ignore[misc]\n    payload = tpl_cls(**provided_kwargs)\n\n    internal_key = _INJECT_CONTEXT_KEY_PREFIX + key\n    context[internal_key] = payload\n
    "},{"location":"reference/django_components/expression/","title":" expression","text":""},{"location":"reference/django_components/expression/#django_components.expression","title":"expression","text":"

    Classes:

    • Operator \u2013

      Operator describes something that somehow changes the inputs

    • SpreadOperator \u2013

      Operator that inserts one or more kwargs at the specified location.

    Functions:

    • process_aggregate_kwargs \u2013

      This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs

    "},{"location":"reference/django_components/expression/#django_components.expression.Operator","title":"Operator","text":"

    Bases: ABC

    Operator describes something that somehow changes the inputs to template tags (the {% %}).

    For example, a SpreadOperator inserts one or more kwargs at the specified location.

    "},{"location":"reference/django_components/expression/#django_components.expression.SpreadOperator","title":"SpreadOperator","text":"
    SpreadOperator(expr: Expression)\n

    Bases: Operator

    Operator that inserts one or more kwargs at the specified location.

    Source code in src/django_components/expression.py
    def __init__(self, expr: Expression) -> None:\n    self.expr = expr\n
    "},{"location":"reference/django_components/expression/#django_components.expression.process_aggregate_kwargs","title":"process_aggregate_kwargs","text":"
    process_aggregate_kwargs(kwargs: Mapping[str, Any]) -> Dict[str, Any]\n

    This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs start with some prefix delimited with : (e.g. attrs:).

    Example:

    process_component_kwargs({\"abc:one\": 1, \"abc:two\": 2, \"def:three\": 3, \"four\": 4})\n# {\"abc\": {\"one\": 1, \"two\": 2}, \"def\": {\"three\": 3}, \"four\": 4}\n

    We want to support a use case similar to Vue's fallthrough attributes. In other words, where a component author can designate a prop (input) which is a dict and which will be rendered as HTML attributes.

    This is useful for allowing component users to tweak styling or add event handling to the underlying HTML. E.g.:

    class=\"pa-4 d-flex text-black\" or @click.stop=\"alert('clicked!')\"

    So if the prop is attrs, and the component is called like so:

    {% component \"my_comp\" attrs=attrs %}\n

    then, if attrs is:

    {\"class\": \"text-red pa-4\", \"@click\": \"dispatch('my_event', 123)\"}\n

    and the component template is:

    <div {% html_attrs attrs add:class=\"extra-class\" %}></div>\n

    Then this renders:

    <div class=\"text-red pa-4 extra-class\" @click=\"dispatch('my_event', 123)\" ></div>\n

    However, this way it is difficult for the component user to define the attrs variable, especially if they want to combine static and dynamic values. Because they will need to pre-process the attrs dict.

    So, instead, we allow to \"aggregate\" props into a dict. So all props that start with attrs:, like attrs:class=\"text-red\", will be collected into a dict at key attrs.

    This provides sufficient flexiblity to make it easy for component users to provide \"fallthrough attributes\", and sufficiently easy for component authors to process that input while still being able to provide their own keys.

    Source code in src/django_components/expression.py
    def process_aggregate_kwargs(kwargs: Mapping[str, Any]) -> Dict[str, Any]:\n    \"\"\"\n    This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs\n    start with some prefix delimited with `:` (e.g. `attrs:`).\n\n    Example:\n    ```py\n    process_component_kwargs({\"abc:one\": 1, \"abc:two\": 2, \"def:three\": 3, \"four\": 4})\n    # {\"abc\": {\"one\": 1, \"two\": 2}, \"def\": {\"three\": 3}, \"four\": 4}\n    ```\n\n    ---\n\n    We want to support a use case similar to Vue's fallthrough attributes.\n    In other words, where a component author can designate a prop (input)\n    which is a dict and which will be rendered as HTML attributes.\n\n    This is useful for allowing component users to tweak styling or add\n    event handling to the underlying HTML. E.g.:\n\n    `class=\"pa-4 d-flex text-black\"` or `@click.stop=\"alert('clicked!')\"`\n\n    So if the prop is `attrs`, and the component is called like so:\n    ```django\n    {% component \"my_comp\" attrs=attrs %}\n    ```\n\n    then, if `attrs` is:\n    ```py\n    {\"class\": \"text-red pa-4\", \"@click\": \"dispatch('my_event', 123)\"}\n    ```\n\n    and the component template is:\n    ```django\n    <div {% html_attrs attrs add:class=\"extra-class\" %}></div>\n    ```\n\n    Then this renders:\n    ```html\n    <div class=\"text-red pa-4 extra-class\" @click=\"dispatch('my_event', 123)\" ></div>\n    ```\n\n    However, this way it is difficult for the component user to define the `attrs`\n    variable, especially if they want to combine static and dynamic values. Because\n    they will need to pre-process the `attrs` dict.\n\n    So, instead, we allow to \"aggregate\" props into a dict. So all props that start\n    with `attrs:`, like `attrs:class=\"text-red\"`, will be collected into a dict\n    at key `attrs`.\n\n    This provides sufficient flexiblity to make it easy for component users to provide\n    \"fallthrough attributes\", and sufficiently easy for component authors to process\n    that input while still being able to provide their own keys.\n    \"\"\"\n    processed_kwargs = {}\n    nested_kwargs: Dict[str, Dict[str, Any]] = {}\n    for key, val in kwargs.items():\n        if not is_aggregate_key(key):\n            processed_kwargs[key] = val\n            continue\n\n        # NOTE: Trim off the prefix from keys\n        prefix, sub_key = key.split(\":\", 1)\n        if prefix not in nested_kwargs:\n            nested_kwargs[prefix] = {}\n        nested_kwargs[prefix][sub_key] = val\n\n    # Assign aggregated values into normal input\n    for key, val in nested_kwargs.items():\n        if key in processed_kwargs:\n            raise TemplateSyntaxError(\n                f\"Received argument '{key}' both as a regular input ({key}=...)\"\n                f\" and as an aggregate dict ('{key}:key=...'). Must be only one of the two\"\n            )\n        processed_kwargs[key] = val\n\n    return processed_kwargs\n
    "},{"location":"reference/django_components/finders/","title":" finders","text":""},{"location":"reference/django_components/finders/#django_components.finders","title":"finders","text":"

    Classes:

    • ComponentsFileSystemFinder \u2013

      A static files finder based on FileSystemFinder.

    "},{"location":"reference/django_components/finders/#django_components.finders.ComponentsFileSystemFinder","title":"ComponentsFileSystemFinder","text":"
    ComponentsFileSystemFinder(app_names: Any = None, *args: Any, **kwargs: Any)\n

    Bases: BaseFinder

    A static files finder based on FileSystemFinder.

    Differences: - This finder uses COMPONENTS.dirs setting to locate files instead of STATICFILES_DIRS. - Whether a file within COMPONENTS.dirs is considered a STATIC file is configured by COMPONENTS.static_files_allowed and COMPONENTS.forbidden_static_files. - If COMPONENTS.dirs is not set, defaults to settings.BASE_DIR / \"components\"

    Methods:

    • find \u2013

      Look for files in the extra locations as defined in COMPONENTS.dirs.

    • find_location \u2013

      Find a requested static file in a location and return the found

    • list \u2013

      List all files in all locations.

    Source code in src/django_components/finders.py
    def __init__(self, app_names: Any = None, *args: Any, **kwargs: Any) -> None:\n    component_dirs = [str(p) for p in get_dirs()]\n\n    # NOTE: The rest of the __init__ is the same as `django.contrib.staticfiles.finders.FileSystemFinder`,\n    # but using our locations instead of STATICFILES_DIRS.\n\n    # List of locations with static files\n    self.locations: List[Tuple[str, str]] = []\n\n    # Maps dir paths to an appropriate storage instance\n    self.storages: Dict[str, FileSystemStorage] = {}\n    for root in component_dirs:\n        if isinstance(root, (list, tuple)):\n            prefix, root = root\n        else:\n            prefix = \"\"\n        if (prefix, root) not in self.locations:\n            self.locations.append((prefix, root))\n    for prefix, root in self.locations:\n        filesystem_storage = FileSystemStorage(location=root)\n        filesystem_storage.prefix = prefix\n        self.storages[root] = filesystem_storage\n\n    super().__init__(*args, **kwargs)\n
    "},{"location":"reference/django_components/finders/#django_components.finders.ComponentsFileSystemFinder.find","title":"find","text":"
    find(path: str, all: bool = False) -> Union[List[str], str]\n

    Look for files in the extra locations as defined in COMPONENTS.dirs.

    Source code in src/django_components/finders.py
    def find(self, path: str, all: bool = False) -> Union[List[str], str]:\n    \"\"\"\n    Look for files in the extra locations as defined in COMPONENTS.dirs.\n    \"\"\"\n    matches: List[str] = []\n    for prefix, root in self.locations:\n        if root not in searched_locations:\n            searched_locations.append(root)\n        matched_path = self.find_location(root, path, prefix)\n        if matched_path:\n            if not all:\n                return matched_path\n            matches.append(matched_path)\n    return matches\n
    "},{"location":"reference/django_components/finders/#django_components.finders.ComponentsFileSystemFinder.find_location","title":"find_location","text":"
    find_location(root: str, path: str, prefix: Optional[str] = None) -> Optional[str]\n

    Find a requested static file in a location and return the found absolute path (or None if no match).

    Source code in src/django_components/finders.py
    def find_location(self, root: str, path: str, prefix: Optional[str] = None) -> Optional[str]:\n    \"\"\"\n    Find a requested static file in a location and return the found\n    absolute path (or ``None`` if no match).\n    \"\"\"\n    if prefix:\n        prefix = \"%s%s\" % (prefix, os.sep)\n        if not path.startswith(prefix):\n            return None\n        path = path.removeprefix(prefix)\n    path = safe_join(root, path)\n\n    if os.path.exists(path) and self._is_path_valid(path):\n        return path\n    return None\n
    "},{"location":"reference/django_components/finders/#django_components.finders.ComponentsFileSystemFinder.list","title":"list","text":"
    list(ignore_patterns: List[str]) -> Iterable[Tuple[str, FileSystemStorage]]\n

    List all files in all locations.

    Source code in src/django_components/finders.py
    def list(self, ignore_patterns: List[str]) -> Iterable[Tuple[str, FileSystemStorage]]:\n    \"\"\"\n    List all files in all locations.\n    \"\"\"\n    for prefix, root in self.locations:\n        # Skip nonexistent directories.\n        if os.path.isdir(root):\n            storage = self.storages[root]\n            for path in get_files(storage, ignore_patterns):\n                if self._is_path_valid(path):\n                    yield path, storage\n
    "},{"location":"reference/django_components/library/","title":" library","text":""},{"location":"reference/django_components/library/#django_components.library","title":"library","text":"

    Module for interfacing with Django's Library (django.template.library)

    Attributes:

    • PROTECTED_TAGS \u2013

      These are the names that users cannot choose for their components,

    "},{"location":"reference/django_components/library/#django_components.library.PROTECTED_TAGS","title":"PROTECTED_TAGS module-attribute","text":"
    PROTECTED_TAGS = [\n    \"component_dependencies\",\n    \"component_css_dependencies\",\n    \"component_js_dependencies\",\n    \"fill\",\n    \"html_attrs\",\n    \"provide\",\n    \"slot\",\n]\n

    These are the names that users cannot choose for their components, as they would conflict with other tags in the Library.

    "},{"location":"reference/django_components/logger/","title":" logger","text":""},{"location":"reference/django_components/logger/#django_components.logger","title":"logger","text":"

    Functions:

    • trace \u2013

      TRACE level logger.

    • trace_msg \u2013

      TRACE level logger with opinionated format for tracing interaction of components,

    "},{"location":"reference/django_components/logger/#django_components.logger.trace","title":"trace","text":"
    trace(logger: Logger, message: str, *args: Any, **kwargs: Any) -> None\n

    TRACE level logger.

    To display TRACE logs, set the logging level to 5.

    Example:

    LOGGING = {\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\": 5,\n            \"handlers\": [\"console\"],\n        },\n    },\n}\n

    Source code in src/django_components/logger.py
    def trace(logger: logging.Logger, message: str, *args: Any, **kwargs: Any) -> None:\n    \"\"\"\n    TRACE level logger.\n\n    To display TRACE logs, set the logging level to 5.\n\n    Example:\n    ```py\n    LOGGING = {\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\": 5,\n                \"handlers\": [\"console\"],\n            },\n        },\n    }\n    ```\n    \"\"\"\n    if actual_trace_level_num == -1:\n        setup_logging()\n    if logger.isEnabledFor(actual_trace_level_num):\n        logger.log(actual_trace_level_num, message, *args, **kwargs)\n
    "},{"location":"reference/django_components/logger/#django_components.logger.trace_msg","title":"trace_msg","text":"
    trace_msg(\n    action: Literal[\"PARSE\", \"ASSOC\", \"RENDR\", \"GET\", \"SET\"],\n    node_type: Literal[\"COMP\", \"FILL\", \"SLOT\", \"PROVIDE\", \"N/A\"],\n    node_name: str,\n    node_id: str,\n    msg: str = \"\",\n    component_id: Optional[str] = None,\n) -> None\n

    TRACE level logger with opinionated format for tracing interaction of components, nodes, and slots. Formats messages like so:

    \"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"

    Source code in src/django_components/logger.py
    def trace_msg(\n    action: Literal[\"PARSE\", \"ASSOC\", \"RENDR\", \"GET\", \"SET\"],\n    node_type: Literal[\"COMP\", \"FILL\", \"SLOT\", \"PROVIDE\", \"N/A\"],\n    node_name: str,\n    node_id: str,\n    msg: str = \"\",\n    component_id: Optional[str] = None,\n) -> None:\n    \"\"\"\n    TRACE level logger with opinionated format for tracing interaction of components,\n    nodes, and slots. Formats messages like so:\n\n    `\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"`\n    \"\"\"\n    msg_prefix = \"\"\n    if action == \"ASSOC\":\n        if not component_id:\n            raise ValueError(\"component_id must be set for the ASSOC action\")\n        msg_prefix = f\"TO COMP {component_id}\"\n    elif action == \"RENDR\" and node_type == \"FILL\":\n        if not component_id:\n            raise ValueError(\"component_id must be set for the RENDER action\")\n        msg_prefix = f\"FOR COMP {component_id}\"\n\n    msg_parts = [f\"{action} {node_type} {node_name} ID {node_id}\", *([msg_prefix] if msg_prefix else []), msg]\n    full_msg = \" \".join(msg_parts)\n\n    # NOTE: When debugging tests during development, it may be easier to change\n    # this to `print()`\n    trace(logger, full_msg)\n
    "},{"location":"reference/django_components/management/","title":"Index","text":""},{"location":"reference/django_components/management/#django_components.management","title":"management","text":""},{"location":"reference/django_components/management/commands/","title":"Index","text":""},{"location":"reference/django_components/management/commands/#django_components.management.commands","title":"commands","text":""},{"location":"reference/django_components/management/commands/startcomponent/","title":" startcomponent","text":""},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent","title":"startcomponent","text":""},{"location":"reference/django_components/management/commands/upgradecomponent/","title":" upgradecomponent","text":""},{"location":"reference/django_components/management/commands/upgradecomponent/#django_components.management.commands.upgradecomponent","title":"upgradecomponent","text":""},{"location":"reference/django_components/middleware/","title":" middleware","text":""},{"location":"reference/django_components/middleware/#django_components.middleware","title":"middleware","text":"

    Classes:

    • ComponentDependencyMiddleware \u2013

      Middleware that inserts CSS/JS dependencies for all rendered components at points marked with template tags.

    • DependencyReplacer \u2013

      Replacer for use in re.sub that replaces the first placeholder CSS and JS

    Functions:

    • join_media \u2013

      Return combined media object for iterable of components.

    "},{"location":"reference/django_components/middleware/#django_components.middleware.ComponentDependencyMiddleware","title":"ComponentDependencyMiddleware","text":"
    ComponentDependencyMiddleware(get_response: Callable[[HttpRequest], HttpResponse])\n

    Middleware that inserts CSS/JS dependencies for all rendered components at points marked with template tags.

    Source code in src/django_components/middleware.py
    def __init__(self, get_response: \"Callable[[HttpRequest], HttpResponse]\") -> None:\n    self.get_response = get_response\n\n    if iscoroutinefunction(self.get_response):\n        markcoroutinefunction(self)\n
    "},{"location":"reference/django_components/middleware/#django_components.middleware.DependencyReplacer","title":"DependencyReplacer","text":"
    DependencyReplacer(css_string: bytes, js_string: bytes)\n

    Replacer for use in re.sub that replaces the first placeholder CSS and JS tags it encounters and removes any subsequent ones.

    Source code in src/django_components/middleware.py
    def __init__(self, css_string: bytes, js_string: bytes) -> None:\n    self.js_string = js_string\n    self.css_string = css_string\n
    "},{"location":"reference/django_components/middleware/#django_components.middleware.join_media","title":"join_media","text":"
    join_media(components: Iterable[Component]) -> Media\n

    Return combined media object for iterable of components.

    Source code in src/django_components/middleware.py
    def join_media(components: Iterable[\"Component\"]) -> Media:\n    \"\"\"Return combined media object for iterable of components.\"\"\"\n\n    return sum([component.media for component in components], Media())\n
    "},{"location":"reference/django_components/node/","title":" node","text":""},{"location":"reference/django_components/node/#django_components.node","title":"node","text":"

    Classes:

    • BaseNode \u2013

      Shared behavior for our subclasses of Django's Node

    Functions:

    • get_node_children \u2013

      Get child Nodes from Node's nodelist atribute.

    • get_template_for_include_node \u2013

      This snippet is taken directly from IncludeNode.render(). Unfortunately the

    • walk_nodelist \u2013

      Recursively walk a NodeList, calling callback for each Node.

    "},{"location":"reference/django_components/node/#django_components.node.BaseNode","title":"BaseNode","text":"
    BaseNode(\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    args: Optional[List[Expression]] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n)\n

    Bases: Node

    Shared behavior for our subclasses of Django's Node

    Source code in src/django_components/node.py
    def __init__(\n    self,\n    nodelist: Optional[NodeList] = None,\n    node_id: Optional[str] = None,\n    args: Optional[List[Expression]] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n):\n    self.nodelist = nodelist or NodeList()\n    self.node_id = node_id or gen_id()\n    self.args = args or []\n    self.kwargs = kwargs or RuntimeKwargs({})\n
    "},{"location":"reference/django_components/node/#django_components.node.get_node_children","title":"get_node_children","text":"
    get_node_children(node: Node, context: Optional[Context] = None) -> NodeList\n

    Get child Nodes from Node's nodelist atribute.

    This function is taken from get_nodes_by_type method of django.template.base.Node.

    Source code in src/django_components/node.py
    def get_node_children(node: Node, context: Optional[Context] = None) -> NodeList:\n    \"\"\"\n    Get child Nodes from Node's nodelist atribute.\n\n    This function is taken from `get_nodes_by_type` method of `django.template.base.Node`.\n    \"\"\"\n    # Special case - {% extends %} tag - Load the template and go deeper\n    if isinstance(node, ExtendsNode):\n        # NOTE: When {% extends %} node is being parsed, it collects all remaining template\n        # under node.nodelist.\n        # Hence, when we come across ExtendsNode in the template, we:\n        # 1. Go over all nodes in the template using `node.nodelist`\n        # 2. Go over all nodes in the \"parent\" template, via `node.get_parent`\n        nodes = NodeList()\n        nodes.extend(node.nodelist)\n        template = node.get_parent(context)\n        nodes.extend(template.nodelist)\n        return nodes\n\n    # Special case - {% include %} tag - Load the template and go deeper\n    elif isinstance(node, IncludeNode):\n        template = get_template_for_include_node(node, context)\n        return template.nodelist\n\n    nodes = NodeList()\n    for attr in node.child_nodelists:\n        nodelist = getattr(node, attr, [])\n        if nodelist:\n            nodes.extend(nodelist)\n    return nodes\n
    "},{"location":"reference/django_components/node/#django_components.node.get_template_for_include_node","title":"get_template_for_include_node","text":"
    get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template\n

    This snippet is taken directly from IncludeNode.render(). Unfortunately the render logic doesn't separate out template loading logic from rendering, so we have to copy the method.

    Source code in src/django_components/node.py
    def get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template:\n    \"\"\"\n    This snippet is taken directly from `IncludeNode.render()`. Unfortunately the\n    render logic doesn't separate out template loading logic from rendering, so we\n    have to copy the method.\n    \"\"\"\n    template = include_node.template.resolve(context)\n    # Does this quack like a Template?\n    if not callable(getattr(template, \"render\", None)):\n        # If not, try the cache and select_template().\n        template_name = template or ()\n        if isinstance(template_name, str):\n            template_name = (\n                construct_relative_path(\n                    include_node.origin.template_name,\n                    template_name,\n                ),\n            )\n        else:\n            template_name = tuple(template_name)\n        cache = context.render_context.dicts[0].setdefault(include_node, {})\n        template = cache.get(template_name)\n        if template is None:\n            template = context.template.engine.select_template(template_name)\n            cache[template_name] = template\n    # Use the base.Template of a backends.django.Template.\n    elif hasattr(template, \"template\"):\n        template = template.template\n    return template\n
    "},{"location":"reference/django_components/node/#django_components.node.walk_nodelist","title":"walk_nodelist","text":"
    walk_nodelist(nodes: NodeList, callback: Callable[[Node], Optional[str]], context: Optional[Context] = None) -> None\n

    Recursively walk a NodeList, calling callback for each Node.

    Source code in src/django_components/node.py
    def walk_nodelist(\n    nodes: NodeList,\n    callback: Callable[[Node], Optional[str]],\n    context: Optional[Context] = None,\n) -> None:\n    \"\"\"Recursively walk a NodeList, calling `callback` for each Node.\"\"\"\n    node_queue: List[NodeTraverse] = [NodeTraverse(node=node, parent=None) for node in nodes]\n    while len(node_queue):\n        traverse = node_queue.pop()\n        callback(traverse)\n        child_nodes = get_node_children(traverse.node, context)\n        child_traverses = [NodeTraverse(node=child_node, parent=traverse) for child_node in child_nodes]\n        node_queue.extend(child_traverses)\n
    "},{"location":"reference/django_components/provide/","title":" provide","text":""},{"location":"reference/django_components/provide/#django_components.provide","title":"provide","text":"

    Classes:

    • ProvideNode \u2013

      Implementation of the {% provide %} tag.

    "},{"location":"reference/django_components/provide/#django_components.provide.ProvideNode","title":"ProvideNode","text":"
    ProvideNode(nodelist: NodeList, trace_id: str, node_id: Optional[str] = None, kwargs: Optional[RuntimeKwargs] = None)\n

    Bases: BaseNode

    Implementation of the {% provide %} tag. For more info see Component.inject.

    Source code in src/django_components/provide.py
    def __init__(\n    self,\n    nodelist: NodeList,\n    trace_id: str,\n    node_id: Optional[str] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n):\n    super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n    self.nodelist = nodelist\n    self.node_id = node_id or gen_id()\n    self.trace_id = trace_id\n    self.kwargs = kwargs or RuntimeKwargs({})\n
    "},{"location":"reference/django_components/slots/","title":" slots","text":""},{"location":"reference/django_components/slots/#django_components.slots","title":"slots","text":"

    Classes:

    • FillContent \u2013

      This represents content set with the {% fill %} tag, e.g.:

    • FillNode \u2013

      Set when a component tag pair is passed template content that

    • Slot \u2013

      This represents content set with the {% slot %} tag, e.g.:

    • SlotFill \u2013

      SlotFill describes what WILL be rendered.

    • SlotNode \u2013
    • SlotRef \u2013

      SlotRef allows to treat a slot as a variable. The slot is rendered only once

    Functions:

    • parse_slot_fill_nodes_from_component_nodelist \u2013

      Given a component body (django.template.NodeList), find all slot fills,

    • resolve_slots \u2013

      Search the template for all SlotNodes, and associate the slots

    "},{"location":"reference/django_components/slots/#django_components.slots.FillContent","title":"FillContent dataclass","text":"
    FillContent(content_func: SlotFunc[TSlotData], slot_default_var: Optional[SlotDefaultName], slot_data_var: Optional[SlotDataName])\n

    Bases: Generic[TSlotData]

    This represents content set with the {% fill %} tag, e.g.:

    {% component \"my_comp\" %}\n    {% fill \"first_slot\" %} <--- This\n        hi\n        {{ my_var }}\n        hello\n    {% endfill %}\n{% endcomponent %}\n
    "},{"location":"reference/django_components/slots/#django_components.slots.FillNode","title":"FillNode","text":"
    FillNode(nodelist: NodeList, kwargs: RuntimeKwargs, trace_id: str, node_id: Optional[str] = None, is_implicit: bool = False)\n

    Bases: BaseNode

    Set when a component tag pair is passed template content that excludes fill tags. Nodes of this type contribute their nodelists to slots marked as 'default'.

    Source code in src/django_components/slots.py
    def __init__(\n    self,\n    nodelist: NodeList,\n    kwargs: RuntimeKwargs,\n    trace_id: str,\n    node_id: Optional[str] = None,\n    is_implicit: bool = False,\n):\n    super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n    self.is_implicit = is_implicit\n    self.trace_id = trace_id\n    self.component_id: Optional[str] = None\n
    "},{"location":"reference/django_components/slots/#django_components.slots.Slot","title":"Slot","text":"

    Bases: NamedTuple

    This represents content set with the {% slot %} tag, e.g.:

    {% slot \"my_comp\" default %} <--- This\n    hi\n    {{ my_var }}\n    hello\n{% endslot %}\n
    "},{"location":"reference/django_components/slots/#django_components.slots.SlotFill","title":"SlotFill dataclass","text":"
    SlotFill(\n    name: str,\n    escaped_name: str,\n    is_filled: bool,\n    content_func: SlotFunc[TSlotData],\n    slot_default_var: Optional[SlotDefaultName],\n    slot_data_var: Optional[SlotDataName],\n)\n

    Bases: Generic[TSlotData]

    SlotFill describes what WILL be rendered.

    It is a Slot that has been resolved against FillContents passed to a Component.

    "},{"location":"reference/django_components/slots/#django_components.slots.SlotNode","title":"SlotNode","text":"
    SlotNode(\n    nodelist: NodeList,\n    trace_id: str,\n    node_id: Optional[str] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n    is_required: bool = False,\n    is_default: bool = False,\n)\n

    Bases: BaseNode

    Source code in src/django_components/slots.py
    def __init__(\n    self,\n    nodelist: NodeList,\n    trace_id: str,\n    node_id: Optional[str] = None,\n    kwargs: Optional[RuntimeKwargs] = None,\n    is_required: bool = False,\n    is_default: bool = False,\n):\n    super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n    self.is_required = is_required\n    self.is_default = is_default\n    self.trace_id = trace_id\n
    "},{"location":"reference/django_components/slots/#django_components.slots.SlotRef","title":"SlotRef","text":"
    SlotRef(slot: SlotNode, context: Context)\n

    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.

    Source code in src/django_components/slots.py
    def __init__(self, slot: \"SlotNode\", context: Context):\n    self._slot = slot\n    self._context = context\n
    "},{"location":"reference/django_components/slots/#django_components.slots.parse_slot_fill_nodes_from_component_nodelist","title":"parse_slot_fill_nodes_from_component_nodelist","text":"
    parse_slot_fill_nodes_from_component_nodelist(nodes: Tuple[Node, ...], ignored_nodes: Tuple[Type[Node]]) -> List[FillNode]\n

    Given a component body (django.template.NodeList), find all slot fills, whether defined explicitly with {% fill %} or implicitly.

    So if we have a component body:

    {% component \"mycomponent\" %}\n    {% fill \"first_fill\" %}\n        Hello!\n    {% endfill %}\n    {% fill \"second_fill\" %}\n        Hello too!\n    {% endfill %}\n{% endcomponent %}\n
    Then this function returns the nodes (django.template.Node) for fill \"first_fill\" and fill \"second_fill\".

    Source code in src/django_components/slots.py
    @lazy_cache(lambda: lru_cache(maxsize=app_settings.TEMPLATE_CACHE_SIZE))\ndef parse_slot_fill_nodes_from_component_nodelist(\n    nodes: Tuple[Node, ...],\n    ignored_nodes: Tuple[Type[Node]],\n) -> List[FillNode]:\n    \"\"\"\n    Given a component body (`django.template.NodeList`), find all slot fills,\n    whether defined explicitly with `{% fill %}` or implicitly.\n\n    So if we have a component body:\n    ```django\n    {% component \"mycomponent\" %}\n        {% fill \"first_fill\" %}\n            Hello!\n        {% endfill %}\n        {% fill \"second_fill\" %}\n            Hello too!\n        {% endfill %}\n    {% endcomponent %}\n    ```\n    Then this function returns the nodes (`django.template.Node`) for `fill \"first_fill\"`\n    and `fill \"second_fill\"`.\n    \"\"\"\n    fill_nodes: List[FillNode] = []\n    if nodelist_has_content(nodes):\n        for parse_fn in (\n            _try_parse_as_default_fill,\n            _try_parse_as_named_fill_tag_set,\n        ):\n            curr_fill_nodes = parse_fn(nodes, ignored_nodes)\n            if curr_fill_nodes:\n                fill_nodes = curr_fill_nodes\n                break\n        else:\n            raise TemplateSyntaxError(\n                \"Illegal content passed to 'component' tag pair. \"\n                \"Possible causes: 1) Explicit 'fill' tags cannot occur alongside other \"\n                \"tags except comment tags; 2) Default (default slot-targeting) content \"\n                \"is mixed with explict 'fill' tags.\"\n            )\n    return fill_nodes\n
    "},{"location":"reference/django_components/slots/#django_components.slots.resolve_slots","title":"resolve_slots","text":"
    resolve_slots(\n    context: Context,\n    template: Template,\n    component_name: Optional[str],\n    fill_content: Dict[SlotName, FillContent],\n    is_dynamic_component: bool = False,\n) -> Tuple[Dict[SlotId, Slot], Dict[SlotId, SlotFill]]\n

    Search the template for all SlotNodes, and associate the slots with the given fills.

    Returns tuple of: - Slots defined in the component's Template with {% slot %} tag - SlotFills (AKA slots matched with fills) describing what will be rendered for each slot.

    Source code in src/django_components/slots.py
    def resolve_slots(\n    context: Context,\n    template: Template,\n    component_name: Optional[str],\n    fill_content: Dict[SlotName, FillContent],\n    is_dynamic_component: bool = False,\n) -> Tuple[Dict[SlotId, Slot], Dict[SlotId, SlotFill]]:\n    \"\"\"\n    Search the template for all SlotNodes, and associate the slots\n    with the given fills.\n\n    Returns tuple of:\n    - Slots defined in the component's Template with `{% slot %}` tag\n    - SlotFills (AKA slots matched with fills) describing what will be rendered for each slot.\n    \"\"\"\n    slot_fills = {\n        name: SlotFill(\n            name=name,\n            escaped_name=_escape_slot_name(name),\n            is_filled=True,\n            content_func=fill.content_func,\n            slot_default_var=fill.slot_default_var,\n            slot_data_var=fill.slot_data_var,\n        )\n        for name, fill in fill_content.items()\n    }\n\n    slots: Dict[SlotId, Slot] = {}\n    # This holds info on which slot (key) has which slots nested in it (value list)\n    slot_children: Dict[SlotId, List[SlotId]] = {}\n    all_nested_slots: Set[SlotId] = set()\n\n    def on_node(entry: NodeTraverse) -> None:\n        node = entry.node\n        if not isinstance(node, SlotNode):\n            return\n\n        slot_name, _ = node.resolve_kwargs(context, component_name)\n\n        # 1. Collect slots\n        # Basically we take all the important info form the SlotNode, so the logic is\n        # less coupled to Django's Template/Node. Plain tuples should also help with\n        # troubleshooting.\n        slot = Slot(\n            id=node.node_id,\n            name=slot_name,\n            nodelist=node.nodelist,\n            is_default=node.is_default,\n            is_required=node.is_required,\n        )\n        slots[node.node_id] = slot\n\n        # 2. Figure out which Slots are nested in other Slots, so we can render\n        # them from outside-inwards, so we can skip inner Slots if fills are provided.\n        # We should end up with a graph-like data like:\n        # - 0001: [0002]\n        # - 0002: []\n        # - 0003: [0004]\n        # In other words, the data tells us that slot ID 0001 is PARENT of slot 0002.\n        parent_slot_entry = entry.parent\n        while parent_slot_entry is not None:\n            if not isinstance(parent_slot_entry.node, SlotNode):\n                parent_slot_entry = parent_slot_entry.parent\n                continue\n\n            parent_slot_id = parent_slot_entry.node.node_id\n            if parent_slot_id not in slot_children:\n                slot_children[parent_slot_id] = []\n            slot_children[parent_slot_id].append(node.node_id)\n            all_nested_slots.add(node.node_id)\n            break\n\n    walk_nodelist(template.nodelist, on_node, context)\n\n    # 3. Figure out which slot the default/implicit fill belongs to\n    slot_fills = _resolve_default_slot(\n        template_name=template.name,\n        component_name=component_name,\n        slots=slots,\n        slot_fills=slot_fills,\n        is_dynamic_component=is_dynamic_component,\n    )\n\n    # 4. Detect any errors with slots/fills\n    # NOTE: We ignore errors for the dynamic component, as the underlying component\n    # will deal with it\n    if not is_dynamic_component:\n        _report_slot_errors(slots, slot_fills, component_name)\n\n    # 5. Find roots of the slot relationships\n    top_level_slot_ids: List[SlotId] = [node_id for node_id in slots.keys() if node_id not in all_nested_slots]\n\n    # 6. Walk from out-most slots inwards, and decide whether and how\n    # we will render each slot.\n    resolved_slots: Dict[SlotId, SlotFill] = {}\n    slot_ids_queue = deque([*top_level_slot_ids])\n    while len(slot_ids_queue):\n        slot_id = slot_ids_queue.pop()\n        slot = slots[slot_id]\n\n        # Check if there is a slot fill for given slot name\n        if slot.name in slot_fills:\n            # If yes, we remember which slot we want to replace with already-rendered fills\n            resolved_slots[slot_id] = slot_fills[slot.name]\n            # Since the fill cannot include other slots, we can leave this path\n            continue\n        else:\n            # If no, then the slot is NOT filled, and we will render the slot's default (what's\n            # between the slot tags)\n            resolved_slots[slot_id] = SlotFill(\n                name=slot.name,\n                escaped_name=_escape_slot_name(slot.name),\n                is_filled=False,\n                content_func=_nodelist_to_slot_render_func(slot.nodelist),\n                slot_default_var=None,\n                slot_data_var=None,\n            )\n            # Since the slot's default CAN include other slots (because it's defined in\n            # the same template), we need to enqueue the slot's children\n            if slot_id in slot_children and slot_children[slot_id]:\n                slot_ids_queue.extend(slot_children[slot_id])\n\n    # By the time we get here, we should know, for each slot, how it will be rendered\n    # -> Whether it will be replaced with a fill, or whether we render slot's defaults.\n    return slots, resolved_slots\n
    "},{"location":"reference/django_components/tag_formatter/","title":" tag_formatter","text":""},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter","title":"tag_formatter","text":"

    Classes:

    • ComponentFormatter \u2013

      The original django_component's component tag formatter, it uses the component

    • InternalTagFormatter \u2013

      Internal wrapper around user-provided TagFormatters, so that we validate the outputs.

    • ShorthandComponentFormatter \u2013

      The component tag formatter that uses <name> / end<name> tags.

    • TagFormatterABC \u2013
    • TagResult \u2013

      The return value from TagFormatter.parse()

    Functions:

    • get_tag_formatter \u2013

      Returns an instance of the currently configured component tag formatter.

    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.ComponentFormatter","title":"ComponentFormatter","text":"
    ComponentFormatter(tag: str)\n

    Bases: TagFormatterABC

    The original django_component's component tag formatter, it uses the component and endcomponent tags, and the component name is gives 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

    Source code in src/django_components/tag_formatter.py
    def __init__(self, tag: str):\n    self.tag = tag\n
    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.InternalTagFormatter","title":"InternalTagFormatter","text":"
    InternalTagFormatter(tag_formatter: TagFormatterABC)\n

    Internal wrapper around user-provided TagFormatters, so that we validate the outputs.

    Source code in src/django_components/tag_formatter.py
    def __init__(self, tag_formatter: TagFormatterABC):\n    self.tag_formatter = tag_formatter\n
    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":"

    Bases: TagFormatterABC

    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/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC","title":"TagFormatterABC","text":"

    Bases: ABC

    Methods:

    • end_tag \u2013

      Formats the end tag of a block component.

    • parse \u2013

      Given the tokens (words) of a component start tag, this function extracts

    • start_tag \u2013

      Formats the start tag of a component.

    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC.end_tag","title":"end_tag abstractmethod","text":"
    end_tag(name: str) -> str\n

    Formats the end tag of a block component.

    Source code in src/django_components/tag_formatter.py
    @abc.abstractmethod\ndef end_tag(self, name: str) -> str:\n    \"\"\"Formats the end tag of a block component.\"\"\"\n    ...\n
    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC.parse","title":"parse abstractmethod","text":"
    parse(tokens: List[str]) -> TagResult\n

    Given the tokens (words) of 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).

    Example:

    Given a component declarations:

    {% component \"my_comp\" key=val key2=val2 %}

    This function receives a list of tokens

    ['component', '\"my_comp\"', 'key=val', 'key2=val2']

    component is the tag name, which we drop. \"my_comp\" is the component name, but we must remove the extra quotes. And we pass remaining tokens unmodified, as that's the input to the component.

    So in the end, we return a tuple:

    ('my_comp', ['key=val', 'key2=val2'])

    Source code in src/django_components/tag_formatter.py
    @abc.abstractmethod\ndef parse(self, tokens: List[str]) -> TagResult:\n    \"\"\"\n    Given the tokens (words) of a component start tag, this function extracts\n    the component name from the tokens list, and returns `TagResult`, which\n    is a tuple of `(component_name, remaining_tokens)`.\n\n    Example:\n\n    Given a component declarations:\n\n    `{% component \"my_comp\" key=val key2=val2 %}`\n\n    This function receives a list of tokens\n\n    `['component', '\"my_comp\"', 'key=val', 'key2=val2']`\n\n    `component` is the tag name, which we drop. `\"my_comp\"` is the component name,\n    but we must remove the extra quotes. And we pass remaining tokens unmodified,\n    as that's the input to the component.\n\n    So in the end, we return a tuple:\n\n    `('my_comp', ['key=val', 'key2=val2'])`\n    \"\"\"\n    ...\n
    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC.start_tag","title":"start_tag abstractmethod","text":"
    start_tag(name: str) -> str\n

    Formats the start tag of a component.

    Source code in src/django_components/tag_formatter.py
    @abc.abstractmethod\ndef start_tag(self, name: str) -> str:\n    \"\"\"Formats the start tag of a component.\"\"\"\n    ...\n
    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagResult","title":"TagResult","text":"

    Bases: NamedTuple

    The return value from TagFormatter.parse()

    Attributes:

    • component_name (str) \u2013

      Component name extracted from the template tag

    • tokens (List[str]) \u2013

      Remaining tokens (words) that were passed to the tag, with component name removed

    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagResult.component_name","title":"component_name instance-attribute","text":"
    component_name: str\n

    Component name extracted from the template tag

    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagResult.tokens","title":"tokens instance-attribute","text":"
    tokens: List[str]\n

    Remaining tokens (words) that were passed to the tag, with component name removed

    "},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.get_tag_formatter","title":"get_tag_formatter","text":"
    get_tag_formatter(registry: ComponentRegistry) -> InternalTagFormatter\n

    Returns an instance of the currently configured component tag formatter.

    Source code in src/django_components/tag_formatter.py
    def get_tag_formatter(registry: \"ComponentRegistry\") -> InternalTagFormatter:\n    \"\"\"Returns an instance of the currently configured component tag formatter.\"\"\"\n    # Allow users to configure the component TagFormatter\n    formatter_cls_or_str = registry.settings.TAG_FORMATTER\n\n    if isinstance(formatter_cls_or_str, str):\n        tag_formatter: TagFormatterABC = import_string(formatter_cls_or_str)\n    else:\n        tag_formatter = formatter_cls_or_str\n\n    return InternalTagFormatter(tag_formatter)\n
    "},{"location":"reference/django_components/template/","title":" template","text":""},{"location":"reference/django_components/template/#django_components.template","title":"template","text":"

    Functions:

    • cached_template \u2013

      Create a Template instance that will be cached as per the TEMPLATE_CACHE_SIZE setting.

    "},{"location":"reference/django_components/template/#django_components.template.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

    Create a Template instance that will be cached as per the TEMPLATE_CACHE_SIZE setting.

    Source code in src/django_components/template.py
    def 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    \"\"\"Create a Template instance that will be cached as per the `TEMPLATE_CACHE_SIZE` setting.\"\"\"\n    template = _create_template(template_cls or Template, template_string, engine)\n\n    # Assign the origin and name separately, so the caching doesn't depend on them\n    # Since we might be accessing a template from cache, we want to define these only once\n    if not getattr(template, \"_dc_cached\", False):\n        template.origin = origin or Origin(UNKNOWN_SOURCE)\n        template.name = name\n        template._dc_cached = True\n\n    return template\n
    "},{"location":"reference/django_components/template_loader/","title":" template_loader","text":""},{"location":"reference/django_components/template_loader/#django_components.template_loader","title":"template_loader","text":"

    Template loader that loads templates from each Django app's \"components\" directory.

    Classes:

    • Loader \u2013

    Functions:

    • get_dirs \u2013

      Helper for using django_component's FilesystemLoader class to obtain a list

    "},{"location":"reference/django_components/template_loader/#django_components.template_loader.Loader","title":"Loader","text":"

    Bases: Loader

    Methods:

    • get_dirs \u2013

      Prepare directories that may contain component files:

    "},{"location":"reference/django_components/template_loader/#django_components.template_loader.Loader.get_dirs","title":"get_dirs","text":"
    get_dirs(include_apps: bool = True) -> List[Path]\n

    Prepare directories that may contain component files:

    Searches for dirs set in COMPONENTS.dirs settings. If none set, defaults to searching for a \"components\" app. The dirs in COMPONENTS.dirs must be absolute paths.

    In addition to that, also all apps are checked for [app]/components dirs.

    Paths are accepted only if they resolve to a directory. E.g. /path/to/django_project/my_app/components/.

    BASE_DIR setting is required.

    Source code in src/django_components/template_loader.py
    def get_dirs(self, include_apps: bool = True) -> List[Path]:\n    \"\"\"\n    Prepare directories that may contain component files:\n\n    Searches for dirs set in `COMPONENTS.dirs` settings. If none set, defaults to searching\n    for a \"components\" app. The dirs in `COMPONENTS.dirs` must be absolute paths.\n\n    In addition to that, also all apps are checked for `[app]/components` dirs.\n\n    Paths are accepted only if they resolve to a directory.\n    E.g. `/path/to/django_project/my_app/components/`.\n\n    `BASE_DIR` setting is required.\n    \"\"\"\n    # Allow to configure from settings which dirs should be checked for components\n    component_dirs = app_settings.DIRS\n\n    # TODO_REMOVE_IN_V1\n    is_legacy_paths = (\n        # Use value of `STATICFILES_DIRS` ONLY if `COMPONENT.dirs` not set\n        not getattr(settings, \"COMPONENTS\", {}).get(\"dirs\", None) is not None\n        and hasattr(settings, \"STATICFILES_DIRS\")\n        and settings.STATICFILES_DIRS\n    )\n    if is_legacy_paths:\n        # NOTE: For STATICFILES_DIRS, we use the defaults even for empty list.\n        # We don't do this for COMPONENTS.dirs, so user can explicitly specify \"NO dirs\".\n        component_dirs = settings.STATICFILES_DIRS or [settings.BASE_DIR / \"components\"]\n    source = \"STATICFILES_DIRS\" if is_legacy_paths else \"COMPONENTS.dirs\"\n\n    logger.debug(\n        \"Template loader will search for valid template dirs from following options:\\n\"\n        + \"\\n\".join([f\" - {str(d)}\" for d in component_dirs])\n    )\n\n    # Add `[app]/[APP_DIR]` to the directories. This is, by default `[app]/components`\n    app_paths: List[Path] = []\n    if include_apps:\n        for conf in apps.get_app_configs():\n            for app_dir in app_settings.APP_DIRS:\n                comps_path = Path(conf.path).joinpath(app_dir)\n                if comps_path.exists():\n                    app_paths.append(comps_path)\n\n    directories: Set[Path] = set(app_paths)\n\n    # Validate and add other values from the config\n    for component_dir in component_dirs:\n        # Consider tuples for STATICFILES_DIRS (See #489)\n        # See https://docs.djangoproject.com/en/5.0/ref/settings/#prefixes-optional\n        if isinstance(component_dir, (tuple, list)):\n            component_dir = component_dir[1]\n        try:\n            Path(component_dir)\n        except TypeError:\n            logger.warning(\n                f\"{source} expected str, bytes or os.PathLike object, or tuple/list of length 2. \"\n                f\"See Django documentation for STATICFILES_DIRS. Got {type(component_dir)} : {component_dir}\"\n            )\n            continue\n\n        if not Path(component_dir).is_absolute():\n            raise ValueError(f\"{source} must contain absolute paths, got '{component_dir}'\")\n        else:\n            directories.add(Path(component_dir).resolve())\n\n    logger.debug(\n        \"Template loader matched following template dirs:\\n\" + \"\\n\".join([f\" - {str(d)}\" for d in directories])\n    )\n    return list(directories)\n
    "},{"location":"reference/django_components/template_loader/#django_components.template_loader.get_dirs","title":"get_dirs","text":"
    get_dirs(include_apps: bool = True, engine: Optional[Engine] = None) -> List[Path]\n

    Helper for using django_component's FilesystemLoader class to obtain a list of directories where component python files may be defined.

    Source code in src/django_components/template_loader.py
    def get_dirs(include_apps: bool = True, engine: Optional[Engine] = None) -> List[Path]:\n    \"\"\"\n    Helper for using django_component's FilesystemLoader class to obtain a list\n    of directories where component python files may be defined.\n    \"\"\"\n    current_engine = engine\n    if current_engine is None:\n        current_engine = Engine.get_default()\n\n    loader = Loader(current_engine)\n    return loader.get_dirs(include_apps)\n
    "},{"location":"reference/django_components/template_parser/","title":" template_parser","text":""},{"location":"reference/django_components/template_parser/#django_components.template_parser","title":"template_parser","text":"

    Overrides for the Django Template system to allow finer control over template parsing.

    Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py

    Functions:

    • parse_bits \u2013

      Parse bits for template tag helpers simple_tag and inclusion_tag, in

    • token_kwargs \u2013

      Parse token keyword arguments and return a dictionary of the arguments

    "},{"location":"reference/django_components/template_parser/#django_components.template_parser.parse_bits","title":"parse_bits","text":"
    parse_bits(\n    parser: Parser, bits: List[str], params: List[str], name: str\n) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]\n

    Parse bits for template tag helpers simple_tag and inclusion_tag, in particular by detecting syntax errors and by extracting positional and keyword arguments.

    This is a simplified version of django.template.library.parse_bits where we use custom regex to handle special characters in keyword names.

    Furthermore, our version allows duplicate keys, and instead of return kwargs as a dict, we return it as a list of key-value pairs. So it is up to the user of this function to decide whether they support duplicate keys or not.

    Source code in src/django_components/template_parser.py
    def parse_bits(\n    parser: Parser,\n    bits: List[str],\n    params: List[str],\n    name: str,\n) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]:\n    \"\"\"\n    Parse bits for template tag helpers simple_tag and inclusion_tag, in\n    particular by detecting syntax errors and by extracting positional and\n    keyword arguments.\n\n    This is a simplified version of `django.template.library.parse_bits`\n    where we use custom regex to handle special characters in keyword names.\n\n    Furthermore, our version allows duplicate keys, and instead of return kwargs\n    as a dict, we return it as a list of key-value pairs. So it is up to the\n    user of this function to decide whether they support duplicate keys or not.\n    \"\"\"\n    args: List[FilterExpression] = []\n    kwargs: List[Tuple[str, FilterExpression]] = []\n    unhandled_params = list(params)\n    for bit in bits:\n        # First we try to extract a potential kwarg from the bit\n        kwarg = token_kwargs([bit], parser)\n        if kwarg:\n            # The kwarg was successfully extracted\n            param, value = kwarg.popitem()\n            # All good, record the keyword argument\n            kwargs.append((str(param), value))\n            if param in unhandled_params:\n                # If using the keyword syntax for a positional arg, then\n                # consume it.\n                unhandled_params.remove(param)\n        else:\n            if kwargs:\n                raise TemplateSyntaxError(\n                    \"'%s' received some positional argument(s) after some \" \"keyword argument(s)\" % name\n                )\n            else:\n                # Record the positional argument\n                args.append(parser.compile_filter(bit))\n                try:\n                    # Consume from the list of expected positional arguments\n                    unhandled_params.pop(0)\n                except IndexError:\n                    pass\n    if unhandled_params:\n        # Some positional arguments were not supplied\n        raise TemplateSyntaxError(\n            \"'%s' did not receive value(s) for the argument(s): %s\"\n            % (name, \", \".join(\"'%s'\" % p for p in unhandled_params))\n        )\n    return args, kwargs\n
    "},{"location":"reference/django_components/template_parser/#django_components.template_parser.token_kwargs","title":"token_kwargs","text":"
    token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]\n

    Parse token keyword arguments and return a dictionary of the arguments retrieved from the bits token list.

    bits is a list containing the remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments are removed from this list.

    There is no requirement for all remaining token bits to be keyword arguments, so return the dictionary as soon as an invalid argument format is reached.

    Source code in src/django_components/template_parser.py
    def token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]:\n    \"\"\"\n    Parse token keyword arguments and return a dictionary of the arguments\n    retrieved from the ``bits`` token list.\n\n    `bits` is a list containing the remainder of the token (split by spaces)\n    that is to be checked for arguments. Valid arguments are removed from this\n    list.\n\n    There is no requirement for all remaining token ``bits`` to be keyword\n    arguments, so return the dictionary as soon as an invalid argument format\n    is reached.\n    \"\"\"\n    if not bits:\n        return {}\n    match = kwarg_re.match(bits[0])\n    kwarg_format = match and match[1]\n    if not kwarg_format:\n        return {}\n\n    kwargs: Dict[str, FilterExpression] = {}\n    while bits:\n        if kwarg_format:\n            match = kwarg_re.match(bits[0])\n            if not match or not match[1]:\n                return kwargs\n            key, value = match.groups()\n            del bits[:1]\n        else:\n            if len(bits) < 3 or bits[1] != \"as\":\n                return kwargs\n            key, value = bits[2], bits[0]\n            del bits[:3]\n\n        # This is the only difference from the original token_kwargs. We use\n        # the ComponentsFilterExpression instead of the original FilterExpression.\n        kwargs[key] = ComponentsFilterExpression(value, parser)\n        if bits and not kwarg_format:\n            if bits[0] != \"and\":\n                return kwargs\n            del bits[:1]\n    return kwargs\n
    "},{"location":"reference/django_components/templatetags/","title":"Index","text":""},{"location":"reference/django_components/templatetags/#django_components.templatetags","title":"templatetags","text":"

    Modules:

    • component_tags \u2013
    "},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags","title":"component_tags","text":"

    Functions:

    • component \u2013

      To give the component access to the template context:

    • component_css_dependencies \u2013

      Marks location where CSS link tags should be rendered.

    • component_dependencies \u2013

      Marks location where CSS link and JS script tags should be rendered.

    • component_js_dependencies \u2013

      Marks location where JS script tags should be rendered.

    • fill \u2013

      Block tag whose contents 'fill' (are inserted into) an identically named

    • html_attrs \u2013

      This tag takes:

    "},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component","title":"component","text":"
    component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode\n
    To give the component access to the template context

    {% component \"name\" positional_arg keyword_arg=value ... %}

    To render the component in an isolated context

    {% component \"name\" positional_arg keyword_arg=value ... only %}

    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 or, if there are no positional arguments, passed as 'name'.

    Source code in src/django_components/templatetags/component_tags.py
    def component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode:\n    \"\"\"\n    To give the component access to the template context:\n        ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... %}```\n\n    To render the component in an isolated context:\n        ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... only %}```\n\n    Positional and keyword arguments can be literals or template variables.\n    The component name must be a single- or double-quotes string and must\n    be either the first positional argument or, if there are no positional\n    arguments, passed as 'name'.\n    \"\"\"\n    _fix_nested_tags(parser, token)\n    bits = token.split_contents()\n\n    # Let the TagFormatter pre-process the tokens\n    formatter = get_tag_formatter(registry)\n    result = formatter.parse([*bits])\n    end_tag = formatter.end_tag(result.component_name)\n\n    # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n    bits = [bits[0], *result.tokens]\n    token.contents = \" \".join(bits)\n\n    tag = _parse_tag(\n        tag_name,\n        parser,\n        token,\n        params=[],\n        extra_params=True,  # Allow many args\n        flags=[COMP_ONLY_FLAG],\n        keywordonly_kwargs=True,\n        repeatable_kwargs=False,\n        end_tag=end_tag,\n    )\n\n    # Check for isolated context keyword\n    isolated_context = tag.flags[COMP_ONLY_FLAG]\n\n    trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n    body = tag.parse_body()\n    fill_nodes = parse_slot_fill_nodes_from_component_nodelist(tuple(body), ignored_nodes=(ComponentNode,))\n\n    # Tag all fill nodes as children of this particular component instance\n    for node in fill_nodes:\n        trace_msg(\"ASSOC\", \"FILL\", node.trace_id, node.node_id, component_id=tag.id)\n        node.component_id = tag.id\n\n    component_node = ComponentNode(\n        name=result.component_name,\n        args=tag.args,\n        kwargs=tag.kwargs,\n        isolated_context=isolated_context,\n        fill_nodes=fill_nodes,\n        node_id=tag.id,\n        registry=registry,\n    )\n\n    trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n    return component_node\n
    "},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"
    component_css_dependencies(preload: str = '') -> SafeString\n

    Marks location where CSS link tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_css_dependencies\")\ndef component_css_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where CSS link tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_css_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component_dependencies","title":"component_dependencies","text":"
    component_dependencies(preload: str = '') -> SafeString\n

    Marks location where CSS link and JS script tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_dependencies\")\ndef component_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where CSS link and JS script tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER + JS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"
    component_js_dependencies(preload: str = '') -> SafeString\n

    Marks location where JS script tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_js_dependencies\")\ndef component_js_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where JS script tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + JS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_js_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.fill","title":"fill","text":"
    fill(parser: Parser, token: Token) -> FillNode\n

    Block tag whose contents 'fill' (are inserted into) an identically named 'slot'-block in the component template referred to by a parent component. It exists to make component nesting easier.

    This tag is available only within a {% component %}..{% endcomponent %} block. Runtime checks should prohibit other usages.

    Source code in src/django_components/templatetags/component_tags.py
    @register.tag(\"fill\")\ndef fill(parser: Parser, token: Token) -> FillNode:\n    \"\"\"\n    Block tag whose contents 'fill' (are inserted into) an identically named\n    'slot'-block in the component template referred to by a parent component.\n    It exists to make component nesting easier.\n\n    This tag is available only within a {% component %}..{% endcomponent %} block.\n    Runtime checks should prohibit other usages.\n    \"\"\"\n    tag = _parse_tag(\n        \"fill\",\n        parser,\n        token,\n        params=[SLOT_NAME_KWARG],\n        optional_params=[SLOT_NAME_KWARG],\n        keywordonly_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n        repeatable_kwargs=False,\n        end_tag=\"endfill\",\n    )\n\n    fill_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n    trace_id = f\"fill-id-{tag.id} ({fill_name_kwarg})\" if fill_name_kwarg else f\"fill-id-{tag.id}\"\n\n    trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id)\n\n    body = tag.parse_body()\n    fill_node = FillNode(\n        nodelist=body,\n        node_id=tag.id,\n        kwargs=tag.kwargs,\n        trace_id=trace_id,\n    )\n\n    trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id, \"...Done!\")\n    return fill_node\n
    "},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"
    html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode\n

    This tag takes: - Optional dictionary of attributes (attrs) - Optional dictionary of defaults (defaults) - Additional kwargs that are appended to the former two

    The inputs are merged and resulting dict is rendered as HTML attributes (key=\"value\").

    Rules: 1. Both attrs and defaults can be passed as positional args or as kwargs 2. Both attrs and defaults are optional (can be omitted) 3. 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. 4. All other kwargs (key=value) are appended and can be repeated.

    Normal kwargs (key=value) are concatenated to existing keys. So if e.g. key \"class\" is supplied with value \"my-class\", then adding class=\"extra-class\" will result in `class=\"my-class extra-class\".

    Example:

    {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n

    Source code in src/django_components/templatetags/component_tags.py
    @register.tag(\"html_attrs\")\ndef html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode:\n    \"\"\"\n    This tag takes:\n    - Optional dictionary of attributes (`attrs`)\n    - Optional dictionary of defaults (`defaults`)\n    - Additional kwargs that are appended to the former two\n\n    The inputs are merged and resulting dict is rendered as HTML attributes\n    (`key=\"value\"`).\n\n    Rules:\n    1. Both `attrs` and `defaults` can be passed as positional args or as kwargs\n    2. Both `attrs` and `defaults` are optional (can be omitted)\n    3. Both `attrs` and `defaults` are dictionaries, and we can define them the same way\n       we define dictionaries for the `component` tag. So either as `attrs=attrs` or\n       `attrs:key=value`.\n    4. All other kwargs (`key=value`) are appended and can be repeated.\n\n    Normal kwargs (`key=value`) are concatenated to existing keys. So if e.g. key\n    \"class\" is supplied with value \"my-class\", then adding `class=\"extra-class\"`\n    will result in `class=\"my-class extra-class\".\n\n    Example:\n    ```htmldjango\n    {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n    ```\n    \"\"\"\n    tag = _parse_tag(\n        \"html_attrs\",\n        parser,\n        token,\n        params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n        optional_params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n        flags=[],\n        keywordonly_kwargs=True,\n        repeatable_kwargs=True,\n    )\n\n    return HtmlAttrsNode(\n        kwargs=tag.kwargs,\n        kwarg_pairs=tag.kwarg_pairs,\n    )\n
    "},{"location":"reference/django_components/templatetags/component_tags/","title":" component_tags","text":""},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags","title":"component_tags","text":"

    Functions:

    • component \u2013

      To give the component access to the template context:

    • component_css_dependencies \u2013

      Marks location where CSS link tags should be rendered.

    • component_dependencies \u2013

      Marks location where CSS link and JS script tags should be rendered.

    • component_js_dependencies \u2013

      Marks location where JS script tags should be rendered.

    • fill \u2013

      Block tag whose contents 'fill' (are inserted into) an identically named

    • html_attrs \u2013

      This tag takes:

    "},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component","title":"component","text":"
    component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode\n
    To give the component access to the template context

    {% component \"name\" positional_arg keyword_arg=value ... %}

    To render the component in an isolated context

    {% component \"name\" positional_arg keyword_arg=value ... only %}

    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 or, if there are no positional arguments, passed as 'name'.

    Source code in src/django_components/templatetags/component_tags.py
    def component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str) -> ComponentNode:\n    \"\"\"\n    To give the component access to the template context:\n        ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... %}```\n\n    To render the component in an isolated context:\n        ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... only %}```\n\n    Positional and keyword arguments can be literals or template variables.\n    The component name must be a single- or double-quotes string and must\n    be either the first positional argument or, if there are no positional\n    arguments, passed as 'name'.\n    \"\"\"\n    _fix_nested_tags(parser, token)\n    bits = token.split_contents()\n\n    # Let the TagFormatter pre-process the tokens\n    formatter = get_tag_formatter(registry)\n    result = formatter.parse([*bits])\n    end_tag = formatter.end_tag(result.component_name)\n\n    # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n    bits = [bits[0], *result.tokens]\n    token.contents = \" \".join(bits)\n\n    tag = _parse_tag(\n        tag_name,\n        parser,\n        token,\n        params=[],\n        extra_params=True,  # Allow many args\n        flags=[COMP_ONLY_FLAG],\n        keywordonly_kwargs=True,\n        repeatable_kwargs=False,\n        end_tag=end_tag,\n    )\n\n    # Check for isolated context keyword\n    isolated_context = tag.flags[COMP_ONLY_FLAG]\n\n    trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n    body = tag.parse_body()\n    fill_nodes = parse_slot_fill_nodes_from_component_nodelist(tuple(body), ignored_nodes=(ComponentNode,))\n\n    # Tag all fill nodes as children of this particular component instance\n    for node in fill_nodes:\n        trace_msg(\"ASSOC\", \"FILL\", node.trace_id, node.node_id, component_id=tag.id)\n        node.component_id = tag.id\n\n    component_node = ComponentNode(\n        name=result.component_name,\n        args=tag.args,\n        kwargs=tag.kwargs,\n        isolated_context=isolated_context,\n        fill_nodes=fill_nodes,\n        node_id=tag.id,\n        registry=registry,\n    )\n\n    trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n    return component_node\n
    "},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"
    component_css_dependencies(preload: str = '') -> SafeString\n

    Marks location where CSS link tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_css_dependencies\")\ndef component_css_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where CSS link tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_css_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component_dependencies","title":"component_dependencies","text":"
    component_dependencies(preload: str = '') -> SafeString\n

    Marks location where CSS link and JS script tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_dependencies\")\ndef component_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where CSS link and JS script tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER + JS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"
    component_js_dependencies(preload: str = '') -> SafeString\n

    Marks location where JS script tags should be rendered.

    Source code in src/django_components/templatetags/component_tags.py
    @register.simple_tag(name=\"component_js_dependencies\")\ndef component_js_dependencies(preload: str = \"\") -> SafeString:\n    \"\"\"Marks location where JS script tags should be rendered.\"\"\"\n\n    if is_dependency_middleware_active():\n        preloaded_dependencies = []\n        for component in _get_components_from_preload_str(preload):\n            preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n        return mark_safe(\"\\n\".join(preloaded_dependencies) + JS_DEPENDENCY_PLACEHOLDER)\n    else:\n        rendered_dependencies = []\n        for component in _get_components_from_registry(component_registry):\n            rendered_dependencies.append(component.render_js_dependencies())\n\n        return mark_safe(\"\\n\".join(rendered_dependencies))\n
    "},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.fill","title":"fill","text":"
    fill(parser: Parser, token: Token) -> FillNode\n

    Block tag whose contents 'fill' (are inserted into) an identically named 'slot'-block in the component template referred to by a parent component. It exists to make component nesting easier.

    This tag is available only within a {% component %}..{% endcomponent %} block. Runtime checks should prohibit other usages.

    Source code in src/django_components/templatetags/component_tags.py
    @register.tag(\"fill\")\ndef fill(parser: Parser, token: Token) -> FillNode:\n    \"\"\"\n    Block tag whose contents 'fill' (are inserted into) an identically named\n    'slot'-block in the component template referred to by a parent component.\n    It exists to make component nesting easier.\n\n    This tag is available only within a {% component %}..{% endcomponent %} block.\n    Runtime checks should prohibit other usages.\n    \"\"\"\n    tag = _parse_tag(\n        \"fill\",\n        parser,\n        token,\n        params=[SLOT_NAME_KWARG],\n        optional_params=[SLOT_NAME_KWARG],\n        keywordonly_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n        repeatable_kwargs=False,\n        end_tag=\"endfill\",\n    )\n\n    fill_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n    trace_id = f\"fill-id-{tag.id} ({fill_name_kwarg})\" if fill_name_kwarg else f\"fill-id-{tag.id}\"\n\n    trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id)\n\n    body = tag.parse_body()\n    fill_node = FillNode(\n        nodelist=body,\n        node_id=tag.id,\n        kwargs=tag.kwargs,\n        trace_id=trace_id,\n    )\n\n    trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id, \"...Done!\")\n    return fill_node\n
    "},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"
    html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode\n

    This tag takes: - Optional dictionary of attributes (attrs) - Optional dictionary of defaults (defaults) - Additional kwargs that are appended to the former two

    The inputs are merged and resulting dict is rendered as HTML attributes (key=\"value\").

    Rules: 1. Both attrs and defaults can be passed as positional args or as kwargs 2. Both attrs and defaults are optional (can be omitted) 3. 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. 4. All other kwargs (key=value) are appended and can be repeated.

    Normal kwargs (key=value) are concatenated to existing keys. So if e.g. key \"class\" is supplied with value \"my-class\", then adding class=\"extra-class\" will result in `class=\"my-class extra-class\".

    Example:

    {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n

    Source code in src/django_components/templatetags/component_tags.py
    @register.tag(\"html_attrs\")\ndef html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode:\n    \"\"\"\n    This tag takes:\n    - Optional dictionary of attributes (`attrs`)\n    - Optional dictionary of defaults (`defaults`)\n    - Additional kwargs that are appended to the former two\n\n    The inputs are merged and resulting dict is rendered as HTML attributes\n    (`key=\"value\"`).\n\n    Rules:\n    1. Both `attrs` and `defaults` can be passed as positional args or as kwargs\n    2. Both `attrs` and `defaults` are optional (can be omitted)\n    3. Both `attrs` and `defaults` are dictionaries, and we can define them the same way\n       we define dictionaries for the `component` tag. So either as `attrs=attrs` or\n       `attrs:key=value`.\n    4. All other kwargs (`key=value`) are appended and can be repeated.\n\n    Normal kwargs (`key=value`) are concatenated to existing keys. So if e.g. key\n    \"class\" is supplied with value \"my-class\", then adding `class=\"extra-class\"`\n    will result in `class=\"my-class extra-class\".\n\n    Example:\n    ```htmldjango\n    {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n    ```\n    \"\"\"\n    tag = _parse_tag(\n        \"html_attrs\",\n        parser,\n        token,\n        params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n        optional_params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n        flags=[],\n        keywordonly_kwargs=True,\n        repeatable_kwargs=True,\n    )\n\n    return HtmlAttrsNode(\n        kwargs=tag.kwargs,\n        kwarg_pairs=tag.kwarg_pairs,\n    )\n
    "},{"location":"reference/django_components/types/","title":" types","text":""},{"location":"reference/django_components/types/#django_components.types","title":"types","text":"

    Helper types for IDEs.

    "},{"location":"reference/django_components/utils/","title":" utils","text":""},{"location":"reference/django_components/utils/#django_components.utils","title":"utils","text":"

    Functions:

    • gen_id \u2013

      Generate a unique ID that can be associated with a Node

    • lazy_cache \u2013

      Decorator that caches the given function similarly to functools.lru_cache.

    "},{"location":"reference/django_components/utils/#django_components.utils.gen_id","title":"gen_id","text":"
    gen_id(length: int = 5) -> str\n

    Generate a unique ID that can be associated with a Node

    Source code in src/django_components/utils.py
    def gen_id(length: int = 5) -> str:\n    \"\"\"Generate a unique ID that can be associated with a Node\"\"\"\n    # Global counter to avoid conflicts\n    global _id\n    _id += 1\n\n    # Pad the ID with `0`s up to 4 digits, e.g. `0007`\n    return f\"{_id:04}\"\n
    "},{"location":"reference/django_components/utils/#django_components.utils.lazy_cache","title":"lazy_cache","text":"
    lazy_cache(make_cache: Callable[[], Callable[[Callable], Callable]]) -> Callable[[TFunc], TFunc]\n

    Decorator that caches the given function similarly to functools.lru_cache. But the cache is instantiated only at first invocation.

    cache argument is a function that generates the cache function, e.g. functools.lru_cache().

    Source code in src/django_components/utils.py
    def lazy_cache(\n    make_cache: Callable[[], Callable[[Callable], Callable]],\n) -> Callable[[TFunc], TFunc]:\n    \"\"\"\n    Decorator that caches the given function similarly to `functools.lru_cache`.\n    But the cache is instantiated only at first invocation.\n\n    `cache` argument is a function that generates the cache function,\n    e.g. `functools.lru_cache()`.\n    \"\"\"\n    _cached_fn = None\n\n    def decorator(fn: TFunc) -> TFunc:\n        @functools.wraps(fn)\n        def wrapper(*args: Any, **kwargs: Any) -> Any:\n            # Lazily initialize the cache\n            nonlocal _cached_fn\n            if not _cached_fn:\n                # E.g. `lambda: functools.lru_cache(maxsize=app_settings.TEMPLATE_CACHE_SIZE)`\n                cache = make_cache()\n                _cached_fn = cache(fn)\n\n            return _cached_fn(*args, **kwargs)\n\n        # Allow to access the LRU cache methods\n        # See https://stackoverflow.com/a/37654201/9788634\n        wrapper.cache_info = lambda: _cached_fn.cache_info()  # type: ignore\n        wrapper.cache_clear = lambda: _cached_fn.cache_clear()  # type: ignore\n\n        # And allow to remove the cache instance (mostly for tests)\n        def cache_remove() -> None:\n            nonlocal _cached_fn\n            _cached_fn = None\n\n        wrapper.cache_remove = cache_remove  # type: ignore\n\n        return cast(TFunc, wrapper)\n\n    return decorator\n
    "},{"location":"reference/django_components_js/build/","title":" build","text":""},{"location":"reference/django_components_js/build/#django_components_js.build","title":"build","text":""}]} \ No newline at end of file diff --git a/dev/sitemap.xml b/dev/sitemap.xml index d7440c3a..cbc8c3da 100644 --- a/dev/sitemap.xml +++ b/dev/sitemap.xml @@ -2,166 +2,166 @@ https://emilstenstrom.github.io/django-components/latest/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/CHANGELOG/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/CODE_OF_CONDUCT/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/SUMMARY/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/license/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/migrating_from_safer_staticfiles/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/slot_rendering/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/slots_and_blocks/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/SUMMARY/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/app_settings/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/apps/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/attributes/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/autodiscover/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/component/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/component_media/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/component_registry/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/components/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/components/dynamic/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/context/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/expression/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/finders/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/library/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/logger/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/management/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/management/commands/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/management/commands/startcomponent/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/management/commands/upgradecomponent/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/middleware/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/node/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/provide/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/slots/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/tag_formatter/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/template/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/template_loader/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/template_parser/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/templatetags/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/templatetags/component_tags/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/types/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components/utils/ - 2024-10-10 + 2024-10-29 https://emilstenstrom.github.io/django-components/latest/reference/django_components_js/build/ - 2024-10-10 + 2024-10-29 \ No newline at end of file diff --git a/dev/sitemap.xml.gz b/dev/sitemap.xml.gz index 2f1b9526..74b96605 100644 Binary files a/dev/sitemap.xml.gz and b/dev/sitemap.xml.gz differ diff --git a/dev/slot_rendering/index.html b/dev/slot_rendering/index.html index f3556f15..9a6674d0 100644 --- a/dev/slot_rendering/index.html +++ b/dev/slot_rendering/index.html @@ -1,4 +1,4 @@ - Slot rendering - Django-Components

    Slot rendering¤

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

    Flow¤

    1. Imagine you have a template. Some kind of text, maybe HTML:

      | ------
      + Slot rendering - Django-Components      

      Slot rendering¤

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

      Flow¤

      1. Imagine you have a template. Some kind of text, maybe HTML:

        | ------
         | ---------
         | ----
         | -------
        diff --git a/dev/slots_and_blocks/index.html b/dev/slots_and_blocks/index.html
        index 88344086..42c01ad1 100644
        --- a/dev/slots_and_blocks/index.html
        +++ b/dev/slots_and_blocks/index.html
        @@ -1,4 +1,4 @@
        - Using slot and block tags - Django-Components      

        Using slot and block tags¤

        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`:
          + Using slot and block tags - Django-Components      

          Using slot and block tags¤

          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`:
             ```django
             <div>
               hello
            diff --git a/versions.json b/versions.json
            index d77c728f..916f259c 100644
            --- a/versions.json
            +++ b/versions.json
            @@ -1,7 +1,7 @@
             [
               {
                 "version": "dev",
            -    "title": "dev (0064de9)",
            +    "title": "dev (de09adc)",
                 "aliases": []
               },
               {