When you pass in request, the component will use RenderContext instead of Context. Thus the context processors will be applied to the context.
NOTE: When you pass in both request and context to Component.render(), and context is already an instance of Context, the request kwarg will be ignored.
Scripts in Component.Media.js are executed in the order they are defined
Scripts in Component.js are executed AFTER Media.js scripts
Fix compatibility with AlpineJS
Scripts in Component.Media.js are now again inserted as <script> tags
By default, Component.Media.js are inserted as synchronous <script> tags, so the AlpineJS components registered in the Media.js scripts will now again run BEFORE the core AlpineJS script.
AlpineJS can be configured like so:
Option 1 - AlpineJS loaded in <head> with defer attribute:
<html>
+
When you pass in request, the component will use RenderContext instead of Context. Thus the context processors will be applied to the context.
NOTE: When you pass in both request and context to Component.render(), and context is already an instance of Context, the request kwarg will be ignored.
Scripts in Component.Media.js are executed in the order they are defined
Scripts in Component.js are executed AFTER Media.js scripts
Fix compatibility with AlpineJS
Scripts in Component.Media.js are now again inserted as <script> tags
By default, Component.Media.js are inserted as synchronous <script> tags, so the AlpineJS components registered in the Media.js scripts will now again run BEFORE the core AlpineJS script.
AlpineJS can be configured like so:
Option 1 - AlpineJS loaded in <head> with defer attribute:
Prevent rendering Component tags during fill discovery stage to fix a case when a component inside the default slot tried to access provided data too early.
If your components include JS or CSS, you now must use the middleware and add django-components' URLs to your urlpatterns (See "Adding support for JS and CSS")
Prevent rendering Component tags during fill discovery stage to fix a case when a component inside the default slot tried to access provided data too early.
If your components include JS or CSS, you now must use the middleware and add django-components' URLs to your urlpatterns (See "Adding support for JS and CSS")
Component typing signature changed from
Component[Args,Kwargs,Data,Slots]
to
Component[Args,Kwargs,Slots,Data,JsData,CssData]
If you rendered a component A with Component.render() and then inserted that into another component B, now you must pass render_dependencies=False to component A:
Use get_component_dirs() and get_component_files() to get the same list of dirs / files that would be imported by autodiscover(), but without actually importing them.
The old uppercase settings CONTEXT_BEHAVIOR and TAG_FORMATTER are deprecated and will be removed in v1.
The setting reload_on_template_change was renamed to reload_on_file_change. And now it properly triggers server reload when any file in the component dirs change. The old name reload_on_template_change is deprecated and will be removed in v1.
The setting forbidden_static_files was renamed to static_files_forbidden to align with static_files_allowed The old name forbidden_static_files is deprecated and will be removed in v1.
{% component_dependencies %} tag was removed. Instead, use {% component_js_dependencies %} and {% component_css_dependencies %}
The combined tag was removed to encourage the best practice of putting JS scripts at the end of <body>, and CSS styles inside <head>.
On the other hand, co-locating JS script and CSS styles can lead to a flash of unstyled content, as either JS scripts will block the rendering, or CSS will load too late.
The undocumented keyword arg preload of {% component_js_dependencies %} and {% component_css_dependencies %} tags was removed. This will be replaced with HTML fragment support.
{% component_dependencies %} tags are now OPTIONAL - If your components use JS and CSS, but you don't use {% component_dependencies %} tags, the JS and CSS will now be, by default, inserted at the end of <body> and at the end of <head> respectively.
Fills can now be defined within loops ({% for %}) or other tags (like {% with %}), or even other templates using {% include %}.
Following is now possible
{%component"table"%}
+
Use get_component_dirs() and get_component_files() to get the same list of dirs / files that would be imported by autodiscover(), but without actually importing them.
The old uppercase settings CONTEXT_BEHAVIOR and TAG_FORMATTER are deprecated and will be removed in v1.
The setting reload_on_template_change was renamed to reload_on_file_change. And now it properly triggers server reload when any file in the component dirs change. The old name reload_on_template_change is deprecated and will be removed in v1.
The setting forbidden_static_files was renamed to static_files_forbidden to align with static_files_allowed The old name forbidden_static_files is deprecated and will be removed in v1.
{% component_dependencies %} tag was removed. Instead, use {% component_js_dependencies %} and {% component_css_dependencies %}
The combined tag was removed to encourage the best practice of putting JS scripts at the end of <body>, and CSS styles inside <head>.
On the other hand, co-locating JS script and CSS styles can lead to a flash of unstyled content, as either JS scripts will block the rendering, or CSS will load too late.
The undocumented keyword arg preload of {% component_js_dependencies %} and {% component_css_dependencies %} tags was removed. This will be replaced with HTML fragment support.
{% component_dependencies %} tags are now OPTIONAL - If your components use JS and CSS, but you don't use {% component_dependencies %} tags, the JS and CSS will now be, by default, inserted at the end of <body> and at the end of <head> respectively.
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.
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
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)
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.
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
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)
{% 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.
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).
Changed the syntax for {% slot %} tags. From now on, we separate defining a slot ({% slot %}) from filling a slot with content ({% fill %}). This means you will likely need to change a lot of slot tags to fill.
We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice feature to have access to. Hoping that this will feel worth it!
All files inside components subdirectores are autoimported to simplify setup.
An existing project might start to get AlreadyRegistered errors because of this. To solve this, either remove your custom loading of components, or set "autodiscover": False in settings.COMPONENTS.
Renamed Component.context and Component.template to get_context_data and get_template_name. The old methods still work, but emit a deprecation warning.
This change was done to sync naming with Django's class based views, and make using django-components more familiar to Django users. Component.context and Component.template will be removed when version 1.0 is released.
{% 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.
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).
Changed the syntax for {% slot %} tags. From now on, we separate defining a slot ({% slot %}) from filling a slot with content ({% fill %}). This means you will likely need to change a lot of slot tags to fill.
We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice feature to have access to. Hoping that this will feel worth it!
All files inside components subdirectores are autoimported to simplify setup.
An existing project might start to get AlreadyRegistered errors because of this. To solve this, either remove your custom loading of components, or set "autodiscover": False in settings.COMPONENTS.
Renamed Component.context and Component.template to get_context_data and get_template_name. The old methods still work, but emit a deprecation warning.
This change was done to sync naming with Django's class based views, and make using django-components more familiar to Django users. Component.context and Component.template will be removed when version 1.0 is released.
\ No newline at end of file
diff --git a/dev/search/search_index.json b/dev/search/search_index.json
index dd15b26a..59ca3023 100644
--- a/dev/search/search_index.json
+++ b/dev/search/search_index.json
@@ -1 +1 @@
-{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Welcome to Django Components","text":"
django-components introduces component-based architecture to Django's server-side rendering. It combines Django's templating system with the modularity seen in modern frontend frameworks like Vue or React.
\ud83e\udde9 Reusability: Allows creation of self-contained, reusable UI elements.
\ud83d\udce6 Encapsulation: Each component can include its own HTML, CSS, and JavaScript.
\ud83d\ude80 Server-side rendering: Components render on the server, improving initial load times and SEO.
\ud83d\udc0d Django integration: Works within the Django ecosystem, using familiar concepts like template tags.
\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.
One of our goals with django-components is to make it easy to share components between projects. If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.
django-htmx-components: A set of components for use with htmx. Try out the live demo.
"},{"location":"#contributing-and-development","title":"Contributing and development","text":"
Get involved or sponsor this project - See here
Running django-components locally for development - See here
When you pass in request, the component will use RenderContext instead of Context. Thus the context processors will be applied to the context.
NOTE: When you pass in both request and context to Component.render(), and context is already an instance of Context, the request kwarg will be ignored.
Scripts in Component.Media.js are executed in the order they are defined
Scripts in Component.js are executed AFTER Media.js scripts
Fix compatibility with AlpineJS
Scripts in Component.Media.js are now again inserted as <script> tags
By default, Component.Media.js are inserted as synchronous <script> tags, so the AlpineJS components registered in the Media.js scripts will now again run BEFORE the core AlpineJS script.
AlpineJS can be configured like so:
Option 1 - AlpineJS loaded in <head> with defer attribute:
Prevent rendering Component tags during fill discovery stage to fix a case when a component inside the default slot tried to access provided data too early.
If your components include JS or CSS, you now must use the middleware and add django-components' URLs to your urlpatterns (See \"Adding support for JS and CSS\")
If you rendered a component A with Component.render() and then inserted that into another component B, now you must pass render_dependencies=False to component A:
Use get_component_dirs() and get_component_files() to get the same list of dirs / files that would be imported by autodiscover(), but without actually importing them.
The old uppercase settings CONTEXT_BEHAVIOR and TAG_FORMATTER are deprecated and will be removed in v1.
The setting reload_on_template_change was renamed to reload_on_file_change. And now it properly triggers server reload when any file in the component dirs change. The old name reload_on_template_change is deprecated and will be removed in v1.
The setting forbidden_static_files was renamed to static_files_forbidden to align with static_files_allowed The old name forbidden_static_files is deprecated and will be removed in v1.
{% component_dependencies %} tag was removed. Instead, use {% component_js_dependencies %} and {% component_css_dependencies %}
The combined tag was removed to encourage the best practice of putting JS scripts at the end of <body>, and CSS styles inside <head>.
On the other hand, co-locating JS script and CSS styles can lead to a flash of unstyled content, as either JS scripts will block the rendering, or CSS will load too late.
The undocumented keyword arg preload of {% component_js_dependencies %} and {% component_css_dependencies %} tags was removed. This will be replaced with HTML fragment support.
{% component_dependencies %} tags are now OPTIONAL - If your components use JS and CSS, but you don't use {% component_dependencies %} tags, the JS and CSS will now be, by default, inserted at the end of <body> and at the end of <head> respectively.
This means you can also have multiple slots with the same name but different conditions.
E.g. in this example, we have a component that renders a user avatar - a small circular image with a profile picture of name initials.
If the component is given image_src or name_initials variables, the image slot is optional. But if neither of those are provided, you MUST fill the image slot.
The slot fills that were passed to a component and which can be accessed as Component.input.slots can now be passed through the Django template, e.g. as inputs to other tags.
Internally, django-components handles slot fills as functions.
Previously, if you tried to pass a slot fill within a template, Django would try to call it as a function.
NOTE: Using {% slot %} and {% fill %} tags is still the preferred method, but the approach above may be necessary in some complex or edge cases.
The is_filled variable (and the {{ component_vars.is_filled }} context variable) now returns False when you try to access a slot name which has not been defined:
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.
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
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)
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)
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).
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.
{% 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.
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).
Changed the syntax for {% slot %} tags. From now on, we separate defining a slot ({% slot %}) from filling a slot with content ({% fill %}). This means you will likely need to change a lot of slot tags to fill.
We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice feature to have access to. Hoping that this will feel worth it!
All files inside components subdirectores are autoimported to simplify setup.
An existing project might start to get AlreadyRegistered errors because of this. To solve this, either remove your custom loading of components, or set \"autodiscover\": False in settings.COMPONENTS.
Renamed Component.context and Component.template to get_context_data and get_template_name. The old methods still work, but emit a deprecation warning.
This change was done to sync naming with Django's class based views, and make using django-components more familiar to Django users. Component.context and Component.template will be removed when version 1.0 is released.
As you can see above, this is also the place where we configure how our components should behave, using the settings argument. If omitted, default settings are used.
For library authors, we recommend setting context_behavior to \"isolated\", so that the state cannot leak into the components, and so the components' behavior is configured solely through the inputs. This means that the components will be more predictable and easier to debug.
Next, you can decide how will others use your components by setting the tag_formatter options.
If omitted or set to \"django_components.component_formatter\", your components will be used like this:
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
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.
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().
If you use components where the HTML / CSS / JS files are separate, you may need to define MANIFEST.in to include those files with the distribution (see user guide).
"},{"location":"concepts/advanced/authoring_component_libraries/#installing-and-using-component-libraries","title":"Installing and using component libraries","text":"
After the package has been published, all that remains is to install it in other django projects:
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
As you can see, @register links up the component class with the {% component %} template tag. So when the template tag comes across a component called \"calendar\", it can look up it's class and instantiate it.
"},{"location":"concepts/advanced/component_registry/#what-is-componentregistry","title":"What is ComponentRegistry","text":"
The @register decorator is a shortcut for working with the ComponentRegistry.
ComponentRegistry manages which components can be used in the template tags.
Each ComponentRegistry instance is associated with an instance of Django's Library. And Libraries are inserted into Django template using the {% load %} tags.
The @register decorator accepts an optional kwarg registry, which specifies, the ComponentRegistry to register components into. If omitted, the default ComponentRegistry instance defined in django_components is used.
The default ComponentRegistry is associated with the Library that you load when you call {% load component_tags %} inside your template, or when you add django_components.templatetags.component_tags to the template builtins.
So when you register or unregister a component to/from a component registry, then behind the scenes the registry automatically adds/removes the component's template tags to/from the Library, so you can call the component from within the templates such as {% component \"my_comp\" %}.
"},{"location":"concepts/advanced/component_registry/#working-with-componentregistry","title":"Working with ComponentRegistry","text":"
The default ComponentRegistry instance can be imported as:
from django_components import registry\n
You can use the registry to manually add/remove/get components:
from django_components import registry\n\n# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get all or single\nregistry.all() # {\"button\": ButtonComponent, \"card\": CardComponent}\nregistry.get(\"card\") # CardComponent\n\n# Unregister single component\nregistry.unregister(\"card\")\n\n# Unregister all components\nregistry.clear()\n
"},{"location":"concepts/advanced/component_registry/#registering-components-to-custom-componentregistry","title":"Registering components to custom ComponentRegistry","text":"
If you are writing a component library to be shared with others, you may want to manage your own instance of ComponentRegistry and register components onto a different Library instance than the default one.
The Library instance can be set at instantiation of ComponentRegistry. If omitted, then the default Library instance from django_components is used.
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.
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template:
def on_render_before(self, context, template) -> None:\n # Insert value into the Context\n context[\"from_on_before\"] = \":)\"\n\n # Append text into the Template\n template.nodelist.append(TextNode(\"FROM_ON_BEFORE\"))\n
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.
"},{"location":"concepts/advanced/provide_inject/","title":"Prop drilling and provide / inject","text":"
New in version 0.80:
Django components supports the provide / inject or ContextProvider pattern with the combination of:
{% provide %} tag
inject() method of the Component class
"},{"location":"concepts/advanced/provide_inject/#what-is-prop-drilling","title":"What is \"prop drilling\"?","text":"
Prop drilling refers to a scenario in UI development where you need to pass data through many layers of a component tree to reach the nested components that actually need the data.
Normally, you'd use props to send data from a parent component to its children. However, this straightforward method becomes cumbersome and inefficient if the data has to travel through many levels or if several components scattered at different depths all need the same piece of information.
This results in a situation where the intermediate components, which don't need the data for their own functioning, end up having to manage and pass along these props. This clutters the component tree and makes the code verbose and harder to manage.
A neat solution to avoid prop drilling is using the \"provide and inject\" technique.
With provide / inject, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.
This feature is inspired by Vue's Provide / Inject and React's Context / useContext.
"},{"location":"concepts/advanced/provide_inject/#how-to-use-provide-inject","title":"How to use provide / inject","text":"
As the name suggest, using provide / inject consists of 2 steps
Providing data
Injecting provided data
For examples of advanced uses of provide / inject, see this discussion.
"},{"location":"concepts/advanced/provide_inject/#using-provide-tag","title":"Using {% provide %} tag","text":"
First we use the {% provide %} tag to define the data we want to \"provide\" (make available).
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:
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.
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):
The instance returned from inject() is a subclass of NamedTuple, so the instance is immutable. This ensures that the data returned from inject will always have all the keys that were passed to the provide tag.
NOTE: inject() works strictly only in get_context_data. If you try to call it from elsewhere, it will raise an error.
"},{"location":"concepts/advanced/rendering_js_css/#setting-up-the-middleware","title":"Setting up the middleware","text":"
ComponentDependencyMiddleware is a Django middleware designed to manage and inject CSS / JS dependencies of rendered components dynamically. It ensures that only the necessary stylesheets and scripts are loaded in your HTML responses, based on the components used in your Django templates.
To set it up, add the middleware to your MIDDLEWARE in settings.py:
MIDDLEWARE = [\n # ... other middleware classes ...\n 'django_components.middleware.ComponentDependencyMiddleware'\n # ... other middleware classes ...\n]\n
"},{"location":"concepts/advanced/rendering_js_css/#render_dependencies-and-rendering-js-css-without-the-middleware","title":"render_dependencies and rendering JS / CSS without the middleware","text":"
For most scenarios, using the ComponentDependencyMiddleware middleware will be just fine.
However, this section is for you if you want to:
Render HTML that will NOT be sent as a server response
Insert pre-rendered HTML into another component
Render HTML fragments (partials)
Every time there is an HTML string that has parts which were rendered using components, and any of those components has JS / CSS, then this HTML string MUST be processed with render_dependencies().
It is actually render_dependencies() that finds all used components in the HTML string, and inserts the component's JS and CSS into {% component_dependencies %} tags, or at the default locations.
"},{"location":"concepts/advanced/rendering_js_css/#render-js-css-without-the-middleware","title":"Render JS / CSS without the middleware","text":"
The truth is that the ComponentDependencyMiddleware middleware just calls render_dependencies(), passing in the HTML content. So if you render a template that contained {% component %} tags, you MUST pass the result through render_dependencies(). And the middleware is just one of the options.
Here is how you can achieve the same, without the middleware, using render_dependencies():
Alternatively, when you render HTML with Component.render() or Component.render_to_response(), these, by default, call render_dependencies() for you, so you don't have to:
from django_components import Component\n\nclass MyButton(Component):\n ...\n\n# No need to call `render_dependencies()`\nrendered = MyButton.render()\n
"},{"location":"concepts/advanced/rendering_js_css/#inserting-pre-rendered-html-into-another-component","title":"Inserting pre-rendered HTML into another component","text":"
In previous section we've shown that render_dependencies() does NOT need to be called when you render a component via Component.render().
API of django_components makes it possible to compose components in a \"React-like\" way, where we pre-render a piece of HTML and then insert it into a larger structure.
To do this, you must add render_dependencies=False to the nested components:
This is a technical limitation of the current implementation.
As mentioned earlier, each time we call Component.render(), we also call render_dependencies().
However, there is a problem here - When we call render_dependencies() inside CardActions.render(), we extract and REMOVE the info on components' JS and CSS from the HTML. But the template of CardActions contains no {% component_depedencies %} tags, and nor <head> nor <body> HTML tags. So the component's JS and CSS will NOT be inserted, and will be lost.
To work around this, you must set render_dependencies=False when rendering pieces of HTML with Component.render() and inserting them into larger structures.
"},{"location":"concepts/advanced/tag_formatter/#writing-your-own-tagformatter","title":"Writing your own TagFormatter","text":""},{"location":"concepts/advanced/tag_formatter/#background","title":"Background","text":"
First, let's discuss how TagFormatters work, and how components are rendered in django_components.
When you render a component with {% component %} (or your own tag), the following happens:
component must be registered as a Django's template tag
Django triggers django_components's tag handler for tag component.
The tag handler passes the tag contents for pre-processing to TagFormatter.parse().
TagFormatter handles following parts of the process above:
Generates start/end tags, given a component. This is what you then call from within your template as {% component %}.
When you {% component %}, tag formatter pre-processes the tag contents, so it can link back the custom template tag to the right component.
To do so, subclass from TagFormatterABC and implement following method:
start_tag
end_tag
parse
For example, this is the implementation of ShorthandComponentFormatter
class ShorthandComponentFormatter(TagFormatterABC):\n # Given a component name, generate the start template tag\n def start_tag(self, name: str) -> str:\n return name # e.g. 'button'\n\n # Given a component name, generate the start template tag\n def end_tag(self, name: str) -> str:\n return f\"end{name}\" # e.g. 'endbutton'\n\n # Given a tag, e.g.\n # `{% button href=\"...\" disabled %}`\n #\n # The parser receives:\n # `['button', 'href=\"...\"', 'disabled']`\n def parse(self, tokens: List[str]) -> TagResult:\n tokens = [*tokens]\n name = tokens.pop(0)\n return TagResult(\n name, # e.g. 'button'\n tokens # e.g. ['href=\"...\"', 'disabled']\n )\n
That's it! And once your TagFormatter is ready, don't forget to update the settings!
"},{"location":"concepts/advanced/typing_and_validation/","title":"Typing and validation","text":""},{"location":"concepts/advanced/typing_and_validation/#adding-type-hints-with-generics","title":"Adding type hints with Generics","text":"
New in version 0.92
The Component class optionally accepts type parameters that allow you to specify the types of args, kwargs, slots, and data:
class Button(Component[Args, Kwargs, Slots, Data, JsData, CssData]):\n ...\n
Args - Must be a Tuple or Any
Kwargs - Must be a TypedDict or Any
Data - Must be a TypedDict or Any
Slots - Must be a TypedDict or Any
Here's a full example:
from typing import NotRequired, Tuple, TypedDict, SlotContent, SlotFunc\n\n# Positional inputs\nArgs = Tuple[int, str]\n\n# Kwargs inputs\nclass Kwargs(TypedDict):\n variable: str\n another: int\n maybe_var: NotRequired[int] # May be ommited\n\n# Data returned from `get_context_data`\nclass Data(TypedDict):\n variable: str\n\n# The data available to the `my_slot` scoped slot\nclass MySlotData(TypedDict):\n value: int\n\n# Slots\nclass Slots(TypedDict):\n # Use SlotFunc for slot functions.\n # The generic specifies the `data` dictionary\n my_slot: NotRequired[SlotFunc[MySlotData]]\n # SlotContent == Union[str, SafeString]\n another_slot: SlotContent\n\nclass Button(Component[Args, Kwargs, Slots, Data, JsData, CssData]):\n def get_context_data(self, variable, another):\n return {\n \"variable\": variable,\n }\n
When you then call Component.render or Component.render_to_response, you will get type hints:
Button.render(\n # Error: First arg must be `int`, got `float`\n args=(1.25, \"abc\"),\n # Error: Key \"another\" is missing\n kwargs={\n \"variable\": \"text\",\n },\n)\n
"},{"location":"concepts/advanced/typing_and_validation/#usage-for-python-311","title":"Usage for Python <3.11","text":"
On Python 3.8-3.10, use typing_extensions
from typing_extensions import TypedDict, NotRequired\n
Additionally on Python 3.8-3.9, also import annotations:
from __future__ import annotations\n
Moreover, on 3.10 and less, you may not be able to use NotRequired, and instead you will need to mark either all keys are required, or all keys as optional, using TypeDict's total kwarg.
See PEP-655 for more info.
"},{"location":"concepts/advanced/typing_and_validation/#passing-additional-args-or-kwargs","title":"Passing additional args or kwargs","text":"
You may have a function that supports any number of args or kwargs:
"},{"location":"concepts/advanced/typing_and_validation/#runtime-input-validation-with-types","title":"Runtime input validation with types","text":"
New in version 0.96
NOTE: Kwargs, slots, and data validation is supported only for Python >=3.11
In Python 3.11 and later, when you specify the component types, you will get also runtime validation of the inputs you pass to Component.render or Component.render_to_response.
So, using the example from before, if you ignored the type errors and still ran the following code:
Button.render(\n # Error: First arg must be `int`, got `float`\n args=(1.25, \"abc\"),\n # Error: Key \"another\" is missing\n kwargs={\n \"variable\": \"text\",\n },\n)\n
This would raise a TypeError:
Component 'Button' expected positional argument at index 0 to be <class 'int'>, got 1.25 of type <class 'float'>\n
In case you need to skip these errors, you can either set the faulty member to Any, e.g.:
# Changed `int` to `Any`\nArgs = Tuple[Any, str]\n
Or you can replace Args with Any altogether, to skip the validation of args:
Every component that you want to use in the template with the {% component %} tag needs to be registered with the ComponentRegistry. Normally, we use the @register decorator for that:
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n ...\n
But for the component to be registered, the code needs to be executed - the file needs to be imported as a module.
One way to do that is by importing all your components in apps.py:
from django.apps import AppConfig\n\nclass MyAppConfig(AppConfig):\n name = \"my_app\"\n\n def ready(self) -> None:\n from components.card.card import Card\n from components.list.list import List\n from components.menu.menu import Menu\n from components.button.button import Button\n ...\n
However, there's a simpler way!
By default, the Python files in the COMPONENTS.dirs directories (and app-level [app]/components/) are auto-imported in order to auto-register the components.
Autodiscovery occurs when Django is loaded, during the AppConfig.ready hook of the apps.py file.
If you are using autodiscovery, keep a few points in mind:
Avoid defining any logic on the module-level inside the components dir, that you would not want to run anyway.
Components inside the auto-imported files still need to be registered with @registerp
Auto-imported component files must be valid Python modules, they must use suffix .py, and module name should follow PEP-8.
Autodiscovery can be also triggered manually, using the autodiscover function. This is useful if you want to run autodiscovery at a custom point of the lifecycle:
from django_components import autodiscover\n\nautodiscover()\n
To get the same list of modules that autodiscover() would return, but without importing them, use get_component_files():
from django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
"},{"location":"concepts/fundamentals/component_context_scope/","title":"Component context and scope","text":"
By default, context variables are passed down the template as in regular Django - deeper scopes can access the variables from the outer scopes. So if you have several nested forloops, then inside the deep-most loop you can access variables defined by all previous loops.
With this in mind, the {% component %} tag behaves similarly to {% include %} tag - inside the component tag, you can access all variables that were defined outside of it.
And just like with {% include %}, if you don't want a specific component template to have access to the parent context, add only to the {% component %} tag:
{% component \"calendar\" date=\"2015-06-19\" only / %}\n
NOTE: {% csrf_token %} tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the only modifier.
If you find yourself using the only modifier often, you can set the context_behavior option to \"isolated\", which automatically applies the only modifier. This is useful if you want to make sure that components don't accidentally access the outer context.
Components can also access the outer context in their context methods like get_context_data by accessing the property self.outer_context.
"},{"location":"concepts/fundamentals/component_context_scope/#example-of-accessing-outer-context","title":"Example of Accessing Outer Context","text":"
<div>\n {% component \"calender\" / %}\n</div>\n
Assuming that the rendering context has variables such as date, you can use self.outer_context to access them from within get_context_data. Here's how you might implement it:
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.
django_components supports both Django and Vue-like behavior when it comes to passing data to and through components. This can be configured in context_behavior.
This has two modes:
\"django\"
The default Django template behavior.
Inside the {% fill %} tag, the context variables you can access are a union of:
All the variables that were OUTSIDE the fill tag, including any\\ {% with %} tags.
Any loops ({% for ... %}) that the {% fill %} tag is part of.
Data returned from Component.get_context_data() of the component that owns the fill tag.
\"isolated\"
Similar behavior to Vue or React, this is useful if you want to make sure that components don't accidentally access variables defined outside of the component.
Inside the {% fill %} tag, you can ONLY access variables from 2 places:
Any loops ({% for ... %}) that the {% fill %} tag is part of.
Component.get_context_data() of the component which defined the template (AKA the \"root\" component).
Warning
Notice that the component whose get_context_data() we use inside {% fill %} is NOT the same across the two modes!
\"django\" - my_var has access to data from get_context_data() of both Inner and Outer. If there are variables defined in both, then Inner overshadows Outer.
\"isolated\" - my_var has access to data from get_context_data() of ONLY Outer.
Then if get_context_data() of the component \"my_comp\" returns following data:
{ \"my_var\": 456 }\n
Then the template will be rendered as:
123 # my_var\n # cheese\n
Because variables \"my_var\" and \"cheese\" are searched only inside RootComponent.get_context_data(). But since \"cheese\" is not defined there, it's empty.
Info
Notice that the variables defined with the {% with %} tag are ignored inside the {% fill %} tag with the \"isolated\" mode.
"},{"location":"concepts/fundamentals/components_as_views/","title":"Components as views","text":"
New in version 0.34
Note: Since 0.92, Component no longer subclasses View. To configure the View class, set the nested Component.View class
Components can now be used as views:
Components define the Component.as_view() class method that can be used the same as View.as_view().
By default, you can define GET, POST or other HTTP handlers directly on the Component, same as you do with View. For example, you can override get and post to handle GET and POST requests, respectively.
In addition, Component now has a render_to_response method that renders the component template based on the provided context and slots' data and returns an HttpResponse object.
"},{"location":"concepts/fundamentals/components_as_views/#component-as-view-example","title":"Component as view example","text":"
Here's an example of a calendar component defined as a view:
# In a file called [project root]/components/calendar.py\nfrom django_components import Component, ComponentView, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n\n template = \"\"\"\n <div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" / %}\n </div>\n <div class=\"body\">\n Today's date is <span>{{ date }}</span>\n </div>\n </div>\n \"\"\"\n\n # Handle GET requests\n def get(self, request, *args, **kwargs):\n context = {\n \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n }\n slots = {\n \"header\": \"Calendar header\",\n }\n # Return HttpResponse with the rendered content\n return self.render_to_response(\n context=context,\n slots=slots,\n )\n
Then, to use this component as a view, you should create a urls.py file in your components directory, and add a path to the component's view:
# In a file called [project root]/components/urls.py\nfrom django.urls import path\nfrom components.calendar.calendar import Calendar\n\nurlpatterns = [\n path(\"calendar/\", Calendar.as_view()),\n]\n
Component.as_view() is a shorthand for calling View.as_view() and passing the component instance as one of the arguments.
Remember to add __init__.py to your components directory, so that Django can find the urls.py file.
Finally, include the component's urls in your project's urls.py file:
# In a file called [project root]/urls.py\nfrom django.urls import include, path\n\nurlpatterns = [\n path(\"components/\", include(\"components.urls\")),\n]\n
Note: Slots content are automatically escaped by default to prevent XSS attacks. To disable escaping, set escape_slots_content=False in the render_to_response method. If you do so, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.
If you're planning on passing an HTML string, check Django's use of format_html and mark_safe.
"},{"location":"concepts/fundamentals/components_as_views/#modifying-the-view-class","title":"Modifying the View class","text":"
The View class that handles the requests is defined on Component.View.
When you define a GET or POST handlers on the Component class, like so:
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.
If you want to define your own View class, you need to:
Set the class as Component.View
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.
"},{"location":"concepts/fundamentals/components_in_python/","title":"Components in Python","text":"
New in version 0.81
Components can be rendered outside of Django templates, calling them as regular functions (\"React-style\").
The component class defines render and render_to_response class methods. These methods accept positional args, kwargs, and slots, offering the same flexibility as the {% component %} tag:
"},{"location":"concepts/fundamentals/components_in_python/#inputs-of-render-and-render_to_response","title":"Inputs of render and render_to_response","text":"
Both render and render_to_response accept the same input:
args - Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %}
kwargs - Keyword args for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %}
slots - Component slot fills. This is the same as pasing {% fill %} tags to the component. Accepts a dictionary of { slot_name: slot_content } where slot_content can be a string or SlotFunc.
escape_slots_content - Whether the content from slots should be escaped. True by default to prevent XSS attacks. If you disable escaping, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.
context - A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template.
NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs.
request - A Django request object. This is used to enable Django template context_processors to run, allowing for template tags like {% csrf_token %} and variables like {{ debug }}.
Similar behavior can be achieved with provide / inject.
This is used internally to convert context to a RequestContext. It does nothing if context is already a Context instance.
"},{"location":"concepts/fundamentals/components_in_python/#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:
<!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":"concepts/fundamentals/defining_js_css_html_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":"concepts/fundamentals/defining_js_css_html_files/#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":"concepts/fundamentals/defining_js_css_html_files/#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__).
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.
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.
Both attrs and defaults are optional (can be omitted)
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.
All other kwargs are appended and can be repeated.
"},{"location":"concepts/fundamentals/html_attributes/#examples-for-html_attrs","title":"Examples for html_attrs","text":"
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 %}
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.
"},{"location":"concepts/fundamentals/html_attributes/#rendering-html-attributes-outside-of-templates","title":"Rendering HTML attributes outside of templates","text":"
If you need to use serialize HTML attributes outside of Django template and the html_attrs tag, you can use attributes_to_string:
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.
The slot tag now serves only to declare new slots inside the component template.
To override the content of a declared slot, use the newly introduced fill tag instead.
Whereas unfilled slots used to raise a warning, filling a slot is now optional by default.
To indicate that a slot must be filled, the new required option should be added at the end of the slot tag.
Components support something called 'slots'. When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content. This mechanism makes components more reusable and composable. This behavior is similar to slots in Vue.
In the example below we introduce two block tags that work hand in hand to make this work. These are...
{% slot <name> %}/{% endslot %}: Declares a new slot in the component template.
{% fill <name> %}/{% endfill %}: (Used inside a {% component %} tag pair.) Fills a declared slot with the specified content.
Let's update our calendar component to support more customization. We'll add slot tag pairs to its template, template.html.
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" %}Calendar header{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"body\" %}Today's date is <span>{{ date }}</span>{% endslot %}\n </div>\n</div>\n
When using the component, you specify which slots you want to fill and where you want to use the defaults from the template. It looks like this:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"body\" %}\n Can you believe it's already <span>{{ date }}</span>??\n {% endfill %}\n{% endcomponent %}\n
Since the 'header' fill is unspecified, it's taken from the base template. If you put this in a template, and pass in date=2020-06-06, this is what gets rendered:
<div class=\"calendar-component\">\n <div class=\"header\">\n Calendar header\n </div>\n <div class=\"body\">\n Can you believe it's already <span>2020-06-06</span>??\n </div>\n</div>\n
As seen in the previouse section, you can use {% fill slot_name %} to insert content into a specific slot.
You can define fills for multiple slot simply by defining them all within the {% component %} {% endcomponent %} tags:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}\n Hi this is header!\n {% endfill %}\n {% fill \"body\" %}\n Can you believe it's already <span>{{ date }}</span>??\n {% endfill %}\n{% endcomponent %}\n
You can also use {% for %}, {% with %}, or other non-component tags (even {% include %}) to construct the {% fill %} tags, as long as these other tags do not leave any text behind!
{% component \"table\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name %}\n {{ slot_name }}\n {% endfill %}\n {% endfor %}\n\n {% with slot_name=\"abc\" %}\n {% fill name=slot_name %}\n {{ slot_name }}\n {% endfill %}\n {% endwith %}\n{% endcomponent %}\n
As you can see, component slots lets you write reusable containers that you fill in when you use a component. This makes for highly reusable components that can be used in different circumstances.
It can become tedious to use fill tags everywhere, especially when you're using a component that declares only one slot. To make things easier, slot tags can be marked with an optional keyword: default.
When added to the tag (as shown below), this option lets you pass filling content directly in the body of a component tag pair \u2013 without using a fill tag. Choose carefully, though: a component template may contain at most one slot that is marked as default. The default option can be combined with other slot options, e.g. required.
Here's the same example as before, except with default slots and implicit filling.
The template:
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" %}Calendar header{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"body\" default %}Today's date is <span>{{ date }}</span>{% endslot %}\n </div>\n</div>\n
Including the component (notice how the fill tag is omitted):
{% component \"calendar\" date=\"2020-06-06\" %}\n Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n
You may be tempted to combine implicit fills with explicit fill tags. This will not work. The following component template will raise an error when rendered.
{# DON'T DO THIS #}\n{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}Totally new header!{% endfill %}\n Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n
Instead, you can use a named fill with name default to target the default fill:
{# THIS WORKS #}\n{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}Totally new header!{% endfill %}\n {% fill \"default\" %}\n Can you believe it's already <span>{{ date }}</span>??\n {% endfill %}\n{% endcomponent %}\n
NOTE: If you doubly-fill a slot, that is, that both {% fill \"default\" %} and {% fill \"header\" %} would point to the same slot, this will raise an error when rendered.
"},{"location":"concepts/fundamentals/slots/#accessing-default-slot-in-python","title":"Accessing default slot in Python","text":"
Since the default slot is stored under the slot name default, you can access the default slot like so:
Since each slot is tagged individually, you can have multiple slots with the same name but different conditions.
E.g. in this example, we have a component that renders a user avatar - a small circular image with a profile picture or name initials.
If the component is given image_src or name_initials variables, the image slot is optional. But if neither of those are provided, you MUST fill the image slot.
"},{"location":"concepts/fundamentals/slots/#accessing-original-content-of-slots","title":"Accessing original content of slots","text":"
Added in version 0.26
NOTE: In version 0.77, the syntax was changed from
{% fill \"my_slot\" as \"alias\" %} {{ alias.default }}\n
to
{% fill \"my_slot\" default=\"slot_default\" %} {{ slot_default }}\n
Sometimes you may want to keep the original slot, but only wrap or prepend/append content to it. To do so, you can access the default slot via the default kwarg.
Similarly to the data attribute, you specify the variable name through which the default slot will be made available.
For instance, let's say you're filling a slot called 'body'. To render the original slot, assign it to a variable using the 'default' keyword. You then render this variable to insert the default content:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"body\" default=\"body_default\" %}\n {{ body_default }}. Have a great day!\n {% endfill %}\n{% endcomponent %}\n
This produces:
<div class=\"calendar-component\">\n <div class=\"header\">\n Calendar header\n </div>\n <div class=\"body\">\n Today's date is <span>2020-06-06</span>. Have a great day!\n </div>\n</div>\n
To access the original content of a default slot, set the name to default:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"default\" default=\"slot_default\" %}\n {{ slot_default }}. Have a great day!\n {% endfill %}\n{% endcomponent %}\n
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:
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:
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.
Sometimes you're not interested in whether a slot is filled, but rather that it isn't. To negate the meaning of component_vars.is_filled, simply treat it as boolean and negate it with not:
{% if not component_vars.is_filled.subtitle %}\n<div class=\"subtitle\">\n {% slot \"subtitle\" / %}\n</div>\n{% endif %}\n
"},{"location":"concepts/fundamentals/slots/#accessing-is_filled-of-slot-names-with-special-characters","title":"Accessing is_filled of slot names with special characters","text":"
To be able to access a slot name via component_vars.is_filled, the slot name needs to be composed of only alphanumeric characters and underscores (e.g. this__isvalid_123).
However, you can still define slots with other special characters. In such case, the slot name in component_vars.is_filled is modified to replace all invalid characters into _.
So a slot named \"my super-slot :)\" will be available as component_vars.is_filled.my_super_slot___.
Same applies when you are accessing is_filled from within the Python, e.g.:
class MyTable(Component):\n def on_render_before(self, context, template) -> None:\n # \u2705 Works\n if self.is_filled[\"my_super_slot___\"]:\n # Do something\n\n # \u274c Does not work\n if self.is_filled[\"my super-slot :)\"]:\n # Do something\n
Similarly, you can use {% if %} and {% for %} when defining the {% fill %} tags, to conditionally fill the slots when using the componnet:
In the example below, the {% fill \"footer\" %} fill is used only if the condition is true. If falsy, the fill is ignored, and so the my_table component will use its default content for the footer slot.
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:
"},{"location":"concepts/fundamentals/slots/#accessing-slot-data-in-fill","title":"Accessing slot data in fill","text":"
Next, we head over to where we define a fill for this slot. Here, to access the slot data we set the data attribute to the name of the variable through which we want to access the slot data. In the example below, we set it to data:
"},{"location":"concepts/fundamentals/slots/#dynamic-slots-and-fills","title":"Dynamic slots and fills","text":"
Until now, we were declaring slot and fill names statically, as a string literal, e.g.
{% slot \"content\" / %}\n
However, sometimes you may want to generate slots based on the given input. One example of this is a table component like that of Vuetify, which creates a header and an item slots for each user-defined column.
In django_components you can achieve the same, simply by using a variable (or a template expression) instead of a string literal:
{% 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:
"},{"location":"concepts/fundamentals/template_tag_syntax/","title":"Template tag syntax","text":"
All template tags in django_component, like {% component %} or {% slot %}, and so on, support extra syntax that makes it possible to write components like in Vue or React (JSX).
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 %}:
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
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.
Component test receives a positional argument with value \"As positional arg \". The comment is omitted.
Kwarg title is passed as a string, e.g. John Doe
Kwarg id is passed as int, e.g. 15
Kwarg readonly is passed as bool, e.g. False
Kwarg author is passed as a string, e.g. John Wick (Comment omitted)
This is inspired by django-cotton.
"},{"location":"concepts/fundamentals/template_tag_syntax/#passing-data-as-string-vs-original-values","title":"Passing data as string vs original values","text":"
Sometimes you may want to use the template tags to transform or generate the data that is then passed to the component.
The data doesn't necessarily have to be strings. In the example above, the kwarg id was passed as an integer, NOT a string.
Although the string literals for components inputs are treated as regular Django templates, there is one special case:
When the string literal contains only a single template tag, with no extra text, then the value is passed as the original type instead of a string.
{% component 'cat_list' items=\"{{ cats|slice:':2' }} See more\" / %}\n
"},{"location":"concepts/fundamentals/template_tag_syntax/#evaluating-python-expressions-in-template","title":"Evaluating Python expressions in template","text":"
You can even go a step further and have a similar experience to Vue or React, where you can evaluate arbitrary code expressions:
Note: Never use this feature to mix business logic and template logic. Business logic should still be in the view!
"},{"location":"concepts/fundamentals/template_tag_syntax/#pass-dictonary-by-its-key-value-pairs","title":"Pass dictonary by its key-value pairs","text":"
New in version 0.74:
Sometimes, a component may expect a dictionary as one of its inputs.
Most commonly, this happens when a component accepts a dictionary of HTML attributes (usually called attrs) to pass to the underlying template.
In such cases, we may want to define some HTML attributes statically, and other dynamically. But for that, we need to define this dictionary on Python side:
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:
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":"devguides/dependency_mgmt/","title":"JS and CSS rendering","text":"
Aim of this doc is to share the intuition on how we manage the JS and CSS (\"dependencies\") associated with components, and how we render them.
First of all, when we consider a component, it has two kind of dependencies - the \"inlined\" JS and CSS, and additional linked JS and CSS via Media.js/css:
Second thing to keep in mind is that all component's are eventually rendered into a string. And so, if we want to associate extra info with a rendered component, it has to be serialized to a string.
This is because a component may be embedded in a Django Template with the {% component %} tag, which, when rendered, is turned into a string:
And for this reason, we take the same approach also when we render a component with Component.render() - It returns a string.
Thirdly, we also want to add support for JS / CSS variables. That is, that a variable defined on the component would be somehow accessible from within the JS script / CSS style.
A simple approach to this would be to modify the inlined JS / CSS directly, and insert them for each component. But if you had extremely large JS / CSS, and e.g. only a single JS / CSS variable that you want to insert, it would be extremely wasteful to copy-paste the JS / CSS for each component instance.
So instead, a preferred approach here is to defined and insert the inlined JS / CSS only once, and have some kind of mechanism on how we make correct the JS / CSS variables available only to the correct components.
Last important thing is that we want the JS / CSS dependencies to work also with HTML fragments.
So normally, e.g. when a user hits URL of a web page, the server renders full HTML document, with <!doctype>, <html>, <head>, and <body>. In such case, we know about ALL JS and CSS dependencies at render time, so we can e.g. insert them into <head> and <body> ourselves.
However this renders only the initial state. HTML fragments is a common pattern where interactivity is added to the web page by fetching and replacing bits of HTML on the main HTML document after some user action.
In the case of HTML fragments, the HTML is NOT a proper document, but only the HTML that will be inserted somewhere into the DOM.
The challenge here is that Django template for the HTML fragment MAY contain components, and these components MAY have inlined or linked JS and CSS.
User may use different libraries to fetch and insert the HTML fragments (e.g. HTMX, AlpineJS, ...). From our perspective, the only thing that we can reliably say is that we expect that the HTML fragment WILL be eventually inserted into the DOM.
So to include the corresponding JS and CSS, a simple approach could be to append them to the HTML as <style> and <script>, e.g.:
The JS scripts would run for each instance of the component.
Bloating of the HTML file, as each inlined JS or CSS would be included fully for each component.
While this sound OK, this could really bloat the HTML files if we used a UI component library for the basic building blocks like buttons, lists, cards, etc.
So the solution should address all the points above. To achieve that, we manage the JS / CSS dependencies ourselves in the browser. So when a full HTML document is loaded, we keep track of which JS and CSS have been loaded. And when an HTML fragment is inserted, we check which JS / CSS dependencies it has, and load only those that have NOT been loaded yet.
This is how we achieve that:
When a component is rendered, it inserts an HTML comment containing metadata about the rendered component.
Each <!-- _RENDERED --> comment includes comma-separated data - a unique hash for the component class, e.g. my_table_10bc2c, and the component ID, e.g. c020ad.
This way, we or the user can freely pass the rendered around or transform it, treating it as a string to add / remove / replace bits. As long as the <!-- _RENDERED --> comments remain in the rendered string, we will be able to deduce which JS and CSS dependencies the component needs.
Post-process the rendered HTML, extracting the <!-- _RENDERED --> comments, and instead inserting the corresponding JS and CSS dependencies.
If we dealt only with JS, then we could get away with processing the <!-- _RENDERED --> comments on the client (browser). However, the CSS needs to be processed still on the server, so the browser receives CSS styles already inserted as <style> or <link> HTML tags. Because if we do not do that, we get a flash of unstyled content, as there will be a delay between when the HTML page loaded and when the CSS was fetched and loaded.
So, assuming that a user has already rendered their template, which still contains <!-- _RENDERED --> comments, we need to extract and process these comments.
There's multiple ways to achieve this:
The approach recommended to the users is to use the ComponentDependencyMiddleware middleware, which scans all outgoing HTML, and post-processes the <!-- _RENDERED --> comments.
If users are using Component.render() or Component.render_to_response(), these post-process the <!-- _RENDERED --> comments by default.
NOTE: Users are able to opt out of the post-processing by setting render_dependencies=False.
For advanced use cases, users may use render_dependencies() directly. This is the function that both ComponentDependencyMiddleware and Component.render() call internally.
render_dependencies(), whether called directly, via middleware or other way, does the following:
Find all <!-- _RENDERED --> comments, and for each comment:
Look up the corresponding component class.
Get the component's inlined JS / CSS from Component.js/css, and linked JS / CSS from Component.Media.js/css.
Generate JS script that loads the JS / CSS dependencies.
Insert the JS scripts either at the end of <body>, or in place of {% component_dependencies %} / {% component_js_dependencies %} tags.
To avoid the flash of unstyled content, we need place the styles into the HTML instead of dynamically loading them from within a JS script. The CSS is placed either at the end of <head>, or in place of {% component_dependencies %} / {% component_css_dependencies %}
We cache the component's inlined JS and CSS, so they can be fetched via an URL, so the inlined JS / CSS an be treated the same way as the JS / CSS dependencies set in Component.Media.js/css.
NOTE: While this is currently not entirely necessary, it opens up the doors for allowing plugins to post-process the inlined JS and CSS. Because after it has been post-processed, we need to store it somewhere.
Server returns the post-processed HTML.
In the browser, the generated JS script from step 2.4 is executed. It goes through all JS and CSS dependencies it was given. If some JS / CSS was already loaded, it is NOT fetched again. Otherwise it generates the corresponding <script> or <link> HTML tags to load the JS / CSS dependencies.
In the browser, the \"dependency manager JS\" may look like this:
// Load JS or CSS script if not loaded already\nComponents.loadJs('<script src=\"/abc/xyz/script.js\">');\nComponents.loadCss('<link href=\"/abc/xyz/style.css\">');\n\n// Or mark one as already-loaded, so it is ignored when\n// we call `loadJs`\nComponents.markScriptLoaded(\"js\", \"/abc/def\");\n
Note that loadJs() / loadCss() receive whole <script> / <link> tags, not just the URL. This is because when Django's Media class renders JS and CSS, it formats it as <script> and <link> tags. And we allow users to modify how the JS and CSS should be rendered into the <script> and <link> tags.
So, if users decided to add an extra attribute to their <script> tags, e.g. <script defer src=\"http://...\"></script>, then this way we make sure that the defer attribute will be present on the <script> tag when it is inserted into the DOM at the time of loading the JS script.
To be able to fetch component's inlined JS and CSS, django-components adds a URL path under:
Variables for names and for loops allow us implement \"passthrough slots\" - that is, taking all slots that our component received, and passing them to a child component, dynamically.
Given the above, we want to render the slots with {% fill %} tag that were defined OUTSIDE of this template. How do I do that?
NOTE: Before v0.110, slots were resolved statically, by walking down the Django Template and Nodes. However, this did not allow for using for loops or other variables defined in the template.
Currently, this consists of 2 steps:
If a component is rendered within a template using {% component %} tag, determine the given {% fill %} tags in the component's body (the content in between {% component %} and {% endcomponent %}).
After this step, we know about all the fills that were passed to the component.
Then we simply render the template as usual. And then we reach the {% slot %} tag, we search the context for the available fills.
If there IS a fill with the same name as the slot, we render the fill.
If the slot is marked default, and there is a fill named default, then we render that.
Otherwise, we render the slot's default content.
Obtaining the fills from {% fill %}.
When a component is rendered with {% component %} tag, and it has some content in between {% component %} and {% endcomponent %}, we want to figure out if that content is a default slot (no {% fill %} used), or if there is a collection of named {% fill %} tags:
To respect any forloops or other variables defined within the template to which the fills may have access, we:
Render the content between {% component %} and {% endcomponent %} using the context outside of the component.
When we reach a {% fill %} tag, we capture any variables that were created between the {% component %} and {% fill %} tags.
When we reach {% fill %} tag, we do not continue rendering deeper. Instead we make a record that we found the fill tag with given name, kwargs, etc.
After the rendering is done, we check if we've encountered any fills. If yes, we expect only named fills. If no, we assume that the the component's body is a default slot.
Lastly we process the found fills, and make them available to the context, so any slots inside the component may access these fills.
Rendering slots
Slot rendering works similarly to collecting fills, in a sense that we do not search for the slots ahead of the time, but instead let Django handle the rendering of the template, and we step in only when Django come across as {% slot %} tag.
When we reach a slot tag, we search the context for the available fills.
If there IS a fill with the same name as the slot, we render the fill.
If the slot is marked default, and there is a fill named default, then we render that.
Otherwise, we render the slot's default content.
"},{"location":"devguides/slot_rendering/#using-the-correct-context-in-slotfill-tags","title":"Using the correct context in {% slot/fill %} tags","text":"
In previous section, we said that the {% fill %} tags should be already rendered by the time they are inserted into the {% slot %} tags.
This is not quite true. To help you understand, consider this complex case:
| -- {% for var in [1, 2, 3] %} ---\n| ---- {% component \"mycomp2\" %} ---\n| ------ {% fill \"first\" %}\n| ------- STU {{ my_var }}\n| ------- {{ var }}\n| ------ {% endfill %}\n| ------ {% fill \"second\" %}\n| -------- {% component var=var my_var=my_var %}\n| ---------- VWX {{ my_var }}\n| -------- {% endcomponent %}\n| ------ {% endfill %}\n| ---- {% endcomponent %} ---\n| -- {% endfor %} ---\n| -------\n
We want the forloop variables to be available inside the {% fill %} tags. Because of that, however, we CANNOT render the fills/slots in advance.
Instead, our solution is closer to how Vue handles slots. In Vue, slots are effectively functions that accept a context variables and render some content.
While we do not wrap the logic in a function, we do PREPARE IN ADVANCE: 1. The content that should be rendered for each slot 2. The context variables from get_context_data()
Thus, once we reach the {% slot %} node, in it's render() method, we access the data above, and, depending on the context_behavior setting, include the current context or not. For more info, see SlotNode.render().
"},{"location":"devguides/slots_and_blocks/","title":"Using slot and block tags","text":"
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
Will still render the component content just the same:
<div>hello 1 XYZ</div>\n
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:
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:
"},{"location":"guides/setup/dev_server_setup/","title":"Running with development server","text":""},{"location":"guides/setup/dev_server_setup/#reload-dev-server-on-component-file-changes","title":"Reload dev server on component file changes","text":"
This is relevant if you are using the project structure as shown in our examples, where HTML, JS, CSS and Python are in separate files and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.
From relevant StackOverflow thread:
TL;DR is that the server won't reload if it thinks the changed file is in a templates directory, or in a nested sub directory of a templates directory. This is by design.
To make the dev server reload on all component files, set reload_on_file_change to True. This configures Django to watch for component files too.
Note
This setting should be enabled only for the dev environment!
"},{"location":"guides/setup/logging_and_debugging/","title":"Logging and debugging","text":"
Django components supports logging with Django. This can help with troubleshooting.
To configure logging for Django components, set the django_components logger in LOGGING in settings.py (below).
Also see the settings.py file in sampleproject for a real-life example.
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":"guides/setup/syntax_highlight/#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:
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":"overview/code_of_conduct/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"overview/code_of_conduct/#our-pledge","title":"Our Pledge","text":"
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
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.
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.
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.
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
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.
Another way you can get involved is by donating to the development of django_components.
"},{"location":"overview/development/","title":"Development","text":""},{"location":"overview/development/#install-locally-and-run-the-tests","title":"Install locally and run the tests","text":"
Start by forking the project by clicking the Fork button up in the right corner in the GitHub . This makes a copy of the repository in your own name. Now you can clone this repository locally and start adding features:
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:
Make sure you are inside src/django_components_js:
cd src/django_components_js\n
Install the JS dependencies
npm install\n
Compile the JS/TS code:
python build.py\n
The script will combine all JS/TS code into a single .js file, minify it, and copy it to django_components/static/django_components/django_components.min.js.
"},{"location":"overview/development/#packaging-and-publishing","title":"Packaging and publishing","text":"
To package the library into a distribution that can be published to PyPI, run:
# Install pypa/build\npython -m pip install build --user\n# Build a binary wheel and a source tarball\npython -m build --sdist --wheel --outdir dist/ .\n
To publish the package to PyPI, use twine (See Python user guide):
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.
Next, to make Django load component HTML files as Django templates, modify TEMPLATES section of settings.py as follows:
Remove 'APP_DIRS': True,
NOTE: Instead of APP_DIRS, for the same effect, we will use django.template.loaders.app_directories.Loader
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
"},{"location":"overview/installation/#adding-support-for-js-and-css","title":"Adding support for JS and CSS","text":"
If you want to use JS or CSS with components, you will need to:
Modify STATICFILES_FINDERS section of settings.py as follows to be able to serve the component JS and CSS files as static files:
Add ComponentDependencyMiddleware to MIDDLEWARE setting.
The middleware searches the outgoing HTML for all components that were rendered to generate the HTML, and adds the JS and CSS associated with those components.
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.
Components can be organized however you prefer. That said, our prefered way is to keep the files of a component close together by bundling them in the same directory.
This means that files containing backend logic, such as Python modules and HTML templates, live in the same directory as static files, e.g. JS and CSS.
From v0.100 onwards, we keep component files (as defined by COMPONENTS.dirs and COMPONENTS.app_dirs) separate from the rest of the static files (defined by STATICFILES_DIRS). That way, the Python and HTML files are NOT exposed by the server. Only the static JS, CSS, and other common formats.
NOTE: If you need to expose different file formats, you can configure these with COMPONENTS.static_files_allowed and COMPONENTS.static_files_forbidden.
"},{"location":"overview/security_notes/#static-files-prior-to-v0100","title":"Static files prior to v0.100","text":"
Prior to v0.100, if your were using django.contrib.staticfiles to collect static files, no distinction was made between the different kinds of files.
As a result, your Python code and templates may inadvertently become available on your static file server. You probably don't want this, as parts of your backend logic will be exposed, posing a potential security vulnerability.
From v0.27 until v0.100, django-components shipped with an additional installable app django_components.safer_staticfiles. It was a drop-in replacement for django.contrib.staticfiles. Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server. To use it, add it to INSTALLED_APPS and remove django.contrib.staticfiles.
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":"overview/welcome/","title":"Welcome to Django Components","text":"
django-components introduces component-based architecture to Django's server-side rendering. It combines Django's templating system with the modularity seen in modern frontend frameworks like Vue or React.
\ud83e\udde9 Reusability: Allows creation of self-contained, reusable UI elements.
\ud83d\udce6 Encapsulation: Each component can include its own HTML, CSS, and JavaScript.
\ud83d\ude80 Server-side rendering: Components render on the server, improving initial load times and SEO.
\ud83d\udc0d Django integration: Works within the Django ecosystem, using familiar concepts like template tags.
\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.
One of our goals with django-components is to make it easy to share components between projects. If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.
django-htmx-components: A set of components for use with htmx. Try out the live demo.
"},{"location":"overview/welcome/#contributing-and-development","title":"Contributing and development","text":"
Get involved or sponsor this project - See here
Running django-components locally for development - See here
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.
Inputs: - args - Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %} - kwargs - Kwargs for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %} - slots - Component slot fills. This is the same as pasing {% fill %} tags to the component. Accepts a dictionary of { slot_name: slot_content } where slot_content can be a string or render function. - escape_slots_content - Whether the content from slots should be escaped. - context - A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. - type - Configure how to handle JS and CSS dependencies. - \"document\" (default) - JS dependencies are inserted into {% component_js_dependencies %}, or to the end of the <body> tag. CSS dependencies are inserted into {% component_css_dependencies %}, or the end of the <head> tag. - render_dependencies - Set this to False if you want to insert the resulting HTML into another component. - request - The request object. This is only required when needing to use RequestContext, e.g. to enable template context_processors. Unused if context is already an instance of Context Example:
Render the component and wrap the content in the response class.
The response class is taken from Component.response_class. Defaults to django.http.HttpResponse.
This is the interface for the django.views.View class which allows us to use components as Django views with component.as_view().
Inputs: - args - Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %} - kwargs - Kwargs for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %} - slots - Component slot fills. This is the same as pasing {% fill %} tags to the component. Accepts a dictionary of { slot_name: slot_content } where slot_content can be a string or render function. - escape_slots_content - Whether the content from slots should be escaped. - context - A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. - type - Configure how to handle JS and CSS dependencies. - \"document\" (default) - JS dependencies are inserted into {% component_js_dependencies %}, or to the end of the <body> tag. CSS dependencies are inserted into {% component_css_dependencies %}, or the end of the <head> tag. - request - The request object. This is only required when needing to use RequestContext, e.g. to enable template context_processors. Unused if context is already an instance of Context
Any additional args and kwargs are passed to the response_class.
To enable a component to be used in a template, the component must be registered with a component registry.
When you register a component to a registry, behind the scenes the registry automatically adds the component's template tag (e.g. {% component %} to the Library. And the opposite happens when you unregister a component - the tag is removed.
See Registering components.
Parameters:
library (Library, default: None ) \u2013
Django Library associated with this registry. If omitted, the default Library instance from django_components is used.
Configure how the components registered with this registry will behave when rendered. See RegistrySettings. Can be either a static value or a callable that returns the settings. If omitted, the settings from COMPONENTS are used.
Notes:
The default registry is available as django_components.registry.
The default registry is used when registering components with @register decorator.
Example:
# Use with default Library\nregistry = ComponentRegistry()\n\n# Or a custom one\nmy_lib = Library()\nregistry = ComponentRegistry(library=my_lib)\n\n# Usage\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\nregistry.all()\nregistry.clear()\nregistry.get()\n
"},{"location":"reference/api/#django_components.ComponentRegistry--using-registry-to-share-components","title":"Using registry to share components","text":"
You can use component registry for isolating or \"packaging\" components:
Create new instance of ComponentRegistry and Library:
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
Dictonary describing which component slots are filled (True) or are not (False).
New in version 0.70
Use as {{ component_vars.is_filled }}
Example:
{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n <div class=\"slot-wrapper\">\n {% slot \"my_slot\" / %}\n </div>\n{% endif %}\n
This is equivalent to checking if a given key is among the slot fills:
class MyTable(Component):\n def get_context_data(self, *args, **kwargs):\n return {\n \"my_slot_filled\": \"my_slot\" in self.input.slots\n }\n
Configure whether, inside a component template, you can use variables from the outside (\"django\") or not (\"isolated\"). This also affects what variables are available inside the {% fill %} tags.
Configure extra python modules that should be loaded.
This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.
Expects a list of python module paths. Defaults to empty list.
This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.
Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.
The setting reload_on_file_change fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.
If True, django_components configures Django to reload when files inside COMPONENTS.dirs or COMPONENTS.app_dirs change.
See Reload dev server on component file changes.
Defaults to False.
Warning
This setting should be enabled only for the dev environment!
A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs are treated as static files.
If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running collectstatic, and can be accessed under the static file endpoint.
You can also pass in compiled regexes (re.Pattern) for more advanced patterns.
By default, JS, CSS, and common image and font file formats are considered static files:
A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs will NEVER be treated as static files.
If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in static_files_allowed.
Use this setting together with static_files_allowed for a fine control over what file types will be exposed.
You can also pass in compiled regexes (re.Pattern) for more advanced patterns.
By default, any HTML and Python are considered NOT static files:
Configure the maximum amount of Django templates to be cached.
Defaults to 128.
Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.
By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding Component.get_template() to render many dynamic templates, you can increase this number.
This setting makes the component fills behave similar to Vue or React, where the fills use EXCLUSIVELY the context variables defined in Component.get_context_data().
You can use this to define a Component that accepts NO kwargs, or NO slots, or returns NO data from Component.get_context_data() / Component.get_js_data() / Component.get_css_data():
Going back to the example with NO kwargs, when you then call Component.render() or Component.render_to_response(), the kwargs parameter will raise type error if kwargs is anything else than an empty dict.
Table.render(\n kwargs: {},\n)\n
Omitting kwargs is also fine:
Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
After that, when you call Component.render() or Component.render_to_response(), the args parameter will raise type error if args is anything else than an empty tuple.
Table.render(\n args: (),\n)\n
Omitting args is also fine:
Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
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.
Given the tokens (words) passed to a component start tag, this function extracts the component name from the tokens list, and returns TagResult, which is a tuple of (component_name, remaining_tokens).
Parameters:
tokens ([List(str]) \u2013
List of tokens passed to the component tag.
Returns:
TagResult ( TagResult ) \u2013
Parsed component name and remaining tokens.
Example:
Assuming we used a component in a template like this:
This is the heart of all features that deal with filesystem and file lookup. Autodiscovery, Django template resolution, static file resolution - They all use this.
Parameters:
include_apps (bool, default: True ) \u2013
Include directories from installed Django apps. Defaults to True.
Returns:
List[Path] \u2013
List[Path]: A list of directories that may contain component files.
get_component_dirs() searches for dirs set in COMPONENTS.dirs settings. If none set, defaults to searching for a \"components\" app.
In addition to that, also all installed Django apps are checked whether they contain directories as set in COMPONENTS.app_dirs (e.g. [app]/components).
Notes:
Paths that do not point to directories are ignored.
BASE_DIR setting is required.
The paths in COMPONENTS.dirs must be absolute paths.
Given a string that contains parts that were rendered by components, this function inserts all used JS and CSS.
By default, the string is parsed as an HTML and: - CSS is inserted at the end of <head> (if present) - JS is inserted at the end of <body> (if present)
If you used {% component_js_dependencies %} or {% component_css_dependencies %}, then the JS and CSS will be inserted only at these locations.
The Python path to a settings module, e.g. \"myproject.settings.main\". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used.
--pythonpath PYTHONPATH
A directory to add to the Python path, e.g. \"/home/djangoprojects/myproject\".
The name of the component to create. This is a required argument.
Options:
-h, --help
show this help message and exit
--path PATH
The path to the component's directory. This is an optional argument. If not provided, the command will use the COMPONENTS.dirs setting from your Django settings.
--js JS
The name of the JavaScript file. This is an optional argument. The default value is script.js.
--css CSS
The name of the CSS file. This is an optional argument. The default value is style.css.
--template TEMPLATE
The name of the template file. This is an optional argument. The default value is template.html.
--force
This option allows you to overwrite existing files if they exist. This is an optional argument.
--verbose
This option allows the command to print additional information during component creation. This is an optional argument.
--dry-run
This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False.
The Python path to a settings module, e.g. \"myproject.settings.main\". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used.
--pythonpath PYTHONPATH
A directory to add to the Python path, e.g. \"/home/djangoprojects/myproject\".
Here are some examples of how you can use the command:
"},{"location":"reference/commands/#creating-a-component-with-default-settings","title":"Creating a Component with Default Settings","text":"
To create a component with the default settings, you only need to provide the name of the component:
python manage.py startcomponent my_component\n
This will create a new component named my_component in the components directory of your Django project. The JavaScript, CSS, and template files will be named script.js, style.css, and template.html, respectively.
"},{"location":"reference/commands/#creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"
You can also create a component with custom settings by providing additional arguments:
This will create a new component named new_component in the my_components directory. The JavaScript, CSS, and template files will be named my_script.js, my_style.css, and my_template.html, respectively.
"},{"location":"reference/commands/#overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"
If you want to overwrite an existing component, you can use the --force option:
Dynamic components are suitable if you are writing something like a form component. You may design it such that users give you a list of input types, and you render components depending on the input types.
While you could handle this with a series of if / else statements, that's not an extensible approach. Instead, you can use the dynamic component in place of normal components.
By default, the dynamic component is registered under the name \"dynamic\". In case of a conflict, you can set the COMPONENTS.dynamic_component_name setting to change the name used for the dynamic components.
The way the TagFormatter works is that, based on which start and end tags are used for rendering components, the ComponentRegistry behind the scenes un-/registers the template tags with the associated instance of Django's Library.
In other words, if I have registered a component \"table\", and I use the shorthand syntax:
{% table ... %}\n{% endtable %}\n
Then ComponentRegistry registers the tag table onto the Django's Library instance.
However, that means that if we registered a component \"slot\", then we would overwrite the {% slot %} tag from django_components.
Thus, this exception is raised when a component is attempted to be registered under a forbidden name, such that it would overwrite one of django_component's own template tags.
You can configure django_components with a global COMPONENTS variable in your Django settings file, e.g. settings.py. By default you don't need it set, there are resonable defaults.
To configure the settings you can instantiate ComponentsSettings for validation and type hints. Or, for backwards compatibility, you can also use plain dictionary:
Configure whether, inside a component template, you can use variables from the outside (\"django\") or not (\"isolated\"). This also affects what variables are available inside the {% fill %} tags.
Configure extra python modules that should be loaded.
This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.
Expects a list of python module paths. Defaults to empty list.
This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.
Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.
The setting reload_on_file_change fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.
If True, django_components configures Django to reload when files inside COMPONENTS.dirs or COMPONENTS.app_dirs change.
See Reload dev server on component file changes.
Defaults to False.
Warning
This setting should be enabled only for the dev environment!
A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs are treated as static files.
If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running collectstatic, and can be accessed under the static file endpoint.
You can also pass in compiled regexes (re.Pattern) for more advanced patterns.
By default, JS, CSS, and common image and font file formats are considered static files:
A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs will NEVER be treated as static files.
If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in static_files_allowed.
Use this setting together with static_files_allowed for a fine control over what file types will be exposed.
You can also pass in compiled regexes (re.Pattern) for more advanced patterns.
By default, any HTML and Python are considered NOT static files:
Configure the maximum amount of Django templates to be cached.
Defaults to 128.
Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.
By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding Component.get_template() to render many dynamic templates, you can increase this number.
The original django_component's component tag formatter, it uses the {% component %} and {% endcomponent %} tags, and the component name is given as the first positional arg.
"},{"location":"reference/template_tags/#inserting-into-slots","title":"Inserting into slots","text":"
If the component defined any slots, you can pass in the content to be placed inside those slots by inserting {% fill %} tags, directly within the {% component %} tag:
By default, components behave similarly to Django's {% include %}, and the template inside the component has access to the variables defined in the outer template.
You can selectively isolate a component, using the only flag, so that the inner template can access only the data that was explicitly passed to it:
{% component \"name\" positional_arg keyword_arg=value ... only %}\n
Marks location where CSS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted into the <head> tag of the HTML.
If the generated HTML does NOT contain any {% component_css_dependencies %} tags, CSS links are by default inserted into the <head> tag of the HTML. (See JS and CSS output locations)
Note that there should be only one {% component_css_dependencies %} for the whole HTML document. If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.
Marks location where JS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted at the end of the <body> tag of the HTML.
If the generated HTML does NOT contain any {% component_js_dependencies %} tags, JS scripts are by default inserted at the end of the <body> tag of the HTML. (See JS and CSS output locations)
Note that there should be only one {% component_js_dependencies %} for the whole HTML document. If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.
{% fill name data=None default=None %}\n{% endfill %}\n
See source code
Use this tag to insert content into component's slots.
{% fill %} tag may be used only within a {% component %}..{% endcomponent %} block. Runtime checks should prohibit other usages.
Args:
name (str, required): Name of the slot to insert this content into. Use \"default\" for the default slot.
default (str, optional): This argument allows you to access the original content of the slot under the specified variable name. See Accessing original content of slots
data (str, optional): This argument allows you to access the data passed to the slot under the specified variable name. See Scoped slots
"},{"location":"reference/template_tags/#accessing-slots-default-content-with-the-default-kwarg","title":"Accessing slot's default content with the default kwarg","text":"
"},{"location":"reference/template_tags/#accessing-slot-data-and-default-content-on-the-default-slot","title":"Accessing slot data and default content on the default slot","text":"
To access slot data and the default slot content on the default slot, use {% fill %} with name set to \"default\":
{% component \"button\" %}\n {% fill name=\"default\" data=\"slot_data\" default=\"default_slot\" %}\n You clicked me {{ slot_data.count }} times!\n {{ default_slot }}\n {% endfill %}\n{% endcomponent %}\n
The \"provider\" part of the provide / inject feature. Pass kwargs to this tag to define the provider's data. Any components defined within the {% provide %}..{% endprovide %} tags will be able to access this data with Component.inject().
This is similar to React's ContextProvider, or Vue's provide().
Args:
name (str, required): Provider name. This is the name you will then use in Component.inject().
**kwargs: Any extra kwargs will be passed as the provided data.
Since the \"child\" component is used within the {% provide %} / {% endprovide %} tags, we can request the \"user_data\" using Component.inject(\"user_data\"):
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n User is: {{ user }}\n </div>\n \"\"\"\n\n def get_context_data(self):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n
Notice that the keys defined on the {% provide %} tag are then accessed as attributes when accessing them with Component.inject().
"},{"location":"reference/template_tags/#passing-data-to-slots","title":"Passing data to slots","text":"
Any extra kwargs will be considered as slot data, and will be accessible in the {% fill %} tag via fill's data kwarg:
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
The content between the {% slot %}..{% endslot %} tags is the default content that will be rendered if no fill is given for the slot.
This default content can then be accessed from within the {% fill %} tag using the fill's default kwarg. This is useful if you need to wrap / prepend / append the original slot's content.
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" %}\n This is default content!\n {% endslot %}\n </div>\n \"\"\"\n
Dictonary describing which component slots are filled (True) or are not (False).
New in version 0.70
Use as {{ component_vars.is_filled }}
Example:
{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n <div class=\"slot-wrapper\">\n {% slot \"my_slot\" / %}\n </div>\n{% endif %}\n
This is equivalent to checking if a given key is among the slot fills:
class MyTable(Component):\n def get_context_data(self, *args, **kwargs):\n return {\n \"my_slot_filled\": \"my_slot\" in self.input.slots\n }\n
Below are all the URL patterns that will be added by adding django_components.urls.
See Installation on how to add these URLs to your Django project.
Django components already prefixes all URLs with components/. So when you are adding the URLs to urlpatterns, you can use an empty string as the first argument:
from django.urls import include, path\n\nurlpatterns = [\n ...\n path(\"\", include(\"django_components.urls\")),\n]\n
"},{"location":"reference/urls/#list-of-urls","title":"List of URLs","text":"
"}]}
\ No newline at end of file
+{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Welcome to Django Components","text":"
django-components introduces component-based architecture to Django's server-side rendering. It combines Django's templating system with the modularity seen in modern frontend frameworks like Vue or React.
\ud83e\udde9 Reusability: Allows creation of self-contained, reusable UI elements.
\ud83d\udce6 Encapsulation: Each component can include its own HTML, CSS, and JavaScript.
\ud83d\ude80 Server-side rendering: Components render on the server, improving initial load times and SEO.
\ud83d\udc0d Django integration: Works within the Django ecosystem, using familiar concepts like template tags.
\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.
One of our goals with django-components is to make it easy to share components between projects. If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.
django-htmx-components: A set of components for use with htmx. Try out the live demo.
"},{"location":"#contributing-and-development","title":"Contributing and development","text":"
Get involved or sponsor this project - See here
Running django-components locally for development - See here
Fix compatibility with custom subclasses of Django's Template that need to access origin or other initialization arguments. (https://github.com/EmilStenstrom/django-components/pull/828)
When you pass in request, the component will use RenderContext instead of Context. Thus the context processors will be applied to the context.
NOTE: When you pass in both request and context to Component.render(), and context is already an instance of Context, the request kwarg will be ignored.
Scripts in Component.Media.js are executed in the order they are defined
Scripts in Component.js are executed AFTER Media.js scripts
Fix compatibility with AlpineJS
Scripts in Component.Media.js are now again inserted as <script> tags
By default, Component.Media.js are inserted as synchronous <script> tags, so the AlpineJS components registered in the Media.js scripts will now again run BEFORE the core AlpineJS script.
AlpineJS can be configured like so:
Option 1 - AlpineJS loaded in <head> with defer attribute:
Prevent rendering Component tags during fill discovery stage to fix a case when a component inside the default slot tried to access provided data too early.
If your components include JS or CSS, you now must use the middleware and add django-components' URLs to your urlpatterns (See \"Adding support for JS and CSS\")
If you rendered a component A with Component.render() and then inserted that into another component B, now you must pass render_dependencies=False to component A:
Use get_component_dirs() and get_component_files() to get the same list of dirs / files that would be imported by autodiscover(), but without actually importing them.
The old uppercase settings CONTEXT_BEHAVIOR and TAG_FORMATTER are deprecated and will be removed in v1.
The setting reload_on_template_change was renamed to reload_on_file_change. And now it properly triggers server reload when any file in the component dirs change. The old name reload_on_template_change is deprecated and will be removed in v1.
The setting forbidden_static_files was renamed to static_files_forbidden to align with static_files_allowed The old name forbidden_static_files is deprecated and will be removed in v1.
{% component_dependencies %} tag was removed. Instead, use {% component_js_dependencies %} and {% component_css_dependencies %}
The combined tag was removed to encourage the best practice of putting JS scripts at the end of <body>, and CSS styles inside <head>.
On the other hand, co-locating JS script and CSS styles can lead to a flash of unstyled content, as either JS scripts will block the rendering, or CSS will load too late.
The undocumented keyword arg preload of {% component_js_dependencies %} and {% component_css_dependencies %} tags was removed. This will be replaced with HTML fragment support.
{% component_dependencies %} tags are now OPTIONAL - If your components use JS and CSS, but you don't use {% component_dependencies %} tags, the JS and CSS will now be, by default, inserted at the end of <body> and at the end of <head> respectively.
This means you can also have multiple slots with the same name but different conditions.
E.g. in this example, we have a component that renders a user avatar - a small circular image with a profile picture of name initials.
If the component is given image_src or name_initials variables, the image slot is optional. But if neither of those are provided, you MUST fill the image slot.
The slot fills that were passed to a component and which can be accessed as Component.input.slots can now be passed through the Django template, e.g. as inputs to other tags.
Internally, django-components handles slot fills as functions.
Previously, if you tried to pass a slot fill within a template, Django would try to call it as a function.
NOTE: Using {% slot %} and {% fill %} tags is still the preferred method, but the approach above may be necessary in some complex or edge cases.
The is_filled variable (and the {{ component_vars.is_filled }} context variable) now returns False when you try to access a slot name which has not been defined:
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.
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
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)
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)
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).
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.
{% 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.
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).
Changed the syntax for {% slot %} tags. From now on, we separate defining a slot ({% slot %}) from filling a slot with content ({% fill %}). This means you will likely need to change a lot of slot tags to fill.
We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice feature to have access to. Hoping that this will feel worth it!
All files inside components subdirectores are autoimported to simplify setup.
An existing project might start to get AlreadyRegistered errors because of this. To solve this, either remove your custom loading of components, or set \"autodiscover\": False in settings.COMPONENTS.
Renamed Component.context and Component.template to get_context_data and get_template_name. The old methods still work, but emit a deprecation warning.
This change was done to sync naming with Django's class based views, and make using django-components more familiar to Django users. Component.context and Component.template will be removed when version 1.0 is released.
As you can see above, this is also the place where we configure how our components should behave, using the settings argument. If omitted, default settings are used.
For library authors, we recommend setting context_behavior to \"isolated\", so that the state cannot leak into the components, and so the components' behavior is configured solely through the inputs. This means that the components will be more predictable and easier to debug.
Next, you can decide how will others use your components by setting the tag_formatter options.
If omitted or set to \"django_components.component_formatter\", your components will be used like this:
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
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.
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().
If you use components where the HTML / CSS / JS files are separate, you may need to define MANIFEST.in to include those files with the distribution (see user guide).
"},{"location":"concepts/advanced/authoring_component_libraries/#installing-and-using-component-libraries","title":"Installing and using component libraries","text":"
After the package has been published, all that remains is to install it in other django projects:
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
As you can see, @register links up the component class with the {% component %} template tag. So when the template tag comes across a component called \"calendar\", it can look up it's class and instantiate it.
"},{"location":"concepts/advanced/component_registry/#what-is-componentregistry","title":"What is ComponentRegistry","text":"
The @register decorator is a shortcut for working with the ComponentRegistry.
ComponentRegistry manages which components can be used in the template tags.
Each ComponentRegistry instance is associated with an instance of Django's Library. And Libraries are inserted into Django template using the {% load %} tags.
The @register decorator accepts an optional kwarg registry, which specifies, the ComponentRegistry to register components into. If omitted, the default ComponentRegistry instance defined in django_components is used.
The default ComponentRegistry is associated with the Library that you load when you call {% load component_tags %} inside your template, or when you add django_components.templatetags.component_tags to the template builtins.
So when you register or unregister a component to/from a component registry, then behind the scenes the registry automatically adds/removes the component's template tags to/from the Library, so you can call the component from within the templates such as {% component \"my_comp\" %}.
"},{"location":"concepts/advanced/component_registry/#working-with-componentregistry","title":"Working with ComponentRegistry","text":"
The default ComponentRegistry instance can be imported as:
from django_components import registry\n
You can use the registry to manually add/remove/get components:
from django_components import registry\n\n# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get all or single\nregistry.all() # {\"button\": ButtonComponent, \"card\": CardComponent}\nregistry.get(\"card\") # CardComponent\n\n# Unregister single component\nregistry.unregister(\"card\")\n\n# Unregister all components\nregistry.clear()\n
"},{"location":"concepts/advanced/component_registry/#registering-components-to-custom-componentregistry","title":"Registering components to custom ComponentRegistry","text":"
If you are writing a component library to be shared with others, you may want to manage your own instance of ComponentRegistry and register components onto a different Library instance than the default one.
The Library instance can be set at instantiation of ComponentRegistry. If omitted, then the default Library instance from django_components is used.
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.
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template:
def on_render_before(self, context, template) -> None:\n # Insert value into the Context\n context[\"from_on_before\"] = \":)\"\n\n # Append text into the Template\n template.nodelist.append(TextNode(\"FROM_ON_BEFORE\"))\n
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.
"},{"location":"concepts/advanced/provide_inject/","title":"Prop drilling and provide / inject","text":"
New in version 0.80:
Django components supports the provide / inject or ContextProvider pattern with the combination of:
{% provide %} tag
inject() method of the Component class
"},{"location":"concepts/advanced/provide_inject/#what-is-prop-drilling","title":"What is \"prop drilling\"?","text":"
Prop drilling refers to a scenario in UI development where you need to pass data through many layers of a component tree to reach the nested components that actually need the data.
Normally, you'd use props to send data from a parent component to its children. However, this straightforward method becomes cumbersome and inefficient if the data has to travel through many levels or if several components scattered at different depths all need the same piece of information.
This results in a situation where the intermediate components, which don't need the data for their own functioning, end up having to manage and pass along these props. This clutters the component tree and makes the code verbose and harder to manage.
A neat solution to avoid prop drilling is using the \"provide and inject\" technique.
With provide / inject, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.
This feature is inspired by Vue's Provide / Inject and React's Context / useContext.
"},{"location":"concepts/advanced/provide_inject/#how-to-use-provide-inject","title":"How to use provide / inject","text":"
As the name suggest, using provide / inject consists of 2 steps
Providing data
Injecting provided data
For examples of advanced uses of provide / inject, see this discussion.
"},{"location":"concepts/advanced/provide_inject/#using-provide-tag","title":"Using {% provide %} tag","text":"
First we use the {% provide %} tag to define the data we want to \"provide\" (make available).
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:
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.
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):
The instance returned from inject() is a subclass of NamedTuple, so the instance is immutable. This ensures that the data returned from inject will always have all the keys that were passed to the provide tag.
NOTE: inject() works strictly only in get_context_data. If you try to call it from elsewhere, it will raise an error.
"},{"location":"concepts/advanced/rendering_js_css/#setting-up-the-middleware","title":"Setting up the middleware","text":"
ComponentDependencyMiddleware is a Django middleware designed to manage and inject CSS / JS dependencies of rendered components dynamically. It ensures that only the necessary stylesheets and scripts are loaded in your HTML responses, based on the components used in your Django templates.
To set it up, add the middleware to your MIDDLEWARE in settings.py:
MIDDLEWARE = [\n # ... other middleware classes ...\n 'django_components.middleware.ComponentDependencyMiddleware'\n # ... other middleware classes ...\n]\n
"},{"location":"concepts/advanced/rendering_js_css/#render_dependencies-and-rendering-js-css-without-the-middleware","title":"render_dependencies and rendering JS / CSS without the middleware","text":"
For most scenarios, using the ComponentDependencyMiddleware middleware will be just fine.
However, this section is for you if you want to:
Render HTML that will NOT be sent as a server response
Insert pre-rendered HTML into another component
Render HTML fragments (partials)
Every time there is an HTML string that has parts which were rendered using components, and any of those components has JS / CSS, then this HTML string MUST be processed with render_dependencies().
It is actually render_dependencies() that finds all used components in the HTML string, and inserts the component's JS and CSS into {% component_dependencies %} tags, or at the default locations.
"},{"location":"concepts/advanced/rendering_js_css/#render-js-css-without-the-middleware","title":"Render JS / CSS without the middleware","text":"
The truth is that the ComponentDependencyMiddleware middleware just calls render_dependencies(), passing in the HTML content. So if you render a template that contained {% component %} tags, you MUST pass the result through render_dependencies(). And the middleware is just one of the options.
Here is how you can achieve the same, without the middleware, using render_dependencies():
Alternatively, when you render HTML with Component.render() or Component.render_to_response(), these, by default, call render_dependencies() for you, so you don't have to:
from django_components import Component\n\nclass MyButton(Component):\n ...\n\n# No need to call `render_dependencies()`\nrendered = MyButton.render()\n
"},{"location":"concepts/advanced/rendering_js_css/#inserting-pre-rendered-html-into-another-component","title":"Inserting pre-rendered HTML into another component","text":"
In previous section we've shown that render_dependencies() does NOT need to be called when you render a component via Component.render().
API of django_components makes it possible to compose components in a \"React-like\" way, where we pre-render a piece of HTML and then insert it into a larger structure.
To do this, you must add render_dependencies=False to the nested components:
This is a technical limitation of the current implementation.
As mentioned earlier, each time we call Component.render(), we also call render_dependencies().
However, there is a problem here - When we call render_dependencies() inside CardActions.render(), we extract and REMOVE the info on components' JS and CSS from the HTML. But the template of CardActions contains no {% component_depedencies %} tags, and nor <head> nor <body> HTML tags. So the component's JS and CSS will NOT be inserted, and will be lost.
To work around this, you must set render_dependencies=False when rendering pieces of HTML with Component.render() and inserting them into larger structures.
"},{"location":"concepts/advanced/tag_formatter/#writing-your-own-tagformatter","title":"Writing your own TagFormatter","text":""},{"location":"concepts/advanced/tag_formatter/#background","title":"Background","text":"
First, let's discuss how TagFormatters work, and how components are rendered in django_components.
When you render a component with {% component %} (or your own tag), the following happens:
component must be registered as a Django's template tag
Django triggers django_components's tag handler for tag component.
The tag handler passes the tag contents for pre-processing to TagFormatter.parse().
TagFormatter handles following parts of the process above:
Generates start/end tags, given a component. This is what you then call from within your template as {% component %}.
When you {% component %}, tag formatter pre-processes the tag contents, so it can link back the custom template tag to the right component.
To do so, subclass from TagFormatterABC and implement following method:
start_tag
end_tag
parse
For example, this is the implementation of ShorthandComponentFormatter
class ShorthandComponentFormatter(TagFormatterABC):\n # Given a component name, generate the start template tag\n def start_tag(self, name: str) -> str:\n return name # e.g. 'button'\n\n # Given a component name, generate the start template tag\n def end_tag(self, name: str) -> str:\n return f\"end{name}\" # e.g. 'endbutton'\n\n # Given a tag, e.g.\n # `{% button href=\"...\" disabled %}`\n #\n # The parser receives:\n # `['button', 'href=\"...\"', 'disabled']`\n def parse(self, tokens: List[str]) -> TagResult:\n tokens = [*tokens]\n name = tokens.pop(0)\n return TagResult(\n name, # e.g. 'button'\n tokens # e.g. ['href=\"...\"', 'disabled']\n )\n
That's it! And once your TagFormatter is ready, don't forget to update the settings!
"},{"location":"concepts/advanced/typing_and_validation/","title":"Typing and validation","text":""},{"location":"concepts/advanced/typing_and_validation/#adding-type-hints-with-generics","title":"Adding type hints with Generics","text":"
New in version 0.92
The Component class optionally accepts type parameters that allow you to specify the types of args, kwargs, slots, and data:
class Button(Component[Args, Kwargs, Slots, Data, JsData, CssData]):\n ...\n
Args - Must be a Tuple or Any
Kwargs - Must be a TypedDict or Any
Data - Must be a TypedDict or Any
Slots - Must be a TypedDict or Any
Here's a full example:
from typing import NotRequired, Tuple, TypedDict, SlotContent, SlotFunc\n\n# Positional inputs\nArgs = Tuple[int, str]\n\n# Kwargs inputs\nclass Kwargs(TypedDict):\n variable: str\n another: int\n maybe_var: NotRequired[int] # May be ommited\n\n# Data returned from `get_context_data`\nclass Data(TypedDict):\n variable: str\n\n# The data available to the `my_slot` scoped slot\nclass MySlotData(TypedDict):\n value: int\n\n# Slots\nclass Slots(TypedDict):\n # Use SlotFunc for slot functions.\n # The generic specifies the `data` dictionary\n my_slot: NotRequired[SlotFunc[MySlotData]]\n # SlotContent == Union[str, SafeString]\n another_slot: SlotContent\n\nclass Button(Component[Args, Kwargs, Slots, Data, JsData, CssData]):\n def get_context_data(self, variable, another):\n return {\n \"variable\": variable,\n }\n
When you then call Component.render or Component.render_to_response, you will get type hints:
Button.render(\n # Error: First arg must be `int`, got `float`\n args=(1.25, \"abc\"),\n # Error: Key \"another\" is missing\n kwargs={\n \"variable\": \"text\",\n },\n)\n
"},{"location":"concepts/advanced/typing_and_validation/#usage-for-python-311","title":"Usage for Python <3.11","text":"
On Python 3.8-3.10, use typing_extensions
from typing_extensions import TypedDict, NotRequired\n
Additionally on Python 3.8-3.9, also import annotations:
from __future__ import annotations\n
Moreover, on 3.10 and less, you may not be able to use NotRequired, and instead you will need to mark either all keys are required, or all keys as optional, using TypeDict's total kwarg.
See PEP-655 for more info.
"},{"location":"concepts/advanced/typing_and_validation/#passing-additional-args-or-kwargs","title":"Passing additional args or kwargs","text":"
You may have a function that supports any number of args or kwargs:
"},{"location":"concepts/advanced/typing_and_validation/#runtime-input-validation-with-types","title":"Runtime input validation with types","text":"
New in version 0.96
NOTE: Kwargs, slots, and data validation is supported only for Python >=3.11
In Python 3.11 and later, when you specify the component types, you will get also runtime validation of the inputs you pass to Component.render or Component.render_to_response.
So, using the example from before, if you ignored the type errors and still ran the following code:
Button.render(\n # Error: First arg must be `int`, got `float`\n args=(1.25, \"abc\"),\n # Error: Key \"another\" is missing\n kwargs={\n \"variable\": \"text\",\n },\n)\n
This would raise a TypeError:
Component 'Button' expected positional argument at index 0 to be <class 'int'>, got 1.25 of type <class 'float'>\n
In case you need to skip these errors, you can either set the faulty member to Any, e.g.:
# Changed `int` to `Any`\nArgs = Tuple[Any, str]\n
Or you can replace Args with Any altogether, to skip the validation of args:
Every component that you want to use in the template with the {% component %} tag needs to be registered with the ComponentRegistry. Normally, we use the @register decorator for that:
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n ...\n
But for the component to be registered, the code needs to be executed - the file needs to be imported as a module.
One way to do that is by importing all your components in apps.py:
from django.apps import AppConfig\n\nclass MyAppConfig(AppConfig):\n name = \"my_app\"\n\n def ready(self) -> None:\n from components.card.card import Card\n from components.list.list import List\n from components.menu.menu import Menu\n from components.button.button import Button\n ...\n
However, there's a simpler way!
By default, the Python files in the COMPONENTS.dirs directories (and app-level [app]/components/) are auto-imported in order to auto-register the components.
Autodiscovery occurs when Django is loaded, during the AppConfig.ready hook of the apps.py file.
If you are using autodiscovery, keep a few points in mind:
Avoid defining any logic on the module-level inside the components dir, that you would not want to run anyway.
Components inside the auto-imported files still need to be registered with @registerp
Auto-imported component files must be valid Python modules, they must use suffix .py, and module name should follow PEP-8.
Autodiscovery can be also triggered manually, using the autodiscover function. This is useful if you want to run autodiscovery at a custom point of the lifecycle:
from django_components import autodiscover\n\nautodiscover()\n
To get the same list of modules that autodiscover() would return, but without importing them, use get_component_files():
from django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
"},{"location":"concepts/fundamentals/component_context_scope/","title":"Component context and scope","text":"
By default, context variables are passed down the template as in regular Django - deeper scopes can access the variables from the outer scopes. So if you have several nested forloops, then inside the deep-most loop you can access variables defined by all previous loops.
With this in mind, the {% component %} tag behaves similarly to {% include %} tag - inside the component tag, you can access all variables that were defined outside of it.
And just like with {% include %}, if you don't want a specific component template to have access to the parent context, add only to the {% component %} tag:
{% component \"calendar\" date=\"2015-06-19\" only / %}\n
NOTE: {% csrf_token %} tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the only modifier.
If you find yourself using the only modifier often, you can set the context_behavior option to \"isolated\", which automatically applies the only modifier. This is useful if you want to make sure that components don't accidentally access the outer context.
Components can also access the outer context in their context methods like get_context_data by accessing the property self.outer_context.
"},{"location":"concepts/fundamentals/component_context_scope/#example-of-accessing-outer-context","title":"Example of Accessing Outer Context","text":"
<div>\n {% component \"calender\" / %}\n</div>\n
Assuming that the rendering context has variables such as date, you can use self.outer_context to access them from within get_context_data. Here's how you might implement it:
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.
django_components supports both Django and Vue-like behavior when it comes to passing data to and through components. This can be configured in context_behavior.
This has two modes:
\"django\"
The default Django template behavior.
Inside the {% fill %} tag, the context variables you can access are a union of:
All the variables that were OUTSIDE the fill tag, including any\\ {% with %} tags.
Any loops ({% for ... %}) that the {% fill %} tag is part of.
Data returned from Component.get_context_data() of the component that owns the fill tag.
\"isolated\"
Similar behavior to Vue or React, this is useful if you want to make sure that components don't accidentally access variables defined outside of the component.
Inside the {% fill %} tag, you can ONLY access variables from 2 places:
Any loops ({% for ... %}) that the {% fill %} tag is part of.
Component.get_context_data() of the component which defined the template (AKA the \"root\" component).
Warning
Notice that the component whose get_context_data() we use inside {% fill %} is NOT the same across the two modes!
\"django\" - my_var has access to data from get_context_data() of both Inner and Outer. If there are variables defined in both, then Inner overshadows Outer.
\"isolated\" - my_var has access to data from get_context_data() of ONLY Outer.
Then if get_context_data() of the component \"my_comp\" returns following data:
{ \"my_var\": 456 }\n
Then the template will be rendered as:
123 # my_var\n # cheese\n
Because variables \"my_var\" and \"cheese\" are searched only inside RootComponent.get_context_data(). But since \"cheese\" is not defined there, it's empty.
Info
Notice that the variables defined with the {% with %} tag are ignored inside the {% fill %} tag with the \"isolated\" mode.
"},{"location":"concepts/fundamentals/components_as_views/","title":"Components as views","text":"
New in version 0.34
Note: Since 0.92, Component no longer subclasses View. To configure the View class, set the nested Component.View class
Components can now be used as views:
Components define the Component.as_view() class method that can be used the same as View.as_view().
By default, you can define GET, POST or other HTTP handlers directly on the Component, same as you do with View. For example, you can override get and post to handle GET and POST requests, respectively.
In addition, Component now has a render_to_response method that renders the component template based on the provided context and slots' data and returns an HttpResponse object.
"},{"location":"concepts/fundamentals/components_as_views/#component-as-view-example","title":"Component as view example","text":"
Here's an example of a calendar component defined as a view:
# In a file called [project root]/components/calendar.py\nfrom django_components import Component, ComponentView, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n\n template = \"\"\"\n <div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" / %}\n </div>\n <div class=\"body\">\n Today's date is <span>{{ date }}</span>\n </div>\n </div>\n \"\"\"\n\n # Handle GET requests\n def get(self, request, *args, **kwargs):\n context = {\n \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n }\n slots = {\n \"header\": \"Calendar header\",\n }\n # Return HttpResponse with the rendered content\n return self.render_to_response(\n context=context,\n slots=slots,\n )\n
Then, to use this component as a view, you should create a urls.py file in your components directory, and add a path to the component's view:
# In a file called [project root]/components/urls.py\nfrom django.urls import path\nfrom components.calendar.calendar import Calendar\n\nurlpatterns = [\n path(\"calendar/\", Calendar.as_view()),\n]\n
Component.as_view() is a shorthand for calling View.as_view() and passing the component instance as one of the arguments.
Remember to add __init__.py to your components directory, so that Django can find the urls.py file.
Finally, include the component's urls in your project's urls.py file:
# In a file called [project root]/urls.py\nfrom django.urls import include, path\n\nurlpatterns = [\n path(\"components/\", include(\"components.urls\")),\n]\n
Note: Slots content are automatically escaped by default to prevent XSS attacks. To disable escaping, set escape_slots_content=False in the render_to_response method. If you do so, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.
If you're planning on passing an HTML string, check Django's use of format_html and mark_safe.
"},{"location":"concepts/fundamentals/components_as_views/#modifying-the-view-class","title":"Modifying the View class","text":"
The View class that handles the requests is defined on Component.View.
When you define a GET or POST handlers on the Component class, like so:
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.
If you want to define your own View class, you need to:
Set the class as Component.View
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.
"},{"location":"concepts/fundamentals/components_in_python/","title":"Components in Python","text":"
New in version 0.81
Components can be rendered outside of Django templates, calling them as regular functions (\"React-style\").
The component class defines render and render_to_response class methods. These methods accept positional args, kwargs, and slots, offering the same flexibility as the {% component %} tag:
"},{"location":"concepts/fundamentals/components_in_python/#inputs-of-render-and-render_to_response","title":"Inputs of render and render_to_response","text":"
Both render and render_to_response accept the same input:
args - Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %}
kwargs - Keyword args for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %}
slots - Component slot fills. This is the same as pasing {% fill %} tags to the component. Accepts a dictionary of { slot_name: slot_content } where slot_content can be a string or SlotFunc.
escape_slots_content - Whether the content from slots should be escaped. True by default to prevent XSS attacks. If you disable escaping, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.
context - A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template.
NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs.
request - A Django request object. This is used to enable Django template context_processors to run, allowing for template tags like {% csrf_token %} and variables like {{ debug }}.
Similar behavior can be achieved with provide / inject.
This is used internally to convert context to a RequestContext. It does nothing if context is already a Context instance.
"},{"location":"concepts/fundamentals/components_in_python/#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:
<!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":"concepts/fundamentals/defining_js_css_html_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":"concepts/fundamentals/defining_js_css_html_files/#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":"concepts/fundamentals/defining_js_css_html_files/#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__).
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.
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.
Both attrs and defaults are optional (can be omitted)
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.
All other kwargs are appended and can be repeated.
"},{"location":"concepts/fundamentals/html_attributes/#examples-for-html_attrs","title":"Examples for html_attrs","text":"
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 %}
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.
"},{"location":"concepts/fundamentals/html_attributes/#rendering-html-attributes-outside-of-templates","title":"Rendering HTML attributes outside of templates","text":"
If you need to use serialize HTML attributes outside of Django template and the html_attrs tag, you can use attributes_to_string:
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.
The slot tag now serves only to declare new slots inside the component template.
To override the content of a declared slot, use the newly introduced fill tag instead.
Whereas unfilled slots used to raise a warning, filling a slot is now optional by default.
To indicate that a slot must be filled, the new required option should be added at the end of the slot tag.
Components support something called 'slots'. When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content. This mechanism makes components more reusable and composable. This behavior is similar to slots in Vue.
In the example below we introduce two block tags that work hand in hand to make this work. These are...
{% slot <name> %}/{% endslot %}: Declares a new slot in the component template.
{% fill <name> %}/{% endfill %}: (Used inside a {% component %} tag pair.) Fills a declared slot with the specified content.
Let's update our calendar component to support more customization. We'll add slot tag pairs to its template, template.html.
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" %}Calendar header{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"body\" %}Today's date is <span>{{ date }}</span>{% endslot %}\n </div>\n</div>\n
When using the component, you specify which slots you want to fill and where you want to use the defaults from the template. It looks like this:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"body\" %}\n Can you believe it's already <span>{{ date }}</span>??\n {% endfill %}\n{% endcomponent %}\n
Since the 'header' fill is unspecified, it's taken from the base template. If you put this in a template, and pass in date=2020-06-06, this is what gets rendered:
<div class=\"calendar-component\">\n <div class=\"header\">\n Calendar header\n </div>\n <div class=\"body\">\n Can you believe it's already <span>2020-06-06</span>??\n </div>\n</div>\n
As seen in the previouse section, you can use {% fill slot_name %} to insert content into a specific slot.
You can define fills for multiple slot simply by defining them all within the {% component %} {% endcomponent %} tags:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}\n Hi this is header!\n {% endfill %}\n {% fill \"body\" %}\n Can you believe it's already <span>{{ date }}</span>??\n {% endfill %}\n{% endcomponent %}\n
You can also use {% for %}, {% with %}, or other non-component tags (even {% include %}) to construct the {% fill %} tags, as long as these other tags do not leave any text behind!
{% component \"table\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name %}\n {{ slot_name }}\n {% endfill %}\n {% endfor %}\n\n {% with slot_name=\"abc\" %}\n {% fill name=slot_name %}\n {{ slot_name }}\n {% endfill %}\n {% endwith %}\n{% endcomponent %}\n
As you can see, component slots lets you write reusable containers that you fill in when you use a component. This makes for highly reusable components that can be used in different circumstances.
It can become tedious to use fill tags everywhere, especially when you're using a component that declares only one slot. To make things easier, slot tags can be marked with an optional keyword: default.
When added to the tag (as shown below), this option lets you pass filling content directly in the body of a component tag pair \u2013 without using a fill tag. Choose carefully, though: a component template may contain at most one slot that is marked as default. The default option can be combined with other slot options, e.g. required.
Here's the same example as before, except with default slots and implicit filling.
The template:
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" %}Calendar header{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"body\" default %}Today's date is <span>{{ date }}</span>{% endslot %}\n </div>\n</div>\n
Including the component (notice how the fill tag is omitted):
{% component \"calendar\" date=\"2020-06-06\" %}\n Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n
You may be tempted to combine implicit fills with explicit fill tags. This will not work. The following component template will raise an error when rendered.
{# DON'T DO THIS #}\n{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}Totally new header!{% endfill %}\n Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n
Instead, you can use a named fill with name default to target the default fill:
{# THIS WORKS #}\n{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}Totally new header!{% endfill %}\n {% fill \"default\" %}\n Can you believe it's already <span>{{ date }}</span>??\n {% endfill %}\n{% endcomponent %}\n
NOTE: If you doubly-fill a slot, that is, that both {% fill \"default\" %} and {% fill \"header\" %} would point to the same slot, this will raise an error when rendered.
"},{"location":"concepts/fundamentals/slots/#accessing-default-slot-in-python","title":"Accessing default slot in Python","text":"
Since the default slot is stored under the slot name default, you can access the default slot like so:
Since each slot is tagged individually, you can have multiple slots with the same name but different conditions.
E.g. in this example, we have a component that renders a user avatar - a small circular image with a profile picture or name initials.
If the component is given image_src or name_initials variables, the image slot is optional. But if neither of those are provided, you MUST fill the image slot.
"},{"location":"concepts/fundamentals/slots/#accessing-original-content-of-slots","title":"Accessing original content of slots","text":"
Added in version 0.26
NOTE: In version 0.77, the syntax was changed from
{% fill \"my_slot\" as \"alias\" %} {{ alias.default }}\n
to
{% fill \"my_slot\" default=\"slot_default\" %} {{ slot_default }}\n
Sometimes you may want to keep the original slot, but only wrap or prepend/append content to it. To do so, you can access the default slot via the default kwarg.
Similarly to the data attribute, you specify the variable name through which the default slot will be made available.
For instance, let's say you're filling a slot called 'body'. To render the original slot, assign it to a variable using the 'default' keyword. You then render this variable to insert the default content:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"body\" default=\"body_default\" %}\n {{ body_default }}. Have a great day!\n {% endfill %}\n{% endcomponent %}\n
This produces:
<div class=\"calendar-component\">\n <div class=\"header\">\n Calendar header\n </div>\n <div class=\"body\">\n Today's date is <span>2020-06-06</span>. Have a great day!\n </div>\n</div>\n
To access the original content of a default slot, set the name to default:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"default\" default=\"slot_default\" %}\n {{ slot_default }}. Have a great day!\n {% endfill %}\n{% endcomponent %}\n
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:
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:
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.
Sometimes you're not interested in whether a slot is filled, but rather that it isn't. To negate the meaning of component_vars.is_filled, simply treat it as boolean and negate it with not:
{% if not component_vars.is_filled.subtitle %}\n<div class=\"subtitle\">\n {% slot \"subtitle\" / %}\n</div>\n{% endif %}\n
"},{"location":"concepts/fundamentals/slots/#accessing-is_filled-of-slot-names-with-special-characters","title":"Accessing is_filled of slot names with special characters","text":"
To be able to access a slot name via component_vars.is_filled, the slot name needs to be composed of only alphanumeric characters and underscores (e.g. this__isvalid_123).
However, you can still define slots with other special characters. In such case, the slot name in component_vars.is_filled is modified to replace all invalid characters into _.
So a slot named \"my super-slot :)\" will be available as component_vars.is_filled.my_super_slot___.
Same applies when you are accessing is_filled from within the Python, e.g.:
class MyTable(Component):\n def on_render_before(self, context, template) -> None:\n # \u2705 Works\n if self.is_filled[\"my_super_slot___\"]:\n # Do something\n\n # \u274c Does not work\n if self.is_filled[\"my super-slot :)\"]:\n # Do something\n
Similarly, you can use {% if %} and {% for %} when defining the {% fill %} tags, to conditionally fill the slots when using the componnet:
In the example below, the {% fill \"footer\" %} fill is used only if the condition is true. If falsy, the fill is ignored, and so the my_table component will use its default content for the footer slot.
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:
"},{"location":"concepts/fundamentals/slots/#accessing-slot-data-in-fill","title":"Accessing slot data in fill","text":"
Next, we head over to where we define a fill for this slot. Here, to access the slot data we set the data attribute to the name of the variable through which we want to access the slot data. In the example below, we set it to data:
"},{"location":"concepts/fundamentals/slots/#dynamic-slots-and-fills","title":"Dynamic slots and fills","text":"
Until now, we were declaring slot and fill names statically, as a string literal, e.g.
{% slot \"content\" / %}\n
However, sometimes you may want to generate slots based on the given input. One example of this is a table component like that of Vuetify, which creates a header and an item slots for each user-defined column.
In django_components you can achieve the same, simply by using a variable (or a template expression) instead of a string literal:
{% 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:
"},{"location":"concepts/fundamentals/template_tag_syntax/","title":"Template tag syntax","text":"
All template tags in django_component, like {% component %} or {% slot %}, and so on, support extra syntax that makes it possible to write components like in Vue or React (JSX).
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 %}:
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
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.
Component test receives a positional argument with value \"As positional arg \". The comment is omitted.
Kwarg title is passed as a string, e.g. John Doe
Kwarg id is passed as int, e.g. 15
Kwarg readonly is passed as bool, e.g. False
Kwarg author is passed as a string, e.g. John Wick (Comment omitted)
This is inspired by django-cotton.
"},{"location":"concepts/fundamentals/template_tag_syntax/#passing-data-as-string-vs-original-values","title":"Passing data as string vs original values","text":"
Sometimes you may want to use the template tags to transform or generate the data that is then passed to the component.
The data doesn't necessarily have to be strings. In the example above, the kwarg id was passed as an integer, NOT a string.
Although the string literals for components inputs are treated as regular Django templates, there is one special case:
When the string literal contains only a single template tag, with no extra text, then the value is passed as the original type instead of a string.
{% component 'cat_list' items=\"{{ cats|slice:':2' }} See more\" / %}\n
"},{"location":"concepts/fundamentals/template_tag_syntax/#evaluating-python-expressions-in-template","title":"Evaluating Python expressions in template","text":"
You can even go a step further and have a similar experience to Vue or React, where you can evaluate arbitrary code expressions:
Note: Never use this feature to mix business logic and template logic. Business logic should still be in the view!
"},{"location":"concepts/fundamentals/template_tag_syntax/#pass-dictonary-by-its-key-value-pairs","title":"Pass dictonary by its key-value pairs","text":"
New in version 0.74:
Sometimes, a component may expect a dictionary as one of its inputs.
Most commonly, this happens when a component accepts a dictionary of HTML attributes (usually called attrs) to pass to the underlying template.
In such cases, we may want to define some HTML attributes statically, and other dynamically. But for that, we need to define this dictionary on Python side:
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:
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":"devguides/dependency_mgmt/","title":"JS and CSS rendering","text":"
Aim of this doc is to share the intuition on how we manage the JS and CSS (\"dependencies\") associated with components, and how we render them.
First of all, when we consider a component, it has two kind of dependencies - the \"inlined\" JS and CSS, and additional linked JS and CSS via Media.js/css:
Second thing to keep in mind is that all component's are eventually rendered into a string. And so, if we want to associate extra info with a rendered component, it has to be serialized to a string.
This is because a component may be embedded in a Django Template with the {% component %} tag, which, when rendered, is turned into a string:
And for this reason, we take the same approach also when we render a component with Component.render() - It returns a string.
Thirdly, we also want to add support for JS / CSS variables. That is, that a variable defined on the component would be somehow accessible from within the JS script / CSS style.
A simple approach to this would be to modify the inlined JS / CSS directly, and insert them for each component. But if you had extremely large JS / CSS, and e.g. only a single JS / CSS variable that you want to insert, it would be extremely wasteful to copy-paste the JS / CSS for each component instance.
So instead, a preferred approach here is to defined and insert the inlined JS / CSS only once, and have some kind of mechanism on how we make correct the JS / CSS variables available only to the correct components.
Last important thing is that we want the JS / CSS dependencies to work also with HTML fragments.
So normally, e.g. when a user hits URL of a web page, the server renders full HTML document, with <!doctype>, <html>, <head>, and <body>. In such case, we know about ALL JS and CSS dependencies at render time, so we can e.g. insert them into <head> and <body> ourselves.
However this renders only the initial state. HTML fragments is a common pattern where interactivity is added to the web page by fetching and replacing bits of HTML on the main HTML document after some user action.
In the case of HTML fragments, the HTML is NOT a proper document, but only the HTML that will be inserted somewhere into the DOM.
The challenge here is that Django template for the HTML fragment MAY contain components, and these components MAY have inlined or linked JS and CSS.
User may use different libraries to fetch and insert the HTML fragments (e.g. HTMX, AlpineJS, ...). From our perspective, the only thing that we can reliably say is that we expect that the HTML fragment WILL be eventually inserted into the DOM.
So to include the corresponding JS and CSS, a simple approach could be to append them to the HTML as <style> and <script>, e.g.:
The JS scripts would run for each instance of the component.
Bloating of the HTML file, as each inlined JS or CSS would be included fully for each component.
While this sound OK, this could really bloat the HTML files if we used a UI component library for the basic building blocks like buttons, lists, cards, etc.
So the solution should address all the points above. To achieve that, we manage the JS / CSS dependencies ourselves in the browser. So when a full HTML document is loaded, we keep track of which JS and CSS have been loaded. And when an HTML fragment is inserted, we check which JS / CSS dependencies it has, and load only those that have NOT been loaded yet.
This is how we achieve that:
When a component is rendered, it inserts an HTML comment containing metadata about the rendered component.
Each <!-- _RENDERED --> comment includes comma-separated data - a unique hash for the component class, e.g. my_table_10bc2c, and the component ID, e.g. c020ad.
This way, we or the user can freely pass the rendered around or transform it, treating it as a string to add / remove / replace bits. As long as the <!-- _RENDERED --> comments remain in the rendered string, we will be able to deduce which JS and CSS dependencies the component needs.
Post-process the rendered HTML, extracting the <!-- _RENDERED --> comments, and instead inserting the corresponding JS and CSS dependencies.
If we dealt only with JS, then we could get away with processing the <!-- _RENDERED --> comments on the client (browser). However, the CSS needs to be processed still on the server, so the browser receives CSS styles already inserted as <style> or <link> HTML tags. Because if we do not do that, we get a flash of unstyled content, as there will be a delay between when the HTML page loaded and when the CSS was fetched and loaded.
So, assuming that a user has already rendered their template, which still contains <!-- _RENDERED --> comments, we need to extract and process these comments.
There's multiple ways to achieve this:
The approach recommended to the users is to use the ComponentDependencyMiddleware middleware, which scans all outgoing HTML, and post-processes the <!-- _RENDERED --> comments.
If users are using Component.render() or Component.render_to_response(), these post-process the <!-- _RENDERED --> comments by default.
NOTE: Users are able to opt out of the post-processing by setting render_dependencies=False.
For advanced use cases, users may use render_dependencies() directly. This is the function that both ComponentDependencyMiddleware and Component.render() call internally.
render_dependencies(), whether called directly, via middleware or other way, does the following:
Find all <!-- _RENDERED --> comments, and for each comment:
Look up the corresponding component class.
Get the component's inlined JS / CSS from Component.js/css, and linked JS / CSS from Component.Media.js/css.
Generate JS script that loads the JS / CSS dependencies.
Insert the JS scripts either at the end of <body>, or in place of {% component_dependencies %} / {% component_js_dependencies %} tags.
To avoid the flash of unstyled content, we need place the styles into the HTML instead of dynamically loading them from within a JS script. The CSS is placed either at the end of <head>, or in place of {% component_dependencies %} / {% component_css_dependencies %}
We cache the component's inlined JS and CSS, so they can be fetched via an URL, so the inlined JS / CSS an be treated the same way as the JS / CSS dependencies set in Component.Media.js/css.
NOTE: While this is currently not entirely necessary, it opens up the doors for allowing plugins to post-process the inlined JS and CSS. Because after it has been post-processed, we need to store it somewhere.
Server returns the post-processed HTML.
In the browser, the generated JS script from step 2.4 is executed. It goes through all JS and CSS dependencies it was given. If some JS / CSS was already loaded, it is NOT fetched again. Otherwise it generates the corresponding <script> or <link> HTML tags to load the JS / CSS dependencies.
In the browser, the \"dependency manager JS\" may look like this:
// Load JS or CSS script if not loaded already\nComponents.loadJs('<script src=\"/abc/xyz/script.js\">');\nComponents.loadCss('<link href=\"/abc/xyz/style.css\">');\n\n// Or mark one as already-loaded, so it is ignored when\n// we call `loadJs`\nComponents.markScriptLoaded(\"js\", \"/abc/def\");\n
Note that loadJs() / loadCss() receive whole <script> / <link> tags, not just the URL. This is because when Django's Media class renders JS and CSS, it formats it as <script> and <link> tags. And we allow users to modify how the JS and CSS should be rendered into the <script> and <link> tags.
So, if users decided to add an extra attribute to their <script> tags, e.g. <script defer src=\"http://...\"></script>, then this way we make sure that the defer attribute will be present on the <script> tag when it is inserted into the DOM at the time of loading the JS script.
To be able to fetch component's inlined JS and CSS, django-components adds a URL path under:
Variables for names and for loops allow us implement \"passthrough slots\" - that is, taking all slots that our component received, and passing them to a child component, dynamically.
Given the above, we want to render the slots with {% fill %} tag that were defined OUTSIDE of this template. How do I do that?
NOTE: Before v0.110, slots were resolved statically, by walking down the Django Template and Nodes. However, this did not allow for using for loops or other variables defined in the template.
Currently, this consists of 2 steps:
If a component is rendered within a template using {% component %} tag, determine the given {% fill %} tags in the component's body (the content in between {% component %} and {% endcomponent %}).
After this step, we know about all the fills that were passed to the component.
Then we simply render the template as usual. And then we reach the {% slot %} tag, we search the context for the available fills.
If there IS a fill with the same name as the slot, we render the fill.
If the slot is marked default, and there is a fill named default, then we render that.
Otherwise, we render the slot's default content.
Obtaining the fills from {% fill %}.
When a component is rendered with {% component %} tag, and it has some content in between {% component %} and {% endcomponent %}, we want to figure out if that content is a default slot (no {% fill %} used), or if there is a collection of named {% fill %} tags:
To respect any forloops or other variables defined within the template to which the fills may have access, we:
Render the content between {% component %} and {% endcomponent %} using the context outside of the component.
When we reach a {% fill %} tag, we capture any variables that were created between the {% component %} and {% fill %} tags.
When we reach {% fill %} tag, we do not continue rendering deeper. Instead we make a record that we found the fill tag with given name, kwargs, etc.
After the rendering is done, we check if we've encountered any fills. If yes, we expect only named fills. If no, we assume that the the component's body is a default slot.
Lastly we process the found fills, and make them available to the context, so any slots inside the component may access these fills.
Rendering slots
Slot rendering works similarly to collecting fills, in a sense that we do not search for the slots ahead of the time, but instead let Django handle the rendering of the template, and we step in only when Django come across as {% slot %} tag.
When we reach a slot tag, we search the context for the available fills.
If there IS a fill with the same name as the slot, we render the fill.
If the slot is marked default, and there is a fill named default, then we render that.
Otherwise, we render the slot's default content.
"},{"location":"devguides/slot_rendering/#using-the-correct-context-in-slotfill-tags","title":"Using the correct context in {% slot/fill %} tags","text":"
In previous section, we said that the {% fill %} tags should be already rendered by the time they are inserted into the {% slot %} tags.
This is not quite true. To help you understand, consider this complex case:
| -- {% for var in [1, 2, 3] %} ---\n| ---- {% component \"mycomp2\" %} ---\n| ------ {% fill \"first\" %}\n| ------- STU {{ my_var }}\n| ------- {{ var }}\n| ------ {% endfill %}\n| ------ {% fill \"second\" %}\n| -------- {% component var=var my_var=my_var %}\n| ---------- VWX {{ my_var }}\n| -------- {% endcomponent %}\n| ------ {% endfill %}\n| ---- {% endcomponent %} ---\n| -- {% endfor %} ---\n| -------\n
We want the forloop variables to be available inside the {% fill %} tags. Because of that, however, we CANNOT render the fills/slots in advance.
Instead, our solution is closer to how Vue handles slots. In Vue, slots are effectively functions that accept a context variables and render some content.
While we do not wrap the logic in a function, we do PREPARE IN ADVANCE: 1. The content that should be rendered for each slot 2. The context variables from get_context_data()
Thus, once we reach the {% slot %} node, in it's render() method, we access the data above, and, depending on the context_behavior setting, include the current context or not. For more info, see SlotNode.render().
"},{"location":"devguides/slots_and_blocks/","title":"Using slot and block tags","text":"
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
Will still render the component content just the same:
<div>hello 1 XYZ</div>\n
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:
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:
"},{"location":"guides/setup/dev_server_setup/","title":"Running with development server","text":""},{"location":"guides/setup/dev_server_setup/#reload-dev-server-on-component-file-changes","title":"Reload dev server on component file changes","text":"
This is relevant if you are using the project structure as shown in our examples, where HTML, JS, CSS and Python are in separate files and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.
From relevant StackOverflow thread:
TL;DR is that the server won't reload if it thinks the changed file is in a templates directory, or in a nested sub directory of a templates directory. This is by design.
To make the dev server reload on all component files, set reload_on_file_change to True. This configures Django to watch for component files too.
Note
This setting should be enabled only for the dev environment!
"},{"location":"guides/setup/logging_and_debugging/","title":"Logging and debugging","text":"
Django components supports logging with Django. This can help with troubleshooting.
To configure logging for Django components, set the django_components logger in LOGGING in settings.py (below).
Also see the settings.py file in sampleproject for a real-life example.
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":"guides/setup/syntax_highlight/#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:
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":"overview/code_of_conduct/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"overview/code_of_conduct/#our-pledge","title":"Our Pledge","text":"
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
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.
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.
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.
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
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.
Another way you can get involved is by donating to the development of django_components.
"},{"location":"overview/development/","title":"Development","text":""},{"location":"overview/development/#install-locally-and-run-the-tests","title":"Install locally and run the tests","text":"
Start by forking the project by clicking the Fork button up in the right corner in the GitHub . This makes a copy of the repository in your own name. Now you can clone this repository locally and start adding features:
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:
Make sure you are inside src/django_components_js:
cd src/django_components_js\n
Install the JS dependencies
npm install\n
Compile the JS/TS code:
python build.py\n
The script will combine all JS/TS code into a single .js file, minify it, and copy it to django_components/static/django_components/django_components.min.js.
"},{"location":"overview/development/#packaging-and-publishing","title":"Packaging and publishing","text":"
To package the library into a distribution that can be published to PyPI, run:
# Install pypa/build\npython -m pip install build --user\n# Build a binary wheel and a source tarball\npython -m build --sdist --wheel --outdir dist/ .\n
To publish the package to PyPI, use twine (See Python user guide):
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.
Next, to make Django load component HTML files as Django templates, modify TEMPLATES section of settings.py as follows:
Remove 'APP_DIRS': True,
NOTE: Instead of APP_DIRS, for the same effect, we will use django.template.loaders.app_directories.Loader
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
"},{"location":"overview/installation/#adding-support-for-js-and-css","title":"Adding support for JS and CSS","text":"
If you want to use JS or CSS with components, you will need to:
Modify STATICFILES_FINDERS section of settings.py as follows to be able to serve the component JS and CSS files as static files:
Add ComponentDependencyMiddleware to MIDDLEWARE setting.
The middleware searches the outgoing HTML for all components that were rendered to generate the HTML, and adds the JS and CSS associated with those components.
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.
Components can be organized however you prefer. That said, our prefered way is to keep the files of a component close together by bundling them in the same directory.
This means that files containing backend logic, such as Python modules and HTML templates, live in the same directory as static files, e.g. JS and CSS.
From v0.100 onwards, we keep component files (as defined by COMPONENTS.dirs and COMPONENTS.app_dirs) separate from the rest of the static files (defined by STATICFILES_DIRS). That way, the Python and HTML files are NOT exposed by the server. Only the static JS, CSS, and other common formats.
NOTE: If you need to expose different file formats, you can configure these with COMPONENTS.static_files_allowed and COMPONENTS.static_files_forbidden.
"},{"location":"overview/security_notes/#static-files-prior-to-v0100","title":"Static files prior to v0.100","text":"
Prior to v0.100, if your were using django.contrib.staticfiles to collect static files, no distinction was made between the different kinds of files.
As a result, your Python code and templates may inadvertently become available on your static file server. You probably don't want this, as parts of your backend logic will be exposed, posing a potential security vulnerability.
From v0.27 until v0.100, django-components shipped with an additional installable app django_components.safer_staticfiles. It was a drop-in replacement for django.contrib.staticfiles. Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server. To use it, add it to INSTALLED_APPS and remove django.contrib.staticfiles.
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":"overview/welcome/","title":"Welcome to Django Components","text":"
django-components introduces component-based architecture to Django's server-side rendering. It combines Django's templating system with the modularity seen in modern frontend frameworks like Vue or React.
\ud83e\udde9 Reusability: Allows creation of self-contained, reusable UI elements.
\ud83d\udce6 Encapsulation: Each component can include its own HTML, CSS, and JavaScript.
\ud83d\ude80 Server-side rendering: Components render on the server, improving initial load times and SEO.
\ud83d\udc0d Django integration: Works within the Django ecosystem, using familiar concepts like template tags.
\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.
One of our goals with django-components is to make it easy to share components between projects. If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.
django-htmx-components: A set of components for use with htmx. Try out the live demo.
"},{"location":"overview/welcome/#contributing-and-development","title":"Contributing and development","text":"
Get involved or sponsor this project - See here
Running django-components locally for development - See here
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.
Inputs: - args - Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %} - kwargs - Kwargs for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %} - slots - Component slot fills. This is the same as pasing {% fill %} tags to the component. Accepts a dictionary of { slot_name: slot_content } where slot_content can be a string or render function. - escape_slots_content - Whether the content from slots should be escaped. - context - A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. - type - Configure how to handle JS and CSS dependencies. - \"document\" (default) - JS dependencies are inserted into {% component_js_dependencies %}, or to the end of the <body> tag. CSS dependencies are inserted into {% component_css_dependencies %}, or the end of the <head> tag. - render_dependencies - Set this to False if you want to insert the resulting HTML into another component. - request - The request object. This is only required when needing to use RequestContext, e.g. to enable template context_processors. Unused if context is already an instance of Context Example:
Render the component and wrap the content in the response class.
The response class is taken from Component.response_class. Defaults to django.http.HttpResponse.
This is the interface for the django.views.View class which allows us to use components as Django views with component.as_view().
Inputs: - args - Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %} - kwargs - Kwargs for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %} - slots - Component slot fills. This is the same as pasing {% fill %} tags to the component. Accepts a dictionary of { slot_name: slot_content } where slot_content can be a string or render function. - escape_slots_content - Whether the content from slots should be escaped. - context - A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. - type - Configure how to handle JS and CSS dependencies. - \"document\" (default) - JS dependencies are inserted into {% component_js_dependencies %}, or to the end of the <body> tag. CSS dependencies are inserted into {% component_css_dependencies %}, or the end of the <head> tag. - request - The request object. This is only required when needing to use RequestContext, e.g. to enable template context_processors. Unused if context is already an instance of Context
Any additional args and kwargs are passed to the response_class.
To enable a component to be used in a template, the component must be registered with a component registry.
When you register a component to a registry, behind the scenes the registry automatically adds the component's template tag (e.g. {% component %} to the Library. And the opposite happens when you unregister a component - the tag is removed.
See Registering components.
Parameters:
library (Library, default: None ) \u2013
Django Library associated with this registry. If omitted, the default Library instance from django_components is used.
Configure how the components registered with this registry will behave when rendered. See RegistrySettings. Can be either a static value or a callable that returns the settings. If omitted, the settings from COMPONENTS are used.
Notes:
The default registry is available as django_components.registry.
The default registry is used when registering components with @register decorator.
Example:
# Use with default Library\nregistry = ComponentRegistry()\n\n# Or a custom one\nmy_lib = Library()\nregistry = ComponentRegistry(library=my_lib)\n\n# Usage\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\nregistry.all()\nregistry.clear()\nregistry.get()\n
"},{"location":"reference/api/#django_components.ComponentRegistry--using-registry-to-share-components","title":"Using registry to share components","text":"
You can use component registry for isolating or \"packaging\" components:
Create new instance of ComponentRegistry and Library:
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
Dictonary describing which component slots are filled (True) or are not (False).
New in version 0.70
Use as {{ component_vars.is_filled }}
Example:
{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n <div class=\"slot-wrapper\">\n {% slot \"my_slot\" / %}\n </div>\n{% endif %}\n
This is equivalent to checking if a given key is among the slot fills:
class MyTable(Component):\n def get_context_data(self, *args, **kwargs):\n return {\n \"my_slot_filled\": \"my_slot\" in self.input.slots\n }\n
Configure whether, inside a component template, you can use variables from the outside (\"django\") or not (\"isolated\"). This also affects what variables are available inside the {% fill %} tags.
Configure extra python modules that should be loaded.
This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.
Expects a list of python module paths. Defaults to empty list.
This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.
Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.
The setting reload_on_file_change fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.
If True, django_components configures Django to reload when files inside COMPONENTS.dirs or COMPONENTS.app_dirs change.
See Reload dev server on component file changes.
Defaults to False.
Warning
This setting should be enabled only for the dev environment!
A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs are treated as static files.
If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running collectstatic, and can be accessed under the static file endpoint.
You can also pass in compiled regexes (re.Pattern) for more advanced patterns.
By default, JS, CSS, and common image and font file formats are considered static files:
A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs will NEVER be treated as static files.
If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in static_files_allowed.
Use this setting together with static_files_allowed for a fine control over what file types will be exposed.
You can also pass in compiled regexes (re.Pattern) for more advanced patterns.
By default, any HTML and Python are considered NOT static files:
Configure the maximum amount of Django templates to be cached.
Defaults to 128.
Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.
By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding Component.get_template() to render many dynamic templates, you can increase this number.
This setting makes the component fills behave similar to Vue or React, where the fills use EXCLUSIVELY the context variables defined in Component.get_context_data().
You can use this to define a Component that accepts NO kwargs, or NO slots, or returns NO data from Component.get_context_data() / Component.get_js_data() / Component.get_css_data():
Going back to the example with NO kwargs, when you then call Component.render() or Component.render_to_response(), the kwargs parameter will raise type error if kwargs is anything else than an empty dict.
Table.render(\n kwargs: {},\n)\n
Omitting kwargs is also fine:
Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
After that, when you call Component.render() or Component.render_to_response(), the args parameter will raise type error if args is anything else than an empty tuple.
Table.render(\n args: (),\n)\n
Omitting args is also fine:
Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
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.
Given the tokens (words) passed to a component start tag, this function extracts the component name from the tokens list, and returns TagResult, which is a tuple of (component_name, remaining_tokens).
Parameters:
tokens ([List(str]) \u2013
List of tokens passed to the component tag.
Returns:
TagResult ( TagResult ) \u2013
Parsed component name and remaining tokens.
Example:
Assuming we used a component in a template like this:
This is the heart of all features that deal with filesystem and file lookup. Autodiscovery, Django template resolution, static file resolution - They all use this.
Parameters:
include_apps (bool, default: True ) \u2013
Include directories from installed Django apps. Defaults to True.
Returns:
List[Path] \u2013
List[Path]: A list of directories that may contain component files.
get_component_dirs() searches for dirs set in COMPONENTS.dirs settings. If none set, defaults to searching for a \"components\" app.
In addition to that, also all installed Django apps are checked whether they contain directories as set in COMPONENTS.app_dirs (e.g. [app]/components).
Notes:
Paths that do not point to directories are ignored.
BASE_DIR setting is required.
The paths in COMPONENTS.dirs must be absolute paths.
Given a string that contains parts that were rendered by components, this function inserts all used JS and CSS.
By default, the string is parsed as an HTML and: - CSS is inserted at the end of <head> (if present) - JS is inserted at the end of <body> (if present)
If you used {% component_js_dependencies %} or {% component_css_dependencies %}, then the JS and CSS will be inserted only at these locations.
The Python path to a settings module, e.g. \"myproject.settings.main\". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used.
--pythonpath PYTHONPATH
A directory to add to the Python path, e.g. \"/home/djangoprojects/myproject\".
The name of the component to create. This is a required argument.
Options:
-h, --help
show this help message and exit
--path PATH
The path to the component's directory. This is an optional argument. If not provided, the command will use the COMPONENTS.dirs setting from your Django settings.
--js JS
The name of the JavaScript file. This is an optional argument. The default value is script.js.
--css CSS
The name of the CSS file. This is an optional argument. The default value is style.css.
--template TEMPLATE
The name of the template file. This is an optional argument. The default value is template.html.
--force
This option allows you to overwrite existing files if they exist. This is an optional argument.
--verbose
This option allows the command to print additional information during component creation. This is an optional argument.
--dry-run
This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False.
The Python path to a settings module, e.g. \"myproject.settings.main\". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used.
--pythonpath PYTHONPATH
A directory to add to the Python path, e.g. \"/home/djangoprojects/myproject\".
Here are some examples of how you can use the command:
"},{"location":"reference/commands/#creating-a-component-with-default-settings","title":"Creating a Component with Default Settings","text":"
To create a component with the default settings, you only need to provide the name of the component:
python manage.py startcomponent my_component\n
This will create a new component named my_component in the components directory of your Django project. The JavaScript, CSS, and template files will be named script.js, style.css, and template.html, respectively.
"},{"location":"reference/commands/#creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"
You can also create a component with custom settings by providing additional arguments:
This will create a new component named new_component in the my_components directory. The JavaScript, CSS, and template files will be named my_script.js, my_style.css, and my_template.html, respectively.
"},{"location":"reference/commands/#overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"
If you want to overwrite an existing component, you can use the --force option:
Dynamic components are suitable if you are writing something like a form component. You may design it such that users give you a list of input types, and you render components depending on the input types.
While you could handle this with a series of if / else statements, that's not an extensible approach. Instead, you can use the dynamic component in place of normal components.
By default, the dynamic component is registered under the name \"dynamic\". In case of a conflict, you can set the COMPONENTS.dynamic_component_name setting to change the name used for the dynamic components.
The way the TagFormatter works is that, based on which start and end tags are used for rendering components, the ComponentRegistry behind the scenes un-/registers the template tags with the associated instance of Django's Library.
In other words, if I have registered a component \"table\", and I use the shorthand syntax:
{% table ... %}\n{% endtable %}\n
Then ComponentRegistry registers the tag table onto the Django's Library instance.
However, that means that if we registered a component \"slot\", then we would overwrite the {% slot %} tag from django_components.
Thus, this exception is raised when a component is attempted to be registered under a forbidden name, such that it would overwrite one of django_component's own template tags.
You can configure django_components with a global COMPONENTS variable in your Django settings file, e.g. settings.py. By default you don't need it set, there are resonable defaults.
To configure the settings you can instantiate ComponentsSettings for validation and type hints. Or, for backwards compatibility, you can also use plain dictionary:
Configure whether, inside a component template, you can use variables from the outside (\"django\") or not (\"isolated\"). This also affects what variables are available inside the {% fill %} tags.
Configure extra python modules that should be loaded.
This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.
Expects a list of python module paths. Defaults to empty list.
This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.
Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.
The setting reload_on_file_change fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.
If True, django_components configures Django to reload when files inside COMPONENTS.dirs or COMPONENTS.app_dirs change.
See Reload dev server on component file changes.
Defaults to False.
Warning
This setting should be enabled only for the dev environment!
A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs are treated as static files.
If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running collectstatic, and can be accessed under the static file endpoint.
You can also pass in compiled regexes (re.Pattern) for more advanced patterns.
By default, JS, CSS, and common image and font file formats are considered static files:
A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs will NEVER be treated as static files.
If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in static_files_allowed.
Use this setting together with static_files_allowed for a fine control over what file types will be exposed.
You can also pass in compiled regexes (re.Pattern) for more advanced patterns.
By default, any HTML and Python are considered NOT static files:
Configure the maximum amount of Django templates to be cached.
Defaults to 128.
Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.
By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding Component.get_template() to render many dynamic templates, you can increase this number.
The original django_component's component tag formatter, it uses the {% component %} and {% endcomponent %} tags, and the component name is given as the first positional arg.
"},{"location":"reference/template_tags/#inserting-into-slots","title":"Inserting into slots","text":"
If the component defined any slots, you can pass in the content to be placed inside those slots by inserting {% fill %} tags, directly within the {% component %} tag:
By default, components behave similarly to Django's {% include %}, and the template inside the component has access to the variables defined in the outer template.
You can selectively isolate a component, using the only flag, so that the inner template can access only the data that was explicitly passed to it:
{% component \"name\" positional_arg keyword_arg=value ... only %}\n
Marks location where CSS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted into the <head> tag of the HTML.
If the generated HTML does NOT contain any {% component_css_dependencies %} tags, CSS links are by default inserted into the <head> tag of the HTML. (See JS and CSS output locations)
Note that there should be only one {% component_css_dependencies %} for the whole HTML document. If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.
Marks location where JS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted at the end of the <body> tag of the HTML.
If the generated HTML does NOT contain any {% component_js_dependencies %} tags, JS scripts are by default inserted at the end of the <body> tag of the HTML. (See JS and CSS output locations)
Note that there should be only one {% component_js_dependencies %} for the whole HTML document. If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.
{% fill name data=None default=None %}\n{% endfill %}\n
See source code
Use this tag to insert content into component's slots.
{% fill %} tag may be used only within a {% component %}..{% endcomponent %} block. Runtime checks should prohibit other usages.
Args:
name (str, required): Name of the slot to insert this content into. Use \"default\" for the default slot.
default (str, optional): This argument allows you to access the original content of the slot under the specified variable name. See Accessing original content of slots
data (str, optional): This argument allows you to access the data passed to the slot under the specified variable name. See Scoped slots
"},{"location":"reference/template_tags/#accessing-slots-default-content-with-the-default-kwarg","title":"Accessing slot's default content with the default kwarg","text":"
"},{"location":"reference/template_tags/#accessing-slot-data-and-default-content-on-the-default-slot","title":"Accessing slot data and default content on the default slot","text":"
To access slot data and the default slot content on the default slot, use {% fill %} with name set to \"default\":
{% component \"button\" %}\n {% fill name=\"default\" data=\"slot_data\" default=\"default_slot\" %}\n You clicked me {{ slot_data.count }} times!\n {{ default_slot }}\n {% endfill %}\n{% endcomponent %}\n
The \"provider\" part of the provide / inject feature. Pass kwargs to this tag to define the provider's data. Any components defined within the {% provide %}..{% endprovide %} tags will be able to access this data with Component.inject().
This is similar to React's ContextProvider, or Vue's provide().
Args:
name (str, required): Provider name. This is the name you will then use in Component.inject().
**kwargs: Any extra kwargs will be passed as the provided data.
Since the \"child\" component is used within the {% provide %} / {% endprovide %} tags, we can request the \"user_data\" using Component.inject(\"user_data\"):
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n User is: {{ user }}\n </div>\n \"\"\"\n\n def get_context_data(self):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n
Notice that the keys defined on the {% provide %} tag are then accessed as attributes when accessing them with Component.inject().
"},{"location":"reference/template_tags/#passing-data-to-slots","title":"Passing data to slots","text":"
Any extra kwargs will be considered as slot data, and will be accessible in the {% fill %} tag via fill's data kwarg:
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
The content between the {% slot %}..{% endslot %} tags is the default content that will be rendered if no fill is given for the slot.
This default content can then be accessed from within the {% fill %} tag using the fill's default kwarg. This is useful if you need to wrap / prepend / append the original slot's content.
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" %}\n This is default content!\n {% endslot %}\n </div>\n \"\"\"\n
Dictonary describing which component slots are filled (True) or are not (False).
New in version 0.70
Use as {{ component_vars.is_filled }}
Example:
{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n <div class=\"slot-wrapper\">\n {% slot \"my_slot\" / %}\n </div>\n{% endif %}\n
This is equivalent to checking if a given key is among the slot fills:
class MyTable(Component):\n def get_context_data(self, *args, **kwargs):\n return {\n \"my_slot_filled\": \"my_slot\" in self.input.slots\n }\n
Below are all the URL patterns that will be added by adding django_components.urls.
See Installation on how to add these URLs to your Django project.
Django components already prefixes all URLs with components/. So when you are adding the URLs to urlpatterns, you can use an empty string as the first argument:
from django.urls import include, path\n\nurlpatterns = [\n ...\n path(\"\", include(\"django_components.urls\")),\n]\n
"},{"location":"reference/urls/#list-of-urls","title":"List of URLs","text":"