And with that, you're all set! When you visit the URL, the component will be rendered and the content will be returned.
The get(), post(), etc methods will receive the HttpRequest object as the first argument. So you can parametrize how the component is rendered for example by passing extra query parameters to the URL:
http://localhost:8000/calendar/?date=2024-12-13
-
\ No newline at end of file
+
\ No newline at end of file
diff --git a/dev/search/search_index.json b/dev/search/search_index.json
index 5d8e5876..4e594654 100644
--- a/dev/search/search_index.json
+++ b/dev/search/search_index.json
@@ -1 +1 @@
-{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Welcome to Django Components","text":"
django-components combines Django's templating system with the modularity seen in modern frontend frameworks like Vue or React.
With django-components you can support Django projects small and large without leaving the Django ecosystem.
{% html_attrs %} offers a Vue-like granular control for class and style HTML attributes, where you can use a dictionary to manage each class name or style property separately.
One of our goals with django-components is to make it easy to share components between projects. Head over to the Community examples to see some examples.
"},{"location":"#contributing-and-development","title":"Contributing and development","text":"
Get involved or sponsor this project - See here
Running django-components locally for development - See here
"},{"location":"migrating_from_safer_staticfiles/","title":"Migrating from safer_staticfiles","text":"
This guide is for you if you're upgrating django_components to v0.100 or later from older versions.
In version 0.100, we changed how components' static JS and CSS files are handled. See more in the \"Static files\" section.
Migration steps:
Remove django_components.safer_staticfiles from INSTALLED_APPS in your settings.py, and replace it with django.contrib.staticfiles.
Components' JS and CSS scripts (e.g. from Component.js or Component.js_file) are now cached at class creation time.
This means that when you now restart the server while having a page opened in the browser, the JS / CSS files are immediately available.
Previously, the JS/CSS were cached only after the components were rendered. So you had to reload the page to trigger the rendering, in order to make the JS/CSS files available.
Fix the default cache for JS / CSS scripts to be unbounded.
Previously, the default cache for the JS/CSS scripts (LocMemCache) was accidentally limited to 300 entries (~150 components).
Do not send template_rendered signal when rendering a component with no template. (#1277)
Subclassing - Previously, if a parent component defined Component.template or Component.template_file, it's subclass would use the same Template instance.
This could lead to unexpected behavior, where a change to the template of the subclass would also change the template of the parent class.
Now, each subclass has it's own Template instance, and changes to the template of the subclass do not affect the template of the parent class.
Fix Django failing to restart due to \"TypeError: 'Dynamic' object is not iterable\" (#1232)
Fix bug when error formatting failed when error value was not a string.
\u26a0\ufe0f Major release \u26a0\ufe0f - Please test thoroughly before / after upgrading.
This is the biggest step towards v1. While this version introduces many small API changes, we don't expect to make further changes to the affected parts before v1.
For more details see #433.
Summary:
Overhauled typing system
Middleware removed, no longer needed
get_template_data() is the new canonical way to define template data. get_context_data() is now deprecated but will remain until v2.
The middleware ComponentDependencyMiddleware was removed as it is no longer needed.
The middleware served one purpose - to render the JS and CSS dependencies of components when you rendered templates with Template.render() or django.shortcuts.render() and those templates contained {% component %} tags.
NOTE: If you rendered HTML with Component.render() or Component.render_to_response(), the JS and CSS were already rendered.
Now, the JS and CSS dependencies of components are automatically rendered, even when you render Templates with Template.render() or django.shortcuts.render().
To disable this behavior, set the DJC_DEPS_STRATEGY context key to \"ignore\" when rendering the template:
# With `Template.render()`:\ntemplate = Template(template_str)\nrendered = template.render(Context({\"DJC_DEPS_STRATEGY\": \"ignore\"}))\n\n# Or with django.shortcuts.render():\nfrom django.shortcuts import render\nrendered = render(\n request,\n \"my_template.html\",\n context={\"DJC_DEPS_STRATEGY\": \"ignore\"},\n)\n
In fact, you can set the DJC_DEPS_STRATEGY context key to any of the strategies:
\"document\"
\"fragment\"
\"simple\"
\"prepend\"
\"append\"
\"ignore\"
See Dependencies rendering for more info.
Typing
Component typing no longer uses generics. Instead, the types are now defined as class attributes of the component class.
Subclassing of components with None values has changed:
Previously, when a child component's template / JS / CSS attributes were set to None, the child component still inherited the parent's template / JS / CSS.
Now, the child component will not inherit the parent's template / JS / CSS if it sets the attribute to None.
Before:
class Parent(Component):\n template = \"parent.html\"\n\nclass Child(Parent):\n template = None\n\n# Child still inherited parent's template\nassert Child.template == Parent.template\n
After:
class Parent(Component):\n template = \"parent.html\"\n\nclass Child(Parent):\n template = None\n\n# Child does not inherit parent's template\nassert Child.template is None\n
The Component.Url class was merged with Component.View.
Instead of Component.Url.public, use Component.View.public.
If you imported ComponentUrl from django_components, you need to update your import to ComponentView.
Before:
class MyComponent(Component):\n class Url:\n public = True\n\n class View:\n def get(self, request):\n return self.render_to_response()\n
After:
class MyComponent(Component):\n class View:\n public = True\n\n def get(self, request):\n return self.render_to_response()\n
Caching - The function signatures of Component.Cache.get_cache_key() and Component.Cache.hash() have changed to enable passing slots.
Args and kwargs are no longer spread, but passed as a list and a dict, respectively.
Component.get_context_data() is now deprecated. Use Component.get_template_data() instead.
get_template_data() behaves the same way, but has a different function signature to accept also slots and context.
Since get_context_data() is widely used, it will remain available until v2.
Component.get_template_name() and Component.get_template() are now deprecated. Use Component.template, Component.template_file or Component.on_render() instead.
Component.get_template_name() and Component.get_template() will be removed in v1.
In v1, each Component will have at most one static template. This is needed to enable support for Markdown, Pug, or other pre-processing of templates by extensions.
If you are using the deprecated methods to point to different templates, there's 2 ways to migrate:
Split the single Component into multiple Components, each with its own template. Then switch between them in Component.on_render():
The type kwarg in Component.render() and Component.render_to_response() is now deprecated. Use deps_strategy instead. The type kwarg will be removed in v1.
The render_dependencies kwarg in Component.render() and Component.render_to_response() is now deprecated. Use deps_strategy=\"ignore\" instead. The render_dependencies kwarg will be removed in v1.
When creating extensions, the ComponentExtension.ExtensionClass attribute was renamed to ComponentConfig.
The old name is deprecated and will be removed in v1.
Before:
from django_components import ComponentExtension\n\nclass MyExtension(ComponentExtension):\n class ExtensionClass(ComponentExtension.ExtensionClass):\n pass\n
After:
from django_components import ComponentExtension, ExtensionComponentConfig\n\nclass MyExtension(ComponentExtension):\n class ComponentConfig(ExtensionComponentConfig):\n pass\n
When creating extensions, to access the Component class from within the methods of the extension nested classes, use component_cls.
Previously this field was named component_class. The old name is deprecated and will be removed in v1.
ComponentExtension.ExtensionClass attribute was renamed to ComponentConfig.
The old name is deprecated and will be removed in v1.\n\nBefore:\n\n```py\nfrom django_components import ComponentExtension, ExtensionComponentConfig\n\nclass LoggerExtension(ComponentExtension):\n name = \"logger\"\n\n class ComponentConfig(ExtensionComponentConfig):\n def log(self, msg: str) -> None:\n print(f\"{self.component_class.__name__}: {msg}\")\n```\n\nAfter:\n\n```py\nfrom django_components import ComponentExtension, ExtensionComponentConfig\n\nclass LoggerExtension(ComponentExtension):\n name = \"logger\"\n\n class ComponentConfig(ExtensionComponentConfig):\n def log(self, msg: str) -> None:\n print(f\"{self.component_cls.__name__}: {msg}\")\n```\n
Slots
SlotContent was renamed to SlotInput. The old name is deprecated and will be removed in v1.
SlotRef was renamed to SlotFallback. The old name is deprecated and will be removed in v1.
The default kwarg in {% fill %} tag was renamed to fallback. The old name is deprecated and will be removed in v1.
Before:
{% fill \"footer\" default=\"footer\" %}\n {{ footer }}\n{% endfill %}\n
After:
{% fill \"footer\" fallback=\"footer\" %}\n {{ footer }}\n{% endfill %}\n
The template variable {{ component_vars.is_filled }} is now deprecated. Will be removed in v1. Use {{ component_vars.slots }} instead.
NOTE: component_vars.is_filled automatically escaped slot names, so that even slot names that are not valid python identifiers could be set as slot names. component_vars.slots no longer does that.
Component attribute Component.is_filled is now deprecated. Will be removed in v1. Use Component.slots instead.
Before:
class MyComponent(Component):\n def get_template_data(self, args, kwargs, slots, context):\n if self.is_filled.footer:\n color = \"red\"\n else:\n color = \"blue\"\n\n return {\n \"color\": color,\n }\n
After:
class MyComponent(Component):\n def get_template_data(self, args, kwargs, slots, context):\n if \"footer\" in slots:\n color = \"red\"\n else:\n color = \"blue\"\n\n return {\n \"color\": color,\n }\n
NOTE: Component.is_filled automatically escaped slot names, so that even slot names that are not valid python identifiers could be set as slot names. Component.slots no longer does that.
Miscellaneous
Template caching with cached_template() helper and template_cache_size setting is deprecated. These will be removed in v1.
This feature made sense if you were dynamically generating templates for components using Component.get_template_string() and Component.get_template().
However, in v1, each Component will have at most one static template. This static template is cached internally per component class, and reused across renders.
This makes the template caching feature obsolete.
If you relied on cached_template(), you should either:
Wrap the templates as Components.
Manage the cache of Templates yourself.
The debug_highlight_components and debug_highlight_slots settings are deprecated. These will be removed in v1.
The debug highlighting feature was re-implemented as an extension. As such, the recommended way for enabling it has changed:
If you define Component.Args, Component.Kwargs, Component.Slots, then the args, kwargs, slots arguments will be instances of these classes:
class Button(Component):\n class Args(NamedTuple):\n field1: str\n\n class Kwargs(NamedTuple):\n field2: int\n\n def get_template_data(self, args: Args, kwargs: Kwargs, slots, context):\n return {\n \"val1\": args.field1,\n \"val2\": kwargs.field2,\n }\n
Input validation is now part of the render process.
When you specify the input types (such as Component.Args, Component.Kwargs, etc), the actual inputs to data methods (Component.get_template_data(), etc) will be instances of the types you specified.
This practically brings back input validation, because the instantiation of the types will raise an error if the inputs are not valid.
Read more on Typing and validation
Render emails or other non-browser HTML with new \"dependencies strategies\"
When rendering a component with Component.render() or Component.render_to_response(), the deps_strategy kwarg (previously type) now accepts additional options:
Smartly inserts JS / CSS into placeholders or into <head> and <body> tags.
Inserts extra script to allow fragment strategy to work.
Assumes the HTML will be rendered in a JS-enabled browser.
\"fragment\"
A lightweight HTML fragment to be inserted into a document with AJAX.
Ignores placeholders and any <head> / <body> tags.
No JS / CSS included.
\"simple\"
Smartly insert JS / CSS into placeholders or into <head> and <body> tags.
No extra script loaded.
\"prepend\"
Insert JS / CSS before the rendered HTML.
Ignores placeholders and any <head> / <body> tags.
No extra script loaded.
\"append\"
Insert JS / CSS after the rendered HTML.
Ignores placeholders and any <head> / <body> tags.
No extra script loaded.
\"ignore\"
Rendered HTML is left as-is. You can still process it with a different strategy later with render_dependencies().
Used for inserting rendered HTML into other components.
See Dependencies rendering for more info.
New Component.args, Component.kwargs, Component.slots attributes available on the component class itself.
These attributes are the same as the ones available in Component.get_template_data().
You can use these in other methods like Component.on_render_before() or Component.on_render_after().
from django_components import Component, SlotInput\n\nclass Table(Component):\n class Args(NamedTuple):\n page: int\n\n class Kwargs(NamedTuple):\n per_page: int\n\n class Slots(NamedTuple):\n content: SlotInput\n\n def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n assert self.args.page == 123\n assert self.kwargs.per_page == 10\n content_html = self.slots.content()\n
Same as with the parameters in Component.get_template_data(), they will be instances of the Args, Kwargs, Slots classes if defined, or plain lists / dictionaries otherwise.
4 attributes that were previously available only under the Component.input attribute are now available directly on the Component instance:
Component.raw_args
Component.raw_kwargs
Component.raw_slots
Component.deps_strategy
The first 3 attributes are the same as the deprecated Component.input.args, Component.input.kwargs, Component.input.slots properties.
Compared to the Component.args / Component.kwargs / Component.slots attributes, these \"raw\" attributes are not typed and will remain as plain lists / dictionaries even if you define the Args, Kwargs, Slots classes.
The Component.deps_strategy attribute is the same as the deprecated Component.input.deps_strategy property.
Same as with the parameters in Component.get_template_data(), they will be instances of the Args, Kwargs, Slots classes if defined, or plain lists / dictionaries otherwise.
New component lifecycle hook Component.on_render().
This hook is called when the component is being rendered.
You can override this method to:
Change what template gets rendered
Modify the context
Modify the rendered output after it has been rendered
Handle errors
See on_render for more info.
get_component_url() now optionally accepts query and fragment arguments.
You can now access the {% component %} tag (ComponentNode instance) from which a Component was created. Use Component.node to access it.
This is mostly useful for extensions, which can use this to detect if the given Component comes from a {% component %} tag or from a different source (such as Component.render()).
Component.node is None if the component is created by Component.render() (but you can pass in the node kwarg yourself).
class MyComponent(Component):\n def get_template_data(self, context, template):\n if self.node is not None:\n assert self.node.name == \"my_component\"\n
Node classes ComponentNode, FillNode, ProvideNode, and SlotNode are part of the public API.
These classes are what is instantiated when you use {% component %}, {% fill %}, {% provide %}, and {% slot %} tags.
If you don't want to modify the rendered result, return None.
See all Extension hooks.
When creating extensions, the previous syntax with ComponentExtension.ExtensionClass was causing Mypy errors, because Mypy doesn't allow using class attributes as bases:
Before:
from django_components import ComponentExtension\n\nclass MyExtension(ComponentExtension):\n class ExtensionClass(ComponentExtension.ExtensionClass): # Error!\n pass\n
Instead, you can import ExtensionComponentConfig directly:
After:
from django_components import ComponentExtension, ExtensionComponentConfig\n\nclass MyExtension(ComponentExtension):\n class ComponentConfig(ExtensionComponentConfig):\n pass\n
When a component is being rendered, a proper Component instance is now created.
Previously, the Component state was managed as half-instance, half-stack.
Component's \"Render API\" (args, kwargs, slots, context, inputs, request, context data, etc) can now be accessed also outside of the render call. So now its possible to take the component instance out of get_template_data() (although this is not recommended).
Components can now be defined without a template.
Previously, the following would raise an error:
class MyComponent(Component):\n pass\n
\"Template-less\" components can be used together with Component.on_render() to dynamically pick what to render:
Fix bug: Context processors data was being generated anew for each component. Now the data is correctly created once and reused across components with the same request (#1165).
Fix KeyError on component_context_cache when slots are rendered outside of the component's render context. (#1189)
Component classes now have do_not_call_in_templates=True to prevent them from being called as functions in templates.
Each Component class now has a class_id attribute, which is unique to the component subclass.
NOTE: This is different from Component.id, which is unique to each rendered instance.
To look up a component class by its class_id, use get_component_by_class_id().
It's now easier to create URLs for component views.
Before, you had to call Component.as_view() and pass that to urlpatterns.
Now this can be done for you if you set Component.Url.public to True:
class MyComponent(Component):\n class Url:\n public = True\n ...\n
Then, to get the URL for the component, use get_component_url():
from django_components import get_component_url\n\nurl = get_component_url(MyComponent)\n
This way you don't have to mix your app URLs with component URLs.
Read more on Component views and URLs.
Per-component caching - Set Component.Cache.enabled to True to enable caching for a component.
Component caching allows you to store the rendered output of a component. Next time the component is rendered with the same input, the cached output is returned instead of re-rendering the component.
class TestComponent(Component):\n template = \"Hello\"\n\n class Cache:\n enabled = True\n ttl = 0.1 # .1 seconds TTL\n cache_name = \"custom_cache\"\n\n # Custom hash method for args and kwargs\n # NOTE: The default implementation simply serializes the input into a string.\n # As such, it might not be suitable for complex objects like Models.\n def hash(self, *args, **kwargs):\n return f\"{json.dumps(args)}:{json.dumps(kwargs)}\"\n
Read more on Component caching.
@djc_test can now be called without first calling django.setup(), in which case it does it for you.
Expose ComponentInput class, which is a typing for Component.input.
Add defaults for the component inputs with the Component.Defaults nested class. Defaults are applied if the argument is not given, or if it set to None.
For lists, dictionaries, or other objects, wrap the value in Default() class to mark it as a factory function:
```python\nfrom django_components import Default\n\nclass Table(Component):\n class Defaults:\n position = \"left\"\n width = \"200px\"\n options = Default(lambda: [\"left\", \"right\", \"center\"])\n\n def get_context_data(self, position, width, options):\n return {\n \"position\": position,\n \"width\": width,\n \"options\": options,\n }\n\n# `position` is used as given, `\"right\"`\n# `width` uses default because it's `None`\n# `options` uses default because it's missing\nTable.render(\n kwargs={\n \"position\": \"right\",\n \"width\": None,\n }\n)\n```\n
{% html_attrs %} now offers a Vue-like granular control over class and style HTML attributes, where each class name or style property can be managed separately.
Settings are now loaded only once, and thus are considered immutable once loaded. Previously, django-components would load settings from settings.COMPONENTS on each access. The new behavior aligns with Django's settings.
Access the HttpRequest object under Component.request.
To pass the request object to a component, either: - Render a template or component with RequestContext, - Or set the request kwarg to Component.render() or Component.render_to_response().
Read more on HttpRequest.
Access the context processors data under Component.context_processors_data.
Context processors data is available only when the component has access to the request object, either by: - Passing the request to Component.render() or Component.render_to_response(), - Or by rendering a template or component with RequestContext, - Or being nested in another component that has access to the request object.
The data from context processors is automatically available within the component's template.
Configurable cache - Set COMPONENTS.cache to change where and how django-components caches JS and CSS files. (#946)
Read more on Caching.
Highlight coponents and slots in the UI - We've added two boolean settings COMPONENTS.debug_highlight_components and COMPONENTS.debug_highlight_slots, which can be independently set to True. First will wrap components in a blue border, the second will wrap slots in a red border. (#942)
@template_tag and BaseNode - A decorator and a class that allow you to define custom template tags that will behave similarly to django-components' own template tags.
Read more on Template tags.
Template tags defined with @template_tag and BaseNode will have the following features:
Accepting args, kwargs, and flags.
Allowing literal lists and dicts as inputs as:
key=[1, 2, 3] or key={\"a\": 1, \"b\": 2} - Using template tags tag inputs as:
{% my_tag key=\"{% lorem 3 w %}\" / %} - Supporting the flat dictionary definition:
attr:key=value - Spreading args and kwargs with ...:
{% my_tag ...args ...kwargs / %} - Being able to call the template tag as:
Refactored template tag input validation. When you now call template tags like {% slot %}, {% fill %}, {% html_attrs %}, and others, their inputs are now validated the same way as Python function inputs are.
So, for example
{% slot \"my_slot\" name=\"content\" / %}\n
will raise an error, because the positional argument name is given twice.
NOTE: Special kwargs whose keys are not valid Python variable names are not affected by this change. So when you define:
{% component data-id=123 / %}\n
The data-id will still be accepted as a valid kwarg, assuming that your get_context_data() accepts **kwargs:
Instead of inlining the JS and CSS under Component.js and Component.css, you can move them to their own files, and link the JS/CSS files with Component.js_file and Component.css_file.
Even when you specify the JS/CSS with Component.js_file or Component.css_file, then you can still access the content under Component.js or Component.css - behind the scenes, the content of the JS/CSS files will be set to Component.js / Component.css upon first access.
The same applies to Component.template_file, which will populate Component.template upon first access.
With this change, the role of Component.js/css and the JS/CSS in Component.Media has changed:
The JS/CSS defined in Component.js/css or Component.js/css_file is the \"main\" JS/CSS
The JS/CSS defined in Component.Media.js/css are secondary or additional
The canonical way to define a template file was changed from template_name to template_file, to align with the rest of the API.
template_name remains for backwards compatibility. When you get / set template_name, internally this is proxied to template_file.
The undocumented Component.component_id was removed. Instead, use Component.id. Changes:
While component_id was unique every time you instantiated Component, the new id is unique every time you render the component (e.g. with Component.render())
The new id is available only during render, so e.g. from within get_context_data()
Component's HTML / CSS / JS are now resolved and loaded lazily. That is, if you specify template_name/template_file, js_file, css_file, or Media.js/css, the file paths will be resolved only once you:
Try to access component's HTML / CSS / JS, or
Render the component.
Read more on Accessing component's HTML / JS / CSS.
Component inheritance:
When you subclass a component, the JS and CSS defined on parent's Media class is now inherited by the child component.
You can disable or customize Media inheritance by setting extend attribute on the Component.Media nested class. This work similarly to Django's Media.extend.
When child component defines either template or template_file, both of parent's template and template_file are ignored. The same applies to js_file and css_file.
Autodiscovery now ignores files and directories that start with an underscore (_), except __init__.py
The Signals emitted by or during the use of django-components are now documented, together the template_rendered signal.
Add support for HTML fragments. HTML fragments can be rendered by passing type=\"fragment\" to Component.render() or Component.render_to_response(). Read more on how to use HTML fragments with HTMX, AlpineJS, or vanillaJS.
Fix compatibility with custom subclasses of Django's Template that need to access origin or other initialization arguments. (https://github.com/django-components/django-components/pull/828)
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.
Component caching allows you to store the rendered output of a component. Next time the component is rendered with the same input, the cached output is returned instead of re-rendering the component.
This is particularly useful for components that are expensive to render or do not change frequently.
Info
Component caching uses Django's cache framework, so you can use any cache backend that is supported by Django.
You can specify a time-to-live (TTL) for the cache entry with Component.Cache.ttl, which determines how long the entry remains valid. The TTL is specified in seconds.
class MyComponent(Component):\n class Cache:\n enabled = True\n ttl = 60 * 60 * 24 # 1 day\n
If ttl > 0, entries are cached for the specified number of seconds.
Since component caching uses Django's cache framework, you can specify a custom cache name with Component.Cache.cache_name to use a different cache backend:
class MyComponent(Component):\n class Cache:\n enabled = True\n cache_name = \"my_cache\"\n
By default, the cache key is generated based on the component's input (args and kwargs). So the following two calls would generate separate entries in the cache:
However, you have full control over the cache key generation. As such, you can:
Cache the component on all inputs (default)
Cache the component on particular inputs
Cache the component irrespective of the inputs
To achieve that, you can override the Component.Cache.hash() method to customize how arguments are hashed into the cache key.
class MyComponent(Component):\n class Cache:\n enabled = True\n\n def hash(self, *args, **kwargs):\n return f\"{json.dumps(args)}:{json.dumps(kwargs)}\"\n
For even more control, you can override other methods available on the ComponentCache class.
Warning
The default implementation of Cache.hash() simply serializes the input into a string. As such, it might not be suitable if you need to hash complex objects like Models.
Here's a complete example of a component with caching enabled:
from django_components import Component\n\nclass MyComponent(Component):\n template = \"Hello, {{ name }}\"\n\n class Cache:\n enabled = True\n ttl = 300 # Cache for 5 minutes\n cache_name = \"my_cache\"\n\n def get_template_data(self, args, kwargs, slots, context):\n return {\"name\": kwargs[\"name\"]}\n
In this example, the component's rendered output is cached for 5 minutes using the my_cache backend.
"},{"location":"concepts/advanced/component_context_scope/","title":"Component context and scope","text":"
By default, context variables are passed down the template as in regular Django - deeper scopes can access the variables from the outer scopes. So if you have several nested forloops, then inside the deep-most loop you can access variables defined by all previous loops.
With this in mind, the {% component %} tag behaves similarly to {% include %} tag - inside the component tag, you can access all variables that were defined outside of it.
And just like with {% include %}, if you don't want a specific component template to have access to the parent context, add only to the {% component %} tag:
{% component \"calendar\" date=\"2015-06-19\" only / %}\n
NOTE: {% csrf_token %} tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the only modifier.
If you find yourself using the only modifier often, you can set the context_behavior option to \"isolated\", which automatically applies the only modifier. This is useful if you want to make sure that components don't accidentally access the outer context.
Components can also access the outer context in their context methods like get_template_data by accessing the property self.outer_context.
"},{"location":"concepts/advanced/component_context_scope/#example-of-accessing-outer-context","title":"Example of Accessing Outer Context","text":"
<div>\n {% component \"calender\" / %}\n</div>\n
Assuming that the rendering context has variables such as date, you can use self.outer_context to access them from within get_template_data. Here's how you might implement it:
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_template_data() of the component that owns the fill tag.
\"isolated\"
Similar behavior to Vue or React, this is useful if you want to make sure that components don't accidentally access variables defined outside of the component.
Inside the {% fill %} tag, you can ONLY access variables from 2 places:
Any loops ({% for ... %}) that the {% fill %} tag is part of.
Component.get_template_data() of the component which defined the template (AKA the \"root\" component).
Warning
Notice that the component whose get_template_data() we use inside {% fill %} is NOT the same across the two modes!
\"django\" - my_var has access to data from get_template_data() of both Inner and Outer. If there are variables defined in both, then Inner overshadows Outer.
\"isolated\" - my_var has access to data from get_template_data() of ONLY Outer.
Then if get_template_data() of the component \"my_comp\" returns following data:
{ \"my_var\": 456 }\n
Then the template will be rendered as:
123 # my_var\n # cheese\n
Because variables \"my_var\" and \"cheese\" are searched only inside RootComponent.get_template_data(). But since \"cheese\" is not defined there, it's empty.
Info
Notice that the variables defined with the {% with %} tag are ignored inside the {% fill %} tag with the \"isolated\" mode.
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/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_file = \"template.html\"\n\n # This component takes one parameter, a date string to show in the template\n def get_template_data(self, args, kwargs, slots, context):\n return {\n \"date\": kwargs[\"date\"],\n }\n
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# Check if component is registered\nregistry.has(\"button\") # True\n\n# Unregister single component\nregistry.unregister(\"card\")\n\n# Unregister all components\nregistry.clear()\n
"},{"location":"concepts/advanced/component_registry/#registering-components-to-custom-componentregistry","title":"Registering components to custom ComponentRegistry","text":"
If you are writing a component library to be shared with others, you may want to manage your own instance of ComponentRegistry and register components onto a different Library instance than the default one.
The Library instance can be set at instantiation of ComponentRegistry. If omitted, then the default Library instance from django_components is used.
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.
Each extension has a corresponding nested class within the Component class. These allow to configure the extensions on a per-component basis.
E.g.:
\"view\" extension -> Component.View
\"cache\" extension -> Component.Cache
\"defaults\" extension -> Component.Defaults
Note
Accessing the component instance from inside the nested classes:
Each method of the nested classes has access to the component attribute, which points to the component instance.
class MyTable(Component):\n class MyExtension:\n def get(self, request):\n # `self.component` points to the instance of `MyTable` Component.\n return self.component.render_to_response(request=request)\n
"},{"location":"concepts/advanced/extensions/#example-component-as-view","title":"Example: Component as View","text":"
The Components as Views feature is actually implemented as an extension that is configured by a View nested class.
You can override the get(), post(), etc methods to customize the behavior of the component as a view:
class MyTable(Component):\n class View:\n def get(self, request):\n return self.component_class.render_to_response(request=request)\n\n def post(self, request):\n return self.component_class.render_to_response(request=request)\n\n ...\n
Which is equivalent to setting the following for every component:
class MyTable(Component):\n class MyExtension:\n key = \"value\"\n\n class View:\n public = True\n\n class Cache:\n ttl = 60\n\n class Storybook:\n def title(self):\n return self.component_cls.__name__\n
Info
If you define an attribute as a function, it is like defining a method on the extension class.
E.g. in the example above, title is a method on the Storybook extension class.
As the name suggests, these are defaults, and so you can still selectively override them on a per-component basis:
class MyTable(Component):\n class View:\n public = False\n
"},{"location":"concepts/advanced/extensions/#extensions-in-component-instances","title":"Extensions in component instances","text":"
Above, we've configured extensions View and Storybook for the MyTable component.
You can access the instances of these extension classes in the component instance.
Extensions are available under their names (e.g. self.view, self.storybook).
For example, the View extension is available as self.view:
class MyTable(Component):\n def get_template_data(self, args, kwargs, slots, context):\n # `self.view` points to the instance of `View` extension.\n return {\n \"view\": self.view,\n }\n
And the Storybook extension is available as self.storybook:
class MyTable(Component):\n def get_template_data(self, args, kwargs, slots, context):\n # `self.storybook` points to the instance of `Storybook` extension.\n return {\n \"title\": self.storybook.title(),\n }\n
Creating extensions in django-components involves defining a class that inherits from ComponentExtension. This class can implement various lifecycle hooks and define new attributes or methods to be added to components.
To create an extension, define a class that inherits from ComponentExtension and implement the desired hooks.
Each extension MUST have a name attribute. The name MUST be a valid Python identifier.
The extension may implement any of the hook methods.
Each hook method receives a context object with relevant data.
Extension may own URLs or CLI commands.
from django_components.extension import ComponentExtension, OnComponentClassCreatedContext\n\nclass MyExtension(ComponentExtension):\n name = \"my_extension\"\n\n def on_component_class_created(self, ctx: OnComponentClassCreatedContext) -> None:\n # Custom logic for when a component class is created\n ctx.component_cls.my_attr = \"my_value\"\n
Warning
The name attribute MUST be unique across all extensions.
Moreover, the name attribute MUST NOT conflict with existing Component class API.
So if you name an extension render, it will conflict with the render() method of the Component class.
In previous sections we've seen the View and Storybook extensions classes that were nested within the Component class:
class MyComponent(Component):\n class View:\n ...\n\n class Storybook:\n ...\n
These can be understood as component-specific overrides or configuration.
Whether it's Component.View or Component.Storybook, their respective extensions defined how these nested classes will behave.
For example, the View extension defines the API that users may override in ViewExtension.ComponentConfig:
from django_components.extension import ComponentExtension, ExtensionComponentConfig\n\nclass ViewExtension(ComponentExtension):\n name = \"view\"\n\n # The default behavior of the `View` extension class.\n class ComponentConfig(ExtensionComponentConfig):\n def get(self, request):\n raise NotImplementedError(\"You must implement the `get` method.\")\n\n def post(self, request):\n raise NotImplementedError(\"You must implement the `post` method.\")\n\n ...\n
In any component that then defines a nested Component.View extension class, the resulting View class will actually subclass from the ViewExtension.ComponentConfig class.
In other words, when you define a component like this:
class MyTable(Component):\n class View:\n def get(self, request):\n # Do something\n ...\n
Behind the scenes it is as if you defined the following:
class MyTable(Component):\n class View(ViewExtension.ComponentConfig):\n def get(self, request):\n # Do something\n ...\n
Warning
When writing an extension, the ComponentConfig MUST subclass the base class ExtensionComponentConfig.
This base class ensures that the extension class will have access to the component instance.
"},{"location":"concepts/advanced/extensions/#install-your-extension","title":"Install your extension","text":"
Once the extension is defined, it needs to be installed in the Django settings to be used by the application.
Extensions can be given either as an extension class, or its import string:
To tie it all together, here's an example of a custom logging extension that logs when components are created, deleted, or rendered:
Each component can specify which color to use for the logging by setting Component.ColorLogger.color.
The extension will log the component name and color when the component is created, deleted, or rendered.
from django_components.extension import (\n ComponentExtension,\n ExtensionComponentConfig,\n OnComponentClassCreatedContext,\n OnComponentClassDeletedContext,\n OnComponentInputContext,\n)\n\n\nclass ColorLoggerExtension(ComponentExtension):\n name = \"color_logger\"\n\n # All `Component.ColorLogger` classes will inherit from this class.\n class ComponentConfig(ExtensionComponentConfig):\n color: str\n\n # These hooks don't have access to the Component instance,\n # only to the Component class, so we access the color\n # as `Component.ColorLogger.color`.\n def on_component_class_created(self, ctx: OnComponentClassCreatedContext):\n log.info(\n f\"Component {ctx.component_cls} created.\",\n color=ctx.component_cls.ColorLogger.color,\n )\n\n def on_component_class_deleted(self, ctx: OnComponentClassDeletedContext):\n log.info(\n f\"Component {ctx.component_cls} deleted.\",\n color=ctx.component_cls.ColorLogger.color,\n )\n\n # This hook has access to the Component instance, so we access the color\n # as `self.component.color_logger.color`.\n def on_component_input(self, ctx: OnComponentInputContext):\n log.info(\n f\"Rendering component {ctx.component_cls}.\",\n color=ctx.component.color_logger.color,\n )\n
To use the ColorLoggerExtension, add it to your settings:
You can access the owner Component class (MyTable) from within methods of the extension class (MyExtension) by using the component_cls attribute:
class MyTable(Component):\n class MyExtension:\n def some_method(self):\n print(self.component_cls)\n
Here is how the component_cls attribute may be used with our ColorLogger extension shown above:
class ColorLoggerComponentConfig(ExtensionComponentConfig):\n color: str\n\n def log(self, msg: str) -> None:\n print(f\"{self.component_cls.__name__}: {msg}\")\n\n\nclass ColorLoggerExtension(ComponentExtension):\n name = \"color_logger\"\n\n # All `Component.ColorLogger` classes will inherit from this class.\n ComponentConfig = ColorLoggerComponentConfig\n
When a slot is passed to a component, it is copied, so that the original slot is not modified with rendering metadata.
Therefore, don't use slot's identity to associate metadata with the slot:
# \u274c Don't do this:\nslots_cache = {}\n\nclass LoggerExtension(ComponentExtension):\n name = \"logger\"\n\n def on_component_input(self, ctx: OnComponentInputContext):\n for slot in ctx.component.slots.values():\n slots_cache[id(slot)] = {\"some\": \"metadata\"}\n
Instead, use the Slot.extra attribute, which is copied from the original slot:
# \u2705 Do this:\nclass LoggerExtension(ComponentExtension):\n name = \"logger\"\n\n # Save component-level logger settings for each slot when a component is rendered.\n def on_component_input(self, ctx: OnComponentInputContext):\n for slot in ctx.component.slots.values():\n slot.extra[\"logger\"] = ctx.component.logger\n\n # Then, when a fill is rendered with `{% slot %}`, we can access the logger settings\n # from the slot's metadata.\n def on_slot_rendered(self, ctx: OnSlotRenderedContext):\n logger = ctx.slot.extra[\"logger\"]\n logger.log(...)\n
Extensions in django-components can define custom commands that can be executed via the Django management command interface. This allows for powerful automation and customization capabilities.
For example, if you have an extension that defines a command that prints \"Hello world\", you can run the command with:
python manage.py components ext run my_ext hello\n
Where:
python manage.py components - is the Django entrypoint
ext run - is the subcommand to run extension commands
To define a command, subclass from ComponentCommand. This subclass should define:
name - the command's name
help - the command's help text
handle - the logic to execute when the command is run
from django_components import ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n name = \"hello\"\n help = \"Say hello\"\n\n def handle(self, *args, **kwargs):\n print(\"Hello, world!\")\n\nclass MyExt(ComponentExtension):\n name = \"my_ext\"\n commands = [HelloCommand]\n
"},{"location":"concepts/advanced/extensions/#define-arguments-and-options","title":"Define arguments and options","text":"
Commands can accept positional arguments and options (e.g. --foo), which are defined using the arguments attribute of the ComponentCommand class.
The arguments are parsed with argparse into a dictionary of arguments and options. These are then available as keyword arguments to the handle method of the command.
from django_components import CommandArg, ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n name = \"hello\"\n help = \"Say hello\"\n\n arguments = [\n # Positional argument\n CommandArg(\n name_or_flags=\"name\",\n help=\"The name to say hello to\",\n ),\n # Optional argument\n CommandArg(\n name_or_flags=[\"--shout\", \"-s\"],\n action=\"store_true\",\n help=\"Shout the hello\",\n ),\n ]\n\n def handle(self, name: str, *args, **kwargs):\n shout = kwargs.get(\"shout\", False)\n msg = f\"Hello, {name}!\"\n if shout:\n msg = msg.upper()\n print(msg)\n
You can run the command with arguments and options:
python manage.py components ext run my_ext hello John --shout\n>>> HELLO, JOHN!\n
Note
Command definitions are parsed with argparse, so you can use all the features of argparse to define your arguments and options.
See the argparse documentation for more information.
django-components defines types as CommandArg, CommandArgGroup, CommandSubcommand, and CommandParserInput to help with type checking.
Note
If a command doesn't have the handle method defined, the command will print a help message and exit.
Extensions can define subcommands, allowing for more complex command structures.
Subcommands are defined similarly to root commands, as subclasses of ComponentCommand class.
However, instead of defining the subcommands in the commands attribute of the extension, you define them in the subcommands attribute of the parent command:
from django_components import CommandArg, CommandArgGroup, ComponentCommand, ComponentExtension\n\nclass ChildCommand(ComponentCommand):\n name = \"child\"\n help = \"Child command\"\n\n def handle(self, *args, **kwargs):\n print(\"Child command\")\n\nclass ParentCommand(ComponentCommand):\n name = \"parent\"\n help = \"Parent command\"\n subcommands = [\n ChildCommand,\n ]\n\n def handle(self, *args, **kwargs):\n print(\"Parent command\")\n
In this example, we can run two commands.
Either the parent command:
python manage.py components ext run parent\n>>> Parent command\n
Or the child command:
python manage.py components ext run parent child\n>>> Child command\n
Warning
Subcommands are independent of the parent command. When a subcommand runs, the parent command is NOT executed.
As such, if you want to pass arguments to both the parent and child commands, e.g.:
python manage.py components ext run parent --foo child --bar\n
You should instead pass all the arguments to the subcommand:
python manage.py components ext run parent child --foo --bar\n
Extensions can define custom views and endpoints that can be accessed through the Django application.
To define URLs for an extension, set them in the urls attribute of your ComponentExtension class. Each URL is defined using the URLRoute class, which specifies the path, handler, and optional name for the route.
Here's an example of how to define URLs within an extension:
from django_components.extension import ComponentExtension, URLRoute\nfrom django.http import HttpResponse\n\ndef my_view(request):\n return HttpResponse(\"Hello from my extension!\")\n\nclass MyExtension(ComponentExtension):\n name = \"my_extension\"\n\n urls = [\n URLRoute(path=\"my-view/\", handler=my_view, name=\"my_view\"),\n URLRoute(path=\"another-view/<int:id>/\", handler=my_view, name=\"another_view\"),\n ]\n
Warning
The URLRoute objects are different from objects created with Django's django.urls.path(). Do NOT use URLRoute objects in Django's urlpatterns and vice versa!
django-components uses a custom URLRoute class to define framework-agnostic routing rules.
As of v0.131, URLRoute objects are directly converted to Django's URLPattern and URLResolver objects.
Return nothing (or None) to handle the result as usual
If you don't raise an exception, and neither return a new HTML, then original HTML / error will be used:
If rendering succeeded, the original HTML will be used as the final output.
If rendering failed, the original error will be propagated.
class MyTable(Component):\n def on_render(self, context, template):\n html, error = yield template.render(context)\n\n if error is not None:\n # The rendering failed\n print(f\"Error: {error}\")\n
on_render_after() runs when the component was fully rendered, including all its children.
It receives the same arguments as on_render_before(), plus the outcome of the rendering:
result: The rendered output of the component. None if the rendering failed.
error: The error that occurred during the rendering, or None if the rendering succeeded.
on_render_after() behaves the same way as the second part of on_render() (after the yield).
class MyTable(Component):\n def on_render_after(self, context, template, result, error):\n if error is None:\n # The rendering succeeded\n return result\n else:\n # The rendering failed\n print(f\"Error: {error}\")\n
Same as on_render(), you can return a new HTML, raise a new exception, or return nothing:
Return a new HTML
The new HTML will be used as the final output.
If the original template raised an error, it will be ignored.
Return nothing (or None) to handle the result as usual
If you don't raise an exception, and neither return a new HTML, then original HTML / error will be used:
If rendering succeeded, the original HTML will be used as the final output.
If rendering failed, the original error will be propagated.
class MyTable(Component):\n def on_render_after(self, context, template, result, error):\n if error is not None:\n # The rendering failed\n print(f\"Error: {error}\")\n
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.
Django-components provides a seamless integration with HTML fragments with AJAX (HTML over the wire), whether you're using jQuery, HTMX, AlpineJS, vanilla JavaScript, or other.
If the fragment component has any JS or CSS, django-components will:
Automatically load the associated JS and CSS
Ensure that JS is loaded and executed only once even if the fragment is inserted multiple times
Info
What are HTML fragments and \"HTML over the wire\"?
It is one of the methods for updating the state in the browser UI upon user interaction.
How it works is that:
User makes an action - clicks a button or submits a form
The action causes a request to be made from the client to the server.
Server processes the request (e.g. form submission), and responds with HTML of some part of the UI (e.g. a new entry in a table).
A library like HTMX, AlpineJS, or custom function inserts the new HTML into the correct place.
"},{"location":"concepts/advanced/html_fragments/#document-and-fragment-strategies","title":"Document and fragment strategies","text":"
Components support different \"strategies\" for rendering JS and CSS.
Two of them are used to enable HTML fragments - \"document\" and \"fragment\".
Fragment strategy assumes that the main HTML has already been rendered and loaded on the page. The component renders HTML that will be inserted into the page as a fragment, at a LATER time:
JS and CSS is not directly embedded to avoid duplicately executing the same JS scripts. So template tags like {% component_js_dependencies %} inside of fragments are ignored.
Instead, django-components appends the fragment's content with a JSON <script> to trigger a call to its asset manager JS script, which will load the JS and CSS smartly.
The asset manager JS script is assumed to be already loaded on the page.
A component is rendered as \"fragment\" when:
It is rendered with Component.render() or Component.render_to_response() with the deps_strategy kwarg set to \"fragment\"
"},{"location":"concepts/advanced/html_fragments/#2-define-fragment-html_1","title":"2. Define fragment HTML","text":"
The fragment to be inserted into the document.
IMPORTANT: Don't forget to set deps_strategy=\"fragment\"
[root]/components/demo.py
class Frag(Component):\n # NOTE: We wrap the actual fragment in a template tag with x-if=\"false\" to prevent it\n # from being rendered until we have registered the component with AlpineJS.\n template = \"\"\"\n <template x-if=\"false\" data-name=\"frag\">\n <div class=\"frag\">\n 123\n <span x-data=\"frag\" x-text=\"fragVal\">\n </span>\n </div>\n </template>\n \"\"\"\n\n js = \"\"\"\n Alpine.data('frag', () => ({\n fragVal: 'xxx',\n }));\n\n // Now that the component has been defined in AlpineJS, we can \"activate\"\n // all instances where we use the `x-data=\"frag\"` directive.\n document.querySelectorAll('[data-name=\"frag\"]').forEach((el) => {\n el.setAttribute('x-if', 'true');\n });\n \"\"\"\n\n css = \"\"\"\n .frag {\n background: blue;\n }\n \"\"\"\n\n class View:\n def get(self, request):\n return self.component_cls.render_to_response(\n request=request,\n # IMPORTANT: Don't forget `deps_strategy=\"fragment\"`\n deps_strategy=\"fragment\",\n )\n
"},{"location":"concepts/advanced/html_fragments/#3-create-view-and-urls_1","title":"3. Create view and URLs","text":"[app]/urls.py
"},{"location":"concepts/advanced/provide_inject/","title":"Prop drilling and provide / inject","text":"
New in version 0.80:
django-components supports the provide / inject pattern, similarly to React's Context Providers or Vue's provide / inject.
This is achieved with the combination of:
{% provide %} tag
Component.inject() method
"},{"location":"concepts/advanced/provide_inject/#what-is-prop-drilling","title":"What is \"prop drilling\"","text":"
Prop drilling refers to a scenario in UI development where you need to pass data through many layers of a component tree to reach the nested components that actually need the data.
Normally, you'd use props to send data from a parent component to its children. However, this straightforward method becomes cumbersome and inefficient if the data has to travel through many levels or if several components scattered at different depths all need the same piece of information.
This results in a situation where the intermediate components, which don't need the data for their own functioning, end up having to manage and pass along these props. This clutters the component tree and makes the code verbose and harder to manage.
A neat solution to avoid prop drilling is using the \"provide and inject\" technique.
With provide / inject, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.
This feature is inspired by Vue's Provide / Inject and React's Context / useContext.
As the name suggest, using provide / inject consists of 2 steps
Providing data
Injecting provided data
For examples of advanced uses of provide / inject, see this discussion.
The first argument to the {% provide %} tag is the key by which we can later access the data passed to this tag. The key in this case is \"my_data\".
The key must resolve to a valid identifier (AKA a valid Python variable name).
Next you define the data you want to \"provide\" by passing them as keyword arguments. This is similar to how you pass data to the {% with %} tag or the {% slot %} tag.
Note
Kwargs passed to {% provide %} are NOT added to the context. In the example below, the {{ hello }} won't render anything:
To \"inject\" (access) the data defined on the {% provide %} tag, you can use the Component.inject() method from within any other component methods.
For a component to be able to \"inject\" some data, the component ({% component %} tag) must be nested inside the {% provide %} tag.
In the example from previous section, we've defined two kwargs: hello=\"hi\" another=123. That means that if we now inject \"my_data\", we get an object with 2 attributes - hello and another.
The instance returned from inject() is immutable (subclass of NamedTuple). This ensures that the data returned from inject() will always have all the keys that were passed to the {% provide %} tag.
Warning
inject() works strictly only during render execution. If you try to call inject() from outside, it will raise an error.
If the rendered HTML does NOT contain neither {% component_dependencies %} template tags, nor <head> and <body> HTML tags, then the JS and CSS will NOT be inserted!
To force the JS and CSS to be inserted, use the \"append\" or \"prepend\" strategies.
The rendered HTML may be used in different contexts (browser, email, etc). If your components use JS and CSS scripts, you may need to handle them differently.
The different ways for handling JS / CSS are called \"dependencies strategies\".
render() and render_to_response() accept a deps_strategy parameter, which controls where and how the JS / CSS are inserted into the HTML.
deps_strategy=\"fragment\" is used when rendering a piece of HTML that will be inserted into a page that has already been rendered with the \"document\" strategy:
fragment = MyComponent.render(deps_strategy=\"fragment\")\n
The HTML of fragments is very lightweight because it doesn't include the JS and CSS scripts of the rendered components.
With fragments, even if a component has JS and CSS, you can insert the same component into a page hundreds of times, and the JS and CSS will only ever be loaded once.
This is intended for dynamic content that's loaded with AJAX after the initial page load, such as with jQuery, HTMX, AlpineJS or similar libraries.
Location:
None. The fragment's JS and CSS files will be loaded dynamically into the page.
Included scripts:
A special JSON <script> tag that tells the dependency manager what JS and CSS to load.
This is the same as \"simple\", but placeholders like {% component_js_dependencies %} and HTML tags <head> and <body> are all ignored. The JS and CSS are always inserted before the rendered content.
html = MyComponent.render(deps_strategy=\"prepend\")\n
Location:
JS and CSS is always inserted before the rendered content.
This is the same as \"simple\", but placeholders like {% component_js_dependencies %} and HTML tags <head> and <body> are all ignored. The JS and CSS are always inserted after the rendered content.
html = MyComponent.render(deps_strategy=\"append\")\n
Location:
JS and CSS is always inserted after the rendered content.
Django-components provides a seamless integration with HTML fragments with AJAX (HTML over the wire), whether you're using jQuery, HTMX, AlpineJS, vanilla JavaScript, or other.
This is achieved by the combination of the \"document\" and \"fragment\" strategies.
Read more about HTML fragments.
"},{"location":"concepts/advanced/tag_formatters/","title":"Tag formatters","text":""},{"location":"concepts/advanced/tag_formatters/#customizing-component-tags-with-tagformatter","title":"Customizing component tags with TagFormatter","text":"
New in version 0.89
By default, components are rendered using the pair of {% component %} / {% endcomponent %} template tags:
"},{"location":"concepts/advanced/tag_formatters/#writing-your-own-tagformatter","title":"Writing your own TagFormatter","text":""},{"location":"concepts/advanced/tag_formatters/#background","title":"Background","text":"
First, let's discuss how TagFormatters work, and how components are rendered in django_components.
When you render a component with {% component %} (or your own tag), the following happens:
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().
Template tags introduced by django-components, such as {% component %} and {% slot %}, offer additional features over the default Django template tags:
Self-closing tags {% mytag / %}
Allowing the use of :, - (and more) in keys
Spread operator ...
Using template tags as inputs to other template tags
Flat definition of dictionaries attr:key=val
Function-like input validation
You too can easily create custom template tags that use the above features.
"},{"location":"concepts/advanced/template_tags/#defining-template-tags-with-template_tag","title":"Defining template tags with @template_tag","text":"
The simplest way to create a custom template tag is using the template_tag decorator. This decorator allows you to define a template tag by just writing a function that returns the rendered content.
When you pass input to a template tag, it behaves the same way as if you passed the input to a function:
If required parameters are missing, an error is raised
If unexpected parameters are passed, an error is raised
To accept keys that are not valid Python identifiers (e.g. data-id), or would conflict with Python keywords (e.g. is), you can use the **kwargs syntax:
"},{"location":"concepts/advanced/template_tags/#defining-template-tags-with-basenode","title":"Defining template tags with BaseNode","text":"
For more control over your template tag, you can subclass BaseNode directly instead of using the decorator. This gives you access to additional features like the node's internal state and parsing details.
from django_components import BaseNode\n\nclass GreetNode(BaseNode):\n tag = \"greet\"\n end_tag = \"endgreet\"\n allowed_flags = [\"required\"]\n\n def render(self, context: Context, name: str, **kwargs) -> str:\n # Access node properties\n if self.flags[\"required\"]:\n return f\"Required greeting: Hello, {name}!\"\n return f\"Hello, {name}!\"\n\n# Register the node\nGreetNode.register(library)\n
When using BaseNode, you have access to several useful properties:
node_id: A unique identifier for this node instance
flags: Dictionary of flag values (e.g. {\"required\": True})
params: List of raw parameters passed to the tag
nodelist: The template nodes between the start and end tags
contents: The raw contents between the start and end tags
active_flags: List of flags that are currently set to True
template_name: The name of the Template instance inside which the node was defined
template_component: The component class that the Template belongs to
This is what the node parameter in the @template_tag decorator gives you access to - it's the instance of the node class that was automatically created for your template tag.
"},{"location":"concepts/advanced/template_tags/#rendering-content-between-tags","title":"Rendering content between tags","text":"
When your tag has an end tag, you can access and render the content between the tags using nodelist:
class WrapNode(BaseNode):\n tag = \"wrap\"\n end_tag = \"endwrap\"\n\n def render(self, context: Context, tag: str = \"div\", **attrs) -> str:\n # Render the content between tags\n inner = self.nodelist.render(context)\n attrs_str = \" \".join(f'{k}=\"{v}\"' for k, v in attrs.items())\n return f\"<{tag} {attrs_str}>{inner}</{tag}>\"\n\n# Usage:\n{% wrap tag=\"section\" class=\"content\" %}\n Hello, world!\n{% endwrap %}\n
The @djc_test decorator is a powerful tool for testing components created with django-components. It ensures that each test is properly isolated, preventing components registered in one test from affecting others.
Every component that you want to use in the template with the {% component %} tag needs to be registered with the ComponentRegistry.
We use the @register decorator for that:
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n ...\n
But for the component to be registered, the code needs to be executed - and for that, the file needs to be imported as a module.
This is the \"discovery\" part of the process.
One way to do that is by importing all your components in apps.py:
from django.apps import AppConfig\n\nclass MyAppConfig(AppConfig):\n name = \"my_app\"\n\n def ready(self) -> None:\n from components.card.card import Card\n from components.list.list import List\n from components.menu.menu import Menu\n from components.button.button import Button\n ...\n
By default, the Python files found in the COMPONENTS.dirs and COMPONENTS.app_dirs are auto-imported in order to execute the code that registers the components.
Autodiscovery occurs when Django is loaded, during the AppConfig.ready() hook of the apps.py file.
If you are using autodiscovery, keep a few points in mind:
Avoid defining any logic on the module-level inside the components directories, that you would not want to run anyway.
Components inside the auto-imported files still need to be registered with @register
Auto-imported component files must be valid Python modules, they must use suffix .py, and module name should follow PEP-8.
Subdirectories and files starting with an underscore _ (except __init__.py) are ignored.
Autodiscovery can be disabled in the settings with autodiscover=False.
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
When a component is being rendered, the component inputs are passed to various methods like get_template_data(), get_js_data(), or get_css_data().
It can be cumbersome to specify default values for each input in each method.
To make things easier, Components can specify their defaults. Defaults are used when no value is provided, or when the value is set to None for a particular input.
To define defaults for a component, you create a nested Defaults class within your Component class. Each attribute in the Defaults class represents a default value for a corresponding input.
In this example, position is a simple default value, while selected_items uses a factory function wrapped in Default to ensure a new list is created each time the default is used.
Now, when we render the component, the defaults will be applied:
For objects such as lists, dictionaries or other instances, you have to be careful - if you simply set a default value, this instance will be shared across all instances of the component!
from django_components import Component\n\nclass MyTable(Component):\n class Defaults:\n # All instances will share the same list!\n selected_items = [1, 2, 3]\n
To avoid this, you can use a factory function wrapped in Default.
from django_components import Component, Default\n\nclass MyTable(Component):\n class Defaults:\n # A new list is created for each instance\n selected_items = Default(lambda: [1, 2, 3])\n
This is similar to how the dataclass fields work.
In fact, you can also use the dataclass's field function to define the factories:
from dataclasses import field\nfrom django_components import Component\n\nclass MyTable(Component):\n class Defaults:\n selected_items = field(default_factory=lambda: [1, 2, 3])\n
"},{"location":"concepts/fundamentals/component_views_urls/","title":"Component views and URLs","text":"
New in version 0.34
Note: Since 0.92, Component is no longer a subclass of Django's View. Instead, the nested Component.View class is a subclass of Django's View.
For web applications, it's common to define endpoints that serve HTML content (AKA views).
django-components has a suite of features that help you write and manage views and their URLs:
For each component, you can define methods for handling HTTP requests (GET, POST, etc.) - get(), post(), etc.
Use Component.as_view() to be able to use your Components with Django's urlpatterns. This works the same way as View.as_view().
To avoid having to manually define the endpoints for each component, you can set the component to be \"public\" with Component.View.public = True. This will automatically create a URL for the component. To retrieve the component URL, use get_component_url().
In addition, Component has a render_to_response() method that renders the component template based on the provided input and returns an HttpResponse object.
To register the component as a route / endpoint in Django, add an entry to your urlpatterns. In place of the view function, create a view object with Component.as_view():
If you don't care about the exact URL of the component, you can let django-components manage the URLs for you by setting the Component.View.public attribute to True:
class MyComponent(Component):\n class View:\n public = True\n\n def get(self, request):\n return self.component_cls.render_to_response(request=request)\n ...\n
Then, to get the URL for the component, use get_component_url():
from django_components import get_component_url\n\nurl = get_component_url(MyComponent)\n
This way you don't have to mix your app URLs with component URLs.
Info
If you need to pass query parameters or a fragment to the component URL, you can do so by passing the query and fragment arguments to get_component_url():
Moreover, the {% html_attrs %} tag accepts two positional arguments:
attrs - a dictionary of attributes to be rendered
defaults - a dictionary of default attributes
You can use this for example to allow users of your component to add extra attributes. We achieve this by capturing the extra attributes and passing them to the {% html_attrs %} tag as a dictionary:
@register(\"my_comp\")\nclass MyComp(Component):\n # Pass all kwargs as `attrs`\n def get_template_data(self, args, kwargs, slots, context):\n return {\n \"attrs\": kwargs,\n \"classes\": \"text-red\",\n \"my_id\": 123,\n }\n\n template: t.django_html = \"\"\"\n {# Pass the extra attributes to `html_attrs` #}\n <div {% html_attrs attrs class=classes data-id=my_id %}>\n </div>\n \"\"\"\n
This way you can render MyComp with extra attributes:
HTML rendering with html_attrs tag or format_attributes works the same way - an attribute set to True is rendered without the value, and an attribute set to False is not rendered at all.
For the class HTML attribute, it's common that we want to join multiple values, instead of overriding them.
For example, if you're authoring a component, you may want to ensure that the component will ALWAYS have a specific class. Yet, you may want to allow users of your component to supply their own class attribute.
We can achieve this by adding extra kwargs. These values will be appended, instead of overwriting the previous value.
So if we have a variable attrs:
attrs = {\n \"class\": \"my-class pa-4\",\n}\n
And on {% html_attrs %} tag, we set the key class:
If a style property is specified multiple times, the last value is used.
Properties set to None are ignored.
If the last non-None instance of the property is set to False, the property is removed.
Example:
In this example, the width property is specified twice. The last instance is {\"width\": False}, so the property is removed.
Secondly, the background-color property is also set twice. But the second time it's set to None, so that instance is ignored, leaving us only with background-color: blue.
The color property is set to a valid value in both cases, so the latter (green) is used.
Note: For readability, we've split the tags across multiple lines.
Inside MyComp, we defined a default attribute
defaults:class=\"pa-4 text-red\"\n
So if attrs includes key class, the default above will be ignored.
MyComp also defines class key twice. It means that whether the class attribute is taken from attrs or defaults, the two class values will be appended to it.
These \"primary\" files will have special behavior. For example, each will receive variables from the component's data methods. Read more about each file type below:
HTML
CSS
JS
In addition, you can define extra \"secondary\" CSS / JS files using the nested Component.Media class, by setting Component.Media.js and Component.Media.css.
Single component can have many secondary files. There is no special behavior for them.
You can use these for third-party libraries, or for shared CSS / JS files.
Read more about Secondary JS / CSS files.
Warning
You cannot use both inlined code and separate file for a single language type (HTML, CSS, JS).
However, you can freely mix these for different languages:
class MyTable(Component):\n template: types.django_html = \"\"\"\n <div class=\"welcome\">\n Hi there!\n </div>\n \"\"\"\n js_file = \"my_table.js\"\n css_file = \"my_table.css\"\n
Each component has only a single template associated with it.
However, whether it's for A/B testing or for preserving public API when sharing your components, sometimes you may need to render different templates based on the input to your component.
You can use Component.on_render() to dynamically override what template gets rendered.
By default, the component's template is rendered as-is.
class Table(Component):\n def on_render(self, context: Context, template: Optional[Template]):\n if template is not None:\n return template.render(context)\n
If you want to render a different template in its place, we recommended you to:
Wrap the substitute templates as new Components
Then render those Components inside Component.on_render():
Django Components expects the rendered template to be a valid HTML. This is needed to enable features like CSS / JS variables.
Here is how the HTML is post-processed:
Insert component ID: Each root element in the rendered HTML automatically receives a data-djc-id-cxxxxxx attribute containing a unique component instance ID.
<!-- Output HTML -->\n<div class=\"card\" data-djc-id-c1a2b3c>\n ...\n</div>\n<div class=\"backdrop\" data-djc-id-c1a2b3c>\n ...\n</div>\n
Insert CSS ID: If the component defines CSS variables through get_css_data(), the root elements also receive a data-djc-css-xxxxxx attribute. This attribute links the element to its specific CSS variables.
Insert JS and CSS: After the HTML is rendered, Django Components handles inserting JS and CSS dependencies into the page based on the dependencies rendering strategy (document, fragment, or inline).
For example, if your component contains the {% component_js_dependencies %} or {% component_css_dependencies %} tags, or the <head> and <body> elements, the JS and CSS scripts will be inserted into the HTML.
For more information on how JS and CSS dependencies are rendered, see Rendering JS / CSS.
Compared to the secondary JS / CSS files, the definition of file paths for the main HTML / JS / CSS files is quite simple - just strings, without any lists, objects, or globs.
However, similar to the secondary JS / CSS files, you can specify the file paths relative to the component's directory.
If the path cannot be resolved relative to the component, django-components will attempt to resolve the path relative to the component directories, as set in COMPONENTS.dirs or COMPONENTS.app_dirs.
Once the component's media files have been loaded once, they will remain in-memory on the Component class:
HTML from Component.template_file will be available under Component.template
CSS from Component.css_file will be available under Component.css
JS from Component.js_file will be available under Component.js
Thus, whether you define HTML via Component.template_file or Component.template, you can always access the HTML content under Component.template. And the same applies for JS and CSS.
Example:
# When we create Calendar component, the files like `calendar/template.html`\n# are not yet loaded!\n@register(\"calendar\")\nclass Calendar(Component):\n template_file = \"calendar/template.html\"\n css_file = \"calendar/style.css\"\n js_file = \"calendar/script.js\"\n\n class Media:\n css = \"calendar/style1.css\"\n js = \"calendar/script2.js\"\n\n# It's only at this moment that django-components reads the files like `calendar/template.html`\nprint(Calendar.css)\n# Output:\n# .calendar {\n# width: 200px;\n# background: pink;\n# }\n
Warning
Do NOT modify HTML / CSS / JS after it has been loaded
django-components assumes that the component's media files like js_file or Media.js/css are static.
If you need to dynamically change these media files, consider instead defining multiple Components.
Modifying these files AFTER the component has been loaded at best does nothing. However, this is an untested behavior, which may lead to unexpected errors.
When a component recieves input through {% component %} tag, or the Component.render() or Component.render_to_response() methods, you can define how the input is handled, and what variables will be available to the template, JavaScript and CSS.
The get_template_data() method is the primary way to provide variables to your HTML template. It receives the component inputs and returns a dictionary of data that will be available in the template.
If get_template_data() returns None, an empty dictionary will be used.
class ProfileCard(Component):\n template_file = \"profile_card.html\"\n\n class Kwargs(NamedTuple):\n user_id: int\n show_details: bool\n\n def get_template_data(self, args, kwargs: Kwargs, slots, context):\n user = User.objects.get(id=kwargs.user_id)\n\n # Process and transform inputs\n return {\n \"user\": user,\n \"show_details\": kwargs.show_details,\n \"user_joined_days\": (timezone.now() - user.date_joined).days,\n }\n
In your template, you can then use these variables:
The get_context_data() method is the legacy way to provide variables to your HTML template. It serves the same purpose as get_template_data() - it receives the component inputs and returns a dictionary of data that will be available in the template.
However, get_context_data() has a few drawbacks:
It does NOT receive the slots and context parameters.
The args and kwargs parameters are given as variadic *args and **kwargs parameters. As such, they cannot be typed.
The input property is deprecated and will be removed in v1.
Instead, use properties defined on the Component class directly like self.context.
To access the unmodified inputs, use self.raw_args, self.raw_kwargs, and self.raw_slots properties.
The previous two approaches allow you to access only the most important inputs.
There are additional settings that may be passed to components. If you need to access these, you can use self.input property for a low-level access to all the inputs.
The input property contains all the inputs passed to the component (instance of ComponentInput).
This includes:
input.args - List of positional arguments
input.kwargs - Dictionary of keyword arguments
input.slots - Dictionary of slots. Values are normalized to Slot instances
input.context - Context object that should be used to render the component
input.type - The type of the component (document, fragment)
input.render_dependencies - Whether to render dependencies (CSS, JS)
class ProfileCard(Component):\n def get_template_data(self, args, kwargs, slots, context):\n # Access positional arguments\n user_id = self.input.args[0] if self.input.args else None\n\n # Access keyword arguments\n show_details = self.input.kwargs.get(\"show_details\", False)\n\n # Render component differently depending on the type\n if self.input.type == \"fragment\":\n ...\n\n return {\n \"user_id\": user_id,\n \"show_details\": show_details,\n }\n
Info
Unlike the parameters passed to the data methods, the args, kwargs, and slots in self.input property are always lists and dictionaries, regardless of whether you added typing classes to your component (like Args, Kwargs, or Slots).
You can use Defaults class to provide default values for your inputs.
These defaults will be applied either when:
The input is not provided at rendering time
The input is provided as None
When you then access the inputs in your data methods, the default values will be already applied.
Read more about Component Defaults.
from django_components import Component, Default, register\n\n@register(\"profile_card\")\nclass ProfileCard(Component):\n class Kwargs(NamedTuple):\n show_details: bool\n\n class Defaults:\n show_details = True\n\n # show_details will be set to True if `None` or missing\n def get_template_data(self, args, kwargs: Kwargs, slots, context):\n return {\n \"show_details\": kwargs.show_details,\n }\n\n ...\n
Warning
When typing your components with Args, Kwargs, or Slots classes, you may be inclined to define the defaults in the classes.
class ProfileCard(Component):\n class Kwargs(NamedTuple):\n show_details: bool = True\n
This is NOT recommended, because:
The defaults will NOT be applied to inputs when using self.raw_kwargs property.
The defaults will NOT be applied when a field is given but set to None.
Instead, define the defaults in the Defaults class.
You can add type hints for the component inputs to ensure that the component logic is correct.
For this, define the Args, Kwargs, and Slots classes, and then add type hints to the data methods.
This will also validate the inputs at runtime, as the type classes will be instantiated with the inputs.
Read more about Component typing.
from typing import NamedTuple, Optional\nfrom django_components import Component, SlotInput\n\nclass Button(Component):\n class Args(NamedTuple):\n name: str\n\n class Kwargs(NamedTuple):\n surname: str\n maybe_var: Optional[int] = None # May be omitted\n\n class Slots(NamedTuple):\n my_slot: Optional[SlotInput] = None\n footer: SlotInput\n\n # Use the above classes to add type hints to the data method\n def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n # The parameters are instances of the classes we defined\n assert isinstance(args, Button.Args)\n assert isinstance(kwargs, Button.Kwargs)\n assert isinstance(slots, Button.Slots)\n
Note
To access \"untyped\" inputs, use self.raw_args, self.raw_kwargs, and self.raw_slots properties.
These are plain lists and dictionaries, even when you added typing to your component.
It's best practice to explicitly define what args and kwargs a component accepts.
However, if you want a looser setup, you can easily write components that accept any number of kwargs, and pass them all to the template (similar to django-cotton).
To do that, simply return the kwargs dictionary itself from get_template_data():
class MyComponent(Component):\n def get_template_data(self, args, kwargs, slots, context):\n return kwargs\n
You can do the same for get_js_data() and get_css_data(), if needed:
The most common use of django-components is to render HTML when the server receives a request. As such, there are a few features that are dependent on the request object.
"},{"location":"concepts/fundamentals/http_request/#passing-the-httprequest-object","title":"Passing the HttpRequest object","text":"
In regular Django templates, the request object is available only within the RequestContext.
In Components, you can either use RequestContext, or pass the request object explicitly to Component.render() and Component.render_to_response().
So the request object is available to components either when:
The component is rendered with RequestContext (Regular Django behavior)
The component is rendered with a regular Context (or none), but you set the request kwarg of Component.render().
The component is nested and the parent has access to the request object.
# \u2705 With request\nMyComponent.render(request=request)\nMyComponent.render(context=RequestContext(request, {}))\n\n# \u274c Without request\nMyComponent.render()\nMyComponent.render(context=Context({}))\n
When a component is rendered within a template with {% component %} tag, the request object is available depending on whether the template is rendered with RequestContext or not.
template = Template(\"\"\"\n<div>\n {% component \"MyComponent\" / %}\n</div>\n\"\"\")\n\n# \u274c No request\nrendered = template.render(Context({}))\n\n# \u2705 With request\nrendered = template.render(RequestContext(request, {}))\n
"},{"location":"concepts/fundamentals/http_request/#accessing-the-httprequest-object","title":"Accessing the HttpRequest object","text":"
When the component has access to the request object, the request object will be available in Component.request.
When a component is being rendered, whether with Component.render() or {% component %}, a component instance is populated with the current inputs and context. This allows you to access things like component inputs.
We refer to these render-time-only methods and attributes as the \"Render API\".
Render API is available inside these Component methods:
Component ID (or render ID) is a unique identifier for the current render call.
That means that if you call Component.render() multiple times, the ID will be different for each call.
It is available as self.id.
The ID is a 7-letter alphanumeric string in the format cXXXXXX, where XXXXXX is a random string of 6 alphanumeric characters (case-sensitive).
E.g. c1a2b3c.
A single render ID has a chance of collision 1 in 57 billion. However, due to birthday paradox, the chance of collision increases to 1% when approaching ~33K render IDs.
Thus, there is currently a soft-cap of ~30K components rendered on a single page.
If you need to expand this limit, please open an issue on GitHub.
Components support a provide / inject system as known from Vue or React.
When rendering the component, you can call self.inject() with the key of the data you want to inject.
The object returned by self.inject()
To provide data to components, use the {% provide %} template tag.
Read more about Provide / Inject.
class Table(Component):\n def get_template_data(self, args, kwargs, slots, context):\n # Access provided data\n data = self.inject(\"some_data\")\n assert data.some_data == \"some_data\"\n
"},{"location":"concepts/fundamentals/render_api/#template-tag-metadata","title":"Template tag metadata","text":"
If the component is rendered with {% component %} template tag, the following metadata is available:
self.node - The ComponentNode instance
self.registry - The ComponentRegistry instance that was used to render the component
self.registered_name - The name under which the component was registered
self.outer_context - The context outside of the {% component %} tag
{% with abc=123 %}\n {{ abc }} {# <--- This is in outer context #}\n {% component \"my_component\" / %}\n{% endwith %}\n
You can use these to check whether the component was rendered inside a template with {% component %} tag or in Python with Component.render().
class MyComponent(Component):\n def get_template_data(self, args, kwargs, slots, context):\n if self.registered_name is None:\n # Do something for the render() function\n else:\n # Do something for the {% component %} template tag\n
You can access the ComponentNode under Component.node:
class MyComponent(Component):\n def get_template_data(self, context, template):\n if self.node is not None:\n assert self.node.name == \"my_component\"\n
Accessing the ComponentNode is mostly useful for extensions, which can modify their behaviour based on the source of the Component.
For example, if MyComponent was used in another component - that is, with a {% component \"my_component\" %} tag in a template that belongs to another component - then you can use self.node.template_component to access the owner Component class.
class Parent(Component):\n template: types.django_html = \"\"\"\n <div>\n {% component \"my_component\" / %}\n </div>\n \"\"\"\n\n@register(\"my_component\")\nclass MyComponent(Component):\n def get_template_data(self, context, template):\n if self.node is not None:\n assert self.node.template_component == Parent\n
Info
Component.node is None if the component is created by Component.render() (but you can pass in the node kwarg yourself).
Unlike regular Django template tags, django-components' tags offer extra features like defining literal lists and dicts, and more. Read more about Template tag syntax.
By default, components behave similarly to Django's {% include %}, and the template inside the component has access to the variables defined in the outer template.
You can selectively isolate a component, using the only flag, so that the inner template can access only the data that was explicitly passed to it:
{% component \"name\" positional_arg keyword_arg=value ... only / %}\n
Alternatively, you can set all components to be isolated by default, by setting context_behavior to \"isolated\" in your settings:
The rendered HTML may be used in different contexts (browser, email, etc), and each may need different handling of JS and CSS scripts.
render() and render_to_response() accept a deps_strategy parameter, which controls where and how the JS / CSS are inserted into the HTML.
The deps_strategy parameter is ultimately passed to render_dependencies().
Learn more about Rendering JS / CSS.
There are six dependencies rendering strategies:
document (default)
Smartly inserts JS / CSS into placeholders ({% component_js_dependencies %}) or into <head> and <body> tags.
Inserts extra script to allow fragment components to work.
Assumes the HTML will be rendered in a JS-enabled browser.
fragment
A lightweight HTML fragment to be inserted into a document with AJAX.
Assumes the page was already rendered with \"document\" strategy.
No JS / CSS included.
simple
Smartly insert JS / CSS into placeholders ({% component_js_dependencies %}) or into <head> and <body> tags.
No extra script loaded.
prepend
Insert JS / CSS before the rendered HTML.
Ignores the placeholders ({% component_js_dependencies %}) and any <head>/<body> HTML tags.
No extra script loaded.
append
Insert JS / CSS after the rendered HTML.
Ignores the placeholders ({% component_js_dependencies %}) and any <head>/<body> HTML tags.
No extra script loaded.
ignore
HTML is left as-is. You can still process it with a different strategy later with render_dependencies().
Used for inserting rendered HTML into other components.
Info
You can use the \"prepend\" and \"append\" strategies to force to output JS / CSS for components that don't have neither the placeholders like {% component_js_dependencies %}, nor any <head>/<body> HTML tags:
The render() and render_to_response() methods accept an optional context argument. This sets the context within which the component is rendered.
When a component is rendered within a template with the {% component %} tag, this will be automatically set to the Context instance that is used for rendering the template.
When you call Component.render() directly from Python, there is no context object, so you can ignore this input most of the time. Instead, use args, kwargs, and slots to pass data to the component.
However, you can pass RequestContext to the context argument, so that the component will gain access to the request object and will use context processors. Read more on Working with HTTP requests.
For advanced use cases, you can use context argument to \"pre-render\" the component in Python, and then pass the rendered output as plain string to the template. With this, the inner component is rendered as if it was within the template with {% component %}.
class Button(Component):\n def render(self, context, template):\n # Pass `context` to Icon component so it is rendered\n # as if nested within Button.\n icon = Icon.render(\n context=context,\n args=[\"icon-name\"],\n deps_strategy=\"ignore\",\n )\n # Update context with icon\n with context.update({\"icon\": icon}):\n return template.render(context)\n
Warning
Whether the variables defined in context are actually available in the template depends on the context behavior mode:
In \"django\" context behavior mode, the template will have access to the keys of this context.
In \"isolated\" context behavior mode, the template will NOT have access to this context, and data MUST be passed via component's args and kwargs.
Therefore, it's strongly recommended to not rely on defining variables on the context object, but instead passing them through as args and kwargs
\u274c Don't do this:
html = ProfileCard.render(\n context={\"name\": \"John\"},\n)\n
\u2705 Do this:
html = ProfileCard.render(\n kwargs={\"name\": \"John\"},\n)\n
Neither Component.render() nor Component.render_to_response() are typed, due to limitations of Python's type system.
To add type hints, you can wrap the inputs in component's Args, Kwargs, and Slots classes.
Read more on Typing and validation.
from typing import NamedTuple, Optional\nfrom django_components import Component, Slot, SlotInput\n\n# Define the component with the types\nclass Button(Component):\n class Args(NamedTuple):\n name: str\n\n class Kwargs(NamedTuple):\n surname: str\n age: int\n\n class Slots(NamedTuple):\n my_slot: Optional[SlotInput] = None\n footer: SlotInput\n\n# Add type hints to the render call\nButton.render(\n args=Button.Args(\n name=\"John\",\n ),\n kwargs=Button.Kwargs(\n surname=\"Doe\",\n age=30,\n ),\n slots=Button.Slots(\n footer=Slot(lambda ctx: \"Click me!\"),\n ),\n)\n
"},{"location":"concepts/fundamentals/rendering_components/#components-as-input","title":"Components as input","text":"
django_components makes it possible to compose components in a \"React-like\" way, where you can render one component and use its output as input to another component:
from django.utils.safestring import mark_safe\n\n# Render the inner component\ninner_html = InnerComponent.render(\n kwargs={\"some_data\": \"value\"},\n deps_strategy=\"ignore\", # Important for nesting!\n)\n\n# Use inner component's output in the outer component\nouter_html = OuterComponent.render(\n kwargs={\n \"content\": mark_safe(inner_html), # Mark as safe to prevent escaping\n },\n)\n
The key here is setting deps_strategy=\"ignore\" for the inner component. This prevents duplicate rendering of JS / CSS dependencies when the outer component is rendered.
When deps_strategy=\"ignore\":
No JS or CSS dependencies will be added to the output HTML
The component's content is rendered as-is
The outer component will take care of including all needed dependencies
Django components defines a special \"dynamic\" component (DynamicComponent).
Normally, you have to hard-code the component name in the template:
{% component \"button\" / %}\n
The dynamic component allows you to dynamically render any component based on the is kwarg. This is similar to Vue's dynamic components (<component :is>).
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.
Django-components provides a seamless integration with HTML fragments with AJAX (HTML over the wire), whether you're using jQuery, HTMX, AlpineJS, vanilla JavaScript, or other.
This is achieved by the combination of the \"document\" and \"fragment\" dependencies rendering strategies.
Read more about HTML fragments and Rendering JS / CSS.
Each component can define extra or \"secondary\" CSS / JS files using the nested Component.Media class, by setting Component.Media.js and Component.Media.css.
The main HTML / JS / CSS files are limited to 1 per component. This is not the case for the secondary files, where components can have many of them.
There is also no special behavior or post-processing for these secondary files, they are loaded as is.
You can use these for third-party libraries, or for shared CSS / JS files.
These must be set as paths, URLs, or custom objects.
Use the Media class to define secondary JS / CSS files for a component.
This Media class behaves similarly to Django's Media class:
Static paths - Paths are handled as static file paths, and are resolved to URLs with Django's {% static %} template tag.
URLs - A path that starts with http, https, or / is considered a URL. URLs are NOT resolved with {% static %}.
HTML tags - Both static paths and URLs are rendered to <script> and <link> HTML tags with media_class.render_js() and media_class.render_css().
Bypass formatting - A SafeString, or a function (with __html__ method) is considered an already-formatted HTML tag, skipping both static file resolution and rendering with media_class.render_js() or media_class.render_css().
Inheritance - You can set extend to configure whether to inherit JS / CSS from parent components. See Media inheritance.
However, there's a few differences from Django's Media class:
Our Media class accepts various formats for the JS and CSS files: either a single file, a list, or (CSS-only) a dictonary (See ComponentMediaInput).
Individual JS / CSS files can be any of str, bytes, Path, SafeString, or a function (See ComponentMediaInputPath).
Individual JS / CSS files can be glob patterns, e.g. *.js or styles/**/*.css.
If you set Media.extend to a list, it should be a list of Component classes.
from components.layout import LayoutComp\n\nclass MyTable(Component):\n class Media:\n js = [\n \"path/to/script.js\",\n \"path/to/*.js\", # Or as a glob\n \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\", # AlpineJS\n ]\n css = {\n \"all\": [\n \"path/to/style.css\",\n \"path/to/*.css\", # Or as a glob\n \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\", # TailwindCSS\n ],\n \"print\": [\"path/to/style2.css\"],\n }\n\n # Reuse JS / CSS from LayoutComp\n extend = [\n LayoutComp,\n ]\n
"},{"location":"concepts/fundamentals/secondary_js_css_files/#css-media-types","title":"CSS media types","text":"
You can define which stylesheets will be associated with which CSS media types. You do so by defining CSS files as a dictionary.
See the corresponding Django Documentation.
Again, you can set either a single file or a list of files per media type:
class MyComponent(Component):\n class Media:\n css = {\n \"all\": \"path/to/style1.css\",\n \"print\": [\"path/to/style2.css\", \"path/to/style3.css\"],\n }\n
By default, the media files are inherited from the parent component.
class ParentComponent(Component):\n class Media:\n js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n class Media:\n js = [\"script.js\"]\n\nprint(MyComponent.media._js) # [\"parent.js\", \"script.js\"]\n
You can set the component NOT to inherit from the parent component by setting the extend attribute to False:
class ParentComponent(Component):\n class Media:\n js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n class Media:\n extend = False # Don't inherit parent media\n js = [\"script.js\"]\n\nprint(MyComponent.media._js) # [\"script.js\"]\n
Alternatively, you can specify which components to inherit from. In such case, the media files are inherited ONLY from the specified components, and NOT from the original parent components:
class ParentComponent(Component):\n class Media:\n js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n class Media:\n # Only inherit from these, ignoring the files from the parent\n extend = [OtherComponent1, OtherComponent2]\n\n js = [\"script.js\"]\n\nprint(MyComponent.media._js) # [\"script.js\", \"other1.js\", \"other2.js\"]\n
Info
The extend behaves consistently with Django's Media class, with one exception:
When you set extend to a list, the list is expected to contain Component classes (or other classes that have a nested Media class).
"},{"location":"concepts/fundamentals/secondary_js_css_files/#accessing-media-files","title":"Accessing Media files","text":"
To access the files that you defined under Component.Media, use Component.media (lowercase).
This is consistent behavior with Django's Media class.
class MyComponent(Component):\n class Media:\n js = \"path/to/script.js\"\n css = \"path/to/style.css\"\n\nprint(MyComponent.media)\n# Output:\n# <script src=\"/static/path/to/script.js\"></script>\n# <link href=\"/static/path/to/style.css\" media=\"all\" rel=\"stylesheet\">\n
When working with component media files, it is important to understand the difference:
Component.Media
Is the \"raw\" media definition, or the input, which holds only the component's own media definition
This class is NOT instantiated, it merely holds the JS / CSS files.
Component.media
Returns all resolved media files, including those inherited from parent components
Is an instance of Component.media_class
class ParentComponent(Component):\n class Media:\n js = [\"parent.js\"]\n\nclass ChildComponent(ParentComponent):\n class Media:\n js = [\"child.js\"]\n\n# Access only this component's media\nprint(ChildComponent.Media.js) # [\"child.js\"]\n\n# Access all inherited media\nprint(ChildComponent.media._js) # [\"parent.js\", \"child.js\"]\n
Note
You should not manually modify Component.media or Component.Media after the component has been resolved, as this may lead to unexpected behavior.
If you want to modify the class that is instantiated for Component.media, you can configure Component.media_class (See example).
Unlike the main HTML / JS / CSS files, the path definition for the secondary files are quite ergonomic.
"},{"location":"concepts/fundamentals/secondary_js_css_files/#relative-to-component","title":"Relative to component","text":"
As seen in the getting started example, to associate HTML / JS / CSS files with a component, you can set them as Component.template_file, Component.js_file and Component.css_file respectively:
At component class creation, django-components checks all file paths defined on the component (e.g. Component.template_file).
For each file path, it checks if the file path is relative to the component's directory. And such file exists, the component's file path is re-written to be defined relative to a first matching directory in COMPONENTS.dirs or COMPONENTS.app_dirs.
Example:
[root]/components/mytable/mytable.py
class MyTable(Component):\n template_file = \"mytable.html\"\n
Component MyTable is defined in file [root]/components/mytable/mytable.py.
The component's directory is thus [root]/components/mytable/.
Because MyTable.template_file is mytable.html, django-components tries to resolve it as [root]/components/mytable/mytable.html.
django-components checks the filesystem. If there's no such file, nothing happens.
If there IS such file, django-components tries to rewrite the path.
django-components searches COMPONENTS.dirs and COMPONENTS.app_dirs for a first directory that contains [root]/components/mytable/mytable.html.
It comes across [root]/components/, which DOES contain the path to mytable.html.
Thus, it rewrites template_file from mytable.html to mytable/mytable.html.
NOTE: In case of ambiguity, the preference goes to resolving the files relative to the component's directory.
Components can have many secondary files. To simplify their declaration, you can use globs.
Globs MUST be relative to the component's directory.
[project root]/components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n class Media:\n js = [\n \"path/to/*.js\",\n \"another/path/*.js\",\n ]\n css = \"*.css\"\n
How this works is that django-components will detect that the path is a glob, and will try to resolve all files matching the glob pattern relative to the component's directory.
After that, the file paths are handled the same way as if you defined them explicitly.
"},{"location":"concepts/fundamentals/secondary_js_css_files/#paths-as-objects","title":"Paths as objects","text":"
In the example above, you can see that when we used Django's mark_safe() to mark a string as a SafeString, we had to define the URL / path as an HTML <script>/<link> elements.
This is an extension of Django's Paths as objects feature, where \"safe\" strings are taken as is, and are accessed only at render time.
Because of that, the paths defined as \"safe\" strings are NEVER resolved, neither relative to component's directory, nor relative to COMPONENTS.dirs. It is assumed that you will define the full <script>/<link> tag with the correct URL / path.
\"Safe\" strings can be used to lazily resolve a path, or to customize the <script> or <link> tag for individual paths:
In the example below, we make use of \"safe\" strings to add type=\"module\" to the script tag that will fetch calendar/script2.js. In this case, we implemented a \"safe\" string by defining a __html__ method.
As part of the rendering process, the secondary JS / CSS files are resolved and rendered into <link> and <script> HTML tags, so they can be inserted into the render.
In the Paths as objects section, we saw that we can use that to selectively change how the HTML tags are constructed.
However, if you need to change how ALL CSS and JS files are rendered for a given component, you can provide your own subclass of Django's Media class to the Component.media_class attribute.
To change how the tags are constructed, you can override the Media.render_js() and Media.render_css() methods:
from django.forms.widgets import Media\nfrom django_components import Component, register\n\nclass MyMedia(Media):\n # Same as original Media.render_js, except\n # the `<script>` tag has also `type=\"module\"`\n def render_js(self):\n tags = []\n for path in self._js:\n if hasattr(path, \"__html__\"):\n tag = path.__html__()\n else:\n tag = format_html(\n '<script type=\"module\" src=\"{}\"></script>',\n self.absolute_path(path)\n )\n return tags\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_file = \"calendar/template.html\"\n css_file = \"calendar/style.css\"\n js_file = \"calendar/script.js\"\n\n class Media:\n css = \"calendar/style1.css\"\n js = \"calendar/script2.js\"\n\n # Override the behavior of Media class\n media_class = MyMedia\n
If you \"inline\" the HTML, JS and CSS code into the Python class, you should set up syntax highlighting to let your code editor know that the inlined code is HTML, JS and CSS.
In the examples above, we've annotated the template, js, and css attributes with the types.django_html, types.js and types.css types. These are used for syntax highlighting in VSCode.
Warning
Autocompletion / intellisense does not work in the inlined code.
Help us add support for intellisense in the inlined code! Start a conversation in the GitHub Discussions.
First install Python Inline Source Syntax Highlighting extension, it will give you syntax highlighting for the template, CSS, and JS.
Next, in your component, set typings of Component.template, Component.js, Component.css to types.django_html, types.css, and types.js respectively. The extension will recognize these and will activate syntax highlighting.
"},{"location":"concepts/fundamentals/single_file_components/#pycharm-or-other-jetbrains-ides","title":"Pycharm (or other Jetbrains IDEs)","text":"
With PyCharm (or any other editor from Jetbrains), you don't need to use types.django_html, types.css, types.js since Pycharm uses language injections.
You only need to write the comments # language=<lang> above the variables.
"},{"location":"concepts/fundamentals/single_file_components/#markdown-code-blocks-with-pygments","title":"Markdown code blocks with Pygments","text":"
Pygments is a syntax highlighting library written in Python. It's also what's used by this documentation site (mkdocs-material) to highlight code blocks.
To write code blocks with syntax highlighting, you need to install the pygments-djc package.
pip install pygments-djc\n
And then initialize it by importing pygments_djc somewhere in your project:
import pygments_djc\n
Now you can use the djc_py code block to write code blocks with syntax highlighting for components.
django-components has the most extensive slot system of all the popular Python templating engines.
The slot system is based on Vue, and works across both Django templates and Python code.
"},{"location":"concepts/fundamentals/slots/#what-are-slots","title":"What are slots?","text":"
Components support something called 'slots'.
When you write a component, you define its template. The template will always be the same each time you render the component.
However, sometimes you may want to customize the component slightly to change the content of the component. This is where slots come in.
Slots allow you to insert parts of HTML into the component. This makes components more reusable and composable.
<div class=\"calendar-component\">\n <div class=\"header\">\n {# This is where the component will insert the content #}\n {% slot \"header\" / %}\n </div>\n</div>\n
{% slot %} tag - Inside your component you decide where you want to insert the content.
{% fill %} tag - In the parent template (outside the component) you decide what content to insert into the slot. It \"fills\" the slot with the specified content.
Let's look at an example:
First, we define the component template. This component contains two slots, header and body.
Do NOT combine default fills with explicit named {% fill %} tags.
The following component template will raise an error when rendered:
\u274c Don't do this
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}Totally new header!{% endfill %}\n Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n
\u2705 Do this instead
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}Totally new header!{% endfill %}\n {% fill \"default\" %}\n Can you believe it's already <span>{{ date }}</span>??\n {% endfill %}\n{% endcomponent %}\n
Warning
You cannot double-fill a slot.
That is, if both {% fill \"default\" %} and {% fill \"header\" %} point to the same slot, this will raise an error when rendered.
You can access the fills with the {{ component_vars.slots.<name> }} template variable:
{% if component_vars.slots.my_slot %}\n <div>\n {% fill \"my_slot\" %}\n Filled content\n {% endfill %}\n </div>\n{% endif %}\n
And in Python with the Component.slots property:
class Calendar(Component):\n # `get_template_data` receives the `slots` argument directly\n def get_template_data(self, args, kwargs, slots, context):\n if \"my_slot\" in slots:\n content = \"Filled content\"\n else:\n content = \"Default content\"\n\n return {\n \"my_slot\": content,\n }\n\n # In other methods you can still access the slots with `Component.slots`\n def on_render_before(self, context, template):\n if \"my_slot\" in self.slots:\n # Do something\n
The slot and fill names can be set as variables. This way you can fill slots dynamically:
{% with \"body\" as slot_name %}\n {% component \"calendar\" %}\n {% fill slot_name %}\n Filled content\n {% endfill %}\n {% endcomponent %}\n{% endwith %}\n
You can even use {% if %} and {% for %} tags inside the {% component %} tag to fill slots with more control:
{% component \"calendar\" %}\n {% if condition %}\n {% fill \"name\" %}\n Filled content\n {% endfill %}\n {% endif %}\n\n {% for item in items %}\n {% fill item.name %}\n Item: {{ item.value }}\n {% endfill %}\n {% endfor %}\n{% endcomponent %}\n
You can also use {% with %} or even custom tags to generate the fills dynamically:
{% component \"calendar\" %}\n {% with item.name as name %}\n {% fill name %}\n Item: {{ item.value }}\n {% endfill %}\n {% endwith %}\n{% endcomponent %}\n
Warning
If you dynamically generate {% fill %} tags, be careful to render text only inside the {% fill %} tags.
Any text rendered outside {% fill %} tags will be considered a default fill and will raise an error if combined with explicit fills. (See Default slot)
Sometimes the slots need to access data from the component. Imagine an HTML table component which has a slot to configure how to render the rows. Each row has a different data, so you need to pass the data to the slot.
Similarly to Vue's scoped slots, you can pass data to the slot, and then access it in the fill.
This consists of two steps:
Passing data to {% slot %} tag
Accessing data in {% fill %} tag
The data is passed to the slot as extra keyword arguments. Below we set two extra arguments: first_name and job.
{# Pass data to the slot #}\n{% slot \"name\" first_name=\"John\" job=\"Developer\" %}\n {# Fallback implementation #}\n Name: {{ first_name }}\n Job: {{ job }}\n{% endslot %}\n
Note
name kwarg is already used for slot name, so you cannot pass it as slot data.
To access the slot's data in the fill, use the data keyword. This sets the name of the variable that holds the data in the fill:
{# Access data in the fill #}\n{% component \"profile\" %}\n {% fill \"name\" data=\"d\" %}\n Hello, my name is <h1>{{ d.first_name }}</h1>\n and I'm a <h2>{{ d.job }}</h2>\n {% endfill %}\n{% endcomponent %}\n
To access the slot data in Python, use the data attribute in slot functions.
def my_slot(ctx):\n return f\"\"\"\n Hello, my name is <h1>{ctx.data[\"first_name\"]}</h1>\n and I'm a <h2>{ctx.data[\"job\"]}</h2>\n \"\"\"\n\nProfile.render(\n slots={\n \"name\": my_slot,\n },\n)\n
Slot data can be set also when rendering a slot in Python:
In Python code, slot fills can be defined as strings, functions, or Slot instances that wrap the two. Slot functions have access to slot data, fallback, and context.
When accessing slots from within Component methods, the Slot instances are populated with extra metadata:
component_name
slot_name
nodelist
fill_node
extra
These are populated the first time a slot is passed to a component.
So if you pass the same slot through multiple nested components, the metadata will still point to the first component that received the slot.
You can use these for debugging, such as printing out the slot's component name and slot name.
Fill node
Components or extensions can use Slot.fill_node to handle slots differently based on whether the slot was defined in the template with {% fill %} and {% component %} tags, or in the component's Python code.
If the slot was created from a {% fill %} tag, this will be the FillNode instance.
If the slot was a default slot created from a {% component %} tag, this will be the ComponentNode instance.
You can use this to find the Component in whose template the {% fill %} tag was defined:
class MyTable(Component):\n def get_template_data(self, args, kwargs, slots, context):\n footer_slot = slots.get(\"footer\")\n if footer_slot is not None and footer_slot.fill_node is not None:\n owner_component = footer_slot.fill_node.template_component\n # ...\n
Extra
You can also pass any additional data along with the slot by setting it in Slot.extra:
Read more about Django's format_html and mark_safe.
"},{"location":"concepts/fundamentals/slots/#examples","title":"Examples","text":""},{"location":"concepts/fundamentals/slots/#pass-through-all-the-slots","title":"Pass through all the slots","text":"
You can dynamically pass all slots to a child component. This is similar to passing all slots in Vue:
class MyTable(Component):\n template = \"\"\"\n <div>\n {% component \"child\" %}\n {% for slot_name, slot in component_vars.slots.items %}\n {% fill name=slot_name body=slot / %}\n {% endfor %}\n {% endcomponent %}\n </div>\n \"\"\"\n
"},{"location":"concepts/fundamentals/slots/#required-and-default-slots","title":"Required and default slots","text":"
Since each {% slot %} is tagged with required and default individually, you can have multiple slots with the same name but different conditions.
In this example, we have a component that renders a user avatar - a small circular image with a profile picture or name initials.
If the component is given image_src or name_initials variables, the image slot is optional.
But if neither of those are provided, you MUST fill the image slot.
<div class=\"avatar\">\n {# Image given, so slot is optional #}\n {% if image_src %}\n {% slot \"image\" default %}\n <img src=\"{{ image_src }}\" />\n {% endslot %}\n\n {# Image not given, but we can make image from initials, so slot is optional #} \n {% elif name_initials %}\n {% slot \"image\" default %}\n <div style=\"\n border-radius: 25px;\n width: 50px;\n height: 50px;\n background: blue;\n \">\n {{ name_initials }}\n </div>\n {% endslot %}\n\n {# Neither image nor initials given, so slot is required #}\n {% else %}\n {% slot \"image\" default required / %}\n {% endif %}\n</div>\n
"},{"location":"concepts/fundamentals/slots/#dynamic-slots-in-table-component","title":"Dynamic slots in table component","text":"
Sometimes you may want to generate slots based on the given input. One example of this is Vuetify's table component, which creates a header and an item slots for each user-defined column.
So if you pass columns named name and age to the table component:
Since version 0.70, you could check if a slot was filled with
{{ component_vars.is_filled.<name> }}
Since version 0.140, this has been deprecated and superseded with
{% component_vars.slots.<name> %}
The component_vars.is_filled variable is still available, but will be removed in v1.0.
NOTE: component_vars.slots no longer escapes special characters in slot names.
You can use {{ component_vars.is_filled.<name> }} together with Django's {% if / elif / else / endif %} tags to define a block whose contents will be rendered only if the component slot with the corresponding 'name' is filled.
This is what our example looks like with component_vars.is_filled.
"},{"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
In larger projects, you might need to write multiple components with similar behavior. In such cases, you can extract shared behavior into a standalone component class to keep things DRY.
When subclassing a component, there's a couple of things to keep in mind:
"},{"location":"concepts/fundamentals/subclassing_components/#template-js-and-css-inheritance","title":"Template, JS, and CSS inheritance","text":"
When it comes to the pairs:
Component.template/Component.template_file
Component.js/Component.js_file
Component.css/Component.css_file
inheritance follows these rules:
If a child component class defines either member of a pair (e.g., either template or template_file), it takes precedence and the parent's definition is ignored completely.
For example, if a child component defines template_file, the parent's template or template_file will be ignored.
This applies independently to each pair - you can inherit the JS while overriding the template, for instance.
For example:
class BaseCard(Component):\n template = \"\"\"\n <div class=\"card\">\n <div class=\"card-content\">{{ content }}</div>\n </div>\n \"\"\"\n css = \"\"\"\n .card {\n border: 1px solid gray;\n }\n \"\"\"\n js = \"\"\"console.log('Base card loaded');\"\"\"\n\n# This class overrides parent's template, but inherits CSS and JS\nclass SpecialCard(BaseCard):\n template = \"\"\"\n <div class=\"card special\">\n <div class=\"card-content\">\u2728 {{ content }} \u2728</div>\n </div>\n \"\"\"\n\n# This class overrides parent's template and CSS, but inherits JS\nclass CustomCard(BaseCard):\n template_file = \"custom_card.html\"\n css = \"\"\"\n .card {\n border: 2px solid gold;\n }\n \"\"\"\n
The Component.Media nested class follows Django's media inheritance rules:
If both parent and child define a Media class, the child's media will automatically include both its own and the parent's JS and CSS files.
This behavior can be configured using the extend attribute in the Media class, similar to Django's forms. Read more on this in Media inheritance.
For example:
class BaseModal(Component):\n template = \"<div>Modal content</div>\"\n\n class Media:\n css = [\"base_modal.css\"]\n js = [\"base_modal.js\"] # Contains core modal functionality\n\nclass FancyModal(BaseModal):\n class Media:\n # Will include both base_modal.css/js AND fancy_modal.css/js\n css = [\"fancy_modal.css\"] # Additional styling\n js = [\"fancy_modal.js\"] # Additional animations\n\nclass SimpleModal(BaseModal):\n class Media:\n extend = False # Don't inherit parent's media\n css = [\"simple_modal.css\"] # Only this CSS will be included\n js = [\"simple_modal.js\"] # Only this JS will be included\n
"},{"location":"concepts/fundamentals/subclassing_components/#opt-out-of-inheritance","title":"Opt out of inheritance","text":"
For the following media attributes, when you don't want to inherit from the parent, but you also don't need to set the template / JS / CSS to any specific value, you can set these attributes to None.
template / template_file
js / js_file
css / css_file
Media class
For example:
class BaseForm(Component):\n template = \"...\"\n css = \"...\"\n js = \"...\"\n\n class Media:\n js = [\"form.js\"]\n\n# Use parent's template and CSS, but no JS\nclass ContactForm(BaseForm):\n js = None\n Media = None\n
"},{"location":"concepts/fundamentals/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 %}:
When passing data around, sometimes you may need to do light transformations, like negating booleans or filtering lists.
Normally, what you would have to do is to define ALL the variables inside get_template_data(). But this can get messy if your components contain a lot of logic.
author - passed as str, e.g. John Wick (Comment omitted)
This is inspired by django-cotton.
"},{"location":"concepts/fundamentals/template_tag_syntax/#passing-data-as-string-vs-original-values","title":"Passing data as string vs original values","text":"
In the example above, the kwarg id was passed as an integer, NOT a string.
When the string literal contains only a single template tag, with no extra text (and no extra whitespace), then the value is passed as the original type instead of a string.
{% 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:
To disable this behavior, set COMPONENTS.multiline_tag to False
"},{"location":"concepts/fundamentals/typing_and_validation/","title":"Typing and validation","text":""},{"location":"concepts/fundamentals/typing_and_validation/#typing-overview","title":"Typing overview","text":"
Warning
In versions 0.92 to 0.139 (inclusive), the component typing was specified through generics.
Since v0.140, the types must be specified as class attributes of the Component class - Args, Kwargs, Slots, TemplateData, JsData, and CssData.
See Migrating from generics to class attributes for more info.
Warning
Input validation was NOT part of Django Components between versions 0.136 and 0.139 (inclusive).
The Component class optionally accepts class attributes that allow you to define the types of args, kwargs, slots, as well as the data returned from the data methods.
Use this to add type hints to your components, to validate the inputs at runtime, and to document them.
from typing import NamedTuple, Optional\nfrom django.template import Context\nfrom django_components import Component, SlotInput\n\nclass Button(Component):\n class Args(NamedTuple):\n size: int\n text: str\n\n class Kwargs(NamedTuple):\n variable: str\n maybe_var: Optional[int] = None # May be omitted\n\n class Slots(NamedTuple):\n my_slot: Optional[SlotInput] = None\n\n def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n ...\n\n template_file = \"button.html\"\n
The class attributes are:
Args - Type for positional arguments.
Kwargs - Type for keyword arguments.
Slots - Type for slots.
TemplateData - Type for data returned from get_template_data().
JsData - Type for data returned from get_js_data().
CssData - Type for data returned from get_css_data().
You can specify as many or as few of these as you want, the rest will default to None.
You can use Component.Args, Component.Kwargs, and Component.Slots to type the component inputs.
When you set these classes, at render time the args, kwargs, and slots parameters of the data methods (get_template_data(), get_js_data(), get_css_data()) will be instances of these classes.
This way, each component can have runtime validation of the inputs:
When you use NamedTuple or @dataclass, instantiating these classes will check ONLY for the presence of the attributes.
When you use Pydantic models, instantiating these classes will check for the presence AND type of the attributes.
If you omit the Args, Kwargs, or Slots classes, or set them to None, the inputs will be passed as plain lists or dictionaries, and will not be validated.
from typing_extensions import NamedTuple, TypedDict\nfrom django.template import Context\nfrom django_components import Component, Slot, SlotInput\n\n# The data available to the `footer` scoped slot\nclass ButtonFooterSlotData(TypedDict):\n value: int\n\n# Define the component with the types\nclass Button(Component):\n class Args(NamedTuple):\n name: str\n\n class Kwargs(NamedTuple):\n surname: str\n age: int\n maybe_var: Optional[int] = None # May be omitted\n\n class Slots(NamedTuple):\n # Use `SlotInput` to allow slots to be given as `Slot` instance,\n # plain string, or a function that returns a string.\n my_slot: Optional[SlotInput] = None\n # Use `Slot` to allow ONLY `Slot` instances.\n # The generic is optional, and it specifies the data available\n # to the slot function.\n footer: Slot[ButtonFooterSlotData]\n\n # Add type hints to the data method\n def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n # The parameters are instances of the classes we defined\n assert isinstance(args, Button.Args)\n assert isinstance(kwargs, Button.Kwargs)\n assert isinstance(slots, Button.Slots)\n\n args.name # str\n kwargs.age # int\n slots.footer # Slot[ButtonFooterSlotData]\n\n# Add type hints to the render call\nButton.render(\n args=Button.Args(\n name=\"John\",\n ),\n kwargs=Button.Kwargs(\n surname=\"Doe\",\n age=30,\n ),\n slots=Button.Slots(\n footer=Slot(lambda ctx: \"Click me!\"),\n ),\n)\n
If you don't want to validate some parts, set them to None or omit them.
The following will validate only the keyword inputs:
class Button(Component):\n # We could also omit these\n Args = None\n Slots = None\n\n class Kwargs(NamedTuple):\n name: str\n age: int\n\n # Only `kwargs` is instantiated. `args` and `slots` are not.\n def get_template_data(self, args, kwargs: Kwargs, slots, context: Context):\n assert isinstance(args, list)\n assert isinstance(slots, dict)\n assert isinstance(kwargs, Button.Kwargs)\n\n args[0] # str\n slots[\"footer\"] # Slot[ButtonFooterSlotData]\n kwargs.age # int\n
Info
Components can receive slots as strings, functions, or instances of Slot.
Internally these are all normalized to instances of Slot.
Therefore, the slots dictionary available in data methods (like get_template_data()) will always be a dictionary of Slot instances.
To correctly type this dictionary, you should set the fields of Slots to Slot or SlotInput:
SlotInput is a union of Slot, string, and function types.
You can use Component.TemplateData, Component.JsData, and Component.CssData to type the data returned from get_template_data(), get_js_data(), and get_css_data().
When you set these classes, at render time they will be instantiated with the data returned from these methods.
This way, each component can have runtime validation of the returned data:
When you use NamedTuple or @dataclass, instantiating these classes will check ONLY for the presence of the attributes.
When you use Pydantic models, instantiating these classes will check for the presence AND type of the attributes.
If you omit the TemplateData, JsData, or CssData classes, or set them to None, the validation and instantiation will be skipped.
We recommend to use NamedTuple for the Args class, and NamedTuple, dataclasses, or Pydantic models for Kwargs, Slots, TemplateData, JsData, and CssData classes.
However, you can use any class, as long as they meet the conditions below.
For example, here is how you can use Pydantic models to validate the inputs at runtime.
"},{"location":"concepts/fundamentals/typing_and_validation/#passing-variadic-args-and-kwargs","title":"Passing variadic args and kwargs","text":"
You may have a component that accepts any number of args or kwargs.
However, this cannot be described with the current Python's typing system (as of v0.140).
As a workaround:
For a variable number of positional arguments (*args), set a positional argument that accepts a list of values:
class Table(Component):\n class Args(NamedTuple):\n args: List[str]\n\nTable.render(\n args=Table.Args(args=[\"a\", \"b\", \"c\"]),\n)\n
For a variable number of keyword arguments (**kwargs), set a keyword argument that accepts a dictionary of values:
class Table(Component):\n class Kwargs(NamedTuple):\n variable: str\n another: int\n # Pass any extra keys under `extra`\n extra: Dict[str, any]\n\nTable.render(\n kwargs=Table.Kwargs(\n variable=\"a\",\n another=1,\n extra={\"foo\": \"bar\"},\n ),\n)\n
"},{"location":"concepts/fundamentals/typing_and_validation/#handling-no-args-or-no-kwargs","title":"Handling no args or no kwargs","text":"
To declare that a component accepts no args, kwargs, etc, define the types with no attributes using the pass keyword:
from typing import NamedTuple\nfrom django_components import Component\n\nclass Button(Component):\n class Args(NamedTuple):\n pass\n\n class Kwargs(NamedTuple):\n pass\n\n class Slots(NamedTuple):\n pass\n
This can get repetitive, so we added a Empty type to make it easier:
Since each type class is a separate class attribute, you can just override them in the Component subclass.
In the example below, ButtonExtra inherits Kwargs from Button, but overrides the Args class.
from django_components import Component, Empty\n\nclass Button(Component):\n class Args(NamedTuple):\n size: int\n\n class Kwargs(NamedTuple):\n color: str\n\nclass ButtonExtra(Button):\n class Args(NamedTuple):\n name: str\n size: int\n\n# Stil works the same way!\nButtonExtra.render(\n args=ButtonExtra.Args(name=\"John\", size=30),\n kwargs=ButtonExtra.Kwargs(color=\"red\"),\n)\n
The only difference is when it comes to type hints to the data methods like get_template_data().
When you define the nested classes like Args and Kwargs directly on the class, you can reference them just by their class name (Args and Kwargs).
But when you have a Component subclass, and it uses Args or Kwargs from the parent, you will have to reference the type as a forward reference, including the full name of the component (Button.Args and Button.Kwargs).
Compare the following:
class Button(Component):\n class Args(NamedTuple):\n size: int\n\n class Kwargs(NamedTuple):\n color: str\n\n # Both `Args` and `Kwargs` are defined on the class\n def get_template_data(self, args: Args, kwargs: Kwargs, slots, context):\n pass\n\nclass ButtonExtra(Button):\n class Args(NamedTuple):\n name: str\n size: int\n\n # `Args` is defined on the subclass, `Kwargs` is defined on the parent\n def get_template_data(self, args: Args, kwargs: \"ButtonExtra.Kwargs\", slots, context):\n pass\n\nclass ButtonSame(Button):\n # Both `Args` and `Kwargs` are defined on the parent\n def get_template_data(self, args: \"ButtonSame.Args\", kwargs: \"ButtonSame.Kwargs\", slots, context):\n pass\n
"},{"location":"concepts/fundamentals/typing_and_validation/#runtime-type-validation","title":"Runtime type validation","text":"
When you add types to your component, and implement them as NamedTuple or dataclass, the validation will check only for the presence of the attributes.
So this will not catch if you pass a string to an int attribute.
To enable runtime type validation, you need to use Pydantic models, and install the djc-ext-pydantic extension.
The djc-ext-pydantic extension ensures compatibility between django-components' classes such as Component, or Slot and Pydantic models.
"},{"location":"concepts/fundamentals/typing_and_validation/#migrating-from-generics-to-class-attributes","title":"Migrating from generics to class attributes","text":"
In versions 0.92 to 0.139 (inclusive), the component typing was specified through generics.
Since v0.140, the types must be specified as class attributes of the Component class - Args, Kwargs, Slots, TemplateData, JsData, and CssData.
This change was necessary to make it possible to subclass components. Subclassing with generics was otherwise too complicated. Read the discussion here.
Because of this change, the Component.render() method is no longer typed. To type-check the inputs, you should wrap the inputs in Component.Args, Component.Kwargs, Component.Slots, etc.
For example, if you had a component like this:
from typing import NotRequired, Tuple, TypedDict\nfrom django_components import Component, Slot, SlotInput\n\nButtonArgs = Tuple[int, str]\n\nclass ButtonKwargs(TypedDict):\n variable: str\n another: int\n maybe_var: NotRequired[int] # May be omitted\n\nclass ButtonSlots(TypedDict):\n # Use `SlotInput` to allow slots to be given as `Slot` instance,\n # plain string, or a function that returns a string.\n my_slot: NotRequired[SlotInput]\n # Use `Slot` to allow ONLY `Slot` instances.\n another_slot: Slot\n\nButtonType = Component[ButtonArgs, ButtonKwargs, ButtonSlots]\n\nclass Button(ButtonType):\n def get_context_data(self, *args, **kwargs):\n self.input.args[0] # int\n self.input.kwargs[\"variable\"] # str\n self.input.slots[\"my_slot\"] # Slot[MySlotData]\n\nButton.render(\n args=(1, \"hello\"),\n kwargs={\n \"variable\": \"world\",\n \"another\": 123,\n },\n slots={\n \"my_slot\": \"...\",\n \"another_slot\": Slot(lambda ctx: ...),\n },\n)\n
The steps to migrate are:
Convert all the types (ButtonArgs, ButtonKwargs, ButtonSlots) to subclasses of NamedTuple.
Move these types inside the Component class (Button), and rename them to Args, Kwargs, and Slots.
If you defined typing for the data methods (like get_context_data()), move them inside the Component class, and rename them to TemplateData, JsData, and CssData.
Remove the Component generic.
If you accessed the args, kwargs, or slots attributes via self.input, you will need to add the type hints yourself, because self.input is no longer typed.
Otherwise, you may use Component.get_template_data() instead of get_context_data(), as get_template_data() receives args, kwargs, slots and context as arguments. You will still need to add the type hints yourself.
Lastly, you will need to update the Component.render() calls to wrap the inputs in Component.Args, Component.Kwargs, and Component.Slots, to manually add type hints.
Thus, the code above will become:
from typing import NamedTuple, Optional\nfrom django.template import Context\nfrom django_components import Component, Slot, SlotInput\n\n# The Component class does not take any generics\nclass Button(Component):\n # Types are now defined inside the component class\n class Args(NamedTuple):\n size: int\n text: str\n\n class Kwargs(NamedTuple):\n variable: str\n another: int\n maybe_var: Optional[int] = None # May be omitted\n\n class Slots(NamedTuple):\n # Use `SlotInput` to allow slots to be given as `Slot` instance,\n # plain string, or a function that returns a string.\n my_slot: Optional[SlotInput] = None\n # Use `Slot` to allow ONLY `Slot` instances.\n another_slot: Slot\n\n # The args, kwargs, slots are instances of the component's Args, Kwargs, and Slots classes\n def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n args.size # int\n kwargs.variable # str\n slots.my_slot # Slot[MySlotData]\n\nButton.render(\n # Wrap the inputs in the component's Args, Kwargs, and Slots classes\n args=Button.Args(1, \"hello\"),\n kwargs=Button.Kwargs(\n variable=\"world\",\n another=123,\n ),\n slots=Button.Slots(\n my_slot=\"...\",\n another_slot=Slot(lambda ctx: ...),\n ),\n)\n
"},{"location":"getting_started/adding_js_and_css/","title":"Adding JS and CSS","text":"
Next we will add CSS and JavaScript to our template.
Info
In django-components, using JS and CSS is as simple as defining them on the Component class. You don't have to insert the <script> and <link> tags into the HTML manually.
Behind the scenes, django-components keeps track of which components use which JS and CSS files. Thus, when a component is rendered on the page, the page will contain only the JS and CSS used by the components, and nothing more!
Be sure to prefix your rules with unique CSS class like calendar, so the CSS doesn't clash with other rules.
Note
Soon, django-components will automatically scope your CSS by default, so you won't have to worry about CSS class clashes.
This CSS will be inserted into the page as an inlined <style> tag, at the position defined by {% component_css_dependencies %}, or at the end of the inside the <head> tag (See Default JS / CSS locations).
A good way to make sure the JS of this component doesn't clash with other components is to define all JS code inside an anonymous self-invoking function ((() => { ... })()). This makes all variables defined only be defined inside this component and not affect other components.
Note
Soon, django-components will automatically wrap your JS in a self-invoking function by default (except for JS defined with <script type=\"module\">).
Similarly to CSS, JS will be inserted into the page as an inlined <script> tag, at the position defined by {% component_js_dependencies %}, or at the end of the inside the <body> tag (See Default JS / CSS locations).
Then the JS file of the component calendar will be executed first, and the JS file of component table will be executed second.
JS will be executed only once, even if there is multiple instances of the same component
In this case, the JS of calendar will STILL execute first (because it was found first), and will STILL execute only once, even though it's present twice:
And that's it! If you were to embed this component in an HTML, django-components will automatically embed the associated JS and CSS.
Note
Similarly to the template file, the JS and CSS file paths can be either:
Relative to the Python component file (as seen above),
Relative to any of the component directories as defined by COMPONENTS.dirs and/or COMPONENTS.app_dirs (e.g. [your apps]/components dir and [project root]/components)
Relative to any of the directories defined by STATICFILES_DIRS.
"},{"location":"getting_started/adding_js_and_css/#5-link-additional-js-and-css-to-a-component","title":"5. Link additional JS and CSS to a component","text":"
Your components may depend on third-party packages or styling, or other shared logic. To load these additional dependencies, you can use a nested Media class.
This Media class behaves similarly to Django's Media class, with a few differences:
Our Media class accepts various formats for the JS and CSS files: either a single file, a list, or (CSS-only) a dictonary (see below).
Individual JS / CSS files can be any of str, bytes, Path, SafeString, or a function.
Individual JS / CSS files can be glob patterns, e.g. *.js or styles/**/*.css.
If you set Media.extend to a list, it should be a list of Component classes.
Learn more about using Media.
[project root]/components/calendar/calendar.py
from django_components import Component\n\nclass Calendar(Component):\n template_file = \"calendar.html\"\n js_file = \"calendar.js\"\n css_file = \"calendar.css\"\n\n class Media: # <--- new\n js = [\n \"path/to/shared.js\",\n \"path/to/*.js\", # Or as a glob\n \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\", # AlpineJS\n ]\n css = [\n \"path/to/shared.css\",\n \"path/to/*.css\", # Or as a glob\n \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\", # Tailwind\n ]\n\n def get_template_data(self, args, kwargs, slots, context):\n return {\n \"date\": \"1970-01-01\",\n }\n
Note
Same as with the \"primary\" JS and CSS, the file paths files can be either:
Relative to the Python component file (as seen above),
Relative to any of the component directories as defined by COMPONENTS.dirs and/or COMPONENTS.app_dirs (e.g. [your apps]/components dir and [project root]/components)
Info
The Media nested class is shaped based on Django's Media class.
As such, django-components allows multiple formats to define the nested Media class:
# Single files\nclass Media:\n js = \"calendar.js\"\n css = \"calendar.css\"\n\n# Lists of files\nclass Media:\n js = [\"calendar.js\", \"calendar2.js\"]\n css = [\"calendar.css\", \"calendar2.css\"]\n\n# Dictionary of media types for CSS\nclass Media:\n js = [\"calendar.js\", \"calendar2.js\"]\n css = {\n \"all\": [\"calendar.css\", \"calendar2.css\"],\n }\n
If you define a list of JS files, they will be executed one-by-one, left-to-right.
"},{"location":"getting_started/adding_js_and_css/#rules-of-execution-of-scripts-in-mediajs","title":"Rules of execution of scripts in Media.js","text":"
The scripts defined in Media.js still follow the rules outlined above:
JS is executed in the order in which the components are found in the HTML.
JS will be executed only once, even if there is multiple instances of the same component.
Additionally to Media.js applies that:
JS in Media.js is executed before the component's primary JS.
JS in Media.js is executed in the same order as it was defined.
If there is multiple components that specify the same JS path or URL in Media.js, this JS will be still loaded and executed only once.
Putting all of this together, our Calendar component above would render HTML like so:
Our calendar component's looking great! But we just got a new assignment from our colleague - The calendar date needs to be shown on 3 different pages:
On one page, it needs to be shown as is
On the second, the date needs to be bold
On the third, the date needs to be in italics
As a reminder, this is what the component's template looks like:
<div class=\"calendar\">\n Today's date is <span>{{ date }}</span>\n</div>\n
There's many ways we could approach this:
Expose the date in a slot
Style .calendar > span differently on different pages
Pass a variable to the component that decides how the date is rendered
Create a new component
First two options are more flexible, because the custom styling is not baked into a component's implementation. And for the sake of demonstration, we'll solve this challenge with slots.
"},{"location":"getting_started/adding_slots/#1-what-are-slots","title":"1. What are slots","text":"
Components support something called Slots.
When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content.
This mechanism makes components more reusable and composable.
This behavior is similar to slots in Vue.
In the example below we introduce two tags that work hand in hand to make this work. These are...
{% slot <name> %}/{% endslot %}: Declares a new slot in the component template.
{% fill <name> %}/{% endfill %}: (Used inside a {% component %} tag pair.) Fills a declared slot with the specified content.
"},{"location":"getting_started/adding_slots/#2-add-a-slot-tag","title":"2. Add a slot tag","text":"
Let's update our calendar component to support more customization. We'll add {% slot %} tag to the template:
<div class=\"calendar\">\n Today's date is\n {% slot \"date\" default %} {# <--- new #}\n <span>{{ date }}</span>\n {% endslot %}\n</div>\n
Notice that:
We named the slot date - so we can fill this slot by using {% fill \"date\" %}
We also made it the default slot.
We placed our original implementation inside the {% slot %} tag - this is what will be rendered when the slot is NOT overriden.
"},{"location":"getting_started/adding_slots/#3-add-fill-tag","title":"3. Add fill tag","text":"
Now we can use {% fill %} tags inside the {% component %} tags to override the date slot to generate the bold and italics variants:
<!-- Default -->\n<div class=\"calendar\">\n Today's date is <span>2024-12-13</span>\n</div>\n\n<!-- Bold -->\n<div class=\"calendar\">\n Today's date is <b>2024-12-13</b>\n</div>\n\n<!-- Italics -->\n<div class=\"calendar\">\n Today's date is <i>2024-12-13</i>\n</div>\n
Info
Since we used the default flag on {% slot \"date\" %} inside our calendar component, we can target the date component in multiple ways:
"},{"location":"getting_started/adding_slots/#4-wait-theres-a-bug","title":"4. Wait, there's a bug","text":"
There is a mistake in our code! 2024-12-13 is Friday, so that's fine. But if we updated the to 2024-12-14, which is Saturday, our template from previous step would render this:
<!-- Default -->\n<div class=\"calendar\">\n Today's date is <span>2024-12-16</span>\n</div>\n\n<!-- Bold -->\n<div class=\"calendar\">\n Today's date is <b>2024-12-14</b>\n</div>\n\n<!-- Italics -->\n<div class=\"calendar\">\n Today's date is <i>2024-12-14</i>\n</div>\n
The first instance rendered 2024-12-16, while the rest rendered 2024-12-14!
Why? Remember that in the get_template_data() method of our Calendar component, we pre-process the date. If the date falls on Saturday or Sunday, we shift it to next Monday:
[project root]/components/calendar/calendar.py
from datetime import date\n\nfrom django_components import Component, register\n\n# If date is Sat or Sun, shift it to next Mon, so the date is always workweek.\ndef to_workweek_date(d: date):\n ...\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_file = \"calendar.html\"\n ...\n def get_template_data(self, args, kwargs, slots, context):\n workweek_date = to_workweek_date(kwargs[\"date\"])\n return {\n \"date\": workweek_date,\n \"extra_class\": kwargs.get(\"extra_class\", \"text-blue\"),\n }\n
And the issue is that in our template, we used the date value that we used as input, which is NOT the same as the date variable used inside Calendar's template.
"},{"location":"getting_started/adding_slots/#5-adding-data-to-slots","title":"5. Adding data to slots","text":"
We want to use the same date variable that's used inside Calendar's template.
Luckily, django-components allows passing data to slots, also known as Scoped slots.
This consists of two steps:
Pass the date variable to the {% slot %} tag
Access the date variable in the {% fill %} tag by using the special data kwarg
By using the date variable from the slot, we'll render the correct date each time:
<!-- Default -->\n<div class=\"calendar\">\n Today's date is <span>2024-12-16</span>\n</div>\n\n<!-- Bold -->\n<div class=\"calendar\">\n Today's date is <b>2024-12-16</b>\n</div>\n\n<!-- Italics -->\n<div class=\"calendar\">\n Today's date is <i>2024-12-16</i>\n</div>\n
Info
When to use slots vs variables?
Generally, slots are more flexible - you can access the slot data, even the original slot content. Thus, slots behave more like functions that render content based on their context.
On the other hand, variables are simpler - the variable you pass to a component is what will be used.
Moreover, slots are treated as part of the template - for example the CSS scoping (work in progress) is applied to the slot content too.
"},{"location":"getting_started/components_in_templates/","title":"Components in templates","text":"
By the end of this section, we want to be able to use our components in Django templates like so:
First, however, we need to register our component class with ComponentRegistry.
To register a component with a ComponentRegistry, we will use the @register decorator, and give it a name under which the component will be accessible from within the template:
This will register the component to the default registry. Default registry is loaded into the template by calling {% load component_tags %} inside the template.
Info
Why do we have to register components?
We want to use our component as a template tag ({% ... %}) in Django template.
In Django, template tags are managed by the Library instances. Whenever you include {% load xxx %} in your template, you are loading a Library instance into your template.
ComponentRegistry acts like a router and connects the registered components with the associated Library.
That way, when you include {% load component_tags %} in your template, you are able to \"call\" components like {% component \"calendar\" / %}.
ComponentRegistries also make it possible to group and share components as standalone packages. Learn more here.
Note
You can create custom ComponentRegistry instances, which will use different Library instances. In that case you will have to load different libraries depending on which components you want to use:
Example 1 - Using component defined in the default registry
Note that, because the tag name component is use by the default ComponentRegistry, the custom registry was configured to use the tag my_component instead. Read more here
"},{"location":"getting_started/components_in_templates/#2-load-and-use-the-component-in-template","title":"2. Load and use the component in template","text":"
The component is now registered under the name calendar. All that remains to do is to load and render the component inside a template:
{% load component_tags %} {# Load the default registry #}\n<!DOCTYPE html>\n<html>\n <head>\n <title>My example calendar</title>\n </head>\n <body>\n {% component \"calendar\" / %} {# Render the component #}\n </body>\n<html>\n
Info
Component tags should end with / if they do not contain any Slot fills. But you can also use {% endcomponent %} instead:
{% component \"calendar\" %}{% endcomponent %}\n
We defined the Calendar's template as
<div class=\"calendar\">\n Today's date is <span>{{ date }}</span>\n</div>\n
and the variable date as \"1970-01-01\".
Thus, the final output will look something like this:
This makes it possible to organize your front-end around reusable components, instead of relying on template tags and keeping your CSS and Javascript in the static directory.
Info
Remember that you can use {% component_js_dependencies %} and {% component_css_dependencies %} to change where the <script> and <style> tags will be rendered (See Default JS / CSS locations).
Info
How does django-components pick up registered components?
Notice that it was enough to add @register to the component. We didn't need to import the component file anywhere to execute it.
This is because django-components automatically imports all Python files found in the component directories during an event called Autodiscovery.
So with Autodiscovery, it's the same as if you manually imported the component files on the ready() hook:
class MyApp(AppConfig):\n default_auto_field = \"django.db.models.BigAutoField\"\n name = \"myapp\"\n\n def ready(self):\n import myapp.components.calendar\n import myapp.components.table\n ...\n
You can now render the components in templates!
Currently our component always renders the same content. Let's parametrise it, so that our Calendar component is configurable from within the template \u27a1\ufe0f
Let's put this to test. We want to pass date and extra_class kwargs to the component. And so, we can write the get_template_data() method such that it expects those parameters:
get_template_data() differentiates between positional and keyword arguments, so you have to make sure to pass the arguments correctly.
Since date is expected to be a keyword argument, it MUST be provided as such:
\u2705 `date` is kwarg\n{% component \"calendar\" date=\"2024-12-13\" / %}\n\n\u274c `date` is arg\n{% component \"calendar\" \"2024-12-13\" / %}\n
"},{"location":"getting_started/parametrising_components/#3-process-inputs","title":"3. Process inputs","text":"
The get_template_data() method is powerful, because it allows us to decouple component inputs from the template variables. In other words, we can pre-process the component inputs, and massage them into a shape that's most appropriate for what the template needs. And it also allows us to pass in static data into the template.
Imagine our component receives data from the database that looks like below (taken from Django).
Similarly we can make use of get_template_data() to pre-process the date that was given to the component:
[project root]/components/calendar/calendar.py
from datetime import date\n\nfrom django_components import Component, register\n\n# If date is Sat or Sun, shift it to next Mon, so the date is always workweek.\ndef to_workweek_date(d: date):\n ...\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_file = \"calendar.html\"\n ...\n def get_template_data(self, args, kwargs, slots, context):\n workweek_date = to_workweek_date(kwargs[\"date\"]) # <--- new\n return {\n \"date\": workweek_date, # <--- changed\n \"extra_class\": kwargs.get(\"extra_class\", \"text-blue\"),\n }\n
"},{"location":"getting_started/parametrising_components/#4-pass-inputs-to-components","title":"4. Pass inputs to components","text":"
Once we're happy with Calendar.get_template_data(), we can update our templates to use the parametrized version of the component:
In our example, we've set the extra_class to default to \"text-blue\" by setting it in the get_template_data() method.
However, you may want to use the same default value in multiple methods, like get_js_data() or get_css_data().
To make things easier, Components can specify their defaults. Defaults are used when no value is provided, or when the value is set to None for a particular input.
To define defaults for a component, you create a nested Defaults class within your Component class. Each attribute in the Defaults class represents a default value for a corresponding input.
Among other, you can pass also the request object to the render method:
from components.calendar import Calendar\n\ncalendar = Calendar\nrendered_component = calendar.render(request=request)\n
The request object is required for some of the component's features, like using Django's context processors.
"},{"location":"getting_started/rendering_components/#3-render-the-component-to-httpresponse","title":"3. Render the component to HttpResponse","text":"
A common pattern in Django is to render the component and then return the resulting HTML as a response to an HTTP request.
For this, you can use the Component.render_to_response() convenience method.
render_to_response() accepts the same args, kwargs, slots, and more, as Component.render(), but wraps the result in an HttpResponse.
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:
Each of these receive the HttpRequest object as the first argument.
Next, you need to set the URL for the component.
You can either:
Automatically assign the URL by setting the Component.View.public attribute to True.
In this case, use get_component_url() to get the URL for the component view.
from django_components import Component, get_component_url\n\nclass Calendar(Component):\n class View:\n public = True\n\nurl = get_component_url(Calendar)\n
Manually assign the URL by setting Component.as_view() to your urlpatterns:
And with that, you're all set! When you visit the URL, the component will be rendered and the content will be returned.
The get(), post(), etc methods will receive the HttpRequest object as the first argument. So you can parametrize how the component is rendered for example by passing extra query parameters to the URL:
http://localhost:8000/calendar/?date=2024-12-13\n
"},{"location":"getting_started/your_first_component/","title":"Create your first component","text":"
A component in django-components can be as simple as a Django template and Python code to declare the component:
calendar.html
<div class=\"calendar\">\n Today's date is <span>{{ date }}</span>\n</div>\n
calendar.py
from django_components import Component\n\nclass Calendar(Component):\n template_file = \"calendar.html\"\n
Or a combination of Django template, Python, CSS, and Javascript:
calendar.html
<div class=\"calendar\">\n Today's date is <span>{{ date }}</span>\n</div>\n
Alternatively, you can \"inline\" HTML, JS, and CSS right into the component class:
from django_components import Component\n\nclass Calendar(Component):\n template = \"\"\"\n <div class=\"calendar\">\n Today's date is <span>{{ date }}</span>\n </div>\n \"\"\"\n\n css = \"\"\"\n .calendar {\n width: 200px;\n background: pink;\n }\n \"\"\"\n\n js = \"\"\"\n document.querySelector(\".calendar\").onclick = function () {\n alert(\"Clicked calendar!\");\n };\n \"\"\"\n
Note
If you \"inline\" the HTML, JS and CSS code into the Python class, you can set up syntax highlighting for better experience. However, autocompletion / intellisense does not work with syntax highlighting.
We'll start by creating a component that defines only a Django template:
<div class=\"calendar\">\n Today's date is <span>{{ date }}</span>\n</div>\n
In this example we've defined one template variable date. You can use any and as many variables as you like. These variables will be defined in the Python file in get_template_data() when creating an instance of this component.
Note
The template will be rendered with whatever template backend you've specified in your Django settings file.
Currently django-components supports only the default \"django.template.backends.django.DjangoTemplates\" template backend!
"},{"location":"getting_started/your_first_component/#3-create-new-component-in-python","title":"3. Create new Component in Python","text":"
In calendar.py, create a subclass of Component to create a new component.
To link the HTML template with our component, set template_file to the name of the HTML file.
[project root]/components/calendar/calendar.py
from django_components import Component\n\nclass Calendar(Component):\n template_file = \"calendar.html\"\n
Note
The path to the template file can be either:
Relative to the component's python file (as seen above),
Relative to any of the component directories as defined by COMPONENTS.dirs and/or COMPONENTS.app_dirs (e.g. [your apps]/components dir and [project root]/components)
"},{"location":"getting_started/your_first_component/#4-define-the-template-variables","title":"4. Define the template variables","text":"
In calendar.html, we've used the variable date. So we need to define it for the template to work.
This is done using Component.get_template_data(). It's a function that returns a dictionary. The entries in this dictionary will become available within the template as variables, e.g. as {{ date }}.
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 wasteful to create a copy of the JS / CSS scripts for each component instance.
So instead, a preferred approach here is to defined and insert the inlined JS / CSS only once, and have some kind of mechanism on how we make correct the JS / CSS variables available only to the correct components.
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:
If users are using Component.render() or Component.render_to_response(), these post-process the <!-- _RENDERED --> comments by default.
NOTE: Users are able to opt out of the post-processing by setting deps_strategy=\"ignore\".
If one renders a Template directly, the <!-- _RENDERED --> will be processed too. We achieve this by modifying Django's Template.render() method.
For advanced use cases, users may use render_dependencies() directly. This is the function that Component.render() calls internally.
render_dependencies(), whether called directly, or other way, does the following:
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":"guides/devguides/slot_rendering/#using-the-correct-context-in-slotfill-tags","title":"Using the correct context in {% slot/fill %} tags","text":"
In previous section, we said that the {% fill %} tags should be already rendered by the time they are inserted into the {% slot %} tags.
This is not quite true. To help you understand, consider this complex case:
| -- {% for var in [1, 2, 3] %} ---\n| ---- {% component \"mycomp2\" %} ---\n| ------ {% fill \"first\" %}\n| ------- STU {{ my_var }}\n| ------- {{ var }}\n| ------ {% endfill %}\n| ------ {% fill \"second\" %}\n| -------- {% component var=var my_var=my_var %}\n| ---------- VWX {{ my_var }}\n| -------- {% endcomponent %}\n| ------ {% endfill %}\n| ---- {% endcomponent %} ---\n| -- {% endfor %} ---\n| -------\n
We want the forloop variables to be available inside the {% fill %} tags. Because of that, however, we CANNOT render the fills/slots in advance.
Instead, our solution is closer to how Vue handles slots. In Vue, slots are effectively functions that accept a context variables and render some content.
While we do not wrap the logic in a function, we do PREPARE IN ADVANCE: 1. The content that should be rendered for each slot 2. The context variables from get_template_data()
Thus, once we reach the {% slot %} node, in it's render() method, we access the data above, and, depending on the context_behavior setting, include the current context or not. For more info, see SlotNode.render().
"},{"location":"guides/devguides/slots_and_blocks/","title":"Using slot and block tags","text":"
First let's clarify how include and extends tags work inside components.
When component template includes include or extends tags, it's as if the \"included\" template was inlined. So if the \"included\" template contains slot tags, then the component uses those slots.
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 the 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:
As larger projects get more complex, it can be hard to debug issues. Django Components provides a number of tools and approaches that can help you with that.
"},{"location":"guides/other/troubleshooting/#component-and-slot-highlighting","title":"Component and slot highlighting","text":"
Django Components provides a visual debugging feature that helps you understand the structure and boundaries of your components and slots. When enabled, it adds a colored border and a label around each component and slot on your rendered page.
To enable component and slot highlighting for all components and slots, set highlight_components and highlight_slots to True in extensions defaults in your settings.py file:
As of v0.126, django-components primarily uses these logger levels:
DEBUG: Report on loading associated HTML / JS / CSS files, autodiscovery, etc.
TRACE: Detailed interaction of components and slots. Logs when template tags, components, and slots are started / ended rendering, and when a slot is filled.
You can cache the output of your components by setting the Component.Cache options.
Read more about Component caching.
"},{"location":"guides/setup/caching/#components-js-and-css-files","title":"Component's JS and CSS files","text":"
django-components simultaneously supports:
Rendering and fetching components as HTML fragments
Allowing components (even fragments) to have JS and CSS files associated with them
Features like JS/CSS variables or CSS scoping
To achieve all this, django-components defines additional temporary JS and CSS files. These temporary files need to be stored somewhere, so that they can be fetched by the browser when the component is rendered as a fragment. And for that, django-components uses Django's cache framework.
This includes:
Inlined JS/CSS defined via Component.js and Component.css
JS/CSS variables generated from get_js_data() and get_css_data()
By default, django-components uses Django's local memory cache backend to store these assets. You can configure it to use any of your Django cache backends by setting the COMPONENTS.cache option in your settings:
COMPONENTS = {\n # Name of the cache backend to use\n \"cache\": \"my-cache-backend\",\n}\n
The value should be the name of one of your configured cache backends from Django's CACHES setting.
For example, to use Redis for caching component assets:
See COMPONENTS.cache for more details about this setting.
"},{"location":"guides/setup/development_server/","title":"Development server","text":""},{"location":"guides/setup/development_server/#reload-dev-server-on-component-file-changes","title":"Reload dev server on component file changes","text":"
This is relevant if you are using the project structure as shown in our examples, where HTML, JS, CSS and Python are in separate files and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.
From relevant StackOverflow thread:
TL;DR is that the server won't reload if it thinks the changed file is in a templates directory, or in a nested sub directory of a templates directory. This is by design.
To make the dev server reload on all component files, set reload_on_file_change to True. This configures Django to watch for component files too.
Warning
This setting should be enabled only for the dev environment!
"},{"location":"overview/code_of_conduct/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"overview/code_of_conduct/#our-pledge","title":"Our Pledge","text":"
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
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 (see how to package components). If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.
django-htmx-components: A set of components for use with htmx.
djc-heroicons: A component that renders icons from Heroicons.com.
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):
Next, modify TEMPLATES section of settings.py as follows:
Remove 'APP_DIRS': True,
NOTE: Instead of APP_DIRS: True, we will use django.template.loaders.app_directories.Loader, which has the same effect.
Add loaders to OPTIONS list and set it to following value:
This allows Django to load component HTML files as Django templates.
TEMPLATES = [\n {\n ...,\n 'OPTIONS': {\n ...,\n 'loaders':[(\n 'django.template.loaders.cached.Loader', [\n # Default Django loader\n 'django.template.loaders.filesystem.Loader',\n # Including this is the same as APP_DIRS=True\n 'django.template.loaders.app_directories.Loader',\n # Components loader\n 'django_components.template_loader.Loader',\n ]\n )],\n },\n },\n]\n
Add django-component's URL paths to your urlpatterns:
Django components already prefixes all URLs with components/. So when you are adding the URLs to urlpatterns, you can use an empty string as the first argument:
from django.urls import include, path\n\nurlpatterns = [\n ...\n path(\"\", include(\"django_components.urls\")),\n]\n
"},{"location":"overview/installation/#adding-support-for-js-and-css","title":"Adding support for JS and CSS","text":"
If you want to use JS or CSS with components, you will need to:
Add \"django_components.finders.ComponentsFileSystemFinder\" to STATICFILES_FINDERS in your settings file.
This allows Django to serve component JS and CSS as static files.
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.
Since django-components is in pre-1.0 development, the public API is not yet frozen. This means that there may be breaking changes between minor versions. We try to minimize the number of breaking changes, but sometimes it's unavoidable.
When upgrading, please read the Release notes.
"},{"location":"overview/migrating/#migrating-in-pre-v10","title":"Migrating in pre-v1.0","text":"
If you're on older pre-v1.0 versions of django-components, we recommend doing step-wise upgrades in the following order:
v0.26
v0.50
v0.70
v0.77
v0.81
v0.85
v0.92
v0.100
v0.110
v0.140
These versions introduced breaking changes that are not backwards compatible.
TL;DR: No action needed from v0.100 onwards. Before v0.100, use safer_staticfiles to avoid exposing backend logic.
Components can be organized however you prefer. That said, our prefered way is to keep the files of a component close together by bundling them in the same directory.
This means that files containing backend logic, such as Python modules and HTML templates, live in the same directory as static files, e.g. JS and CSS.
From v0.100 onwards, we keep component files (as defined by COMPONENTS.dirs and COMPONENTS.app_dirs) separate from the rest of the static files (defined by STATICFILES_DIRS). That way, the Python and HTML files are NOT exposed by the server. Only the static JS, CSS, and other common formats.
Note
If you need to expose different file formats, you can configure these with COMPONENTS.static_files_allowed and COMPONENTS.static_files_forbidden.
"},{"location":"overview/security_notes/#static-files-prior-to-v0100","title":"Static files prior to v0.100","text":"
Prior to v0.100, if your were using django.contrib.staticfiles to collect static files, no distinction was made between the different kinds of files.
As a result, your Python code and templates may inadvertently become available on your static file server. You probably don't want this, as parts of your backend logic will be exposed, posing a potential security vulnerability.
From v0.27 until v0.100, django-components shipped with an additional installable app django_components.safer_staticfiles. It was a drop-in replacement for django.contrib.staticfiles. Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server.
To use it, add it to INSTALLED_APPS and remove django.contrib.staticfiles.
<div class=\"calendar-component\">\n Today's date is <span>2024-11-06</span>\n</div>\n
Read on to learn about all the exciting details and configuration possibilities!
(If you instead prefer to jump right into the code, check out the example project)
"},{"location":"overview/welcome/#features","title":"Features","text":""},{"location":"overview/welcome/#modern-and-modular-ui","title":"Modern and modular UI","text":"
Create self-contained, reusable UI elements.
Each component can include its own HTML, CSS, and JS, or additional third-party JS and CSS.
HTML, CSS, and JS can be defined on the component class, or loaded from files.
from django_components import Component\n\n@register(\"calendar\")\nclass Calendar(Component):\n template = \"\"\"\n <div class=\"calendar\">\n Today's date is\n <span>{{ date }}</span>\n </div>\n \"\"\"\n\n css = \"\"\"\n .calendar {\n width: 200px;\n background: pink;\n }\n \"\"\"\n\n js = \"\"\"\n document.querySelector(\".calendar\")\n .addEventListener(\"click\", () => {\n alert(\"Clicked calendar!\");\n });\n \"\"\"\n\n # Additional JS and CSS\n class Media:\n js = [\"https://cdn.jsdelivr.net/npm/htmx.org@2/dist/htmx.min.js\"]\n css = [\"bootstrap/dist/css/bootstrap.min.css\"]\n\n # Variables available in the template\n def get_template_data(self, args, kwargs, slots, context):\n return {\n \"date\": kwargs[\"date\"]\n }\n
"},{"location":"overview/welcome/#composition-with-slots","title":"Composition with slots","text":"
Render components inside templates with {% component %} tag.
{% html_attrs %} offers a Vue-like granular control for class and style HTML attributes, where you can use a dictionary to manage each class name or style property separately.
One of our goals with django-components is to make it easy to share components between projects. Head over to the Community examples to see some examples.
"},{"location":"overview/welcome/#contributing-and-development","title":"Contributing and development","text":"
Get involved or sponsor this project - See here
Running django-components locally for development - See here
This function is what is passed to Django's Library.tag() when registering the tag.
In other words, this method is called by Django's template parser when we encounter a tag that matches this node's tag, e.g. {% component %} or {% slot %}.
To register the tag, you can use BaseNode.register().
Optional typing for positional arguments passed to the component.
If set and not None, then the args parameter of the data methods (get_template_data(), get_js_data(), get_css_data()) will be the instance of this class:
Optional typing for keyword arguments passed to the component.
If set and not None, then the kwargs parameter of the data methods (get_template_data(), get_js_data(), get_css_data()) will be the instance of this class:
Defines JS and CSS media files associated with this component.
This Media class behaves similarly to Django's Media class:
Paths are generally handled as static file paths, and resolved URLs are rendered to HTML with media_class.render_js() or media_class.render_css().
A path that starts with http, https, or / is considered a URL, skipping the static file resolution. This path is still rendered to HTML with media_class.render_js() or media_class.render_css().
A SafeString (with __html__ method) is considered an already-formatted HTML tag, skipping both static file resolution and rendering with media_class.render_js() or media_class.render_css().
You can set extend to configure whether to inherit JS / CSS from parent components. See Media inheritance.
However, there's a few differences from Django's Media class:
Our Media class accepts various formats for the JS and CSS files: either a single file, a list, or (CSS-only) a dictionary (See ComponentMediaInput).
Individual JS / CSS files can be any of str, bytes, Path, SafeString, or a function (See ComponentMediaInputPath).
Optional typing for slots passed to the component.
If set and not None, then the slots parameter of the data methods (get_template_data(), get_js_data(), get_css_data()) will be the instance of this class:
This ID is unique for every time a Component.render() (or equivalent) is called (AKA \"render ID\").
This is useful for logging or debugging.
The ID is a 7-letter alphanumeric string in the format cXXXXXX, where XXXXXX is a random string of 6 alphanumeric characters (case-sensitive).
E.g. c1A2b3c.
A single render ID has a chance of collision 1 in 57 billion. However, due to birthday paradox, the chance of collision increases to 1% when approaching ~33K render IDs.
Thus, there is currently a soft-cap of ~30K components rendered on a single page.
If you need to expand this limit, please open an issue on GitHub.
Set the Media class that will be instantiated with the JS and CSS media files from Component.Media.
This is useful when you want to customize the behavior of the media files, like customizing how the JS or CSS files are rendered into <script> or <link> HTML tags.
Read more in Defining HTML / JS / CSS files.
Example:
class MyTable(Component):\n class Media:\n js = \"path/to/script.js\"\n css = \"path/to/style.css\"\n\n media_class = MyMediaClass\n
The ComponentNode instance that was used to render the component.
This will be set only if the component was rendered with the {% component %} tag.
Accessing the ComponentNode is mostly useful for extensions, which can modify their behaviour based on the source of the Component.
class MyComponent(Component):\n def get_template_data(self, context, template):\n if self.node is not None:\n assert self.node.name == \"my_component\"\n
For example, if MyComponent was used in another component - that is, with a {% component \"my_component\" %} tag in a template that belongs to another component - then you can use self.node.template_component to access the owner Component class.
class Parent(Component):\n template: types.django_html = '''\n <div>\n {% component \"my_component\" / %}\n </div>\n '''\n\n@register(\"my_component\")\nclass MyComponent(Component):\n def get_template_data(self, context, template):\n if self.node is not None:\n assert self.node.template_component == Parent\n
Info
Component.node is None if the component is created by Component.render() (but you can pass in the node kwarg yourself).
If the component was rendered with the {% component %} template tag, this will be the name under which the component was registered in the ComponentRegistry.
args: Positional arguments passed to the component.
kwargs: Keyword arguments passed to the component.
slots: Slots passed to the component.
context: Context used for rendering the component template.
Pass-through kwargs:
It's best practice to explicitly define what args and kwargs a component accepts.
However, if you want a looser setup, you can easily write components that accept any number of kwargs, and pass them all to the CSS code.
To do that, simply return the kwargs dictionary itself from get_css_data():
class MyComponent(Component):\n def get_css_data(self, args, kwargs, slots, context):\n return kwargs\n
Type hints:
To get type hints for the args, kwargs, and slots parameters, you can define the Args, Kwargs, and Slots classes on the component class, and then directly reference them in the function signature of get_css_data().
When you set these classes, the args, kwargs, and slots parameters will be given as instances of these (args instance of Args, etc).
When you omit these classes, or set them to None, then the args, kwargs, and slots parameters will be given as plain lists / dictionaries, unmodified.
args: Positional arguments passed to the component.
kwargs: Keyword arguments passed to the component.
slots: Slots passed to the component.
context: Context used for rendering the component template.
Pass-through kwargs:
It's best practice to explicitly define what args and kwargs a component accepts.
However, if you want a looser setup, you can easily write components that accept any number of kwargs, and pass them all to the JavaScript code.
To do that, simply return the kwargs dictionary itself from get_js_data():
class MyComponent(Component):\n def get_js_data(self, args, kwargs, slots, context):\n return kwargs\n
Type hints:
To get type hints for the args, kwargs, and slots parameters, you can define the Args, Kwargs, and Slots classes on the component class, and then directly reference them in the function signature of get_js_data().
When you set these classes, the args, kwargs, and slots parameters will be given as instances of these (args instance of Args, etc).
When you omit these classes, or set them to None, then the args, kwargs, and slots parameters will be given as plain lists / dictionaries, unmodified.
args: Positional arguments passed to the component.
kwargs: Keyword arguments passed to the component.
slots: Slots passed to the component.
context: Context used for rendering the component template.
Pass-through kwargs:
It's best practice to explicitly define what args and kwargs a component accepts.
However, if you want a looser setup, you can easily write components that accept any number of kwargs, and pass them all to the template (similar to django-cotton).
To do that, simply return the kwargs dictionary itself from get_template_data():
class MyComponent(Component):\n def get_template_data(self, args, kwargs, slots, context):\n return kwargs\n
Type hints:
To get type hints for the args, kwargs, and slots parameters, you can define the Args, Kwargs, and Slots classes on the component class, and then directly reference them in the function signature of get_template_data().
When you set these classes, the args, kwargs, and slots parameters will be given as instances of these (args instance of Args, etc).
When you omit these classes, or set them to None, then the args, kwargs, and slots parameters will be given as plain lists / dictionaries, unmodified.
Return nothing (or None) to handle the result as usual
If you don't raise an exception, and neither return a new HTML, then original HTML / error will be used:
If rendering succeeded, the original HTML will be used as the final output.
If rendering failed, the original error will be propagated.
class MyTable(Component):\n def on_render(self, context, template):\n html, error = yield template.render(context)\n\n if error is not None:\n # The rendering failed\n print(f\"Error: {error}\")\n
Hook that runs when the component was fully rendered, including all its children.
It receives the same arguments as on_render_before(), plus the outcome of the rendering:
result: The rendered output of the component. None if the rendering failed.
error: The error that occurred during the rendering, or None if the rendering succeeded.
on_render_after() behaves the same way as the second part of on_render() (after the yield).
class MyTable(Component):\n def on_render_after(self, context, template, result, error):\n if error is None:\n # The rendering succeeded\n return result\n else:\n # The rendering failed\n print(f\"Error: {error}\")\n
Same as on_render(), you can return a new HTML, raise a new exception, or return nothing:
Return a new HTML
The new HTML will be used as the final output.
If the original template raised an error, it will be ignored.
Return nothing (or None) to handle the result as usual
If you don't raise an exception, and neither return a new HTML, then original HTML / error will be used:
If rendering succeeded, the original HTML will be used as the final output.
If rendering failed, the original error will be propagated.
class MyTable(Component):\n def on_render_after(self, context, template, result, error):\n if error is not None:\n # The rendering failed\n print(f\"Error: {error}\")\n
context - Optional. Plain dictionary or Django's Context. The context within which the component is rendered.
When a component is rendered within a template with the {% component %} tag, this will be set to the Context instance that is used for rendering the template.
When you call Component.render() directly from Python, you can ignore this input most of the time. Instead use args, kwargs, and slots to pass data to the component.
You can pass RequestContext to the context argument, so that the component will gain access to the request object and will use context processors. Read more on Working with HTTP requests.
For advanced use cases, you can use context argument to \"pre-render\" the component in Python, and then pass the rendered output as plain string to the template. With this, the inner component is rendered as if it was within the template with {% component %}.
class Button(Component):\n def render(self, context, template):\n # Pass `context` to Icon component so it is rendered\n # as if nested within Button.\n icon = Icon.render(\n context=context,\n args=[\"icon-name\"],\n deps_strategy=\"ignore\",\n )\n # Update context with icon\n with context.update({\"icon\": icon}):\n return template.render(context)\n
Whether the variables defined in context are available to the template depends on the context behavior mode:
In \"django\" context behavior mode, the template will have access to the keys of this context.
In \"isolated\" context behavior mode, the template will NOT have access to this context, and data MUST be passed via component's args and kwargs.
deps_strategy - Optional. Configure how to handle JS and CSS dependencies. Read more about Dependencies rendering.
There are six strategies:
\"document\" (default)
Smartly inserts JS / CSS into placeholders or into <head> and <body> tags.
Inserts extra script to allow fragment types to work.
Assumes the HTML will be rendered in a JS-enabled browser.
\"fragment\"
A lightweight HTML fragment to be inserted into a document with AJAX.
No JS / CSS included.
\"simple\"
Smartly insert JS / CSS into placeholders or into <head> and <body> tags.
No extra script loaded.
\"prepend\"
Insert JS / CSS before the rendered HTML.
No extra script loaded.
\"append\"
Insert JS / CSS after the rendered HTML.
No extra script loaded.
\"ignore\"
HTML is left as-is. You can still process it with a different strategy later with render_dependencies().
Used for inserting rendered HTML into other components.
request - Optional. HTTPRequest object. Pass a request object directly to the component to apply context processors.
Read more about Working with HTTP requests.
Type hints:
Component.render() is NOT typed. To add type hints, you can wrap the inputs in component's Args, Kwargs, and Slots classes.
Read more on Typing and validation.
from typing import NamedTuple, Optional\nfrom django_components import Component, Slot, SlotInput\n\n# Define the component with the types\nclass Button(Component):\n class Args(NamedTuple):\n name: str\n\n class Kwargs(NamedTuple):\n surname: str\n age: int\n\n class Slots(NamedTuple):\n my_slot: Optional[SlotInput] = None\n footer: SlotInput\n\n# Add type hints to the render call\nButton.render(\n args=Button.Args(\n name=\"John\",\n ),\n kwargs=Button.Kwargs(\n surname=\"Doe\",\n age=30,\n ),\n slots=Button.Slots(\n footer=Slot(lambda ctx: \"Click me!\"),\n ),\n)\n
When a Component is instantiated, also the nested extension classes (such as Component.View) are instantiated, receiving the component instance as an argument.
This attribute holds the owner Component instance that this extension is defined on.
Currently it's impossible to capture used variables. This will be addressed in v2. Read more about it in https://github.com/django-components/django-components/issues/1164.
When a Component is instantiated, also the nested extension classes (such as Component.View) are instantiated, receiving the component instance as an argument.
This attribute holds the owner Component instance that this extension is defined on.
When a Component is instantiated, also the nested extension classes (such as Component.View) are instantiated, receiving the component instance as an argument.
This attribute holds the owner Component instance that this extension is defined on.
class ExampleExtension(ComponentExtension):\n name = \"example\"\n\n # Component-level behavior and settings. User will be able to override\n # the attributes and methods defined here on the component classes.\n class ComponentConfig(ComponentExtension.ComponentConfig):\n foo = \"1\"\n bar = \"2\"\n\n def baz(cls):\n return \"3\"\n\n # URLs\n urls = [\n URLRoute(path=\"dummy-view/\", handler=dummy_view, name=\"dummy\"),\n URLRoute(path=\"dummy-view-2/<int:id>/<str:name>/\", handler=dummy_view_2, name=\"dummy-2\"),\n ]\n\n # Commands\n commands = [\n HelloWorldCommand,\n ]\n\n # Hooks\n def on_component_class_created(self, ctx: OnComponentClassCreatedContext) -> None:\n print(ctx.component_cls.__name__)\n\n def on_component_class_deleted(self, ctx: OnComponentClassDeletedContext) -> None:\n print(ctx.component_cls.__name__)\n
Which users then can override on a per-component basis. E.g.:
class MyComp(Component):\n class Example:\n foo = \"overridden\"\n\n def baz(self):\n return \"overridden baz\"\n
Base class that the \"component-level\" extension config nested within a Component class will inherit from.
This is where you can define new methods and attributes that will be available to the component instance.
Background:
The extension may add new features to the Component class by allowing users to define and access a nested class in the Component class. E.g.:
class MyComp(Component):\n class MyExtension:\n ...\n\n def get_template_data(self, args, kwargs, slots, context):\n return {\n \"my_extension\": self.my_extension.do_something(),\n }\n
When rendering a component, the nested extension class will be set as a subclass of ComponentConfig. So it will be same as if the user had directly inherited from extension's ComponentConfig. E.g.:
class MyComp(Component):\n class MyExtension(ComponentExtension.ComponentConfig):\n ...\n
This setting decides what the extension class will inherit from.
By default, this is set automatically at class creation. The class name is the same as the name attribute, but with snake_case converted to PascalCase.
So if the extension name is \"my_extension\", then the extension class name will be \"MyExtension\".
class MyComp(Component):\n class MyExtension: # <--- This is the extension class\n ...\n
To customize the class name, you can manually set the class_name attribute.
The class name must be a valid Python identifier.
Example:
class MyExt(ComponentExtension):\n name = \"my_extension\"\n class_name = \"MyCustomExtension\"\n
This will make the extension class name \"MyCustomExtension\".
class MyComp(Component):\n class MyCustomExtension: # <--- This is the extension class\n ...\n
List of commands that can be run by the extension.
These commands will be available to the user as components ext run <extension> <command>.
Commands are defined as subclasses of ComponentCommand.
Example:
This example defines an extension with a command that prints \"Hello world\". To run the command, the user would run components ext run hello_world hello.
from django_components import ComponentCommand, ComponentExtension, CommandArg, CommandArgGroup\n\nclass HelloWorldCommand(ComponentCommand):\n name = \"hello\"\n help = \"Hello world command.\"\n\n # Allow to pass flags `--foo`, `--bar` and `--baz`.\n # Argument parsing is managed by `argparse`.\n arguments = [\n CommandArg(\n name_or_flags=\"--foo\",\n help=\"Foo description.\",\n ),\n # When printing the command help message, `bar` and `baz`\n # will be grouped under \"group bar\".\n CommandArgGroup(\n title=\"group bar\",\n description=\"Group description.\",\n arguments=[\n CommandArg(\n name_or_flags=\"--bar\",\n help=\"Bar description.\",\n ),\n CommandArg(\n name_or_flags=\"--baz\",\n help=\"Baz description.\",\n ),\n ],\n ),\n ]\n\n # Callback that receives the parsed arguments and options.\n def handle(self, *args, **kwargs):\n print(f\"HelloWorldCommand.handle: args={args}, kwargs={kwargs}\")\n\n# Associate the command with the extension\nclass HelloWorldExtension(ComponentExtension):\n name = \"hello_world\"\n\n commands = [\n HelloWorldCommand,\n ]\n
Name must be lowercase, and must be a valid Python identifier (e.g. \"my_extension\").
The extension may add new features to the Component class by allowing users to define and access a nested class in the Component class.
The extension name determines the name of the nested class in the Component class, and the attribute under which the extension will be accessible.
E.g. if the extension name is \"my_extension\", then the nested class in the Component class will be MyExtension, and the extension will be accessible as MyComp.my_extension.
class MyComp(Component):\n class MyExtension:\n ...\n\n def get_template_data(self, args, kwargs, slots, context):\n return {\n \"my_extension\": self.my_extension.do_something(),\n }\n
Info
The extension class name can be customized by setting the class_name attribute.
This hook is called after the Component class is fully defined but before it's registered.
Use this hook to perform any initialization or validation of the Component class.
Example:
from django_components import ComponentExtension, OnComponentClassCreatedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_class_created(self, ctx: OnComponentClassCreatedContext) -> None:\n # Add a new attribute to the Component class\n ctx.component_cls.my_attr = \"my_value\"\n
This hook is called before the Component class is deleted from memory.
Use this hook to perform any cleanup related to the Component class.
Example:
from django_components import ComponentExtension, OnComponentClassDeletedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_class_deleted(self, ctx: OnComponentClassDeletedContext) -> None:\n # Remove Component class from the extension's cache on deletion\n self.cache.pop(ctx.component_cls, None)\n
Called when a Component was triggered to render, after a component's context and data methods have been processed.
This hook is called after Component.get_template_data(), Component.get_js_data() and Component.get_css_data().
This hook runs after on_component_input.
Use this hook to modify or validate the component's data before rendering.
Example:
from django_components import ComponentExtension, OnComponentDataContext\n\nclass MyExtension(ComponentExtension):\n def on_component_data(self, ctx: OnComponentDataContext) -> None:\n # Add extra template variable to all components when they are rendered\n ctx.template_data[\"my_template_var\"] = \"my_value\"\n
Called when a Component was triggered to render, but before a component's context and data methods are invoked.
Use this hook to modify or validate component inputs before they're processed.
This is the first hook that is called when rendering a component. As such this hook is called before Component.get_template_data(), Component.get_js_data(), and Component.get_css_data() methods, and the on_component_data hook.
This hook also allows to skip the rendering of a component altogether. If the hook returns a non-null value, this value will be used instead of rendering the component.
You can use this to implement a caching mechanism for components, or define components that will be rendered conditionally.
Example:
from django_components import ComponentExtension, OnComponentInputContext\n\nclass MyExtension(ComponentExtension):\n def on_component_input(self, ctx: OnComponentInputContext) -> None:\n # Add extra kwarg to all components when they are rendered\n ctx.kwargs[\"my_input\"] = \"my_value\"\n
Warning
In this hook, the components' inputs are still mutable.
As such, if a component defines Args, Kwargs, Slots types, these types are NOT yet instantiated.
Instead, component fields like Component.args, Component.kwargs, Component.slots are plain list / dict objects.
Called when a Component was rendered, including all its child components.
Use this hook to access or post-process the component's rendered output.
This hook works similarly to Component.on_render_after():
To modify the output, return a new string from this hook. The original output or error will be ignored.
To cause this component to return a new error, raise that error. The original output and error will be ignored.
If you neither raise nor return string, the original output or error will be used.
Examples:
Change the final output of a component:
from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n # Append a comment to the component's rendered output\n return ctx.result + \"<!-- MyExtension comment -->\"\n
Cause the component to raise a new exception:
from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n # Raise a new exception\n raise Exception(\"Error message\")\n
Return nothing (or None) to handle the result as usual:
from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n if ctx.error is not None:\n # The component raised an exception\n print(f\"Error: {ctx.error}\")\n else:\n # The component rendered successfully\n print(f\"Result: {ctx.result}\")\n
This hook is called after a new ComponentRegistry instance is initialized.
Use this hook to perform any initialization needed for the registry.
Example:
from django_components import ComponentExtension, OnRegistryCreatedContext\n\nclass MyExtension(ComponentExtension):\n def on_registry_created(self, ctx: OnRegistryCreatedContext) -> None:\n # Add a new attribute to the registry\n ctx.registry.my_attr = \"my_value\"\n
Use this hook to access or post-process the slot's rendered output.
To modify the output, return a new string from this hook.
Example:
from django_components import ComponentExtension, OnSlotRenderedContext\n\nclass MyExtension(ComponentExtension):\n def on_slot_rendered(self, ctx: OnSlotRenderedContext) -> Optional[str]:\n # Append a comment to the slot's rendered output\n return ctx.result + \"<!-- MyExtension comment -->\"\n
Access slot metadata:
You can access the {% slot %} tag node (SlotNode) and its metadata using ctx.slot_node.
For example, to find the Component class to which belongs the template where the {% slot %} tag is defined, you can use ctx.slot_node.template_component:
Configures whether the component should inherit the media files from the parent component.
If True, the component inherits the media files from the parent component.
If False, the component does not inherit the media files from the parent component.
If a list of components classes, the component inherits the media files ONLY from these specified components.
Read more in Media inheritance section.
Example:
Disable media inheritance:
class ParentComponent(Component):\n class Media:\n js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n class Media:\n extend = False # Don't inherit parent media\n js = [\"script.js\"]\n\nprint(MyComponent.media._js) # [\"script.js\"]\n
Specify which components to inherit from. In this case, the media files are inherited ONLY from the specified components, and NOT from the original parent components:
class ParentComponent(Component):\n class Media:\n js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n class Media:\n # Only inherit from these, ignoring the files from the parent\n extend = [OtherComponent1, OtherComponent2]\n\n js = [\"script.js\"]\n\nprint(MyComponent.media._js) # [\"script.js\", \"other1.js\", \"other2.js\"]\n
A type representing an entry in Media.js or Media.css.
If an entry is a SafeString (or has __html__ method), then entry is assumed to be a formatted HTML tag. Otherwise, it's assumed to be a path to a file.
By default, components behave similarly to Django's {% include %}, and the template inside the component has access to the variables defined in the outer template.
You can selectively isolate a component, using the only flag, so that the inner template can access only the data that was explicitly passed to it:
{% component \"name\" positional_arg keyword_arg=value ... only %}\n
Alternatively, you can set all components to be isolated by default, by setting context_behavior to \"isolated\" in your settings:
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(\"button\")\nregistry.has(\"button\")\n
"},{"location":"reference/api/#django_components.ComponentRegistry--using-registry-to-share-components","title":"Using registry to share components","text":"
You can use component registry for isolating or \"packaging\" components:
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
Deprecated. Will be removed in v1. Use component_vars.slots instead. Note that component_vars.slots no longer escapes the slot names.
Dictonary describing which component slots are filled (True) or are not (False).
New in version 0.70
Use as {{ component_vars.is_filled }}
Example:
{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n <div class=\"slot-wrapper\">\n {% slot \"my_slot\" / %}\n </div>\n{% endif %}\n
This is equivalent to checking if a given key is among the slot fills:
class MyTable(Component):\n def get_template_data(self, args, kwargs, slots, context):\n return {\n \"my_slot_filled\": \"my_slot\" in slots\n }\n
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:
DEPRECATED. Template caching will be removed in v1.
Configure the maximum amount of Django templates to be cached.
Defaults to 128.
Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.
By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding Component.get_template() to render many dynamic templates, you can increase this number.
This setting makes the component fills behave similar to Vue or React, where the fills use EXCLUSIVELY the context variables defined in Component.get_template_data().
Use this class to mark a field on the Component.Defaults class as a factory.
Read more about Component defaults.
Example:
from django_components import Default\n\nclass MyComponent(Component):\n class Defaults:\n # Plain value doesn't need a factory\n position = \"left\"\n # Lists and dicts need to be wrapped in `Default`\n # Otherwise all instances will share the same value\n selected_items = Default(lambda: [1, 2, 3])\n
ExtensionComponentConfig is the base class for all extension component configs.
Extensions can define nested classes on the component class, such as Component.View or Component.Cache:
class MyComp(Component):\n class View:\n def get(self, request):\n ...\n\n class Cache:\n ttl = 60\n
This allows users to configure extension behavior per component.
Behind the scenes, the nested classes that users define on their components are merged with the extension's \"base\" class.
So the example above is the same as:
class MyComp(Component):\n class View(ViewExtension.ComponentConfig):\n def get(self, request):\n ...\n\n class Cache(CacheExtension.ComponentConfig):\n ttl = 60\n
Where both ViewExtension.ComponentConfig and CacheExtension.ComponentConfig are subclasses of ExtensionComponentConfig.
When a Component is instantiated, also the nested extension classes (such as Component.View) are instantiated, receiving the component instance as an argument.
This attribute holds the owner Component instance that this extension is defined on.
This function is what is passed to Django's Library.tag() when registering the tag.
In other words, this method is called by Django's template parser when we encounter a tag that matches this node's tag, e.g. {% component %} or {% slot %}.
To register the tag, you can use BaseNode.register().
This is the signature of the Component.on_render() method if it yields (and thus returns a generator).
When on_render() is a generator then it:
Yields a rendered template (string or None)
Receives back a tuple of (final_output, error).
The final output is the rendered template that now has all its children rendered too. May be None if you yielded None earlier.
The error is None if the rendering was successful. Otherwise the error is set and the output is None.
At the end it may return a new string to override the final rendered output.
Example:
from django_components import Component, OnRenderGenerator\n\nclass MyTable(Component):\n def on_render(\n self,\n context: Context,\n template: Optional[Template],\n ) -> OnRenderGenerator:\n # Do something BEFORE rendering template\n # Same as `Component.on_render_before()`\n context[\"hello\"] = \"world\"\n\n # Yield rendered template to receive fully-rendered template or error\n html, error = yield template.render(context)\n\n # Do something AFTER rendering template, or post-process\n # the rendered template.\n # Same as `Component.on_render_after()`\n return html + \"<p>Hello</p>\"\n
Since the \"child\" component is used within the {% provide %} / {% endprovide %} tags, we can request the \"user_data\" using Component.inject(\"user_data\"):
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n User is: {{ user }}\n </div>\n \"\"\"\n\n def get_template_data(self, args, kwargs, slots, context):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n
Notice that the keys defined on the {% provide %} tag are then accessed as attributes when accessing them with Component.inject().
This function is what is passed to Django's Library.tag() when registering the tag.
In other words, this method is called by Django's template parser when we encounter a tag that matches this node's tag, e.g. {% component %} or {% slot %}.
To register the tag, you can use BaseNode.register().
If the slot was created from a {% fill %} tag, this will be the FillNode instance.
If the slot was a default slot created from a {% component %} tag, this will be the ComponentNode instance.
Otherwise, this will be None.
Extensions can use this info to handle slots differently based on their source.
See Slot metadata.
Example:
You can use this to find the Component in whose template the {% fill %} tag was defined:
class MyTable(Component):\n def get_template_data(self, args, kwargs, slots, context):\n footer_slot = slots.get(\"footer\")\n if footer_slot is not None and footer_slot.fill_node is not None:\n owner_component = footer_slot.fill_node.template_component\n # ...\n
Type representing all forms in which slot content can be passed to a component.
When rendering a component with Component.render() or Component.render_to_response(), the slots may be given a strings, functions, or Slot instances. This type describes that union.
Use this type when typing the slots in your component.
SlotInput accepts an optional type parameter to specify the data dictionary that will be passed to the slot content function.
Any extra kwargs will be considered as slot data, and will be accessible in the {% fill %} tag via fill's data kwarg:
Read more about Slot data.
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
The content between the {% slot %}..{% endslot %} tags is the fallback content that will be rendered if no fill is given for the slot.
This fallback content can then be accessed from within the {% fill %} tag using the fill's fallback kwarg. This is useful if you need to wrap / prepend / append the original slot's content.
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" %}\n This is fallback content!\n {% endslot %}\n </div>\n \"\"\"\n
This function is what is passed to Django's Library.tag() when registering the tag.
In other words, this method is called by Django's template parser when we encounter a tag that matches this node's tag, e.g. {% component %} or {% slot %}.
To register the tag, you can use BaseNode.register().
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.
Raises RuntimeError if the component is not public.
Read more about Component views and URLs.
get_component_url() optionally accepts query and fragment arguments.
Example:
from django_components import Component, get_component_url\n\nclass MyComponent(Component):\n class View:\n public = True\n\n# Get the URL for the component\nurl = get_component_url(\n MyComponent,\n query={\"foo\": \"bar\"},\n fragment=\"baz\",\n)\n# /components/ext/view/components/c1ab2c3?foo=bar#baz\n
The default and global component registry. Use this instance to directly register or remove components:
See Registering components.
# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get single\nregistry.get(\"button\")\n\n# Get all\nregistry.all()\n\n# Check if component is registered\nregistry.has(\"button\")\n\n# Unregister single\nregistry.unregister(\"button\")\n\n# Unregister all\nregistry.clear()\n
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 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.
Here are some examples of how you can use the command:
Creating a Component with Default Settings
To create a component with the default settings, you only need to provide the name of the component:
python manage.py components create my_component\n
This will create a new component named my_component in the components directory of your Django project. The JavaScript, CSS, and template files will be named script.js, style.css, and template.html, respectively.
Creating a Component with Custom Settings
You can also create a component with custom settings by providing additional arguments:
This will create a new component named new_component in the my_components directory. The JavaScript, CSS, and template files will be named my_script.js, my_style.css, and my_template.html, respectively.
Overwriting an Existing Component
If you want to overwrite an existing component, you can use the --force option:
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\".
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\".
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.
Title for the argument group in help output; by default \u201cpositional arguments\u201d if description is provided, otherwise uses title for positional arguments.
Usage information that will be displayed with sub-command help, by default the name of the program and any positional arguments before the subparser argument.
Title for the sub-parser group in help output; by default \u201csubcommands\u201d if description is provided, otherwise uses title for positional arguments.
name type description component_clsType[Component] The created Component class
Available data:
name type description component_clsType[Component] The to-be-deleted Component class
Available data:
name type description componentComponent The Component instance that is being rendered component_clsType[Component] The Component class component_idstr The unique identifier for this component instance context_dataDict Deprecated. Use template_data instead. Will be removed in v1.0. css_dataDict Dictionary of CSS data from Component.get_css_data()js_dataDict Dictionary of JavaScript data from Component.get_js_data()template_dataDict Dictionary of template data from Component.get_template_data()
Available data:
name type description argsList List of positional arguments passed to the component componentComponent The Component instance that received the input and is being rendered component_clsType[Component] The Component class component_idstr The unique identifier for this component instance contextContext The Django template Context object kwargsDict Dictionary of keyword arguments passed to the component slotsDict[str, Slot] Dictionary of slot definitions
Available data:
name type description component_clsType[Component] The registered Component class namestr The name the component was registered under registryComponentRegistry The registry the component was registered to
Available data:
name type description componentComponent The Component instance that is being rendered component_clsType[Component] The Component class component_idstr The unique identifier for this component instance errorOptional[Exception] The error that occurred during rendering, or None if rendering was successful resultOptional[str] The rendered component, or None if rendering failed
Available data:
name type description component_clsType[Component] The unregistered Component class namestr The name the component was registered under registryComponentRegistry The registry the component was unregistered from
Available data:
name type description component_clsType[Component] The Component class whose CSS was loaded contentstr The CSS content (string)
Available data:
name type description component_clsType[Component] The Component class whose JS was loaded contentstr The JS content (string)
Available data:
name type description registryComponentRegistry The created ComponentRegistry instance
Available data:
name type description registryComponentRegistry The to-be-deleted ComponentRegistry instance
Available data:
name type description componentComponent The Component instance that contains the {% slot %} tag component_clsType[Component] The Component class that contains the {% slot %} tag component_idstr The unique identifier for this component instance resultSlotResult The rendered result of the slot slotSlot The Slot instance that was rendered slot_is_defaultbool Whether the slot is default slot_is_requiredbool Whether the slot is required slot_namestr The name of the {% slot %} tag slot_nodeSlotNode The node instance of the {% slot %} tag
Available data:
name type description component_clsType[Component] The Component class whose template was loaded templatedjango.template.base.Template The compiled template object
Available data:
name type description component_clsType[Component] The Component class whose template was loaded contentstr The template string nameOptional[str] The name of the template originOptional[django.template.base.Origin] The origin of the template"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_component_class_created","title":"on_component_class_created","text":"
This hook is called after the Component class is fully defined but before it's registered.
Use this hook to perform any initialization or validation of the Component class.
Example:
from django_components import ComponentExtension, OnComponentClassCreatedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_class_created(self, ctx: OnComponentClassCreatedContext) -> None:\n # Add a new attribute to the Component class\n ctx.component_cls.my_attr = \"my_value\"\n
This hook is called before the Component class is deleted from memory.
Use this hook to perform any cleanup related to the Component class.
Example:
from django_components import ComponentExtension, OnComponentClassDeletedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_class_deleted(self, ctx: OnComponentClassDeletedContext) -> None:\n # Remove Component class from the extension's cache on deletion\n self.cache.pop(ctx.component_cls, None)\n
Called when a Component was triggered to render, after a component's context and data methods have been processed.
This hook is called after Component.get_template_data(), Component.get_js_data() and Component.get_css_data().
This hook runs after on_component_input.
Use this hook to modify or validate the component's data before rendering.
Example:
from django_components import ComponentExtension, OnComponentDataContext\n\nclass MyExtension(ComponentExtension):\n def on_component_data(self, ctx: OnComponentDataContext) -> None:\n # Add extra template variable to all components when they are rendered\n ctx.template_data[\"my_template_var\"] = \"my_value\"\n
Called when a Component was triggered to render, but before a component's context and data methods are invoked.
Use this hook to modify or validate component inputs before they're processed.
This is the first hook that is called when rendering a component. As such this hook is called before Component.get_template_data(), Component.get_js_data(), and Component.get_css_data() methods, and the on_component_data hook.
This hook also allows to skip the rendering of a component altogether. If the hook returns a non-null value, this value will be used instead of rendering the component.
You can use this to implement a caching mechanism for components, or define components that will be rendered conditionally.
Example:
from django_components import ComponentExtension, OnComponentInputContext\n\nclass MyExtension(ComponentExtension):\n def on_component_input(self, ctx: OnComponentInputContext) -> None:\n # Add extra kwarg to all components when they are rendered\n ctx.kwargs[\"my_input\"] = \"my_value\"\n
Warning
In this hook, the components' inputs are still mutable.
As such, if a component defines Args, Kwargs, Slots types, these types are NOT yet instantiated.
Instead, component fields like Component.args, Component.kwargs, Component.slots are plain list / dict objects.
Called when a Component was rendered, including all its child components.
Use this hook to access or post-process the component's rendered output.
This hook works similarly to Component.on_render_after():
To modify the output, return a new string from this hook. The original output or error will be ignored.
To cause this component to return a new error, raise that error. The original output and error will be ignored.
If you neither raise nor return string, the original output or error will be used.
Examples:
Change the final output of a component:
from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n # Append a comment to the component's rendered output\n return ctx.result + \"<!-- MyExtension comment -->\"\n
Cause the component to raise a new exception:
from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n # Raise a new exception\n raise Exception(\"Error message\")\n
Return nothing (or None) to handle the result as usual:
from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n if ctx.error is not None:\n # The component raised an exception\n print(f\"Error: {ctx.error}\")\n else:\n # The component rendered successfully\n print(f\"Result: {ctx.result}\")\n
This hook is called after a new ComponentRegistry instance is initialized.
Use this hook to perform any initialization needed for the registry.
Example:
from django_components import ComponentExtension, OnRegistryCreatedContext\n\nclass MyExtension(ComponentExtension):\n def on_registry_created(self, ctx: OnRegistryCreatedContext) -> None:\n # Add a new attribute to the registry\n ctx.registry.my_attr = \"my_value\"\n
Use this hook to access or post-process the slot's rendered output.
To modify the output, return a new string from this hook.
Example:
from django_components import ComponentExtension, OnSlotRenderedContext\n\nclass MyExtension(ComponentExtension):\n def on_slot_rendered(self, ctx: OnSlotRenderedContext) -> Optional[str]:\n # Append a comment to the slot's rendered output\n return ctx.result + \"<!-- MyExtension comment -->\"\n
Access slot metadata:
You can access the {% slot %} tag node (SlotNode) and its metadata using ctx.slot_node.
For example, to find the Component class to which belongs the template where the {% slot %} tag is defined, you can use ctx.slot_node.template_component:
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:
DEPRECATED. Template caching will be removed in v1.
Configure the maximum amount of Django templates to be cached.
Defaults to 128.
Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.
By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding Component.get_template() to render many dynamic templates, you can increase this number.
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.
Marks location where CSS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted into the <head> tag of the HTML.
If the generated HTML does NOT contain any {% component_css_dependencies %} tags, CSS links are by default inserted into the <head> tag of the HTML. (See Default JS / CSS locations)
Note that there should be only one {% component_css_dependencies %} for the whole HTML document. If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.
Marks location where JS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted at the end of the <body> tag of the HTML.
If the generated HTML does NOT contain any {% component_js_dependencies %} tags, JS scripts are by default inserted at the end of the <body> tag of the HTML. (See Default JS / CSS locations)
Note that there should be only one {% component_js_dependencies %} for the whole HTML document. If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.
By default, components behave similarly to Django's {% include %}, and the template inside the component has access to the variables defined in the outer template.
You can selectively isolate a component, using the only flag, so that the inner template can access only the data that was explicitly passed to it:
{% component \"name\" positional_arg keyword_arg=value ... only %}\n
Alternatively, you can set all components to be isolated by default, by setting context_behavior to \"isolated\" in your settings:
Since the \"child\" component is used within the {% provide %} / {% endprovide %} tags, we can request the \"user_data\" using Component.inject(\"user_data\"):
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n User is: {{ user }}\n </div>\n \"\"\"\n\n def get_template_data(self, args, kwargs, slots, context):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n
Notice that the keys defined on the {% provide %} tag are then accessed as attributes when accessing them with Component.inject().
Any extra kwargs will be considered as slot data, and will be accessible in the {% fill %} tag via fill's data kwarg:
Read more about Slot data.
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
The content between the {% slot %}..{% endslot %} tags is the fallback content that will be rendered if no fill is given for the slot.
This fallback content can then be accessed from within the {% fill %} tag using the fill's fallback kwarg. This is useful if you need to wrap / prepend / append the original slot's content.
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" %}\n This is fallback content!\n {% endslot %}\n </div>\n \"\"\"\n
Deprecated. Will be removed in v1. Use component_vars.slots instead. Note that component_vars.slots no longer escapes the slot names.
Dictonary describing which component slots are filled (True) or are not (False).
New in version 0.70
Use as {{ component_vars.is_filled }}
Example:
{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n <div class=\"slot-wrapper\">\n {% slot \"my_slot\" / %}\n </div>\n{% endif %}\n
This is equivalent to checking if a given key is among the slot fills:
class MyTable(Component):\n def get_template_data(self, args, kwargs, slots, context):\n return {\n \"my_slot_filled\": \"my_slot\" in slots\n }\n
Decorator for testing components from django-components.
@djc_test manages the global state of django-components, ensuring that each test is properly isolated and that components registered in one test do not affect other tests.
This decorator can be applied to a function, method, or a class. If applied to a class, it will search for all methods that start with test_, and apply the decorator to them. This is applied recursively to nested classes as well.
Examples:
Applying to a function:
from django_components.testing import djc_test\n\n@djc_test\ndef test_my_component():\n @register(\"my_component\")\n class MyComponent(Component):\n template = \"...\"\n ...\n
Applying to a class:
from django_components.testing import djc_test\n\n@djc_test\nclass TestMyComponent:\n def test_something(self):\n ...\n\n class Nested:\n def test_something_else(self):\n ...\n
Applying to a class is the same as applying the decorator to each test_ method individually:
from django_components.testing import djc_test\n\nclass TestMyComponent:\n @djc_test\n def test_something(self):\n ...\n\n class Nested:\n @djc_test\n def test_something_else(self):\n ...\n
django_settings: Django settings, a dictionary passed to Django's @override_settings. The test runs within the context of these overridden settings.
If django_settings contains django-components settings (COMPONENTS field), these are merged. Other Django settings are simply overridden.
components_settings: Instead of defining django-components settings under django_settings[\"COMPONENTS\"], you can simply set the Components settings here.
These settings are merged with the django-components settings from django_settings[\"COMPONENTS\"].
Fields in components_settings override fields in django_settings[\"COMPONENTS\"].
parametrize: Parametrize the test function with pytest.mark.parametrize. This requires pytest to be installed.
You can parametrize the Django or Components settings by setting up parameters called django_settings and components_settings. These will be merged with the respetive settings from the decorator.
Below are all the URL patterns that will be added by adding django_components.urls.
See Installation on how to add these URLs to your Django project.
Django components already prefixes all URLs with components/. So when you are adding the URLs to urlpatterns, you can use an empty string as the first argument:
from django.urls import include, path\n\nurlpatterns = [\n ...\n path(\"\", include(\"django_components.urls\")),\n]\n
"},{"location":"reference/urls/#list-of-urls","title":"List of URLs","text":"
"}]}
\ No newline at end of file
+{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Welcome to Django Components","text":"
django-components combines Django's templating system with the modularity seen in modern frontend frameworks like Vue or React.
With django-components you can support Django projects small and large without leaving the Django ecosystem.
{% html_attrs %} offers a Vue-like granular control for class and style HTML attributes, where you can use a dictionary to manage each class name or style property separately.
One of our goals with django-components is to make it easy to share components between projects. Head over to the Community examples to see some examples.
"},{"location":"#contributing-and-development","title":"Contributing and development","text":"
Get involved or sponsor this project - See here
Running django-components locally for development - See here
"},{"location":"migrating_from_safer_staticfiles/","title":"Migrating from safer_staticfiles","text":"
This guide is for you if you're upgrating django_components to v0.100 or later from older versions.
In version 0.100, we changed how components' static JS and CSS files are handled. See more in the \"Static files\" section.
Migration steps:
Remove django_components.safer_staticfiles from INSTALLED_APPS in your settings.py, and replace it with django.contrib.staticfiles.
Components' JS and CSS scripts (e.g. from Component.js or Component.js_file) are now cached at class creation time.
This means that when you now restart the server while having a page opened in the browser, the JS / CSS files are immediately available.
Previously, the JS/CSS were cached only after the components were rendered. So you had to reload the page to trigger the rendering, in order to make the JS/CSS files available.
Fix the default cache for JS / CSS scripts to be unbounded.
Previously, the default cache for the JS/CSS scripts (LocMemCache) was accidentally limited to 300 entries (~150 components).
Do not send template_rendered signal when rendering a component with no template. (#1277)
Subclassing - Previously, if a parent component defined Component.template or Component.template_file, it's subclass would use the same Template instance.
This could lead to unexpected behavior, where a change to the template of the subclass would also change the template of the parent class.
Now, each subclass has it's own Template instance, and changes to the template of the subclass do not affect the template of the parent class.
Fix Django failing to restart due to \"TypeError: 'Dynamic' object is not iterable\" (#1232)
Fix bug when error formatting failed when error value was not a string.
\u26a0\ufe0f Major release \u26a0\ufe0f - Please test thoroughly before / after upgrading.
This is the biggest step towards v1. While this version introduces many small API changes, we don't expect to make further changes to the affected parts before v1.
For more details see #433.
Summary:
Overhauled typing system
Middleware removed, no longer needed
get_template_data() is the new canonical way to define template data. get_context_data() is now deprecated but will remain until v2.
The middleware ComponentDependencyMiddleware was removed as it is no longer needed.
The middleware served one purpose - to render the JS and CSS dependencies of components when you rendered templates with Template.render() or django.shortcuts.render() and those templates contained {% component %} tags.
NOTE: If you rendered HTML with Component.render() or Component.render_to_response(), the JS and CSS were already rendered.
Now, the JS and CSS dependencies of components are automatically rendered, even when you render Templates with Template.render() or django.shortcuts.render().
To disable this behavior, set the DJC_DEPS_STRATEGY context key to \"ignore\" when rendering the template:
# With `Template.render()`:\ntemplate = Template(template_str)\nrendered = template.render(Context({\"DJC_DEPS_STRATEGY\": \"ignore\"}))\n\n# Or with django.shortcuts.render():\nfrom django.shortcuts import render\nrendered = render(\n request,\n \"my_template.html\",\n context={\"DJC_DEPS_STRATEGY\": \"ignore\"},\n)\n
In fact, you can set the DJC_DEPS_STRATEGY context key to any of the strategies:
\"document\"
\"fragment\"
\"simple\"
\"prepend\"
\"append\"
\"ignore\"
See Dependencies rendering for more info.
Typing
Component typing no longer uses generics. Instead, the types are now defined as class attributes of the component class.
Subclassing of components with None values has changed:
Previously, when a child component's template / JS / CSS attributes were set to None, the child component still inherited the parent's template / JS / CSS.
Now, the child component will not inherit the parent's template / JS / CSS if it sets the attribute to None.
Before:
class Parent(Component):\n template = \"parent.html\"\n\nclass Child(Parent):\n template = None\n\n# Child still inherited parent's template\nassert Child.template == Parent.template\n
After:
class Parent(Component):\n template = \"parent.html\"\n\nclass Child(Parent):\n template = None\n\n# Child does not inherit parent's template\nassert Child.template is None\n
The Component.Url class was merged with Component.View.
Instead of Component.Url.public, use Component.View.public.
If you imported ComponentUrl from django_components, you need to update your import to ComponentView.
Before:
class MyComponent(Component):\n class Url:\n public = True\n\n class View:\n def get(self, request):\n return self.render_to_response()\n
After:
class MyComponent(Component):\n class View:\n public = True\n\n def get(self, request):\n return self.render_to_response()\n
Caching - The function signatures of Component.Cache.get_cache_key() and Component.Cache.hash() have changed to enable passing slots.
Args and kwargs are no longer spread, but passed as a list and a dict, respectively.
Component.get_context_data() is now deprecated. Use Component.get_template_data() instead.
get_template_data() behaves the same way, but has a different function signature to accept also slots and context.
Since get_context_data() is widely used, it will remain available until v2.
Component.get_template_name() and Component.get_template() are now deprecated. Use Component.template, Component.template_file or Component.on_render() instead.
Component.get_template_name() and Component.get_template() will be removed in v1.
In v1, each Component will have at most one static template. This is needed to enable support for Markdown, Pug, or other pre-processing of templates by extensions.
If you are using the deprecated methods to point to different templates, there's 2 ways to migrate:
Split the single Component into multiple Components, each with its own template. Then switch between them in Component.on_render():
The type kwarg in Component.render() and Component.render_to_response() is now deprecated. Use deps_strategy instead. The type kwarg will be removed in v1.
The render_dependencies kwarg in Component.render() and Component.render_to_response() is now deprecated. Use deps_strategy=\"ignore\" instead. The render_dependencies kwarg will be removed in v1.
When creating extensions, the ComponentExtension.ExtensionClass attribute was renamed to ComponentConfig.
The old name is deprecated and will be removed in v1.
Before:
from django_components import ComponentExtension\n\nclass MyExtension(ComponentExtension):\n class ExtensionClass(ComponentExtension.ExtensionClass):\n pass\n
After:
from django_components import ComponentExtension, ExtensionComponentConfig\n\nclass MyExtension(ComponentExtension):\n class ComponentConfig(ExtensionComponentConfig):\n pass\n
When creating extensions, to access the Component class from within the methods of the extension nested classes, use component_cls.
Previously this field was named component_class. The old name is deprecated and will be removed in v1.
ComponentExtension.ExtensionClass attribute was renamed to ComponentConfig.
The old name is deprecated and will be removed in v1.\n\nBefore:\n\n```py\nfrom django_components import ComponentExtension, ExtensionComponentConfig\n\nclass LoggerExtension(ComponentExtension):\n name = \"logger\"\n\n class ComponentConfig(ExtensionComponentConfig):\n def log(self, msg: str) -> None:\n print(f\"{self.component_class.__name__}: {msg}\")\n```\n\nAfter:\n\n```py\nfrom django_components import ComponentExtension, ExtensionComponentConfig\n\nclass LoggerExtension(ComponentExtension):\n name = \"logger\"\n\n class ComponentConfig(ExtensionComponentConfig):\n def log(self, msg: str) -> None:\n print(f\"{self.component_cls.__name__}: {msg}\")\n```\n
Slots
SlotContent was renamed to SlotInput. The old name is deprecated and will be removed in v1.
SlotRef was renamed to SlotFallback. The old name is deprecated and will be removed in v1.
The default kwarg in {% fill %} tag was renamed to fallback. The old name is deprecated and will be removed in v1.
Before:
{% fill \"footer\" default=\"footer\" %}\n {{ footer }}\n{% endfill %}\n
After:
{% fill \"footer\" fallback=\"footer\" %}\n {{ footer }}\n{% endfill %}\n
The template variable {{ component_vars.is_filled }} is now deprecated. Will be removed in v1. Use {{ component_vars.slots }} instead.
NOTE: component_vars.is_filled automatically escaped slot names, so that even slot names that are not valid python identifiers could be set as slot names. component_vars.slots no longer does that.
Component attribute Component.is_filled is now deprecated. Will be removed in v1. Use Component.slots instead.
Before:
class MyComponent(Component):\n def get_template_data(self, args, kwargs, slots, context):\n if self.is_filled.footer:\n color = \"red\"\n else:\n color = \"blue\"\n\n return {\n \"color\": color,\n }\n
After:
class MyComponent(Component):\n def get_template_data(self, args, kwargs, slots, context):\n if \"footer\" in slots:\n color = \"red\"\n else:\n color = \"blue\"\n\n return {\n \"color\": color,\n }\n
NOTE: Component.is_filled automatically escaped slot names, so that even slot names that are not valid python identifiers could be set as slot names. Component.slots no longer does that.
Miscellaneous
Template caching with cached_template() helper and template_cache_size setting is deprecated. These will be removed in v1.
This feature made sense if you were dynamically generating templates for components using Component.get_template_string() and Component.get_template().
However, in v1, each Component will have at most one static template. This static template is cached internally per component class, and reused across renders.
This makes the template caching feature obsolete.
If you relied on cached_template(), you should either:
Wrap the templates as Components.
Manage the cache of Templates yourself.
The debug_highlight_components and debug_highlight_slots settings are deprecated. These will be removed in v1.
The debug highlighting feature was re-implemented as an extension. As such, the recommended way for enabling it has changed:
If you define Component.Args, Component.Kwargs, Component.Slots, then the args, kwargs, slots arguments will be instances of these classes:
class Button(Component):\n class Args(NamedTuple):\n field1: str\n\n class Kwargs(NamedTuple):\n field2: int\n\n def get_template_data(self, args: Args, kwargs: Kwargs, slots, context):\n return {\n \"val1\": args.field1,\n \"val2\": kwargs.field2,\n }\n
Input validation is now part of the render process.
When you specify the input types (such as Component.Args, Component.Kwargs, etc), the actual inputs to data methods (Component.get_template_data(), etc) will be instances of the types you specified.
This practically brings back input validation, because the instantiation of the types will raise an error if the inputs are not valid.
Read more on Typing and validation
Render emails or other non-browser HTML with new \"dependencies strategies\"
When rendering a component with Component.render() or Component.render_to_response(), the deps_strategy kwarg (previously type) now accepts additional options:
Smartly inserts JS / CSS into placeholders or into <head> and <body> tags.
Inserts extra script to allow fragment strategy to work.
Assumes the HTML will be rendered in a JS-enabled browser.
\"fragment\"
A lightweight HTML fragment to be inserted into a document with AJAX.
Ignores placeholders and any <head> / <body> tags.
No JS / CSS included.
\"simple\"
Smartly insert JS / CSS into placeholders or into <head> and <body> tags.
No extra script loaded.
\"prepend\"
Insert JS / CSS before the rendered HTML.
Ignores placeholders and any <head> / <body> tags.
No extra script loaded.
\"append\"
Insert JS / CSS after the rendered HTML.
Ignores placeholders and any <head> / <body> tags.
No extra script loaded.
\"ignore\"
Rendered HTML is left as-is. You can still process it with a different strategy later with render_dependencies().
Used for inserting rendered HTML into other components.
See Dependencies rendering for more info.
New Component.args, Component.kwargs, Component.slots attributes available on the component class itself.
These attributes are the same as the ones available in Component.get_template_data().
You can use these in other methods like Component.on_render_before() or Component.on_render_after().
from django_components import Component, SlotInput\n\nclass Table(Component):\n class Args(NamedTuple):\n page: int\n\n class Kwargs(NamedTuple):\n per_page: int\n\n class Slots(NamedTuple):\n content: SlotInput\n\n def on_render_before(self, context: Context, template: Optional[Template]) -> None:\n assert self.args.page == 123\n assert self.kwargs.per_page == 10\n content_html = self.slots.content()\n
Same as with the parameters in Component.get_template_data(), they will be instances of the Args, Kwargs, Slots classes if defined, or plain lists / dictionaries otherwise.
4 attributes that were previously available only under the Component.input attribute are now available directly on the Component instance:
Component.raw_args
Component.raw_kwargs
Component.raw_slots
Component.deps_strategy
The first 3 attributes are the same as the deprecated Component.input.args, Component.input.kwargs, Component.input.slots properties.
Compared to the Component.args / Component.kwargs / Component.slots attributes, these \"raw\" attributes are not typed and will remain as plain lists / dictionaries even if you define the Args, Kwargs, Slots classes.
The Component.deps_strategy attribute is the same as the deprecated Component.input.deps_strategy property.
Same as with the parameters in Component.get_template_data(), they will be instances of the Args, Kwargs, Slots classes if defined, or plain lists / dictionaries otherwise.
New component lifecycle hook Component.on_render().
This hook is called when the component is being rendered.
You can override this method to:
Change what template gets rendered
Modify the context
Modify the rendered output after it has been rendered
Handle errors
See on_render for more info.
get_component_url() now optionally accepts query and fragment arguments.
You can now access the {% component %} tag (ComponentNode instance) from which a Component was created. Use Component.node to access it.
This is mostly useful for extensions, which can use this to detect if the given Component comes from a {% component %} tag or from a different source (such as Component.render()).
Component.node is None if the component is created by Component.render() (but you can pass in the node kwarg yourself).
class MyComponent(Component):\n def get_template_data(self, context, template):\n if self.node is not None:\n assert self.node.name == \"my_component\"\n
Node classes ComponentNode, FillNode, ProvideNode, and SlotNode are part of the public API.
These classes are what is instantiated when you use {% component %}, {% fill %}, {% provide %}, and {% slot %} tags.
If you don't want to modify the rendered result, return None.
See all Extension hooks.
When creating extensions, the previous syntax with ComponentExtension.ExtensionClass was causing Mypy errors, because Mypy doesn't allow using class attributes as bases:
Before:
from django_components import ComponentExtension\n\nclass MyExtension(ComponentExtension):\n class ExtensionClass(ComponentExtension.ExtensionClass): # Error!\n pass\n
Instead, you can import ExtensionComponentConfig directly:
After:
from django_components import ComponentExtension, ExtensionComponentConfig\n\nclass MyExtension(ComponentExtension):\n class ComponentConfig(ExtensionComponentConfig):\n pass\n
When a component is being rendered, a proper Component instance is now created.
Previously, the Component state was managed as half-instance, half-stack.
Component's \"Render API\" (args, kwargs, slots, context, inputs, request, context data, etc) can now be accessed also outside of the render call. So now its possible to take the component instance out of get_template_data() (although this is not recommended).
Components can now be defined without a template.
Previously, the following would raise an error:
class MyComponent(Component):\n pass\n
\"Template-less\" components can be used together with Component.on_render() to dynamically pick what to render:
Fix bug: Context processors data was being generated anew for each component. Now the data is correctly created once and reused across components with the same request (#1165).
Fix KeyError on component_context_cache when slots are rendered outside of the component's render context. (#1189)
Component classes now have do_not_call_in_templates=True to prevent them from being called as functions in templates.
Each Component class now has a class_id attribute, which is unique to the component subclass.
NOTE: This is different from Component.id, which is unique to each rendered instance.
To look up a component class by its class_id, use get_component_by_class_id().
It's now easier to create URLs for component views.
Before, you had to call Component.as_view() and pass that to urlpatterns.
Now this can be done for you if you set Component.Url.public to True:
class MyComponent(Component):\n class Url:\n public = True\n ...\n
Then, to get the URL for the component, use get_component_url():
from django_components import get_component_url\n\nurl = get_component_url(MyComponent)\n
This way you don't have to mix your app URLs with component URLs.
Read more on Component views and URLs.
Per-component caching - Set Component.Cache.enabled to True to enable caching for a component.
Component caching allows you to store the rendered output of a component. Next time the component is rendered with the same input, the cached output is returned instead of re-rendering the component.
class TestComponent(Component):\n template = \"Hello\"\n\n class Cache:\n enabled = True\n ttl = 0.1 # .1 seconds TTL\n cache_name = \"custom_cache\"\n\n # Custom hash method for args and kwargs\n # NOTE: The default implementation simply serializes the input into a string.\n # As such, it might not be suitable for complex objects like Models.\n def hash(self, *args, **kwargs):\n return f\"{json.dumps(args)}:{json.dumps(kwargs)}\"\n
Read more on Component caching.
@djc_test can now be called without first calling django.setup(), in which case it does it for you.
Expose ComponentInput class, which is a typing for Component.input.
Add defaults for the component inputs with the Component.Defaults nested class. Defaults are applied if the argument is not given, or if it set to None.
For lists, dictionaries, or other objects, wrap the value in Default() class to mark it as a factory function:
```python\nfrom django_components import Default\n\nclass Table(Component):\n class Defaults:\n position = \"left\"\n width = \"200px\"\n options = Default(lambda: [\"left\", \"right\", \"center\"])\n\n def get_context_data(self, position, width, options):\n return {\n \"position\": position,\n \"width\": width,\n \"options\": options,\n }\n\n# `position` is used as given, `\"right\"`\n# `width` uses default because it's `None`\n# `options` uses default because it's missing\nTable.render(\n kwargs={\n \"position\": \"right\",\n \"width\": None,\n }\n)\n```\n
{% html_attrs %} now offers a Vue-like granular control over class and style HTML attributes, where each class name or style property can be managed separately.
Settings are now loaded only once, and thus are considered immutable once loaded. Previously, django-components would load settings from settings.COMPONENTS on each access. The new behavior aligns with Django's settings.
Access the HttpRequest object under Component.request.
To pass the request object to a component, either: - Render a template or component with RequestContext, - Or set the request kwarg to Component.render() or Component.render_to_response().
Read more on HttpRequest.
Access the context processors data under Component.context_processors_data.
Context processors data is available only when the component has access to the request object, either by: - Passing the request to Component.render() or Component.render_to_response(), - Or by rendering a template or component with RequestContext, - Or being nested in another component that has access to the request object.
The data from context processors is automatically available within the component's template.
Configurable cache - Set COMPONENTS.cache to change where and how django-components caches JS and CSS files. (#946)
Read more on Caching.
Highlight coponents and slots in the UI - We've added two boolean settings COMPONENTS.debug_highlight_components and COMPONENTS.debug_highlight_slots, which can be independently set to True. First will wrap components in a blue border, the second will wrap slots in a red border. (#942)
@template_tag and BaseNode - A decorator and a class that allow you to define custom template tags that will behave similarly to django-components' own template tags.
Read more on Template tags.
Template tags defined with @template_tag and BaseNode will have the following features:
Accepting args, kwargs, and flags.
Allowing literal lists and dicts as inputs as:
key=[1, 2, 3] or key={\"a\": 1, \"b\": 2} - Using template tags tag inputs as:
{% my_tag key=\"{% lorem 3 w %}\" / %} - Supporting the flat dictionary definition:
attr:key=value - Spreading args and kwargs with ...:
{% my_tag ...args ...kwargs / %} - Being able to call the template tag as:
Refactored template tag input validation. When you now call template tags like {% slot %}, {% fill %}, {% html_attrs %}, and others, their inputs are now validated the same way as Python function inputs are.
So, for example
{% slot \"my_slot\" name=\"content\" / %}\n
will raise an error, because the positional argument name is given twice.
NOTE: Special kwargs whose keys are not valid Python variable names are not affected by this change. So when you define:
{% component data-id=123 / %}\n
The data-id will still be accepted as a valid kwarg, assuming that your get_context_data() accepts **kwargs:
Instead of inlining the JS and CSS under Component.js and Component.css, you can move them to their own files, and link the JS/CSS files with Component.js_file and Component.css_file.
Even when you specify the JS/CSS with Component.js_file or Component.css_file, then you can still access the content under Component.js or Component.css - behind the scenes, the content of the JS/CSS files will be set to Component.js / Component.css upon first access.
The same applies to Component.template_file, which will populate Component.template upon first access.
With this change, the role of Component.js/css and the JS/CSS in Component.Media has changed:
The JS/CSS defined in Component.js/css or Component.js/css_file is the \"main\" JS/CSS
The JS/CSS defined in Component.Media.js/css are secondary or additional
The canonical way to define a template file was changed from template_name to template_file, to align with the rest of the API.
template_name remains for backwards compatibility. When you get / set template_name, internally this is proxied to template_file.
The undocumented Component.component_id was removed. Instead, use Component.id. Changes:
While component_id was unique every time you instantiated Component, the new id is unique every time you render the component (e.g. with Component.render())
The new id is available only during render, so e.g. from within get_context_data()
Component's HTML / CSS / JS are now resolved and loaded lazily. That is, if you specify template_name/template_file, js_file, css_file, or Media.js/css, the file paths will be resolved only once you:
Try to access component's HTML / CSS / JS, or
Render the component.
Read more on Accessing component's HTML / JS / CSS.
Component inheritance:
When you subclass a component, the JS and CSS defined on parent's Media class is now inherited by the child component.
You can disable or customize Media inheritance by setting extend attribute on the Component.Media nested class. This work similarly to Django's Media.extend.
When child component defines either template or template_file, both of parent's template and template_file are ignored. The same applies to js_file and css_file.
Autodiscovery now ignores files and directories that start with an underscore (_), except __init__.py
The Signals emitted by or during the use of django-components are now documented, together the template_rendered signal.
Add support for HTML fragments. HTML fragments can be rendered by passing type=\"fragment\" to Component.render() or Component.render_to_response(). Read more on how to use HTML fragments with HTMX, AlpineJS, or vanillaJS.
Fix compatibility with custom subclasses of Django's Template that need to access origin or other initialization arguments. (https://github.com/django-components/django-components/pull/828)
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.
Component caching allows you to store the rendered output of a component. Next time the component is rendered with the same input, the cached output is returned instead of re-rendering the component.
This is particularly useful for components that are expensive to render or do not change frequently.
Info
Component caching uses Django's cache framework, so you can use any cache backend that is supported by Django.
You can specify a time-to-live (TTL) for the cache entry with Component.Cache.ttl, which determines how long the entry remains valid. The TTL is specified in seconds.
class MyComponent(Component):\n class Cache:\n enabled = True\n ttl = 60 * 60 * 24 # 1 day\n
If ttl > 0, entries are cached for the specified number of seconds.
Since component caching uses Django's cache framework, you can specify a custom cache name with Component.Cache.cache_name to use a different cache backend:
class MyComponent(Component):\n class Cache:\n enabled = True\n cache_name = \"my_cache\"\n
By default, the cache key is generated based on the component's input (args and kwargs). So the following two calls would generate separate entries in the cache:
However, you have full control over the cache key generation. As such, you can:
Cache the component on all inputs (default)
Cache the component on particular inputs
Cache the component irrespective of the inputs
To achieve that, you can override the Component.Cache.hash() method to customize how arguments are hashed into the cache key.
class MyComponent(Component):\n class Cache:\n enabled = True\n\n def hash(self, *args, **kwargs):\n return f\"{json.dumps(args)}:{json.dumps(kwargs)}\"\n
For even more control, you can override other methods available on the ComponentCache class.
Warning
The default implementation of Cache.hash() simply serializes the input into a string. As such, it might not be suitable if you need to hash complex objects like Models.
Here's a complete example of a component with caching enabled:
from django_components import Component\n\nclass MyComponent(Component):\n template = \"Hello, {{ name }}\"\n\n class Cache:\n enabled = True\n ttl = 300 # Cache for 5 minutes\n cache_name = \"my_cache\"\n\n def get_template_data(self, args, kwargs, slots, context):\n return {\"name\": kwargs[\"name\"]}\n
In this example, the component's rendered output is cached for 5 minutes using the my_cache backend.
"},{"location":"concepts/advanced/component_context_scope/","title":"Component context and scope","text":"
By default, context variables are passed down the template as in regular Django - deeper scopes can access the variables from the outer scopes. So if you have several nested forloops, then inside the deep-most loop you can access variables defined by all previous loops.
With this in mind, the {% component %} tag behaves similarly to {% include %} tag - inside the component tag, you can access all variables that were defined outside of it.
And just like with {% include %}, if you don't want a specific component template to have access to the parent context, add only to the {% component %} tag:
{% component \"calendar\" date=\"2015-06-19\" only / %}\n
NOTE: {% csrf_token %} tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the only modifier.
If you find yourself using the only modifier often, you can set the context_behavior option to \"isolated\", which automatically applies the only modifier. This is useful if you want to make sure that components don't accidentally access the outer context.
Components can also access the outer context in their context methods like get_template_data by accessing the property self.outer_context.
"},{"location":"concepts/advanced/component_context_scope/#example-of-accessing-outer-context","title":"Example of Accessing Outer Context","text":"
<div>\n {% component \"calender\" / %}\n</div>\n
Assuming that the rendering context has variables such as date, you can use self.outer_context to access them from within get_template_data. Here's how you might implement it:
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_template_data() of the component that owns the fill tag.
\"isolated\"
Similar behavior to Vue or React, this is useful if you want to make sure that components don't accidentally access variables defined outside of the component.
Inside the {% fill %} tag, you can ONLY access variables from 2 places:
Any loops ({% for ... %}) that the {% fill %} tag is part of.
Component.get_template_data() of the component which defined the template (AKA the \"root\" component).
Warning
Notice that the component whose get_template_data() we use inside {% fill %} is NOT the same across the two modes!
\"django\" - my_var has access to data from get_template_data() of both Inner and Outer. If there are variables defined in both, then Inner overshadows Outer.
\"isolated\" - my_var has access to data from get_template_data() of ONLY Outer.
Then if get_template_data() of the component \"my_comp\" returns following data:
{ \"my_var\": 456 }\n
Then the template will be rendered as:
123 # my_var\n # cheese\n
Because variables \"my_var\" and \"cheese\" are searched only inside RootComponent.get_template_data(). But since \"cheese\" is not defined there, it's empty.
Info
Notice that the variables defined with the {% with %} tag are ignored inside the {% fill %} tag with the \"isolated\" mode.
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/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_file = \"template.html\"\n\n # This component takes one parameter, a date string to show in the template\n def get_template_data(self, args, kwargs, slots, context):\n return {\n \"date\": kwargs[\"date\"],\n }\n
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# Check if component is registered\nregistry.has(\"button\") # True\n\n# Unregister single component\nregistry.unregister(\"card\")\n\n# Unregister all components\nregistry.clear()\n
"},{"location":"concepts/advanced/component_registry/#registering-components-to-custom-componentregistry","title":"Registering components to custom ComponentRegistry","text":"
If you are writing a component library to be shared with others, you may want to manage your own instance of ComponentRegistry and register components onto a different Library instance than the default one.
The Library instance can be set at instantiation of ComponentRegistry. If omitted, then the default Library instance from django_components is used.
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.
Each extension has a corresponding nested class within the Component class. These allow to configure the extensions on a per-component basis.
E.g.:
\"view\" extension -> Component.View
\"cache\" extension -> Component.Cache
\"defaults\" extension -> Component.Defaults
Note
Accessing the component instance from inside the nested classes:
Each method of the nested classes has access to the component attribute, which points to the component instance.
class MyTable(Component):\n class MyExtension:\n def get(self, request):\n # `self.component` points to the instance of `MyTable` Component.\n return self.component.render_to_response(request=request)\n
"},{"location":"concepts/advanced/extensions/#example-component-as-view","title":"Example: Component as View","text":"
The Components as Views feature is actually implemented as an extension that is configured by a View nested class.
You can override the get(), post(), etc methods to customize the behavior of the component as a view:
class MyTable(Component):\n class View:\n def get(self, request):\n return self.component_class.render_to_response(request=request)\n\n def post(self, request):\n return self.component_class.render_to_response(request=request)\n\n ...\n
Which is equivalent to setting the following for every component:
class MyTable(Component):\n class MyExtension:\n key = \"value\"\n\n class View:\n public = True\n\n class Cache:\n ttl = 60\n\n class Storybook:\n def title(self):\n return self.component_cls.__name__\n
Info
If you define an attribute as a function, it is like defining a method on the extension class.
E.g. in the example above, title is a method on the Storybook extension class.
As the name suggests, these are defaults, and so you can still selectively override them on a per-component basis:
class MyTable(Component):\n class View:\n public = False\n
"},{"location":"concepts/advanced/extensions/#extensions-in-component-instances","title":"Extensions in component instances","text":"
Above, we've configured extensions View and Storybook for the MyTable component.
You can access the instances of these extension classes in the component instance.
Extensions are available under their names (e.g. self.view, self.storybook).
For example, the View extension is available as self.view:
class MyTable(Component):\n def get_template_data(self, args, kwargs, slots, context):\n # `self.view` points to the instance of `View` extension.\n return {\n \"view\": self.view,\n }\n
And the Storybook extension is available as self.storybook:
class MyTable(Component):\n def get_template_data(self, args, kwargs, slots, context):\n # `self.storybook` points to the instance of `Storybook` extension.\n return {\n \"title\": self.storybook.title(),\n }\n
Creating extensions in django-components involves defining a class that inherits from ComponentExtension. This class can implement various lifecycle hooks and define new attributes or methods to be added to components.
To create an extension, define a class that inherits from ComponentExtension and implement the desired hooks.
Each extension MUST have a name attribute. The name MUST be a valid Python identifier.
The extension may implement any of the hook methods.
Each hook method receives a context object with relevant data.
Extension may own URLs or CLI commands.
from django_components.extension import ComponentExtension, OnComponentClassCreatedContext\n\nclass MyExtension(ComponentExtension):\n name = \"my_extension\"\n\n def on_component_class_created(self, ctx: OnComponentClassCreatedContext) -> None:\n # Custom logic for when a component class is created\n ctx.component_cls.my_attr = \"my_value\"\n
Warning
The name attribute MUST be unique across all extensions.
Moreover, the name attribute MUST NOT conflict with existing Component class API.
So if you name an extension render, it will conflict with the render() method of the Component class.
In previous sections we've seen the View and Storybook extensions classes that were nested within the Component class:
class MyComponent(Component):\n class View:\n ...\n\n class Storybook:\n ...\n
These can be understood as component-specific overrides or configuration.
Whether it's Component.View or Component.Storybook, their respective extensions defined how these nested classes will behave.
For example, the View extension defines the API that users may override in ViewExtension.ComponentConfig:
from django_components.extension import ComponentExtension, ExtensionComponentConfig\n\nclass ViewExtension(ComponentExtension):\n name = \"view\"\n\n # The default behavior of the `View` extension class.\n class ComponentConfig(ExtensionComponentConfig):\n def get(self, request):\n raise NotImplementedError(\"You must implement the `get` method.\")\n\n def post(self, request):\n raise NotImplementedError(\"You must implement the `post` method.\")\n\n ...\n
In any component that then defines a nested Component.View extension class, the resulting View class will actually subclass from the ViewExtension.ComponentConfig class.
In other words, when you define a component like this:
class MyTable(Component):\n class View:\n def get(self, request):\n # Do something\n ...\n
Behind the scenes it is as if you defined the following:
class MyTable(Component):\n class View(ViewExtension.ComponentConfig):\n def get(self, request):\n # Do something\n ...\n
Warning
When writing an extension, the ComponentConfig MUST subclass the base class ExtensionComponentConfig.
This base class ensures that the extension class will have access to the component instance.
"},{"location":"concepts/advanced/extensions/#install-your-extension","title":"Install your extension","text":"
Once the extension is defined, it needs to be installed in the Django settings to be used by the application.
Extensions can be given either as an extension class, or its import string:
To tie it all together, here's an example of a custom logging extension that logs when components are created, deleted, or rendered:
Each component can specify which color to use for the logging by setting Component.ColorLogger.color.
The extension will log the component name and color when the component is created, deleted, or rendered.
from django_components.extension import (\n ComponentExtension,\n ExtensionComponentConfig,\n OnComponentClassCreatedContext,\n OnComponentClassDeletedContext,\n OnComponentInputContext,\n)\n\n\nclass ColorLoggerExtension(ComponentExtension):\n name = \"color_logger\"\n\n # All `Component.ColorLogger` classes will inherit from this class.\n class ComponentConfig(ExtensionComponentConfig):\n color: str\n\n # These hooks don't have access to the Component instance,\n # only to the Component class, so we access the color\n # as `Component.ColorLogger.color`.\n def on_component_class_created(self, ctx: OnComponentClassCreatedContext):\n log.info(\n f\"Component {ctx.component_cls} created.\",\n color=ctx.component_cls.ColorLogger.color,\n )\n\n def on_component_class_deleted(self, ctx: OnComponentClassDeletedContext):\n log.info(\n f\"Component {ctx.component_cls} deleted.\",\n color=ctx.component_cls.ColorLogger.color,\n )\n\n # This hook has access to the Component instance, so we access the color\n # as `self.component.color_logger.color`.\n def on_component_input(self, ctx: OnComponentInputContext):\n log.info(\n f\"Rendering component {ctx.component_cls}.\",\n color=ctx.component.color_logger.color,\n )\n
To use the ColorLoggerExtension, add it to your settings:
You can access the owner Component class (MyTable) from within methods of the extension class (MyExtension) by using the component_cls attribute:
class MyTable(Component):\n class MyExtension:\n def some_method(self):\n print(self.component_cls)\n
Here is how the component_cls attribute may be used with our ColorLogger extension shown above:
class ColorLoggerComponentConfig(ExtensionComponentConfig):\n color: str\n\n def log(self, msg: str) -> None:\n print(f\"{self.component_cls.__name__}: {msg}\")\n\n\nclass ColorLoggerExtension(ComponentExtension):\n name = \"color_logger\"\n\n # All `Component.ColorLogger` classes will inherit from this class.\n ComponentConfig = ColorLoggerComponentConfig\n
When a slot is passed to a component, it is copied, so that the original slot is not modified with rendering metadata.
Therefore, don't use slot's identity to associate metadata with the slot:
# \u274c Don't do this:\nslots_cache = {}\n\nclass LoggerExtension(ComponentExtension):\n name = \"logger\"\n\n def on_component_input(self, ctx: OnComponentInputContext):\n for slot in ctx.component.slots.values():\n slots_cache[id(slot)] = {\"some\": \"metadata\"}\n
Instead, use the Slot.extra attribute, which is copied from the original slot:
# \u2705 Do this:\nclass LoggerExtension(ComponentExtension):\n name = \"logger\"\n\n # Save component-level logger settings for each slot when a component is rendered.\n def on_component_input(self, ctx: OnComponentInputContext):\n for slot in ctx.component.slots.values():\n slot.extra[\"logger\"] = ctx.component.logger\n\n # Then, when a fill is rendered with `{% slot %}`, we can access the logger settings\n # from the slot's metadata.\n def on_slot_rendered(self, ctx: OnSlotRenderedContext):\n logger = ctx.slot.extra[\"logger\"]\n logger.log(...)\n
Extensions in django-components can define custom commands that can be executed via the Django management command interface. This allows for powerful automation and customization capabilities.
For example, if you have an extension that defines a command that prints \"Hello world\", you can run the command with:
python manage.py components ext run my_ext hello\n
Where:
python manage.py components - is the Django entrypoint
ext run - is the subcommand to run extension commands
To define a command, subclass from ComponentCommand. This subclass should define:
name - the command's name
help - the command's help text
handle - the logic to execute when the command is run
from django_components import ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n name = \"hello\"\n help = \"Say hello\"\n\n def handle(self, *args, **kwargs):\n print(\"Hello, world!\")\n\nclass MyExt(ComponentExtension):\n name = \"my_ext\"\n commands = [HelloCommand]\n
"},{"location":"concepts/advanced/extensions/#define-arguments-and-options","title":"Define arguments and options","text":"
Commands can accept positional arguments and options (e.g. --foo), which are defined using the arguments attribute of the ComponentCommand class.
The arguments are parsed with argparse into a dictionary of arguments and options. These are then available as keyword arguments to the handle method of the command.
from django_components import CommandArg, ComponentCommand, ComponentExtension\n\nclass HelloCommand(ComponentCommand):\n name = \"hello\"\n help = \"Say hello\"\n\n arguments = [\n # Positional argument\n CommandArg(\n name_or_flags=\"name\",\n help=\"The name to say hello to\",\n ),\n # Optional argument\n CommandArg(\n name_or_flags=[\"--shout\", \"-s\"],\n action=\"store_true\",\n help=\"Shout the hello\",\n ),\n ]\n\n def handle(self, name: str, *args, **kwargs):\n shout = kwargs.get(\"shout\", False)\n msg = f\"Hello, {name}!\"\n if shout:\n msg = msg.upper()\n print(msg)\n
You can run the command with arguments and options:
python manage.py components ext run my_ext hello John --shout\n>>> HELLO, JOHN!\n
Note
Command definitions are parsed with argparse, so you can use all the features of argparse to define your arguments and options.
See the argparse documentation for more information.
django-components defines types as CommandArg, CommandArgGroup, CommandSubcommand, and CommandParserInput to help with type checking.
Note
If a command doesn't have the handle method defined, the command will print a help message and exit.
Extensions can define subcommands, allowing for more complex command structures.
Subcommands are defined similarly to root commands, as subclasses of ComponentCommand class.
However, instead of defining the subcommands in the commands attribute of the extension, you define them in the subcommands attribute of the parent command:
from django_components import CommandArg, CommandArgGroup, ComponentCommand, ComponentExtension\n\nclass ChildCommand(ComponentCommand):\n name = \"child\"\n help = \"Child command\"\n\n def handle(self, *args, **kwargs):\n print(\"Child command\")\n\nclass ParentCommand(ComponentCommand):\n name = \"parent\"\n help = \"Parent command\"\n subcommands = [\n ChildCommand,\n ]\n\n def handle(self, *args, **kwargs):\n print(\"Parent command\")\n
In this example, we can run two commands.
Either the parent command:
python manage.py components ext run parent\n>>> Parent command\n
Or the child command:
python manage.py components ext run parent child\n>>> Child command\n
Warning
Subcommands are independent of the parent command. When a subcommand runs, the parent command is NOT executed.
As such, if you want to pass arguments to both the parent and child commands, e.g.:
python manage.py components ext run parent --foo child --bar\n
You should instead pass all the arguments to the subcommand:
python manage.py components ext run parent child --foo --bar\n
Extensions can define custom views and endpoints that can be accessed through the Django application.
To define URLs for an extension, set them in the urls attribute of your ComponentExtension class. Each URL is defined using the URLRoute class, which specifies the path, handler, and optional name for the route.
Here's an example of how to define URLs within an extension:
from django_components.extension import ComponentExtension, URLRoute\nfrom django.http import HttpResponse\n\ndef my_view(request):\n return HttpResponse(\"Hello from my extension!\")\n\nclass MyExtension(ComponentExtension):\n name = \"my_extension\"\n\n urls = [\n URLRoute(path=\"my-view/\", handler=my_view, name=\"my_view\"),\n URLRoute(path=\"another-view/<int:id>/\", handler=my_view, name=\"another_view\"),\n ]\n
Warning
The URLRoute objects are different from objects created with Django's django.urls.path(). Do NOT use URLRoute objects in Django's urlpatterns and vice versa!
django-components uses a custom URLRoute class to define framework-agnostic routing rules.
As of v0.131, URLRoute objects are directly converted to Django's URLPattern and URLResolver objects.
Return nothing (or None) to handle the result as usual
If you don't raise an exception, and neither return a new HTML, then original HTML / error will be used:
If rendering succeeded, the original HTML will be used as the final output.
If rendering failed, the original error will be propagated.
class MyTable(Component):\n def on_render(self, context, template):\n html, error = yield template.render(context)\n\n if error is not None:\n # The rendering failed\n print(f\"Error: {error}\")\n
on_render_after() runs when the component was fully rendered, including all its children.
It receives the same arguments as on_render_before(), plus the outcome of the rendering:
result: The rendered output of the component. None if the rendering failed.
error: The error that occurred during the rendering, or None if the rendering succeeded.
on_render_after() behaves the same way as the second part of on_render() (after the yield).
class MyTable(Component):\n def on_render_after(self, context, template, result, error):\n if error is None:\n # The rendering succeeded\n return result\n else:\n # The rendering failed\n print(f\"Error: {error}\")\n
Same as on_render(), you can return a new HTML, raise a new exception, or return nothing:
Return a new HTML
The new HTML will be used as the final output.
If the original template raised an error, it will be ignored.
Return nothing (or None) to handle the result as usual
If you don't raise an exception, and neither return a new HTML, then original HTML / error will be used:
If rendering succeeded, the original HTML will be used as the final output.
If rendering failed, the original error will be propagated.
class MyTable(Component):\n def on_render_after(self, context, template, result, error):\n if error is not None:\n # The rendering failed\n print(f\"Error: {error}\")\n
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.
Django-components provides a seamless integration with HTML fragments with AJAX (HTML over the wire), whether you're using jQuery, HTMX, AlpineJS, vanilla JavaScript, or other.
If the fragment component has any JS or CSS, django-components will:
Automatically load the associated JS and CSS
Ensure that JS is loaded and executed only once even if the fragment is inserted multiple times
Info
What are HTML fragments and \"HTML over the wire\"?
It is one of the methods for updating the state in the browser UI upon user interaction.
How it works is that:
User makes an action - clicks a button or submits a form
The action causes a request to be made from the client to the server.
Server processes the request (e.g. form submission), and responds with HTML of some part of the UI (e.g. a new entry in a table).
A library like HTMX, AlpineJS, or custom function inserts the new HTML into the correct place.
"},{"location":"concepts/advanced/html_fragments/#document-and-fragment-strategies","title":"Document and fragment strategies","text":"
Components support different \"strategies\" for rendering JS and CSS.
Two of them are used to enable HTML fragments - \"document\" and \"fragment\".
Fragment strategy assumes that the main HTML has already been rendered and loaded on the page. The component renders HTML that will be inserted into the page as a fragment, at a LATER time:
JS and CSS is not directly embedded to avoid duplicately executing the same JS scripts. So template tags like {% component_js_dependencies %} inside of fragments are ignored.
Instead, django-components appends the fragment's content with a JSON <script> to trigger a call to its asset manager JS script, which will load the JS and CSS smartly.
The asset manager JS script is assumed to be already loaded on the page.
A component is rendered as \"fragment\" when:
It is rendered with Component.render() or Component.render_to_response() with the deps_strategy kwarg set to \"fragment\"
"},{"location":"concepts/advanced/html_fragments/#2-define-fragment-html_1","title":"2. Define fragment HTML","text":"
The fragment to be inserted into the document.
IMPORTANT: Don't forget to set deps_strategy=\"fragment\"
[root]/components/demo.py
class Frag(Component):\n # NOTE: We wrap the actual fragment in a template tag with x-if=\"false\" to prevent it\n # from being rendered until we have registered the component with AlpineJS.\n template = \"\"\"\n <template x-if=\"false\" data-name=\"frag\">\n <div class=\"frag\">\n 123\n <span x-data=\"frag\" x-text=\"fragVal\">\n </span>\n </div>\n </template>\n \"\"\"\n\n js = \"\"\"\n Alpine.data('frag', () => ({\n fragVal: 'xxx',\n }));\n\n // Now that the component has been defined in AlpineJS, we can \"activate\"\n // all instances where we use the `x-data=\"frag\"` directive.\n document.querySelectorAll('[data-name=\"frag\"]').forEach((el) => {\n el.setAttribute('x-if', 'true');\n });\n \"\"\"\n\n css = \"\"\"\n .frag {\n background: blue;\n }\n \"\"\"\n\n class View:\n def get(self, request):\n return self.component_cls.render_to_response(\n request=request,\n # IMPORTANT: Don't forget `deps_strategy=\"fragment\"`\n deps_strategy=\"fragment\",\n )\n
"},{"location":"concepts/advanced/html_fragments/#3-create-view-and-urls_1","title":"3. Create view and URLs","text":"[app]/urls.py
"},{"location":"concepts/advanced/provide_inject/","title":"Prop drilling and provide / inject","text":"
New in version 0.80:
django-components supports the provide / inject pattern, similarly to React's Context Providers or Vue's provide / inject.
This is achieved with the combination of:
{% provide %} tag
Component.inject() method
"},{"location":"concepts/advanced/provide_inject/#what-is-prop-drilling","title":"What is \"prop drilling\"","text":"
Prop drilling refers to a scenario in UI development where you need to pass data through many layers of a component tree to reach the nested components that actually need the data.
Normally, you'd use props to send data from a parent component to its children. However, this straightforward method becomes cumbersome and inefficient if the data has to travel through many levels or if several components scattered at different depths all need the same piece of information.
This results in a situation where the intermediate components, which don't need the data for their own functioning, end up having to manage and pass along these props. This clutters the component tree and makes the code verbose and harder to manage.
A neat solution to avoid prop drilling is using the \"provide and inject\" technique.
With provide / inject, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.
This feature is inspired by Vue's Provide / Inject and React's Context / useContext.
As the name suggest, using provide / inject consists of 2 steps
Providing data
Injecting provided data
For examples of advanced uses of provide / inject, see this discussion.
The first argument to the {% provide %} tag is the key by which we can later access the data passed to this tag. The key in this case is \"my_data\".
The key must resolve to a valid identifier (AKA a valid Python variable name).
Next you define the data you want to \"provide\" by passing them as keyword arguments. This is similar to how you pass data to the {% with %} tag or the {% slot %} tag.
Note
Kwargs passed to {% provide %} are NOT added to the context. In the example below, the {{ hello }} won't render anything:
To \"inject\" (access) the data defined on the {% provide %} tag, you can use the Component.inject() method from within any other component methods.
For a component to be able to \"inject\" some data, the component ({% component %} tag) must be nested inside the {% provide %} tag.
In the example from previous section, we've defined two kwargs: hello=\"hi\" another=123. That means that if we now inject \"my_data\", we get an object with 2 attributes - hello and another.
The instance returned from inject() is immutable (subclass of NamedTuple). This ensures that the data returned from inject() will always have all the keys that were passed to the {% provide %} tag.
Warning
inject() works strictly only during render execution. If you try to call inject() from outside, it will raise an error.
If the rendered HTML does NOT contain neither {% component_dependencies %} template tags, nor <head> and <body> HTML tags, then the JS and CSS will NOT be inserted!
To force the JS and CSS to be inserted, use the \"append\" or \"prepend\" strategies.
The rendered HTML may be used in different contexts (browser, email, etc). If your components use JS and CSS scripts, you may need to handle them differently.
The different ways for handling JS / CSS are called \"dependencies strategies\".
render() and render_to_response() accept a deps_strategy parameter, which controls where and how the JS / CSS are inserted into the HTML.
deps_strategy=\"fragment\" is used when rendering a piece of HTML that will be inserted into a page that has already been rendered with the \"document\" strategy:
fragment = MyComponent.render(deps_strategy=\"fragment\")\n
The HTML of fragments is very lightweight because it doesn't include the JS and CSS scripts of the rendered components.
With fragments, even if a component has JS and CSS, you can insert the same component into a page hundreds of times, and the JS and CSS will only ever be loaded once.
This is intended for dynamic content that's loaded with AJAX after the initial page load, such as with jQuery, HTMX, AlpineJS or similar libraries.
Location:
None. The fragment's JS and CSS files will be loaded dynamically into the page.
Included scripts:
A special JSON <script> tag that tells the dependency manager what JS and CSS to load.
This is the same as \"simple\", but placeholders like {% component_js_dependencies %} and HTML tags <head> and <body> are all ignored. The JS and CSS are always inserted before the rendered content.
html = MyComponent.render(deps_strategy=\"prepend\")\n
Location:
JS and CSS is always inserted before the rendered content.
This is the same as \"simple\", but placeholders like {% component_js_dependencies %} and HTML tags <head> and <body> are all ignored. The JS and CSS are always inserted after the rendered content.
html = MyComponent.render(deps_strategy=\"append\")\n
Location:
JS and CSS is always inserted after the rendered content.
Django-components provides a seamless integration with HTML fragments with AJAX (HTML over the wire), whether you're using jQuery, HTMX, AlpineJS, vanilla JavaScript, or other.
This is achieved by the combination of the \"document\" and \"fragment\" strategies.
Read more about HTML fragments.
"},{"location":"concepts/advanced/tag_formatters/","title":"Tag formatters","text":""},{"location":"concepts/advanced/tag_formatters/#customizing-component-tags-with-tagformatter","title":"Customizing component tags with TagFormatter","text":"
New in version 0.89
By default, components are rendered using the pair of {% component %} / {% endcomponent %} template tags:
"},{"location":"concepts/advanced/tag_formatters/#writing-your-own-tagformatter","title":"Writing your own TagFormatter","text":""},{"location":"concepts/advanced/tag_formatters/#background","title":"Background","text":"
First, let's discuss how TagFormatters work, and how components are rendered in django_components.
When you render a component with {% component %} (or your own tag), the following happens:
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().
Template tags introduced by django-components, such as {% component %} and {% slot %}, offer additional features over the default Django template tags:
Self-closing tags {% mytag / %}
Allowing the use of :, - (and more) in keys
Spread operator ...
Using template tags as inputs to other template tags
Flat definition of dictionaries attr:key=val
Function-like input validation
You too can easily create custom template tags that use the above features.
"},{"location":"concepts/advanced/template_tags/#defining-template-tags-with-template_tag","title":"Defining template tags with @template_tag","text":"
The simplest way to create a custom template tag is using the template_tag decorator. This decorator allows you to define a template tag by just writing a function that returns the rendered content.
When you pass input to a template tag, it behaves the same way as if you passed the input to a function:
If required parameters are missing, an error is raised
If unexpected parameters are passed, an error is raised
To accept keys that are not valid Python identifiers (e.g. data-id), or would conflict with Python keywords (e.g. is), you can use the **kwargs syntax:
"},{"location":"concepts/advanced/template_tags/#defining-template-tags-with-basenode","title":"Defining template tags with BaseNode","text":"
For more control over your template tag, you can subclass BaseNode directly instead of using the decorator. This gives you access to additional features like the node's internal state and parsing details.
from django_components import BaseNode\n\nclass GreetNode(BaseNode):\n tag = \"greet\"\n end_tag = \"endgreet\"\n allowed_flags = [\"required\"]\n\n def render(self, context: Context, name: str, **kwargs) -> str:\n # Access node properties\n if self.flags[\"required\"]:\n return f\"Required greeting: Hello, {name}!\"\n return f\"Hello, {name}!\"\n\n# Register the node\nGreetNode.register(library)\n
When using BaseNode, you have access to several useful properties:
node_id: A unique identifier for this node instance
flags: Dictionary of flag values (e.g. {\"required\": True})
params: List of raw parameters passed to the tag
nodelist: The template nodes between the start and end tags
contents: The raw contents between the start and end tags
active_flags: List of flags that are currently set to True
template_name: The name of the Template instance inside which the node was defined
template_component: The component class that the Template belongs to
This is what the node parameter in the @template_tag decorator gives you access to - it's the instance of the node class that was automatically created for your template tag.
"},{"location":"concepts/advanced/template_tags/#rendering-content-between-tags","title":"Rendering content between tags","text":"
When your tag has an end tag, you can access and render the content between the tags using nodelist:
class WrapNode(BaseNode):\n tag = \"wrap\"\n end_tag = \"endwrap\"\n\n def render(self, context: Context, tag: str = \"div\", **attrs) -> str:\n # Render the content between tags\n inner = self.nodelist.render(context)\n attrs_str = \" \".join(f'{k}=\"{v}\"' for k, v in attrs.items())\n return f\"<{tag} {attrs_str}>{inner}</{tag}>\"\n\n# Usage:\n{% wrap tag=\"section\" class=\"content\" %}\n Hello, world!\n{% endwrap %}\n
The @djc_test decorator is a powerful tool for testing components created with django-components. It ensures that each test is properly isolated, preventing components registered in one test from affecting others.
Every component that you want to use in the template with the {% component %} tag needs to be registered with the ComponentRegistry.
We use the @register decorator for that:
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n ...\n
But for the component to be registered, the code needs to be executed - and for that, the file needs to be imported as a module.
This is the \"discovery\" part of the process.
One way to do that is by importing all your components in apps.py:
from django.apps import AppConfig\n\nclass MyAppConfig(AppConfig):\n name = \"my_app\"\n\n def ready(self) -> None:\n from components.card.card import Card\n from components.list.list import List\n from components.menu.menu import Menu\n from components.button.button import Button\n ...\n
By default, the Python files found in the COMPONENTS.dirs and COMPONENTS.app_dirs are auto-imported in order to execute the code that registers the components.
Autodiscovery occurs when Django is loaded, during the AppConfig.ready() hook of the apps.py file.
If you are using autodiscovery, keep a few points in mind:
Avoid defining any logic on the module-level inside the components directories, that you would not want to run anyway.
Components inside the auto-imported files still need to be registered with @register
Auto-imported component files must be valid Python modules, they must use suffix .py, and module name should follow PEP-8.
Subdirectories and files starting with an underscore _ (except __init__.py) are ignored.
Autodiscovery can be disabled in the settings with autodiscover=False.
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
When a component is being rendered, the component inputs are passed to various methods like get_template_data(), get_js_data(), or get_css_data().
It can be cumbersome to specify default values for each input in each method.
To make things easier, Components can specify their defaults. Defaults are used when no value is provided, or when the value is set to None for a particular input.
To define defaults for a component, you create a nested Defaults class within your Component class. Each attribute in the Defaults class represents a default value for a corresponding input.
In this example, position is a simple default value, while selected_items uses a factory function wrapped in Default to ensure a new list is created each time the default is used.
Now, when we render the component, the defaults will be applied:
For objects such as lists, dictionaries or other instances, you have to be careful - if you simply set a default value, this instance will be shared across all instances of the component!
from django_components import Component\n\nclass MyTable(Component):\n class Defaults:\n # All instances will share the same list!\n selected_items = [1, 2, 3]\n
To avoid this, you can use a factory function wrapped in Default.
from django_components import Component, Default\n\nclass MyTable(Component):\n class Defaults:\n # A new list is created for each instance\n selected_items = Default(lambda: [1, 2, 3])\n
This is similar to how the dataclass fields work.
In fact, you can also use the dataclass's field function to define the factories:
from dataclasses import field\nfrom django_components import Component\n\nclass MyTable(Component):\n class Defaults:\n selected_items = field(default_factory=lambda: [1, 2, 3])\n
"},{"location":"concepts/fundamentals/component_views_urls/","title":"Component views and URLs","text":"
New in version 0.34
Note: Since 0.92, Component is no longer a subclass of Django's View. Instead, the nested Component.View class is a subclass of Django's View.
For web applications, it's common to define endpoints that serve HTML content (AKA views).
django-components has a suite of features that help you write and manage views and their URLs:
For each component, you can define methods for handling HTTP requests (GET, POST, etc.) - get(), post(), etc.
Use Component.as_view() to be able to use your Components with Django's urlpatterns. This works the same way as View.as_view().
To avoid having to manually define the endpoints for each component, you can set the component to be \"public\" with Component.View.public = True. This will automatically create a URL for the component. To retrieve the component URL, use get_component_url().
In addition, Component has a render_to_response() method that renders the component template based on the provided input and returns an HttpResponse object.
To register the component as a route / endpoint in Django, add an entry to your urlpatterns. In place of the view function, create a view object with Component.as_view():
If you don't care about the exact URL of the component, you can let django-components manage the URLs for you by setting the Component.View.public attribute to True:
class MyComponent(Component):\n class View:\n public = True\n\n def get(self, request):\n return self.component_cls.render_to_response(request=request)\n ...\n
Then, to get the URL for the component, use get_component_url():
from django_components import get_component_url\n\nurl = get_component_url(MyComponent)\n
This way you don't have to mix your app URLs with component URLs.
Info
If you need to pass query parameters or a fragment to the component URL, you can do so by passing the query and fragment arguments to get_component_url():
Moreover, the {% html_attrs %} tag accepts two positional arguments:
attrs - a dictionary of attributes to be rendered
defaults - a dictionary of default attributes
You can use this for example to allow users of your component to add extra attributes. We achieve this by capturing the extra attributes and passing them to the {% html_attrs %} tag as a dictionary:
@register(\"my_comp\")\nclass MyComp(Component):\n # Pass all kwargs as `attrs`\n def get_template_data(self, args, kwargs, slots, context):\n return {\n \"attrs\": kwargs,\n \"classes\": \"text-red\",\n \"my_id\": 123,\n }\n\n template: t.django_html = \"\"\"\n {# Pass the extra attributes to `html_attrs` #}\n <div {% html_attrs attrs class=classes data-id=my_id %}>\n </div>\n \"\"\"\n
This way you can render MyComp with extra attributes:
HTML rendering with html_attrs tag or format_attributes works the same way - an attribute set to True is rendered without the value, and an attribute set to False is not rendered at all.
For the class HTML attribute, it's common that we want to join multiple values, instead of overriding them.
For example, if you're authoring a component, you may want to ensure that the component will ALWAYS have a specific class. Yet, you may want to allow users of your component to supply their own class attribute.
We can achieve this by adding extra kwargs. These values will be appended, instead of overwriting the previous value.
So if we have a variable attrs:
attrs = {\n \"class\": \"my-class pa-4\",\n}\n
And on {% html_attrs %} tag, we set the key class:
If a style property is specified multiple times, the last value is used.
Properties set to None are ignored.
If the last non-None instance of the property is set to False, the property is removed.
Example:
In this example, the width property is specified twice. The last instance is {\"width\": False}, so the property is removed.
Secondly, the background-color property is also set twice. But the second time it's set to None, so that instance is ignored, leaving us only with background-color: blue.
The color property is set to a valid value in both cases, so the latter (green) is used.
Note: For readability, we've split the tags across multiple lines.
Inside MyComp, we defined a default attribute
defaults:class=\"pa-4 text-red\"\n
So if attrs includes key class, the default above will be ignored.
MyComp also defines class key twice. It means that whether the class attribute is taken from attrs or defaults, the two class values will be appended to it.
These \"primary\" files will have special behavior. For example, each will receive variables from the component's data methods. Read more about each file type below:
HTML
CSS
JS
In addition, you can define extra \"secondary\" CSS / JS files using the nested Component.Media class, by setting Component.Media.js and Component.Media.css.
Single component can have many secondary files. There is no special behavior for them.
You can use these for third-party libraries, or for shared CSS / JS files.
Read more about Secondary JS / CSS files.
Warning
You cannot use both inlined code and separate file for a single language type (HTML, CSS, JS).
However, you can freely mix these for different languages:
class MyTable(Component):\n template: types.django_html = \"\"\"\n <div class=\"welcome\">\n Hi there!\n </div>\n \"\"\"\n js_file = \"my_table.js\"\n css_file = \"my_table.css\"\n
Each component has only a single template associated with it.
However, whether it's for A/B testing or for preserving public API when sharing your components, sometimes you may need to render different templates based on the input to your component.
You can use Component.on_render() to dynamically override what template gets rendered.
By default, the component's template is rendered as-is.
class Table(Component):\n def on_render(self, context: Context, template: Optional[Template]):\n if template is not None:\n return template.render(context)\n
If you want to render a different template in its place, we recommended you to:
Wrap the substitute templates as new Components
Then render those Components inside Component.on_render():
Django Components expects the rendered template to be a valid HTML. This is needed to enable features like CSS / JS variables.
Here is how the HTML is post-processed:
Insert component ID: Each root element in the rendered HTML automatically receives a data-djc-id-cxxxxxx attribute containing a unique component instance ID.
<!-- Output HTML -->\n<div class=\"card\" data-djc-id-c1a2b3c>\n ...\n</div>\n<div class=\"backdrop\" data-djc-id-c1a2b3c>\n ...\n</div>\n
Insert CSS ID: If the component defines CSS variables through get_css_data(), the root elements also receive a data-djc-css-xxxxxx attribute. This attribute links the element to its specific CSS variables.
Insert JS and CSS: After the HTML is rendered, Django Components handles inserting JS and CSS dependencies into the page based on the dependencies rendering strategy (document, fragment, or inline).
For example, if your component contains the {% component_js_dependencies %} or {% component_css_dependencies %} tags, or the <head> and <body> elements, the JS and CSS scripts will be inserted into the HTML.
For more information on how JS and CSS dependencies are rendered, see Rendering JS / CSS.
Compared to the secondary JS / CSS files, the definition of file paths for the main HTML / JS / CSS files is quite simple - just strings, without any lists, objects, or globs.
However, similar to the secondary JS / CSS files, you can specify the file paths relative to the component's directory.
If the path cannot be resolved relative to the component, django-components will attempt to resolve the path relative to the component directories, as set in COMPONENTS.dirs or COMPONENTS.app_dirs.
Once the component's media files have been loaded once, they will remain in-memory on the Component class:
HTML from Component.template_file will be available under Component.template
CSS from Component.css_file will be available under Component.css
JS from Component.js_file will be available under Component.js
Thus, whether you define HTML via Component.template_file or Component.template, you can always access the HTML content under Component.template. And the same applies for JS and CSS.
Example:
# When we create Calendar component, the files like `calendar/template.html`\n# are not yet loaded!\n@register(\"calendar\")\nclass Calendar(Component):\n template_file = \"calendar/template.html\"\n css_file = \"calendar/style.css\"\n js_file = \"calendar/script.js\"\n\n class Media:\n css = \"calendar/style1.css\"\n js = \"calendar/script2.js\"\n\n# It's only at this moment that django-components reads the files like `calendar/template.html`\nprint(Calendar.css)\n# Output:\n# .calendar {\n# width: 200px;\n# background: pink;\n# }\n
Warning
Do NOT modify HTML / CSS / JS after it has been loaded
django-components assumes that the component's media files like js_file or Media.js/css are static.
If you need to dynamically change these media files, consider instead defining multiple Components.
Modifying these files AFTER the component has been loaded at best does nothing. However, this is an untested behavior, which may lead to unexpected errors.
When a component recieves input through {% component %} tag, or the Component.render() or Component.render_to_response() methods, you can define how the input is handled, and what variables will be available to the template, JavaScript and CSS.
The get_template_data() method is the primary way to provide variables to your HTML template. It receives the component inputs and returns a dictionary of data that will be available in the template.
If get_template_data() returns None, an empty dictionary will be used.
class ProfileCard(Component):\n template_file = \"profile_card.html\"\n\n class Kwargs(NamedTuple):\n user_id: int\n show_details: bool\n\n def get_template_data(self, args, kwargs: Kwargs, slots, context):\n user = User.objects.get(id=kwargs.user_id)\n\n # Process and transform inputs\n return {\n \"user\": user,\n \"show_details\": kwargs.show_details,\n \"user_joined_days\": (timezone.now() - user.date_joined).days,\n }\n
In your template, you can then use these variables:
The get_context_data() method is the legacy way to provide variables to your HTML template. It serves the same purpose as get_template_data() - it receives the component inputs and returns a dictionary of data that will be available in the template.
However, get_context_data() has a few drawbacks:
It does NOT receive the slots and context parameters.
The args and kwargs parameters are given as variadic *args and **kwargs parameters. As such, they cannot be typed.
The input property is deprecated and will be removed in v1.
Instead, use properties defined on the Component class directly like self.context.
To access the unmodified inputs, use self.raw_args, self.raw_kwargs, and self.raw_slots properties.
The previous two approaches allow you to access only the most important inputs.
There are additional settings that may be passed to components. If you need to access these, you can use self.input property for a low-level access to all the inputs.
The input property contains all the inputs passed to the component (instance of ComponentInput).
This includes:
input.args - List of positional arguments
input.kwargs - Dictionary of keyword arguments
input.slots - Dictionary of slots. Values are normalized to Slot instances
input.context - Context object that should be used to render the component
input.type - The type of the component (document, fragment)
input.render_dependencies - Whether to render dependencies (CSS, JS)
class ProfileCard(Component):\n def get_template_data(self, args, kwargs, slots, context):\n # Access positional arguments\n user_id = self.input.args[0] if self.input.args else None\n\n # Access keyword arguments\n show_details = self.input.kwargs.get(\"show_details\", False)\n\n # Render component differently depending on the type\n if self.input.type == \"fragment\":\n ...\n\n return {\n \"user_id\": user_id,\n \"show_details\": show_details,\n }\n
Info
Unlike the parameters passed to the data methods, the args, kwargs, and slots in self.input property are always lists and dictionaries, regardless of whether you added typing classes to your component (like Args, Kwargs, or Slots).
You can use Defaults class to provide default values for your inputs.
These defaults will be applied either when:
The input is not provided at rendering time
The input is provided as None
When you then access the inputs in your data methods, the default values will be already applied.
Read more about Component Defaults.
from django_components import Component, Default, register\n\n@register(\"profile_card\")\nclass ProfileCard(Component):\n class Kwargs(NamedTuple):\n show_details: bool\n\n class Defaults:\n show_details = True\n\n # show_details will be set to True if `None` or missing\n def get_template_data(self, args, kwargs: Kwargs, slots, context):\n return {\n \"show_details\": kwargs.show_details,\n }\n\n ...\n
Warning
When typing your components with Args, Kwargs, or Slots classes, you may be inclined to define the defaults in the classes.
class ProfileCard(Component):\n class Kwargs(NamedTuple):\n show_details: bool = True\n
This is NOT recommended, because:
The defaults will NOT be applied to inputs when using self.raw_kwargs property.
The defaults will NOT be applied when a field is given but set to None.
Instead, define the defaults in the Defaults class.
You can add type hints for the component inputs to ensure that the component logic is correct.
For this, define the Args, Kwargs, and Slots classes, and then add type hints to the data methods.
This will also validate the inputs at runtime, as the type classes will be instantiated with the inputs.
Read more about Component typing.
from typing import NamedTuple, Optional\nfrom django_components import Component, SlotInput\n\nclass Button(Component):\n class Args(NamedTuple):\n name: str\n\n class Kwargs(NamedTuple):\n surname: str\n maybe_var: Optional[int] = None # May be omitted\n\n class Slots(NamedTuple):\n my_slot: Optional[SlotInput] = None\n footer: SlotInput\n\n # Use the above classes to add type hints to the data method\n def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n # The parameters are instances of the classes we defined\n assert isinstance(args, Button.Args)\n assert isinstance(kwargs, Button.Kwargs)\n assert isinstance(slots, Button.Slots)\n
Note
To access \"untyped\" inputs, use self.raw_args, self.raw_kwargs, and self.raw_slots properties.
These are plain lists and dictionaries, even when you added typing to your component.
It's best practice to explicitly define what args and kwargs a component accepts.
However, if you want a looser setup, you can easily write components that accept any number of kwargs, and pass them all to the template (similar to django-cotton).
To do that, simply return the kwargs dictionary itself from get_template_data():
class MyComponent(Component):\n def get_template_data(self, args, kwargs, slots, context):\n return kwargs\n
You can do the same for get_js_data() and get_css_data(), if needed:
The most common use of django-components is to render HTML when the server receives a request. As such, there are a few features that are dependent on the request object.
"},{"location":"concepts/fundamentals/http_request/#passing-the-httprequest-object","title":"Passing the HttpRequest object","text":"
In regular Django templates, the request object is available only within the RequestContext.
In Components, you can either use RequestContext, or pass the request object explicitly to Component.render() and Component.render_to_response().
So the request object is available to components either when:
The component is rendered with RequestContext (Regular Django behavior)
The component is rendered with a regular Context (or none), but you set the request kwarg of Component.render().
The component is nested and the parent has access to the request object.
# \u2705 With request\nMyComponent.render(request=request)\nMyComponent.render(context=RequestContext(request, {}))\n\n# \u274c Without request\nMyComponent.render()\nMyComponent.render(context=Context({}))\n
When a component is rendered within a template with {% component %} tag, the request object is available depending on whether the template is rendered with RequestContext or not.
template = Template(\"\"\"\n<div>\n {% component \"MyComponent\" / %}\n</div>\n\"\"\")\n\n# \u274c No request\nrendered = template.render(Context({}))\n\n# \u2705 With request\nrendered = template.render(RequestContext(request, {}))\n
"},{"location":"concepts/fundamentals/http_request/#accessing-the-httprequest-object","title":"Accessing the HttpRequest object","text":"
When the component has access to the request object, the request object will be available in Component.request.
When a component is being rendered, whether with Component.render() or {% component %}, a component instance is populated with the current inputs and context. This allows you to access things like component inputs.
We refer to these render-time-only methods and attributes as the \"Render API\".
Render API is available inside these Component methods:
Component ID (or render ID) is a unique identifier for the current render call.
That means that if you call Component.render() multiple times, the ID will be different for each call.
It is available as self.id.
The ID is a 7-letter alphanumeric string in the format cXXXXXX, where XXXXXX is a random string of 6 alphanumeric characters (case-sensitive).
E.g. c1a2b3c.
A single render ID has a chance of collision 1 in 57 billion. However, due to birthday paradox, the chance of collision increases to 1% when approaching ~33K render IDs.
Thus, there is currently a soft-cap of ~30K components rendered on a single page.
If you need to expand this limit, please open an issue on GitHub.
Components support a provide / inject system as known from Vue or React.
When rendering the component, you can call self.inject() with the key of the data you want to inject.
The object returned by self.inject()
To provide data to components, use the {% provide %} template tag.
Read more about Provide / Inject.
class Table(Component):\n def get_template_data(self, args, kwargs, slots, context):\n # Access provided data\n data = self.inject(\"some_data\")\n assert data.some_data == \"some_data\"\n
"},{"location":"concepts/fundamentals/render_api/#template-tag-metadata","title":"Template tag metadata","text":"
If the component is rendered with {% component %} template tag, the following metadata is available:
self.node - The ComponentNode instance
self.registry - The ComponentRegistry instance that was used to render the component
self.registered_name - The name under which the component was registered
self.outer_context - The context outside of the {% component %} tag
{% with abc=123 %}\n {{ abc }} {# <--- This is in outer context #}\n {% component \"my_component\" / %}\n{% endwith %}\n
You can use these to check whether the component was rendered inside a template with {% component %} tag or in Python with Component.render().
class MyComponent(Component):\n def get_template_data(self, args, kwargs, slots, context):\n if self.registered_name is None:\n # Do something for the render() function\n else:\n # Do something for the {% component %} template tag\n
You can access the ComponentNode under Component.node:
class MyComponent(Component):\n def get_template_data(self, context, template):\n if self.node is not None:\n assert self.node.name == \"my_component\"\n
Accessing the ComponentNode is mostly useful for extensions, which can modify their behaviour based on the source of the Component.
For example, if MyComponent was used in another component - that is, with a {% component \"my_component\" %} tag in a template that belongs to another component - then you can use self.node.template_component to access the owner Component class.
class Parent(Component):\n template: types.django_html = \"\"\"\n <div>\n {% component \"my_component\" / %}\n </div>\n \"\"\"\n\n@register(\"my_component\")\nclass MyComponent(Component):\n def get_template_data(self, context, template):\n if self.node is not None:\n assert self.node.template_component == Parent\n
Info
Component.node is None if the component is created by Component.render() (but you can pass in the node kwarg yourself).
Unlike regular Django template tags, django-components' tags offer extra features like defining literal lists and dicts, and more. Read more about Template tag syntax.
By default, components behave similarly to Django's {% include %}, and the template inside the component has access to the variables defined in the outer template.
You can selectively isolate a component, using the only flag, so that the inner template can access only the data that was explicitly passed to it:
{% component \"name\" positional_arg keyword_arg=value ... only / %}\n
Alternatively, you can set all components to be isolated by default, by setting context_behavior to \"isolated\" in your settings:
The rendered HTML may be used in different contexts (browser, email, etc), and each may need different handling of JS and CSS scripts.
render() and render_to_response() accept a deps_strategy parameter, which controls where and how the JS / CSS are inserted into the HTML.
The deps_strategy parameter is ultimately passed to render_dependencies().
Learn more about Rendering JS / CSS.
There are six dependencies rendering strategies:
document (default)
Smartly inserts JS / CSS into placeholders ({% component_js_dependencies %}) or into <head> and <body> tags.
Inserts extra script to allow fragment components to work.
Assumes the HTML will be rendered in a JS-enabled browser.
fragment
A lightweight HTML fragment to be inserted into a document with AJAX.
Assumes the page was already rendered with \"document\" strategy.
No JS / CSS included.
simple
Smartly insert JS / CSS into placeholders ({% component_js_dependencies %}) or into <head> and <body> tags.
No extra script loaded.
prepend
Insert JS / CSS before the rendered HTML.
Ignores the placeholders ({% component_js_dependencies %}) and any <head>/<body> HTML tags.
No extra script loaded.
append
Insert JS / CSS after the rendered HTML.
Ignores the placeholders ({% component_js_dependencies %}) and any <head>/<body> HTML tags.
No extra script loaded.
ignore
HTML is left as-is. You can still process it with a different strategy later with render_dependencies().
Used for inserting rendered HTML into other components.
Info
You can use the \"prepend\" and \"append\" strategies to force to output JS / CSS for components that don't have neither the placeholders like {% component_js_dependencies %}, nor any <head>/<body> HTML tags:
The render() and render_to_response() methods accept an optional context argument. This sets the context within which the component is rendered.
When a component is rendered within a template with the {% component %} tag, this will be automatically set to the Context instance that is used for rendering the template.
When you call Component.render() directly from Python, there is no context object, so you can ignore this input most of the time. Instead, use args, kwargs, and slots to pass data to the component.
However, you can pass RequestContext to the context argument, so that the component will gain access to the request object and will use context processors. Read more on Working with HTTP requests.
For advanced use cases, you can use context argument to \"pre-render\" the component in Python, and then pass the rendered output as plain string to the template. With this, the inner component is rendered as if it was within the template with {% component %}.
class Button(Component):\n def render(self, context, template):\n # Pass `context` to Icon component so it is rendered\n # as if nested within Button.\n icon = Icon.render(\n context=context,\n args=[\"icon-name\"],\n deps_strategy=\"ignore\",\n )\n # Update context with icon\n with context.update({\"icon\": icon}):\n return template.render(context)\n
Warning
Whether the variables defined in context are actually available in the template depends on the context behavior mode:
In \"django\" context behavior mode, the template will have access to the keys of this context.
In \"isolated\" context behavior mode, the template will NOT have access to this context, and data MUST be passed via component's args and kwargs.
Therefore, it's strongly recommended to not rely on defining variables on the context object, but instead passing them through as args and kwargs
\u274c Don't do this:
html = ProfileCard.render(\n context={\"name\": \"John\"},\n)\n
\u2705 Do this:
html = ProfileCard.render(\n kwargs={\"name\": \"John\"},\n)\n
Neither Component.render() nor Component.render_to_response() are typed, due to limitations of Python's type system.
To add type hints, you can wrap the inputs in component's Args, Kwargs, and Slots classes.
Read more on Typing and validation.
from typing import NamedTuple, Optional\nfrom django_components import Component, Slot, SlotInput\n\n# Define the component with the types\nclass Button(Component):\n class Args(NamedTuple):\n name: str\n\n class Kwargs(NamedTuple):\n surname: str\n age: int\n\n class Slots(NamedTuple):\n my_slot: Optional[SlotInput] = None\n footer: SlotInput\n\n# Add type hints to the render call\nButton.render(\n args=Button.Args(\n name=\"John\",\n ),\n kwargs=Button.Kwargs(\n surname=\"Doe\",\n age=30,\n ),\n slots=Button.Slots(\n footer=Slot(lambda ctx: \"Click me!\"),\n ),\n)\n
"},{"location":"concepts/fundamentals/rendering_components/#components-as-input","title":"Components as input","text":"
django_components makes it possible to compose components in a \"React-like\" way, where you can render one component and use its output as input to another component:
from django.utils.safestring import mark_safe\n\n# Render the inner component\ninner_html = InnerComponent.render(\n kwargs={\"some_data\": \"value\"},\n deps_strategy=\"ignore\", # Important for nesting!\n)\n\n# Use inner component's output in the outer component\nouter_html = OuterComponent.render(\n kwargs={\n \"content\": mark_safe(inner_html), # Mark as safe to prevent escaping\n },\n)\n
The key here is setting deps_strategy=\"ignore\" for the inner component. This prevents duplicate rendering of JS / CSS dependencies when the outer component is rendered.
When deps_strategy=\"ignore\":
No JS or CSS dependencies will be added to the output HTML
The component's content is rendered as-is
The outer component will take care of including all needed dependencies
Django components defines a special \"dynamic\" component (DynamicComponent).
Normally, you have to hard-code the component name in the template:
{% component \"button\" / %}\n
The dynamic component allows you to dynamically render any component based on the is kwarg. This is similar to Vue's dynamic components (<component :is>).
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.
Django-components provides a seamless integration with HTML fragments with AJAX (HTML over the wire), whether you're using jQuery, HTMX, AlpineJS, vanilla JavaScript, or other.
This is achieved by the combination of the \"document\" and \"fragment\" dependencies rendering strategies.
Read more about HTML fragments and Rendering JS / CSS.
Each component can define extra or \"secondary\" CSS / JS files using the nested Component.Media class, by setting Component.Media.js and Component.Media.css.
The main HTML / JS / CSS files are limited to 1 per component. This is not the case for the secondary files, where components can have many of them.
There is also no special behavior or post-processing for these secondary files, they are loaded as is.
You can use these for third-party libraries, or for shared CSS / JS files.
These must be set as paths, URLs, or custom objects.
Use the Media class to define secondary JS / CSS files for a component.
This Media class behaves similarly to Django's Media class:
Static paths - Paths are handled as static file paths, and are resolved to URLs with Django's {% static %} template tag.
URLs - A path that starts with http, https, or / is considered a URL. URLs are NOT resolved with {% static %}.
HTML tags - Both static paths and URLs are rendered to <script> and <link> HTML tags with media_class.render_js() and media_class.render_css().
Bypass formatting - A SafeString, or a function (with __html__ method) is considered an already-formatted HTML tag, skipping both static file resolution and rendering with media_class.render_js() or media_class.render_css().
Inheritance - You can set extend to configure whether to inherit JS / CSS from parent components. See Media inheritance.
However, there's a few differences from Django's Media class:
Our Media class accepts various formats for the JS and CSS files: either a single file, a list, or (CSS-only) a dictonary (See ComponentMediaInput).
Individual JS / CSS files can be any of str, bytes, Path, SafeString, or a function (See ComponentMediaInputPath).
Individual JS / CSS files can be glob patterns, e.g. *.js or styles/**/*.css.
If you set Media.extend to a list, it should be a list of Component classes.
from components.layout import LayoutComp\n\nclass MyTable(Component):\n class Media:\n js = [\n \"path/to/script.js\",\n \"path/to/*.js\", # Or as a glob\n \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\", # AlpineJS\n ]\n css = {\n \"all\": [\n \"path/to/style.css\",\n \"path/to/*.css\", # Or as a glob\n \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\", # TailwindCSS\n ],\n \"print\": [\"path/to/style2.css\"],\n }\n\n # Reuse JS / CSS from LayoutComp\n extend = [\n LayoutComp,\n ]\n
"},{"location":"concepts/fundamentals/secondary_js_css_files/#css-media-types","title":"CSS media types","text":"
You can define which stylesheets will be associated with which CSS media types. You do so by defining CSS files as a dictionary.
See the corresponding Django Documentation.
Again, you can set either a single file or a list of files per media type:
class MyComponent(Component):\n class Media:\n css = {\n \"all\": \"path/to/style1.css\",\n \"print\": [\"path/to/style2.css\", \"path/to/style3.css\"],\n }\n
By default, the media files are inherited from the parent component.
class ParentComponent(Component):\n class Media:\n js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n class Media:\n js = [\"script.js\"]\n\nprint(MyComponent.media._js) # [\"parent.js\", \"script.js\"]\n
You can set the component NOT to inherit from the parent component by setting the extend attribute to False:
class ParentComponent(Component):\n class Media:\n js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n class Media:\n extend = False # Don't inherit parent media\n js = [\"script.js\"]\n\nprint(MyComponent.media._js) # [\"script.js\"]\n
Alternatively, you can specify which components to inherit from. In such case, the media files are inherited ONLY from the specified components, and NOT from the original parent components:
class ParentComponent(Component):\n class Media:\n js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n class Media:\n # Only inherit from these, ignoring the files from the parent\n extend = [OtherComponent1, OtherComponent2]\n\n js = [\"script.js\"]\n\nprint(MyComponent.media._js) # [\"script.js\", \"other1.js\", \"other2.js\"]\n
Info
The extend behaves consistently with Django's Media class, with one exception:
When you set extend to a list, the list is expected to contain Component classes (or other classes that have a nested Media class).
"},{"location":"concepts/fundamentals/secondary_js_css_files/#accessing-media-files","title":"Accessing Media files","text":"
To access the files that you defined under Component.Media, use Component.media (lowercase).
This is consistent behavior with Django's Media class.
class MyComponent(Component):\n class Media:\n js = \"path/to/script.js\"\n css = \"path/to/style.css\"\n\nprint(MyComponent.media)\n# Output:\n# <script src=\"/static/path/to/script.js\"></script>\n# <link href=\"/static/path/to/style.css\" media=\"all\" rel=\"stylesheet\">\n
When working with component media files, it is important to understand the difference:
Component.Media
Is the \"raw\" media definition, or the input, which holds only the component's own media definition
This class is NOT instantiated, it merely holds the JS / CSS files.
Component.media
Returns all resolved media files, including those inherited from parent components
Is an instance of Component.media_class
class ParentComponent(Component):\n class Media:\n js = [\"parent.js\"]\n\nclass ChildComponent(ParentComponent):\n class Media:\n js = [\"child.js\"]\n\n# Access only this component's media\nprint(ChildComponent.Media.js) # [\"child.js\"]\n\n# Access all inherited media\nprint(ChildComponent.media._js) # [\"parent.js\", \"child.js\"]\n
Note
You should not manually modify Component.media or Component.Media after the component has been resolved, as this may lead to unexpected behavior.
If you want to modify the class that is instantiated for Component.media, you can configure Component.media_class (See example).
Unlike the main HTML / JS / CSS files, the path definition for the secondary files are quite ergonomic.
"},{"location":"concepts/fundamentals/secondary_js_css_files/#relative-to-component","title":"Relative to component","text":"
As seen in the getting started example, to associate HTML / JS / CSS files with a component, you can set them as Component.template_file, Component.js_file and Component.css_file respectively:
At component class creation, django-components checks all file paths defined on the component (e.g. Component.template_file).
For each file path, it checks if the file path is relative to the component's directory. And such file exists, the component's file path is re-written to be defined relative to a first matching directory in COMPONENTS.dirs or COMPONENTS.app_dirs.
Example:
[root]/components/mytable/mytable.py
class MyTable(Component):\n template_file = \"mytable.html\"\n
Component MyTable is defined in file [root]/components/mytable/mytable.py.
The component's directory is thus [root]/components/mytable/.
Because MyTable.template_file is mytable.html, django-components tries to resolve it as [root]/components/mytable/mytable.html.
django-components checks the filesystem. If there's no such file, nothing happens.
If there IS such file, django-components tries to rewrite the path.
django-components searches COMPONENTS.dirs and COMPONENTS.app_dirs for a first directory that contains [root]/components/mytable/mytable.html.
It comes across [root]/components/, which DOES contain the path to mytable.html.
Thus, it rewrites template_file from mytable.html to mytable/mytable.html.
NOTE: In case of ambiguity, the preference goes to resolving the files relative to the component's directory.
Components can have many secondary files. To simplify their declaration, you can use globs.
Globs MUST be relative to the component's directory.
[project root]/components/calendar/calendar.py
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n class Media:\n js = [\n \"path/to/*.js\",\n \"another/path/*.js\",\n ]\n css = \"*.css\"\n
How this works is that django-components will detect that the path is a glob, and will try to resolve all files matching the glob pattern relative to the component's directory.
After that, the file paths are handled the same way as if you defined them explicitly.
"},{"location":"concepts/fundamentals/secondary_js_css_files/#paths-as-objects","title":"Paths as objects","text":"
In the example above, you can see that when we used Django's mark_safe() to mark a string as a SafeString, we had to define the URL / path as an HTML <script>/<link> elements.
This is an extension of Django's Paths as objects feature, where \"safe\" strings are taken as is, and are accessed only at render time.
Because of that, the paths defined as \"safe\" strings are NEVER resolved, neither relative to component's directory, nor relative to COMPONENTS.dirs. It is assumed that you will define the full <script>/<link> tag with the correct URL / path.
\"Safe\" strings can be used to lazily resolve a path, or to customize the <script> or <link> tag for individual paths:
In the example below, we make use of \"safe\" strings to add type=\"module\" to the script tag that will fetch calendar/script2.js. In this case, we implemented a \"safe\" string by defining a __html__ method.
As part of the rendering process, the secondary JS / CSS files are resolved and rendered into <link> and <script> HTML tags, so they can be inserted into the render.
In the Paths as objects section, we saw that we can use that to selectively change how the HTML tags are constructed.
However, if you need to change how ALL CSS and JS files are rendered for a given component, you can provide your own subclass of Django's Media class to the Component.media_class attribute.
To change how the tags are constructed, you can override the Media.render_js() and Media.render_css() methods:
from django.forms.widgets import Media\nfrom django_components import Component, register\n\nclass MyMedia(Media):\n # Same as original Media.render_js, except\n # the `<script>` tag has also `type=\"module\"`\n def render_js(self):\n tags = []\n for path in self._js:\n if hasattr(path, \"__html__\"):\n tag = path.__html__()\n else:\n tag = format_html(\n '<script type=\"module\" src=\"{}\"></script>',\n self.absolute_path(path)\n )\n return tags\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_file = \"calendar/template.html\"\n css_file = \"calendar/style.css\"\n js_file = \"calendar/script.js\"\n\n class Media:\n css = \"calendar/style1.css\"\n js = \"calendar/script2.js\"\n\n # Override the behavior of Media class\n media_class = MyMedia\n
If you \"inline\" the HTML, JS and CSS code into the Python class, you should set up syntax highlighting to let your code editor know that the inlined code is HTML, JS and CSS.
In the examples above, we've annotated the template, js, and css attributes with the types.django_html, types.js and types.css types. These are used for syntax highlighting in VSCode.
Warning
Autocompletion / intellisense does not work in the inlined code.
Help us add support for intellisense in the inlined code! Start a conversation in the GitHub Discussions.
First install Python Inline Source Syntax Highlighting extension, it will give you syntax highlighting for the template, CSS, and JS.
Next, in your component, set typings of Component.template, Component.js, Component.css to types.django_html, types.css, and types.js respectively. The extension will recognize these and will activate syntax highlighting.
"},{"location":"concepts/fundamentals/single_file_components/#pycharm-or-other-jetbrains-ides","title":"Pycharm (or other Jetbrains IDEs)","text":"
With PyCharm (or any other editor from Jetbrains), you don't need to use types.django_html, types.css, types.js since Pycharm uses language injections.
You only need to write the comments # language=<lang> above the variables.
"},{"location":"concepts/fundamentals/single_file_components/#markdown-code-blocks-with-pygments","title":"Markdown code blocks with Pygments","text":"
Pygments is a syntax highlighting library written in Python. It's also what's used by this documentation site (mkdocs-material) to highlight code blocks.
To write code blocks with syntax highlighting, you need to install the pygments-djc package.
pip install pygments-djc\n
And then initialize it by importing pygments_djc somewhere in your project:
import pygments_djc\n
Now you can use the djc_py code block to write code blocks with syntax highlighting for components.
django-components has the most extensive slot system of all the popular Python templating engines.
The slot system is based on Vue, and works across both Django templates and Python code.
"},{"location":"concepts/fundamentals/slots/#what-are-slots","title":"What are slots?","text":"
Components support something called 'slots'.
When you write a component, you define its template. The template will always be the same each time you render the component.
However, sometimes you may want to customize the component slightly to change the content of the component. This is where slots come in.
Slots allow you to insert parts of HTML into the component. This makes components more reusable and composable.
<div class=\"calendar-component\">\n <div class=\"header\">\n {# This is where the component will insert the content #}\n {% slot \"header\" / %}\n </div>\n</div>\n
{% slot %} tag - Inside your component you decide where you want to insert the content.
{% fill %} tag - In the parent template (outside the component) you decide what content to insert into the slot. It \"fills\" the slot with the specified content.
Let's look at an example:
First, we define the component template. This component contains two slots, header and body.
Do NOT combine default fills with explicit named {% fill %} tags.
The following component template will raise an error when rendered:
\u274c Don't do this
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}Totally new header!{% endfill %}\n Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n
\u2705 Do this instead
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}Totally new header!{% endfill %}\n {% fill \"default\" %}\n Can you believe it's already <span>{{ date }}</span>??\n {% endfill %}\n{% endcomponent %}\n
Warning
You cannot double-fill a slot.
That is, if both {% fill \"default\" %} and {% fill \"header\" %} point to the same slot, this will raise an error when rendered.
You can access the fills with the {{ component_vars.slots.<name> }} template variable:
{% if component_vars.slots.my_slot %}\n <div>\n {% fill \"my_slot\" %}\n Filled content\n {% endfill %}\n </div>\n{% endif %}\n
And in Python with the Component.slots property:
class Calendar(Component):\n # `get_template_data` receives the `slots` argument directly\n def get_template_data(self, args, kwargs, slots, context):\n if \"my_slot\" in slots:\n content = \"Filled content\"\n else:\n content = \"Default content\"\n\n return {\n \"my_slot\": content,\n }\n\n # In other methods you can still access the slots with `Component.slots`\n def on_render_before(self, context, template):\n if \"my_slot\" in self.slots:\n # Do something\n
The slot and fill names can be set as variables. This way you can fill slots dynamically:
{% with \"body\" as slot_name %}\n {% component \"calendar\" %}\n {% fill slot_name %}\n Filled content\n {% endfill %}\n {% endcomponent %}\n{% endwith %}\n
You can even use {% if %} and {% for %} tags inside the {% component %} tag to fill slots with more control:
{% component \"calendar\" %}\n {% if condition %}\n {% fill \"name\" %}\n Filled content\n {% endfill %}\n {% endif %}\n\n {% for item in items %}\n {% fill item.name %}\n Item: {{ item.value }}\n {% endfill %}\n {% endfor %}\n{% endcomponent %}\n
You can also use {% with %} or even custom tags to generate the fills dynamically:
{% component \"calendar\" %}\n {% with item.name as name %}\n {% fill name %}\n Item: {{ item.value }}\n {% endfill %}\n {% endwith %}\n{% endcomponent %}\n
Warning
If you dynamically generate {% fill %} tags, be careful to render text only inside the {% fill %} tags.
Any text rendered outside {% fill %} tags will be considered a default fill and will raise an error if combined with explicit fills. (See Default slot)
Sometimes the slots need to access data from the component. Imagine an HTML table component which has a slot to configure how to render the rows. Each row has a different data, so you need to pass the data to the slot.
Similarly to Vue's scoped slots, you can pass data to the slot, and then access it in the fill.
This consists of two steps:
Passing data to {% slot %} tag
Accessing data in {% fill %} tag
The data is passed to the slot as extra keyword arguments. Below we set two extra arguments: first_name and job.
{# Pass data to the slot #}\n{% slot \"name\" first_name=\"John\" job=\"Developer\" %}\n {# Fallback implementation #}\n Name: {{ first_name }}\n Job: {{ job }}\n{% endslot %}\n
Note
name kwarg is already used for slot name, so you cannot pass it as slot data.
To access the slot's data in the fill, use the data keyword. This sets the name of the variable that holds the data in the fill:
{# Access data in the fill #}\n{% component \"profile\" %}\n {% fill \"name\" data=\"d\" %}\n Hello, my name is <h1>{{ d.first_name }}</h1>\n and I'm a <h2>{{ d.job }}</h2>\n {% endfill %}\n{% endcomponent %}\n
To access the slot data in Python, use the data attribute in slot functions.
def my_slot(ctx):\n return f\"\"\"\n Hello, my name is <h1>{ctx.data[\"first_name\"]}</h1>\n and I'm a <h2>{ctx.data[\"job\"]}</h2>\n \"\"\"\n\nProfile.render(\n slots={\n \"name\": my_slot,\n },\n)\n
Slot data can be set also when rendering a slot in Python:
In Python code, slot fills can be defined as strings, functions, or Slot instances that wrap the two. Slot functions have access to slot data, fallback, and context.
When accessing slots from within Component methods, the Slot instances are populated with extra metadata:
component_name
slot_name
nodelist
fill_node
extra
These are populated the first time a slot is passed to a component.
So if you pass the same slot through multiple nested components, the metadata will still point to the first component that received the slot.
You can use these for debugging, such as printing out the slot's component name and slot name.
Fill node
Components or extensions can use Slot.fill_node to handle slots differently based on whether the slot was defined in the template with {% fill %} and {% component %} tags, or in the component's Python code.
If the slot was created from a {% fill %} tag, this will be the FillNode instance.
If the slot was a default slot created from a {% component %} tag, this will be the ComponentNode instance.
You can use this to find the Component in whose template the {% fill %} tag was defined:
class MyTable(Component):\n def get_template_data(self, args, kwargs, slots, context):\n footer_slot = slots.get(\"footer\")\n if footer_slot is not None and footer_slot.fill_node is not None:\n owner_component = footer_slot.fill_node.template_component\n # ...\n
Extra
You can also pass any additional data along with the slot by setting it in Slot.extra:
Read more about Django's format_html and mark_safe.
"},{"location":"concepts/fundamentals/slots/#examples","title":"Examples","text":""},{"location":"concepts/fundamentals/slots/#pass-through-all-the-slots","title":"Pass through all the slots","text":"
You can dynamically pass all slots to a child component. This is similar to passing all slots in Vue:
class MyTable(Component):\n template = \"\"\"\n <div>\n {% component \"child\" %}\n {% for slot_name, slot in component_vars.slots.items %}\n {% fill name=slot_name body=slot / %}\n {% endfor %}\n {% endcomponent %}\n </div>\n \"\"\"\n
"},{"location":"concepts/fundamentals/slots/#required-and-default-slots","title":"Required and default slots","text":"
Since each {% slot %} is tagged with required and default individually, you can have multiple slots with the same name but different conditions.
In this example, we have a component that renders a user avatar - a small circular image with a profile picture or name initials.
If the component is given image_src or name_initials variables, the image slot is optional.
But if neither of those are provided, you MUST fill the image slot.
<div class=\"avatar\">\n {# Image given, so slot is optional #}\n {% if image_src %}\n {% slot \"image\" default %}\n <img src=\"{{ image_src }}\" />\n {% endslot %}\n\n {# Image not given, but we can make image from initials, so slot is optional #} \n {% elif name_initials %}\n {% slot \"image\" default %}\n <div style=\"\n border-radius: 25px;\n width: 50px;\n height: 50px;\n background: blue;\n \">\n {{ name_initials }}\n </div>\n {% endslot %}\n\n {# Neither image nor initials given, so slot is required #}\n {% else %}\n {% slot \"image\" default required / %}\n {% endif %}\n</div>\n
"},{"location":"concepts/fundamentals/slots/#dynamic-slots-in-table-component","title":"Dynamic slots in table component","text":"
Sometimes you may want to generate slots based on the given input. One example of this is Vuetify's table component, which creates a header and an item slots for each user-defined column.
So if you pass columns named name and age to the table component:
Since version 0.70, you could check if a slot was filled with
{{ component_vars.is_filled.<name> }}
Since version 0.140, this has been deprecated and superseded with
{% component_vars.slots.<name> %}
The component_vars.is_filled variable is still available, but will be removed in v1.0.
NOTE: component_vars.slots no longer escapes special characters in slot names.
You can use {{ component_vars.is_filled.<name> }} together with Django's {% if / elif / else / endif %} tags to define a block whose contents will be rendered only if the component slot with the corresponding 'name' is filled.
This is what our example looks like with component_vars.is_filled.
"},{"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
In larger projects, you might need to write multiple components with similar behavior. In such cases, you can extract shared behavior into a standalone component class to keep things DRY.
When subclassing a component, there's a couple of things to keep in mind:
"},{"location":"concepts/fundamentals/subclassing_components/#template-js-and-css-inheritance","title":"Template, JS, and CSS inheritance","text":"
When it comes to the pairs:
Component.template/Component.template_file
Component.js/Component.js_file
Component.css/Component.css_file
inheritance follows these rules:
If a child component class defines either member of a pair (e.g., either template or template_file), it takes precedence and the parent's definition is ignored completely.
For example, if a child component defines template_file, the parent's template or template_file will be ignored.
This applies independently to each pair - you can inherit the JS while overriding the template, for instance.
For example:
class BaseCard(Component):\n template = \"\"\"\n <div class=\"card\">\n <div class=\"card-content\">{{ content }}</div>\n </div>\n \"\"\"\n css = \"\"\"\n .card {\n border: 1px solid gray;\n }\n \"\"\"\n js = \"\"\"console.log('Base card loaded');\"\"\"\n\n# This class overrides parent's template, but inherits CSS and JS\nclass SpecialCard(BaseCard):\n template = \"\"\"\n <div class=\"card special\">\n <div class=\"card-content\">\u2728 {{ content }} \u2728</div>\n </div>\n \"\"\"\n\n# This class overrides parent's template and CSS, but inherits JS\nclass CustomCard(BaseCard):\n template_file = \"custom_card.html\"\n css = \"\"\"\n .card {\n border: 2px solid gold;\n }\n \"\"\"\n
The Component.Media nested class follows Django's media inheritance rules:
If both parent and child define a Media class, the child's media will automatically include both its own and the parent's JS and CSS files.
This behavior can be configured using the extend attribute in the Media class, similar to Django's forms. Read more on this in Media inheritance.
For example:
class BaseModal(Component):\n template = \"<div>Modal content</div>\"\n\n class Media:\n css = [\"base_modal.css\"]\n js = [\"base_modal.js\"] # Contains core modal functionality\n\nclass FancyModal(BaseModal):\n class Media:\n # Will include both base_modal.css/js AND fancy_modal.css/js\n css = [\"fancy_modal.css\"] # Additional styling\n js = [\"fancy_modal.js\"] # Additional animations\n\nclass SimpleModal(BaseModal):\n class Media:\n extend = False # Don't inherit parent's media\n css = [\"simple_modal.css\"] # Only this CSS will be included\n js = [\"simple_modal.js\"] # Only this JS will be included\n
"},{"location":"concepts/fundamentals/subclassing_components/#opt-out-of-inheritance","title":"Opt out of inheritance","text":"
For the following media attributes, when you don't want to inherit from the parent, but you also don't need to set the template / JS / CSS to any specific value, you can set these attributes to None.
template / template_file
js / js_file
css / css_file
Media class
For example:
class BaseForm(Component):\n template = \"...\"\n css = \"...\"\n js = \"...\"\n\n class Media:\n js = [\"form.js\"]\n\n# Use parent's template and CSS, but no JS\nclass ContactForm(BaseForm):\n js = None\n Media = None\n
"},{"location":"concepts/fundamentals/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 %}:
When passing data around, sometimes you may need to do light transformations, like negating booleans or filtering lists.
Normally, what you would have to do is to define ALL the variables inside get_template_data(). But this can get messy if your components contain a lot of logic.
author - passed as str, e.g. John Wick (Comment omitted)
This is inspired by django-cotton.
"},{"location":"concepts/fundamentals/template_tag_syntax/#passing-data-as-string-vs-original-values","title":"Passing data as string vs original values","text":"
In the example above, the kwarg id was passed as an integer, NOT a string.
When the string literal contains only a single template tag, with no extra text (and no extra whitespace), then the value is passed as the original type instead of a string.
{% 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:
To disable this behavior, set COMPONENTS.multiline_tag to False
"},{"location":"concepts/fundamentals/typing_and_validation/","title":"Typing and validation","text":""},{"location":"concepts/fundamentals/typing_and_validation/#typing-overview","title":"Typing overview","text":"
Warning
In versions 0.92 to 0.139 (inclusive), the component typing was specified through generics.
Since v0.140, the types must be specified as class attributes of the Component class - Args, Kwargs, Slots, TemplateData, JsData, and CssData.
See Migrating from generics to class attributes for more info.
Warning
Input validation was NOT part of Django Components between versions 0.136 and 0.139 (inclusive).
The Component class optionally accepts class attributes that allow you to define the types of args, kwargs, slots, as well as the data returned from the data methods.
Use this to add type hints to your components, to validate the inputs at runtime, and to document them.
from typing import NamedTuple, Optional\nfrom django.template import Context\nfrom django_components import Component, SlotInput\n\nclass Button(Component):\n class Args(NamedTuple):\n size: int\n text: str\n\n class Kwargs(NamedTuple):\n variable: str\n maybe_var: Optional[int] = None # May be omitted\n\n class Slots(NamedTuple):\n my_slot: Optional[SlotInput] = None\n\n def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n ...\n\n template_file = \"button.html\"\n
The class attributes are:
Args - Type for positional arguments.
Kwargs - Type for keyword arguments.
Slots - Type for slots.
TemplateData - Type for data returned from get_template_data().
JsData - Type for data returned from get_js_data().
CssData - Type for data returned from get_css_data().
You can specify as many or as few of these as you want, the rest will default to None.
You can use Component.Args, Component.Kwargs, and Component.Slots to type the component inputs.
When you set these classes, at render time the args, kwargs, and slots parameters of the data methods (get_template_data(), get_js_data(), get_css_data()) will be instances of these classes.
This way, each component can have runtime validation of the inputs:
When you use NamedTuple or @dataclass, instantiating these classes will check ONLY for the presence of the attributes.
When you use Pydantic models, instantiating these classes will check for the presence AND type of the attributes.
If you omit the Args, Kwargs, or Slots classes, or set them to None, the inputs will be passed as plain lists or dictionaries, and will not be validated.
from typing_extensions import NamedTuple, TypedDict\nfrom django.template import Context\nfrom django_components import Component, Slot, SlotInput\n\n# The data available to the `footer` scoped slot\nclass ButtonFooterSlotData(TypedDict):\n value: int\n\n# Define the component with the types\nclass Button(Component):\n class Args(NamedTuple):\n name: str\n\n class Kwargs(NamedTuple):\n surname: str\n age: int\n maybe_var: Optional[int] = None # May be omitted\n\n class Slots(NamedTuple):\n # Use `SlotInput` to allow slots to be given as `Slot` instance,\n # plain string, or a function that returns a string.\n my_slot: Optional[SlotInput] = None\n # Use `Slot` to allow ONLY `Slot` instances.\n # The generic is optional, and it specifies the data available\n # to the slot function.\n footer: Slot[ButtonFooterSlotData]\n\n # Add type hints to the data method\n def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n # The parameters are instances of the classes we defined\n assert isinstance(args, Button.Args)\n assert isinstance(kwargs, Button.Kwargs)\n assert isinstance(slots, Button.Slots)\n\n args.name # str\n kwargs.age # int\n slots.footer # Slot[ButtonFooterSlotData]\n\n# Add type hints to the render call\nButton.render(\n args=Button.Args(\n name=\"John\",\n ),\n kwargs=Button.Kwargs(\n surname=\"Doe\",\n age=30,\n ),\n slots=Button.Slots(\n footer=Slot(lambda ctx: \"Click me!\"),\n ),\n)\n
If you don't want to validate some parts, set them to None or omit them.
The following will validate only the keyword inputs:
class Button(Component):\n # We could also omit these\n Args = None\n Slots = None\n\n class Kwargs(NamedTuple):\n name: str\n age: int\n\n # Only `kwargs` is instantiated. `args` and `slots` are not.\n def get_template_data(self, args, kwargs: Kwargs, slots, context: Context):\n assert isinstance(args, list)\n assert isinstance(slots, dict)\n assert isinstance(kwargs, Button.Kwargs)\n\n args[0] # str\n slots[\"footer\"] # Slot[ButtonFooterSlotData]\n kwargs.age # int\n
Info
Components can receive slots as strings, functions, or instances of Slot.
Internally these are all normalized to instances of Slot.
Therefore, the slots dictionary available in data methods (like get_template_data()) will always be a dictionary of Slot instances.
To correctly type this dictionary, you should set the fields of Slots to Slot or SlotInput:
SlotInput is a union of Slot, string, and function types.
You can use Component.TemplateData, Component.JsData, and Component.CssData to type the data returned from get_template_data(), get_js_data(), and get_css_data().
When you set these classes, at render time they will be instantiated with the data returned from these methods.
This way, each component can have runtime validation of the returned data:
When you use NamedTuple or @dataclass, instantiating these classes will check ONLY for the presence of the attributes.
When you use Pydantic models, instantiating these classes will check for the presence AND type of the attributes.
If you omit the TemplateData, JsData, or CssData classes, or set them to None, the validation and instantiation will be skipped.
We recommend to use NamedTuple for the Args class, and NamedTuple, dataclasses, or Pydantic models for Kwargs, Slots, TemplateData, JsData, and CssData classes.
However, you can use any class, as long as they meet the conditions below.
For example, here is how you can use Pydantic models to validate the inputs at runtime.
"},{"location":"concepts/fundamentals/typing_and_validation/#passing-variadic-args-and-kwargs","title":"Passing variadic args and kwargs","text":"
You may have a component that accepts any number of args or kwargs.
However, this cannot be described with the current Python's typing system (as of v0.140).
As a workaround:
For a variable number of positional arguments (*args), set a positional argument that accepts a list of values:
class Table(Component):\n class Args(NamedTuple):\n args: List[str]\n\nTable.render(\n args=Table.Args(args=[\"a\", \"b\", \"c\"]),\n)\n
For a variable number of keyword arguments (**kwargs), set a keyword argument that accepts a dictionary of values:
class Table(Component):\n class Kwargs(NamedTuple):\n variable: str\n another: int\n # Pass any extra keys under `extra`\n extra: Dict[str, any]\n\nTable.render(\n kwargs=Table.Kwargs(\n variable=\"a\",\n another=1,\n extra={\"foo\": \"bar\"},\n ),\n)\n
"},{"location":"concepts/fundamentals/typing_and_validation/#handling-no-args-or-no-kwargs","title":"Handling no args or no kwargs","text":"
To declare that a component accepts no args, kwargs, etc, define the types with no attributes using the pass keyword:
from typing import NamedTuple\nfrom django_components import Component\n\nclass Button(Component):\n class Args(NamedTuple):\n pass\n\n class Kwargs(NamedTuple):\n pass\n\n class Slots(NamedTuple):\n pass\n
This can get repetitive, so we added a Empty type to make it easier:
Since each type class is a separate class attribute, you can just override them in the Component subclass.
In the example below, ButtonExtra inherits Kwargs from Button, but overrides the Args class.
from django_components import Component, Empty\n\nclass Button(Component):\n class Args(NamedTuple):\n size: int\n\n class Kwargs(NamedTuple):\n color: str\n\nclass ButtonExtra(Button):\n class Args(NamedTuple):\n name: str\n size: int\n\n# Stil works the same way!\nButtonExtra.render(\n args=ButtonExtra.Args(name=\"John\", size=30),\n kwargs=ButtonExtra.Kwargs(color=\"red\"),\n)\n
The only difference is when it comes to type hints to the data methods like get_template_data().
When you define the nested classes like Args and Kwargs directly on the class, you can reference them just by their class name (Args and Kwargs).
But when you have a Component subclass, and it uses Args or Kwargs from the parent, you will have to reference the type as a forward reference, including the full name of the component (Button.Args and Button.Kwargs).
Compare the following:
class Button(Component):\n class Args(NamedTuple):\n size: int\n\n class Kwargs(NamedTuple):\n color: str\n\n # Both `Args` and `Kwargs` are defined on the class\n def get_template_data(self, args: Args, kwargs: Kwargs, slots, context):\n pass\n\nclass ButtonExtra(Button):\n class Args(NamedTuple):\n name: str\n size: int\n\n # `Args` is defined on the subclass, `Kwargs` is defined on the parent\n def get_template_data(self, args: Args, kwargs: \"ButtonExtra.Kwargs\", slots, context):\n pass\n\nclass ButtonSame(Button):\n # Both `Args` and `Kwargs` are defined on the parent\n def get_template_data(self, args: \"ButtonSame.Args\", kwargs: \"ButtonSame.Kwargs\", slots, context):\n pass\n
"},{"location":"concepts/fundamentals/typing_and_validation/#runtime-type-validation","title":"Runtime type validation","text":"
When you add types to your component, and implement them as NamedTuple or dataclass, the validation will check only for the presence of the attributes.
So this will not catch if you pass a string to an int attribute.
To enable runtime type validation, you need to use Pydantic models, and install the djc-ext-pydantic extension.
The djc-ext-pydantic extension ensures compatibility between django-components' classes such as Component, or Slot and Pydantic models.
"},{"location":"concepts/fundamentals/typing_and_validation/#migrating-from-generics-to-class-attributes","title":"Migrating from generics to class attributes","text":"
In versions 0.92 to 0.139 (inclusive), the component typing was specified through generics.
Since v0.140, the types must be specified as class attributes of the Component class - Args, Kwargs, Slots, TemplateData, JsData, and CssData.
This change was necessary to make it possible to subclass components. Subclassing with generics was otherwise too complicated. Read the discussion here.
Because of this change, the Component.render() method is no longer typed. To type-check the inputs, you should wrap the inputs in Component.Args, Component.Kwargs, Component.Slots, etc.
For example, if you had a component like this:
from typing import NotRequired, Tuple, TypedDict\nfrom django_components import Component, Slot, SlotInput\n\nButtonArgs = Tuple[int, str]\n\nclass ButtonKwargs(TypedDict):\n variable: str\n another: int\n maybe_var: NotRequired[int] # May be omitted\n\nclass ButtonSlots(TypedDict):\n # Use `SlotInput` to allow slots to be given as `Slot` instance,\n # plain string, or a function that returns a string.\n my_slot: NotRequired[SlotInput]\n # Use `Slot` to allow ONLY `Slot` instances.\n another_slot: Slot\n\nButtonType = Component[ButtonArgs, ButtonKwargs, ButtonSlots]\n\nclass Button(ButtonType):\n def get_context_data(self, *args, **kwargs):\n self.input.args[0] # int\n self.input.kwargs[\"variable\"] # str\n self.input.slots[\"my_slot\"] # Slot[MySlotData]\n\nButton.render(\n args=(1, \"hello\"),\n kwargs={\n \"variable\": \"world\",\n \"another\": 123,\n },\n slots={\n \"my_slot\": \"...\",\n \"another_slot\": Slot(lambda ctx: ...),\n },\n)\n
The steps to migrate are:
Convert all the types (ButtonArgs, ButtonKwargs, ButtonSlots) to subclasses of NamedTuple.
Move these types inside the Component class (Button), and rename them to Args, Kwargs, and Slots.
If you defined typing for the data methods (like get_context_data()), move them inside the Component class, and rename them to TemplateData, JsData, and CssData.
Remove the Component generic.
If you accessed the args, kwargs, or slots attributes via self.input, you will need to add the type hints yourself, because self.input is no longer typed.
Otherwise, you may use Component.get_template_data() instead of get_context_data(), as get_template_data() receives args, kwargs, slots and context as arguments. You will still need to add the type hints yourself.
Lastly, you will need to update the Component.render() calls to wrap the inputs in Component.Args, Component.Kwargs, and Component.Slots, to manually add type hints.
Thus, the code above will become:
from typing import NamedTuple, Optional\nfrom django.template import Context\nfrom django_components import Component, Slot, SlotInput\n\n# The Component class does not take any generics\nclass Button(Component):\n # Types are now defined inside the component class\n class Args(NamedTuple):\n size: int\n text: str\n\n class Kwargs(NamedTuple):\n variable: str\n another: int\n maybe_var: Optional[int] = None # May be omitted\n\n class Slots(NamedTuple):\n # Use `SlotInput` to allow slots to be given as `Slot` instance,\n # plain string, or a function that returns a string.\n my_slot: Optional[SlotInput] = None\n # Use `Slot` to allow ONLY `Slot` instances.\n another_slot: Slot\n\n # The args, kwargs, slots are instances of the component's Args, Kwargs, and Slots classes\n def get_template_data(self, args: Args, kwargs: Kwargs, slots: Slots, context: Context):\n args.size # int\n kwargs.variable # str\n slots.my_slot # Slot[MySlotData]\n\nButton.render(\n # Wrap the inputs in the component's Args, Kwargs, and Slots classes\n args=Button.Args(1, \"hello\"),\n kwargs=Button.Kwargs(\n variable=\"world\",\n another=123,\n ),\n slots=Button.Slots(\n my_slot=\"...\",\n another_slot=Slot(lambda ctx: ...),\n ),\n)\n
"},{"location":"getting_started/adding_js_and_css/","title":"Adding JS and CSS","text":"
Next we will add CSS and JavaScript to our template.
Info
In django-components, using JS and CSS is as simple as defining them on the Component class. You don't have to insert the <script> and <link> tags into the HTML manually.
Behind the scenes, django-components keeps track of which components use which JS and CSS files. Thus, when a component is rendered on the page, the page will contain only the JS and CSS used by the components, and nothing more!
Be sure to prefix your rules with unique CSS class like calendar, so the CSS doesn't clash with other rules.
Note
Soon, django-components will automatically scope your CSS by default, so you won't have to worry about CSS class clashes.
This CSS will be inserted into the page as an inlined <style> tag, at the position defined by {% component_css_dependencies %}, or at the end of the inside the <head> tag (See Default JS / CSS locations).
A good way to make sure the JS of this component doesn't clash with other components is to define all JS code inside an anonymous self-invoking function ((() => { ... })()). This makes all variables defined only be defined inside this component and not affect other components.
Note
Soon, django-components will automatically wrap your JS in a self-invoking function by default (except for JS defined with <script type=\"module\">).
Similarly to CSS, JS will be inserted into the page as an inlined <script> tag, at the position defined by {% component_js_dependencies %}, or at the end of the inside the <body> tag (See Default JS / CSS locations).
Then the JS file of the component calendar will be executed first, and the JS file of component table will be executed second.
JS will be executed only once, even if there is multiple instances of the same component
In this case, the JS of calendar will STILL execute first (because it was found first), and will STILL execute only once, even though it's present twice:
And that's it! If you were to embed this component in an HTML, django-components will automatically embed the associated JS and CSS.
Note
Similarly to the template file, the JS and CSS file paths can be either:
Relative to the Python component file (as seen above),
Relative to any of the component directories as defined by COMPONENTS.dirs and/or COMPONENTS.app_dirs (e.g. [your apps]/components dir and [project root]/components)
Relative to any of the directories defined by STATICFILES_DIRS.
"},{"location":"getting_started/adding_js_and_css/#5-link-additional-js-and-css-to-a-component","title":"5. Link additional JS and CSS to a component","text":"
Your components may depend on third-party packages or styling, or other shared logic. To load these additional dependencies, you can use a nested Media class.
This Media class behaves similarly to Django's Media class, with a few differences:
Our Media class accepts various formats for the JS and CSS files: either a single file, a list, or (CSS-only) a dictonary (see below).
Individual JS / CSS files can be any of str, bytes, Path, SafeString, or a function.
Individual JS / CSS files can be glob patterns, e.g. *.js or styles/**/*.css.
If you set Media.extend to a list, it should be a list of Component classes.
Learn more about using Media.
[project root]/components/calendar/calendar.py
from django_components import Component\n\nclass Calendar(Component):\n template_file = \"calendar.html\"\n js_file = \"calendar.js\"\n css_file = \"calendar.css\"\n\n class Media: # <--- new\n js = [\n \"path/to/shared.js\",\n \"path/to/*.js\", # Or as a glob\n \"https://unpkg.com/alpinejs@3.14.7/dist/cdn.min.js\", # AlpineJS\n ]\n css = [\n \"path/to/shared.css\",\n \"path/to/*.css\", # Or as a glob\n \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\", # Tailwind\n ]\n\n def get_template_data(self, args, kwargs, slots, context):\n return {\n \"date\": \"1970-01-01\",\n }\n
Note
Same as with the \"primary\" JS and CSS, the file paths files can be either:
Relative to the Python component file (as seen above),
Relative to any of the component directories as defined by COMPONENTS.dirs and/or COMPONENTS.app_dirs (e.g. [your apps]/components dir and [project root]/components)
Info
The Media nested class is shaped based on Django's Media class.
As such, django-components allows multiple formats to define the nested Media class:
# Single files\nclass Media:\n js = \"calendar.js\"\n css = \"calendar.css\"\n\n# Lists of files\nclass Media:\n js = [\"calendar.js\", \"calendar2.js\"]\n css = [\"calendar.css\", \"calendar2.css\"]\n\n# Dictionary of media types for CSS\nclass Media:\n js = [\"calendar.js\", \"calendar2.js\"]\n css = {\n \"all\": [\"calendar.css\", \"calendar2.css\"],\n }\n
If you define a list of JS files, they will be executed one-by-one, left-to-right.
"},{"location":"getting_started/adding_js_and_css/#rules-of-execution-of-scripts-in-mediajs","title":"Rules of execution of scripts in Media.js","text":"
The scripts defined in Media.js still follow the rules outlined above:
JS is executed in the order in which the components are found in the HTML.
JS will be executed only once, even if there is multiple instances of the same component.
Additionally to Media.js applies that:
JS in Media.js is executed before the component's primary JS.
JS in Media.js is executed in the same order as it was defined.
If there is multiple components that specify the same JS path or URL in Media.js, this JS will be still loaded and executed only once.
Putting all of this together, our Calendar component above would render HTML like so:
Our calendar component's looking great! But we just got a new assignment from our colleague - The calendar date needs to be shown on 3 different pages:
On one page, it needs to be shown as is
On the second, the date needs to be bold
On the third, the date needs to be in italics
As a reminder, this is what the component's template looks like:
<div class=\"calendar\">\n Today's date is <span>{{ date }}</span>\n</div>\n
There's many ways we could approach this:
Expose the date in a slot
Style .calendar > span differently on different pages
Pass a variable to the component that decides how the date is rendered
Create a new component
First two options are more flexible, because the custom styling is not baked into a component's implementation. And for the sake of demonstration, we'll solve this challenge with slots.
"},{"location":"getting_started/adding_slots/#1-what-are-slots","title":"1. What are slots","text":"
Components support something called Slots.
When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content.
This mechanism makes components more reusable and composable.
This behavior is similar to slots in Vue.
In the example below we introduce two tags that work hand in hand to make this work. These are...
{% slot <name> %}/{% endslot %}: Declares a new slot in the component template.
{% fill <name> %}/{% endfill %}: (Used inside a {% component %} tag pair.) Fills a declared slot with the specified content.
"},{"location":"getting_started/adding_slots/#2-add-a-slot-tag","title":"2. Add a slot tag","text":"
Let's update our calendar component to support more customization. We'll add {% slot %} tag to the template:
<div class=\"calendar\">\n Today's date is\n {% slot \"date\" default %} {# <--- new #}\n <span>{{ date }}</span>\n {% endslot %}\n</div>\n
Notice that:
We named the slot date - so we can fill this slot by using {% fill \"date\" %}
We also made it the default slot.
We placed our original implementation inside the {% slot %} tag - this is what will be rendered when the slot is NOT overriden.
"},{"location":"getting_started/adding_slots/#3-add-fill-tag","title":"3. Add fill tag","text":"
Now we can use {% fill %} tags inside the {% component %} tags to override the date slot to generate the bold and italics variants:
<!-- Default -->\n<div class=\"calendar\">\n Today's date is <span>2024-12-13</span>\n</div>\n\n<!-- Bold -->\n<div class=\"calendar\">\n Today's date is <b>2024-12-13</b>\n</div>\n\n<!-- Italics -->\n<div class=\"calendar\">\n Today's date is <i>2024-12-13</i>\n</div>\n
Info
Since we used the default flag on {% slot \"date\" %} inside our calendar component, we can target the date component in multiple ways:
"},{"location":"getting_started/adding_slots/#4-wait-theres-a-bug","title":"4. Wait, there's a bug","text":"
There is a mistake in our code! 2024-12-13 is Friday, so that's fine. But if we updated the to 2024-12-14, which is Saturday, our template from previous step would render this:
<!-- Default -->\n<div class=\"calendar\">\n Today's date is <span>2024-12-16</span>\n</div>\n\n<!-- Bold -->\n<div class=\"calendar\">\n Today's date is <b>2024-12-14</b>\n</div>\n\n<!-- Italics -->\n<div class=\"calendar\">\n Today's date is <i>2024-12-14</i>\n</div>\n
The first instance rendered 2024-12-16, while the rest rendered 2024-12-14!
Why? Remember that in the get_template_data() method of our Calendar component, we pre-process the date. If the date falls on Saturday or Sunday, we shift it to next Monday:
[project root]/components/calendar/calendar.py
from datetime import date\n\nfrom django_components import Component, register\n\n# If date is Sat or Sun, shift it to next Mon, so the date is always workweek.\ndef to_workweek_date(d: date):\n ...\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_file = \"calendar.html\"\n ...\n def get_template_data(self, args, kwargs, slots, context):\n workweek_date = to_workweek_date(kwargs[\"date\"])\n return {\n \"date\": workweek_date,\n \"extra_class\": kwargs.get(\"extra_class\", \"text-blue\"),\n }\n
And the issue is that in our template, we used the date value that we used as input, which is NOT the same as the date variable used inside Calendar's template.
"},{"location":"getting_started/adding_slots/#5-adding-data-to-slots","title":"5. Adding data to slots","text":"
We want to use the same date variable that's used inside Calendar's template.
Luckily, django-components allows passing data to slots, also known as Scoped slots.
This consists of two steps:
Pass the date variable to the {% slot %} tag
Access the date variable in the {% fill %} tag by using the special data kwarg
By using the date variable from the slot, we'll render the correct date each time:
<!-- Default -->\n<div class=\"calendar\">\n Today's date is <span>2024-12-16</span>\n</div>\n\n<!-- Bold -->\n<div class=\"calendar\">\n Today's date is <b>2024-12-16</b>\n</div>\n\n<!-- Italics -->\n<div class=\"calendar\">\n Today's date is <i>2024-12-16</i>\n</div>\n
Info
When to use slots vs variables?
Generally, slots are more flexible - you can access the slot data, even the original slot content. Thus, slots behave more like functions that render content based on their context.
On the other hand, variables are simpler - the variable you pass to a component is what will be used.
Moreover, slots are treated as part of the template - for example the CSS scoping (work in progress) is applied to the slot content too.
"},{"location":"getting_started/components_in_templates/","title":"Components in templates","text":"
By the end of this section, we want to be able to use our components in Django templates like so:
First, however, we need to register our component class with ComponentRegistry.
To register a component with a ComponentRegistry, we will use the @register decorator, and give it a name under which the component will be accessible from within the template:
This will register the component to the default registry. Default registry is loaded into the template by calling {% load component_tags %} inside the template.
Info
Why do we have to register components?
We want to use our component as a template tag ({% ... %}) in Django template.
In Django, template tags are managed by the Library instances. Whenever you include {% load xxx %} in your template, you are loading a Library instance into your template.
ComponentRegistry acts like a router and connects the registered components with the associated Library.
That way, when you include {% load component_tags %} in your template, you are able to \"call\" components like {% component \"calendar\" / %}.
ComponentRegistries also make it possible to group and share components as standalone packages. Learn more here.
Note
You can create custom ComponentRegistry instances, which will use different Library instances. In that case you will have to load different libraries depending on which components you want to use:
Example 1 - Using component defined in the default registry
Note that, because the tag name component is use by the default ComponentRegistry, the custom registry was configured to use the tag my_component instead. Read more here
"},{"location":"getting_started/components_in_templates/#2-load-and-use-the-component-in-template","title":"2. Load and use the component in template","text":"
The component is now registered under the name calendar. All that remains to do is to load and render the component inside a template:
{% load component_tags %} {# Load the default registry #}\n<!DOCTYPE html>\n<html>\n <head>\n <title>My example calendar</title>\n </head>\n <body>\n {% component \"calendar\" / %} {# Render the component #}\n </body>\n<html>\n
Info
Component tags should end with / if they do not contain any Slot fills. But you can also use {% endcomponent %} instead:
{% component \"calendar\" %}{% endcomponent %}\n
We defined the Calendar's template as
<div class=\"calendar\">\n Today's date is <span>{{ date }}</span>\n</div>\n
and the variable date as \"1970-01-01\".
Thus, the final output will look something like this:
This makes it possible to organize your front-end around reusable components, instead of relying on template tags and keeping your CSS and Javascript in the static directory.
Info
Remember that you can use {% component_js_dependencies %} and {% component_css_dependencies %} to change where the <script> and <style> tags will be rendered (See Default JS / CSS locations).
Info
How does django-components pick up registered components?
Notice that it was enough to add @register to the component. We didn't need to import the component file anywhere to execute it.
This is because django-components automatically imports all Python files found in the component directories during an event called Autodiscovery.
So with Autodiscovery, it's the same as if you manually imported the component files on the ready() hook:
class MyApp(AppConfig):\n default_auto_field = \"django.db.models.BigAutoField\"\n name = \"myapp\"\n\n def ready(self):\n import myapp.components.calendar\n import myapp.components.table\n ...\n
You can now render the components in templates!
Currently our component always renders the same content. Let's parametrise it, so that our Calendar component is configurable from within the template \u27a1\ufe0f
Let's put this to test. We want to pass date and extra_class kwargs to the component. And so, we can write the get_template_data() method such that it expects those parameters:
get_template_data() differentiates between positional and keyword arguments, so you have to make sure to pass the arguments correctly.
Since date is expected to be a keyword argument, it MUST be provided as such:
\u2705 `date` is kwarg\n{% component \"calendar\" date=\"2024-12-13\" / %}\n\n\u274c `date` is arg\n{% component \"calendar\" \"2024-12-13\" / %}\n
"},{"location":"getting_started/parametrising_components/#3-process-inputs","title":"3. Process inputs","text":"
The get_template_data() method is powerful, because it allows us to decouple component inputs from the template variables. In other words, we can pre-process the component inputs, and massage them into a shape that's most appropriate for what the template needs. And it also allows us to pass in static data into the template.
Imagine our component receives data from the database that looks like below (taken from Django).
Similarly we can make use of get_template_data() to pre-process the date that was given to the component:
[project root]/components/calendar/calendar.py
from datetime import date\n\nfrom django_components import Component, register\n\n# If date is Sat or Sun, shift it to next Mon, so the date is always workweek.\ndef to_workweek_date(d: date):\n ...\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_file = \"calendar.html\"\n ...\n def get_template_data(self, args, kwargs, slots, context):\n workweek_date = to_workweek_date(kwargs[\"date\"]) # <--- new\n return {\n \"date\": workweek_date, # <--- changed\n \"extra_class\": kwargs.get(\"extra_class\", \"text-blue\"),\n }\n
"},{"location":"getting_started/parametrising_components/#4-pass-inputs-to-components","title":"4. Pass inputs to components","text":"
Once we're happy with Calendar.get_template_data(), we can update our templates to use the parametrized version of the component:
In our example, we've set the extra_class to default to \"text-blue\" by setting it in the get_template_data() method.
However, you may want to use the same default value in multiple methods, like get_js_data() or get_css_data().
To make things easier, Components can specify their defaults. Defaults are used when no value is provided, or when the value is set to None for a particular input.
To define defaults for a component, you create a nested Defaults class within your Component class. Each attribute in the Defaults class represents a default value for a corresponding input.
Among other, you can pass also the request object to the render method:
from components.calendar import Calendar\n\ncalendar = Calendar\nrendered_component = calendar.render(request=request)\n
The request object is required for some of the component's features, like using Django's context processors.
"},{"location":"getting_started/rendering_components/#3-render-the-component-to-httpresponse","title":"3. Render the component to HttpResponse","text":"
A common pattern in Django is to render the component and then return the resulting HTML as a response to an HTTP request.
For this, you can use the Component.render_to_response() convenience method.
render_to_response() accepts the same args, kwargs, slots, and more, as Component.render(), but wraps the result in an HttpResponse.
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:
Each of these receive the HttpRequest object as the first argument.
Next, you need to set the URL for the component.
You can either:
Automatically assign the URL by setting the Component.View.public attribute to True.
In this case, use get_component_url() to get the URL for the component view.
from django_components import Component, get_component_url\n\nclass Calendar(Component):\n class View:\n public = True\n\nurl = get_component_url(Calendar)\n
Manually assign the URL by setting Component.as_view() to your urlpatterns:
And with that, you're all set! When you visit the URL, the component will be rendered and the content will be returned.
The get(), post(), etc methods will receive the HttpRequest object as the first argument. So you can parametrize how the component is rendered for example by passing extra query parameters to the URL:
http://localhost:8000/calendar/?date=2024-12-13\n
"},{"location":"getting_started/your_first_component/","title":"Create your first component","text":"
A component in django-components can be as simple as a Django template and Python code to declare the component:
calendar.html
<div class=\"calendar\">\n Today's date is <span>{{ date }}</span>\n</div>\n
calendar.py
from django_components import Component\n\nclass Calendar(Component):\n template_file = \"calendar.html\"\n
Or a combination of Django template, Python, CSS, and Javascript:
calendar.html
<div class=\"calendar\">\n Today's date is <span>{{ date }}</span>\n</div>\n
Alternatively, you can \"inline\" HTML, JS, and CSS right into the component class:
from django_components import Component\n\nclass Calendar(Component):\n template = \"\"\"\n <div class=\"calendar\">\n Today's date is <span>{{ date }}</span>\n </div>\n \"\"\"\n\n css = \"\"\"\n .calendar {\n width: 200px;\n background: pink;\n }\n \"\"\"\n\n js = \"\"\"\n document.querySelector(\".calendar\").onclick = function () {\n alert(\"Clicked calendar!\");\n };\n \"\"\"\n
Note
If you \"inline\" the HTML, JS and CSS code into the Python class, you can set up syntax highlighting for better experience. However, autocompletion / intellisense does not work with syntax highlighting.
We'll start by creating a component that defines only a Django template:
<div class=\"calendar\">\n Today's date is <span>{{ date }}</span>\n</div>\n
In this example we've defined one template variable date. You can use any and as many variables as you like. These variables will be defined in the Python file in get_template_data() when creating an instance of this component.
Note
The template will be rendered with whatever template backend you've specified in your Django settings file.
Currently django-components supports only the default \"django.template.backends.django.DjangoTemplates\" template backend!
"},{"location":"getting_started/your_first_component/#3-create-new-component-in-python","title":"3. Create new Component in Python","text":"
In calendar.py, create a subclass of Component to create a new component.
To link the HTML template with our component, set template_file to the name of the HTML file.
[project root]/components/calendar/calendar.py
from django_components import Component\n\nclass Calendar(Component):\n template_file = \"calendar.html\"\n
Note
The path to the template file can be either:
Relative to the component's python file (as seen above),
Relative to any of the component directories as defined by COMPONENTS.dirs and/or COMPONENTS.app_dirs (e.g. [your apps]/components dir and [project root]/components)
"},{"location":"getting_started/your_first_component/#4-define-the-template-variables","title":"4. Define the template variables","text":"
In calendar.html, we've used the variable date. So we need to define it for the template to work.
This is done using Component.get_template_data(). It's a function that returns a dictionary. The entries in this dictionary will become available within the template as variables, e.g. as {{ date }}.
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 wasteful to create a copy of the JS / CSS scripts for each component instance.
So instead, a preferred approach here is to defined and insert the inlined JS / CSS only once, and have some kind of mechanism on how we make correct the JS / CSS variables available only to the correct components.
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:
If users are using Component.render() or Component.render_to_response(), these post-process the <!-- _RENDERED --> comments by default.
NOTE: Users are able to opt out of the post-processing by setting deps_strategy=\"ignore\".
If one renders a Template directly, the <!-- _RENDERED --> will be processed too. We achieve this by modifying Django's Template.render() method.
For advanced use cases, users may use render_dependencies() directly. This is the function that Component.render() calls internally.
render_dependencies(), whether called directly, or other way, does the following:
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":"guides/devguides/slot_rendering/#using-the-correct-context-in-slotfill-tags","title":"Using the correct context in {% slot/fill %} tags","text":"
In previous section, we said that the {% fill %} tags should be already rendered by the time they are inserted into the {% slot %} tags.
This is not quite true. To help you understand, consider this complex case:
| -- {% for var in [1, 2, 3] %} ---\n| ---- {% component \"mycomp2\" %} ---\n| ------ {% fill \"first\" %}\n| ------- STU {{ my_var }}\n| ------- {{ var }}\n| ------ {% endfill %}\n| ------ {% fill \"second\" %}\n| -------- {% component var=var my_var=my_var %}\n| ---------- VWX {{ my_var }}\n| -------- {% endcomponent %}\n| ------ {% endfill %}\n| ---- {% endcomponent %} ---\n| -- {% endfor %} ---\n| -------\n
We want the forloop variables to be available inside the {% fill %} tags. Because of that, however, we CANNOT render the fills/slots in advance.
Instead, our solution is closer to how Vue handles slots. In Vue, slots are effectively functions that accept a context variables and render some content.
While we do not wrap the logic in a function, we do PREPARE IN ADVANCE: 1. The content that should be rendered for each slot 2. The context variables from get_template_data()
Thus, once we reach the {% slot %} node, in it's render() method, we access the data above, and, depending on the context_behavior setting, include the current context or not. For more info, see SlotNode.render().
"},{"location":"guides/devguides/slots_and_blocks/","title":"Using slot and block tags","text":"
First let's clarify how include and extends tags work inside components.
When component template includes include or extends tags, it's as if the \"included\" template was inlined. So if the \"included\" template contains slot tags, then the component uses those slots.
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 the 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:
As larger projects get more complex, it can be hard to debug issues. Django Components provides a number of tools and approaches that can help you with that.
"},{"location":"guides/other/troubleshooting/#component-and-slot-highlighting","title":"Component and slot highlighting","text":"
Django Components provides a visual debugging feature that helps you understand the structure and boundaries of your components and slots. When enabled, it adds a colored border and a label around each component and slot on your rendered page.
To enable component and slot highlighting for all components and slots, set highlight_components and highlight_slots to True in extensions defaults in your settings.py file:
As of v0.126, django-components primarily uses these logger levels:
DEBUG: Report on loading associated HTML / JS / CSS files, autodiscovery, etc.
TRACE: Detailed interaction of components and slots. Logs when template tags, components, and slots are started / ended rendering, and when a slot is filled.
You can cache the output of your components by setting the Component.Cache options.
Read more about Component caching.
"},{"location":"guides/setup/caching/#components-js-and-css-files","title":"Component's JS and CSS files","text":"
django-components simultaneously supports:
Rendering and fetching components as HTML fragments
Allowing components (even fragments) to have JS and CSS files associated with them
Features like JS/CSS variables or CSS scoping
To achieve all this, django-components defines additional temporary JS and CSS files. These temporary files need to be stored somewhere, so that they can be fetched by the browser when the component is rendered as a fragment. And for that, django-components uses Django's cache framework.
This includes:
Inlined JS/CSS defined via Component.js and Component.css
JS/CSS variables generated from get_js_data() and get_css_data()
By default, django-components uses Django's local memory cache backend to store these assets. You can configure it to use any of your Django cache backends by setting the COMPONENTS.cache option in your settings:
COMPONENTS = {\n # Name of the cache backend to use\n \"cache\": \"my-cache-backend\",\n}\n
The value should be the name of one of your configured cache backends from Django's CACHES setting.
For example, to use Redis for caching component assets:
See COMPONENTS.cache for more details about this setting.
"},{"location":"guides/setup/development_server/","title":"Development server","text":""},{"location":"guides/setup/development_server/#reload-dev-server-on-component-file-changes","title":"Reload dev server on component file changes","text":"
This is relevant if you are using the project structure as shown in our examples, where HTML, JS, CSS and Python are in separate files and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.
From relevant StackOverflow thread:
TL;DR is that the server won't reload if it thinks the changed file is in a templates directory, or in a nested sub directory of a templates directory. This is by design.
To make the dev server reload on all component files, set reload_on_file_change to True. This configures Django to watch for component files too.
Warning
This setting should be enabled only for the dev environment!
"},{"location":"overview/code_of_conduct/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"overview/code_of_conduct/#our-pledge","title":"Our Pledge","text":"
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
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 (see how to package components). If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.
django-htmx-components: A set of components for use with htmx.
djc-heroicons: A component that renders icons from Heroicons.com.
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):
Next, modify TEMPLATES section of settings.py as follows:
Remove 'APP_DIRS': True,
NOTE: Instead of APP_DIRS: True, we will use django.template.loaders.app_directories.Loader, which has the same effect.
Add loaders to OPTIONS list and set it to following value:
This allows Django to load component HTML files as Django templates.
TEMPLATES = [\n {\n ...,\n 'OPTIONS': {\n ...,\n 'loaders':[(\n 'django.template.loaders.cached.Loader', [\n # Default Django loader\n 'django.template.loaders.filesystem.Loader',\n # Including this is the same as APP_DIRS=True\n 'django.template.loaders.app_directories.Loader',\n # Components loader\n 'django_components.template_loader.Loader',\n ]\n )],\n },\n },\n]\n
Add django-component's URL paths to your urlpatterns:
Django components already prefixes all URLs with components/. So when you are adding the URLs to urlpatterns, you can use an empty string as the first argument:
from django.urls import include, path\n\nurlpatterns = [\n ...\n path(\"\", include(\"django_components.urls\")),\n]\n
"},{"location":"overview/installation/#adding-support-for-js-and-css","title":"Adding support for JS and CSS","text":"
If you want to use JS or CSS with components, you will need to:
Add \"django_components.finders.ComponentsFileSystemFinder\" to STATICFILES_FINDERS in your settings file.
This allows Django to serve component JS and CSS as static files.
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.
Since django-components is in pre-1.0 development, the public API is not yet frozen. This means that there may be breaking changes between minor versions. We try to minimize the number of breaking changes, but sometimes it's unavoidable.
When upgrading, please read the Release notes.
"},{"location":"overview/migrating/#migrating-in-pre-v10","title":"Migrating in pre-v1.0","text":"
If you're on older pre-v1.0 versions of django-components, we recommend doing step-wise upgrades in the following order:
v0.26
v0.50
v0.70
v0.77
v0.81
v0.85
v0.92
v0.100
v0.110
v0.140
These versions introduced breaking changes that are not backwards compatible.
TL;DR: No action needed from v0.100 onwards. Before v0.100, use safer_staticfiles to avoid exposing backend logic.
Components can be organized however you prefer. That said, our prefered way is to keep the files of a component close together by bundling them in the same directory.
This means that files containing backend logic, such as Python modules and HTML templates, live in the same directory as static files, e.g. JS and CSS.
From v0.100 onwards, we keep component files (as defined by COMPONENTS.dirs and COMPONENTS.app_dirs) separate from the rest of the static files (defined by STATICFILES_DIRS). That way, the Python and HTML files are NOT exposed by the server. Only the static JS, CSS, and other common formats.
Note
If you need to expose different file formats, you can configure these with COMPONENTS.static_files_allowed and COMPONENTS.static_files_forbidden.
"},{"location":"overview/security_notes/#static-files-prior-to-v0100","title":"Static files prior to v0.100","text":"
Prior to v0.100, if your were using django.contrib.staticfiles to collect static files, no distinction was made between the different kinds of files.
As a result, your Python code and templates may inadvertently become available on your static file server. You probably don't want this, as parts of your backend logic will be exposed, posing a potential security vulnerability.
From v0.27 until v0.100, django-components shipped with an additional installable app django_components.safer_staticfiles. It was a drop-in replacement for django.contrib.staticfiles. Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server.
To use it, add it to INSTALLED_APPS and remove django.contrib.staticfiles.
<div class=\"calendar-component\">\n Today's date is <span>2024-11-06</span>\n</div>\n
Read on to learn about all the exciting details and configuration possibilities!
(If you instead prefer to jump right into the code, check out the example project)
"},{"location":"overview/welcome/#features","title":"Features","text":""},{"location":"overview/welcome/#modern-and-modular-ui","title":"Modern and modular UI","text":"
Create self-contained, reusable UI elements.
Each component can include its own HTML, CSS, and JS, or additional third-party JS and CSS.
HTML, CSS, and JS can be defined on the component class, or loaded from files.
from django_components import Component\n\n@register(\"calendar\")\nclass Calendar(Component):\n template = \"\"\"\n <div class=\"calendar\">\n Today's date is\n <span>{{ date }}</span>\n </div>\n \"\"\"\n\n css = \"\"\"\n .calendar {\n width: 200px;\n background: pink;\n }\n \"\"\"\n\n js = \"\"\"\n document.querySelector(\".calendar\")\n .addEventListener(\"click\", () => {\n alert(\"Clicked calendar!\");\n });\n \"\"\"\n\n # Additional JS and CSS\n class Media:\n js = [\"https://cdn.jsdelivr.net/npm/htmx.org@2/dist/htmx.min.js\"]\n css = [\"bootstrap/dist/css/bootstrap.min.css\"]\n\n # Variables available in the template\n def get_template_data(self, args, kwargs, slots, context):\n return {\n \"date\": kwargs[\"date\"]\n }\n
"},{"location":"overview/welcome/#composition-with-slots","title":"Composition with slots","text":"
Render components inside templates with {% component %} tag.
{% html_attrs %} offers a Vue-like granular control for class and style HTML attributes, where you can use a dictionary to manage each class name or style property separately.
One of our goals with django-components is to make it easy to share components between projects. Head over to the Community examples to see some examples.
"},{"location":"overview/welcome/#contributing-and-development","title":"Contributing and development","text":"
Get involved or sponsor this project - See here
Running django-components locally for development - See here
This function is what is passed to Django's Library.tag() when registering the tag.
In other words, this method is called by Django's template parser when we encounter a tag that matches this node's tag, e.g. {% component %} or {% slot %}.
To register the tag, you can use BaseNode.register().
Optional typing for positional arguments passed to the component.
If set and not None, then the args parameter of the data methods (get_template_data(), get_js_data(), get_css_data()) will be the instance of this class:
Optional typing for keyword arguments passed to the component.
If set and not None, then the kwargs parameter of the data methods (get_template_data(), get_js_data(), get_css_data()) will be the instance of this class:
Defines JS and CSS media files associated with this component.
This Media class behaves similarly to Django's Media class:
Paths are generally handled as static file paths, and resolved URLs are rendered to HTML with media_class.render_js() or media_class.render_css().
A path that starts with http, https, or / is considered a URL, skipping the static file resolution. This path is still rendered to HTML with media_class.render_js() or media_class.render_css().
A SafeString (with __html__ method) is considered an already-formatted HTML tag, skipping both static file resolution and rendering with media_class.render_js() or media_class.render_css().
You can set extend to configure whether to inherit JS / CSS from parent components. See Media inheritance.
However, there's a few differences from Django's Media class:
Our Media class accepts various formats for the JS and CSS files: either a single file, a list, or (CSS-only) a dictionary (See ComponentMediaInput).
Individual JS / CSS files can be any of str, bytes, Path, SafeString, or a function (See ComponentMediaInputPath).
Optional typing for slots passed to the component.
If set and not None, then the slots parameter of the data methods (get_template_data(), get_js_data(), get_css_data()) will be the instance of this class:
This ID is unique for every time a Component.render() (or equivalent) is called (AKA \"render ID\").
This is useful for logging or debugging.
The ID is a 7-letter alphanumeric string in the format cXXXXXX, where XXXXXX is a random string of 6 alphanumeric characters (case-sensitive).
E.g. c1A2b3c.
A single render ID has a chance of collision 1 in 57 billion. However, due to birthday paradox, the chance of collision increases to 1% when approaching ~33K render IDs.
Thus, there is currently a soft-cap of ~30K components rendered on a single page.
If you need to expand this limit, please open an issue on GitHub.
Set the Media class that will be instantiated with the JS and CSS media files from Component.Media.
This is useful when you want to customize the behavior of the media files, like customizing how the JS or CSS files are rendered into <script> or <link> HTML tags.
Read more in Defining HTML / JS / CSS files.
Example:
class MyTable(Component):\n class Media:\n js = \"path/to/script.js\"\n css = \"path/to/style.css\"\n\n media_class = MyMediaClass\n
The ComponentNode instance that was used to render the component.
This will be set only if the component was rendered with the {% component %} tag.
Accessing the ComponentNode is mostly useful for extensions, which can modify their behaviour based on the source of the Component.
class MyComponent(Component):\n def get_template_data(self, context, template):\n if self.node is not None:\n assert self.node.name == \"my_component\"\n
For example, if MyComponent was used in another component - that is, with a {% component \"my_component\" %} tag in a template that belongs to another component - then you can use self.node.template_component to access the owner Component class.
class Parent(Component):\n template: types.django_html = '''\n <div>\n {% component \"my_component\" / %}\n </div>\n '''\n\n@register(\"my_component\")\nclass MyComponent(Component):\n def get_template_data(self, context, template):\n if self.node is not None:\n assert self.node.template_component == Parent\n
Info
Component.node is None if the component is created by Component.render() (but you can pass in the node kwarg yourself).
If the component was rendered with the {% component %} template tag, this will be the name under which the component was registered in the ComponentRegistry.
args: Positional arguments passed to the component.
kwargs: Keyword arguments passed to the component.
slots: Slots passed to the component.
context: Context used for rendering the component template.
Pass-through kwargs:
It's best practice to explicitly define what args and kwargs a component accepts.
However, if you want a looser setup, you can easily write components that accept any number of kwargs, and pass them all to the CSS code.
To do that, simply return the kwargs dictionary itself from get_css_data():
class MyComponent(Component):\n def get_css_data(self, args, kwargs, slots, context):\n return kwargs\n
Type hints:
To get type hints for the args, kwargs, and slots parameters, you can define the Args, Kwargs, and Slots classes on the component class, and then directly reference them in the function signature of get_css_data().
When you set these classes, the args, kwargs, and slots parameters will be given as instances of these (args instance of Args, etc).
When you omit these classes, or set them to None, then the args, kwargs, and slots parameters will be given as plain lists / dictionaries, unmodified.
args: Positional arguments passed to the component.
kwargs: Keyword arguments passed to the component.
slots: Slots passed to the component.
context: Context used for rendering the component template.
Pass-through kwargs:
It's best practice to explicitly define what args and kwargs a component accepts.
However, if you want a looser setup, you can easily write components that accept any number of kwargs, and pass them all to the JavaScript code.
To do that, simply return the kwargs dictionary itself from get_js_data():
class MyComponent(Component):\n def get_js_data(self, args, kwargs, slots, context):\n return kwargs\n
Type hints:
To get type hints for the args, kwargs, and slots parameters, you can define the Args, Kwargs, and Slots classes on the component class, and then directly reference them in the function signature of get_js_data().
When you set these classes, the args, kwargs, and slots parameters will be given as instances of these (args instance of Args, etc).
When you omit these classes, or set them to None, then the args, kwargs, and slots parameters will be given as plain lists / dictionaries, unmodified.
args: Positional arguments passed to the component.
kwargs: Keyword arguments passed to the component.
slots: Slots passed to the component.
context: Context used for rendering the component template.
Pass-through kwargs:
It's best practice to explicitly define what args and kwargs a component accepts.
However, if you want a looser setup, you can easily write components that accept any number of kwargs, and pass them all to the template (similar to django-cotton).
To do that, simply return the kwargs dictionary itself from get_template_data():
class MyComponent(Component):\n def get_template_data(self, args, kwargs, slots, context):\n return kwargs\n
Type hints:
To get type hints for the args, kwargs, and slots parameters, you can define the Args, Kwargs, and Slots classes on the component class, and then directly reference them in the function signature of get_template_data().
When you set these classes, the args, kwargs, and slots parameters will be given as instances of these (args instance of Args, etc).
When you omit these classes, or set them to None, then the args, kwargs, and slots parameters will be given as plain lists / dictionaries, unmodified.
Return nothing (or None) to handle the result as usual
If you don't raise an exception, and neither return a new HTML, then original HTML / error will be used:
If rendering succeeded, the original HTML will be used as the final output.
If rendering failed, the original error will be propagated.
class MyTable(Component):\n def on_render(self, context, template):\n html, error = yield template.render(context)\n\n if error is not None:\n # The rendering failed\n print(f\"Error: {error}\")\n
Hook that runs when the component was fully rendered, including all its children.
It receives the same arguments as on_render_before(), plus the outcome of the rendering:
result: The rendered output of the component. None if the rendering failed.
error: The error that occurred during the rendering, or None if the rendering succeeded.
on_render_after() behaves the same way as the second part of on_render() (after the yield).
class MyTable(Component):\n def on_render_after(self, context, template, result, error):\n if error is None:\n # The rendering succeeded\n return result\n else:\n # The rendering failed\n print(f\"Error: {error}\")\n
Same as on_render(), you can return a new HTML, raise a new exception, or return nothing:
Return a new HTML
The new HTML will be used as the final output.
If the original template raised an error, it will be ignored.
Return nothing (or None) to handle the result as usual
If you don't raise an exception, and neither return a new HTML, then original HTML / error will be used:
If rendering succeeded, the original HTML will be used as the final output.
If rendering failed, the original error will be propagated.
class MyTable(Component):\n def on_render_after(self, context, template, result, error):\n if error is not None:\n # The rendering failed\n print(f\"Error: {error}\")\n
context - Optional. Plain dictionary or Django's Context. The context within which the component is rendered.
When a component is rendered within a template with the {% component %} tag, this will be set to the Context instance that is used for rendering the template.
When you call Component.render() directly from Python, you can ignore this input most of the time. Instead use args, kwargs, and slots to pass data to the component.
You can pass RequestContext to the context argument, so that the component will gain access to the request object and will use context processors. Read more on Working with HTTP requests.
For advanced use cases, you can use context argument to \"pre-render\" the component in Python, and then pass the rendered output as plain string to the template. With this, the inner component is rendered as if it was within the template with {% component %}.
class Button(Component):\n def render(self, context, template):\n # Pass `context` to Icon component so it is rendered\n # as if nested within Button.\n icon = Icon.render(\n context=context,\n args=[\"icon-name\"],\n deps_strategy=\"ignore\",\n )\n # Update context with icon\n with context.update({\"icon\": icon}):\n return template.render(context)\n
Whether the variables defined in context are available to the template depends on the context behavior mode:
In \"django\" context behavior mode, the template will have access to the keys of this context.
In \"isolated\" context behavior mode, the template will NOT have access to this context, and data MUST be passed via component's args and kwargs.
deps_strategy - Optional. Configure how to handle JS and CSS dependencies. Read more about Dependencies rendering.
There are six strategies:
\"document\" (default)
Smartly inserts JS / CSS into placeholders or into <head> and <body> tags.
Inserts extra script to allow fragment types to work.
Assumes the HTML will be rendered in a JS-enabled browser.
\"fragment\"
A lightweight HTML fragment to be inserted into a document with AJAX.
No JS / CSS included.
\"simple\"
Smartly insert JS / CSS into placeholders or into <head> and <body> tags.
No extra script loaded.
\"prepend\"
Insert JS / CSS before the rendered HTML.
No extra script loaded.
\"append\"
Insert JS / CSS after the rendered HTML.
No extra script loaded.
\"ignore\"
HTML is left as-is. You can still process it with a different strategy later with render_dependencies().
Used for inserting rendered HTML into other components.
request - Optional. HTTPRequest object. Pass a request object directly to the component to apply context processors.
Read more about Working with HTTP requests.
Type hints:
Component.render() is NOT typed. To add type hints, you can wrap the inputs in component's Args, Kwargs, and Slots classes.
Read more on Typing and validation.
from typing import NamedTuple, Optional\nfrom django_components import Component, Slot, SlotInput\n\n# Define the component with the types\nclass Button(Component):\n class Args(NamedTuple):\n name: str\n\n class Kwargs(NamedTuple):\n surname: str\n age: int\n\n class Slots(NamedTuple):\n my_slot: Optional[SlotInput] = None\n footer: SlotInput\n\n# Add type hints to the render call\nButton.render(\n args=Button.Args(\n name=\"John\",\n ),\n kwargs=Button.Kwargs(\n surname=\"Doe\",\n age=30,\n ),\n slots=Button.Slots(\n footer=Slot(lambda ctx: \"Click me!\"),\n ),\n)\n
When a Component is instantiated, also the nested extension classes (such as Component.View) are instantiated, receiving the component instance as an argument.
This attribute holds the owner Component instance that this extension is defined on.
Currently it's impossible to capture used variables. This will be addressed in v2. Read more about it in https://github.com/django-components/django-components/issues/1164.
When a Component is instantiated, also the nested extension classes (such as Component.View) are instantiated, receiving the component instance as an argument.
This attribute holds the owner Component instance that this extension is defined on.
When a Component is instantiated, also the nested extension classes (such as Component.View) are instantiated, receiving the component instance as an argument.
This attribute holds the owner Component instance that this extension is defined on.
class ExampleExtension(ComponentExtension):\n name = \"example\"\n\n # Component-level behavior and settings. User will be able to override\n # the attributes and methods defined here on the component classes.\n class ComponentConfig(ComponentExtension.ComponentConfig):\n foo = \"1\"\n bar = \"2\"\n\n def baz(cls):\n return \"3\"\n\n # URLs\n urls = [\n URLRoute(path=\"dummy-view/\", handler=dummy_view, name=\"dummy\"),\n URLRoute(path=\"dummy-view-2/<int:id>/<str:name>/\", handler=dummy_view_2, name=\"dummy-2\"),\n ]\n\n # Commands\n commands = [\n HelloWorldCommand,\n ]\n\n # Hooks\n def on_component_class_created(self, ctx: OnComponentClassCreatedContext) -> None:\n print(ctx.component_cls.__name__)\n\n def on_component_class_deleted(self, ctx: OnComponentClassDeletedContext) -> None:\n print(ctx.component_cls.__name__)\n
Which users then can override on a per-component basis. E.g.:
class MyComp(Component):\n class Example:\n foo = \"overridden\"\n\n def baz(self):\n return \"overridden baz\"\n
Base class that the \"component-level\" extension config nested within a Component class will inherit from.
This is where you can define new methods and attributes that will be available to the component instance.
Background:
The extension may add new features to the Component class by allowing users to define and access a nested class in the Component class. E.g.:
class MyComp(Component):\n class MyExtension:\n ...\n\n def get_template_data(self, args, kwargs, slots, context):\n return {\n \"my_extension\": self.my_extension.do_something(),\n }\n
When rendering a component, the nested extension class will be set as a subclass of ComponentConfig. So it will be same as if the user had directly inherited from extension's ComponentConfig. E.g.:
class MyComp(Component):\n class MyExtension(ComponentExtension.ComponentConfig):\n ...\n
This setting decides what the extension class will inherit from.
By default, this is set automatically at class creation. The class name is the same as the name attribute, but with snake_case converted to PascalCase.
So if the extension name is \"my_extension\", then the extension class name will be \"MyExtension\".
class MyComp(Component):\n class MyExtension: # <--- This is the extension class\n ...\n
To customize the class name, you can manually set the class_name attribute.
The class name must be a valid Python identifier.
Example:
class MyExt(ComponentExtension):\n name = \"my_extension\"\n class_name = \"MyCustomExtension\"\n
This will make the extension class name \"MyCustomExtension\".
class MyComp(Component):\n class MyCustomExtension: # <--- This is the extension class\n ...\n
List of commands that can be run by the extension.
These commands will be available to the user as components ext run <extension> <command>.
Commands are defined as subclasses of ComponentCommand.
Example:
This example defines an extension with a command that prints \"Hello world\". To run the command, the user would run components ext run hello_world hello.
from django_components import ComponentCommand, ComponentExtension, CommandArg, CommandArgGroup\n\nclass HelloWorldCommand(ComponentCommand):\n name = \"hello\"\n help = \"Hello world command.\"\n\n # Allow to pass flags `--foo`, `--bar` and `--baz`.\n # Argument parsing is managed by `argparse`.\n arguments = [\n CommandArg(\n name_or_flags=\"--foo\",\n help=\"Foo description.\",\n ),\n # When printing the command help message, `bar` and `baz`\n # will be grouped under \"group bar\".\n CommandArgGroup(\n title=\"group bar\",\n description=\"Group description.\",\n arguments=[\n CommandArg(\n name_or_flags=\"--bar\",\n help=\"Bar description.\",\n ),\n CommandArg(\n name_or_flags=\"--baz\",\n help=\"Baz description.\",\n ),\n ],\n ),\n ]\n\n # Callback that receives the parsed arguments and options.\n def handle(self, *args, **kwargs):\n print(f\"HelloWorldCommand.handle: args={args}, kwargs={kwargs}\")\n\n# Associate the command with the extension\nclass HelloWorldExtension(ComponentExtension):\n name = \"hello_world\"\n\n commands = [\n HelloWorldCommand,\n ]\n
Name must be lowercase, and must be a valid Python identifier (e.g. \"my_extension\").
The extension may add new features to the Component class by allowing users to define and access a nested class in the Component class.
The extension name determines the name of the nested class in the Component class, and the attribute under which the extension will be accessible.
E.g. if the extension name is \"my_extension\", then the nested class in the Component class will be MyExtension, and the extension will be accessible as MyComp.my_extension.
class MyComp(Component):\n class MyExtension:\n ...\n\n def get_template_data(self, args, kwargs, slots, context):\n return {\n \"my_extension\": self.my_extension.do_something(),\n }\n
Info
The extension class name can be customized by setting the class_name attribute.
This hook is called after the Component class is fully defined but before it's registered.
Use this hook to perform any initialization or validation of the Component class.
Example:
from django_components import ComponentExtension, OnComponentClassCreatedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_class_created(self, ctx: OnComponentClassCreatedContext) -> None:\n # Add a new attribute to the Component class\n ctx.component_cls.my_attr = \"my_value\"\n
This hook is called before the Component class is deleted from memory.
Use this hook to perform any cleanup related to the Component class.
Example:
from django_components import ComponentExtension, OnComponentClassDeletedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_class_deleted(self, ctx: OnComponentClassDeletedContext) -> None:\n # Remove Component class from the extension's cache on deletion\n self.cache.pop(ctx.component_cls, None)\n
Called when a Component was triggered to render, after a component's context and data methods have been processed.
This hook is called after Component.get_template_data(), Component.get_js_data() and Component.get_css_data().
This hook runs after on_component_input.
Use this hook to modify or validate the component's data before rendering.
Example:
from django_components import ComponentExtension, OnComponentDataContext\n\nclass MyExtension(ComponentExtension):\n def on_component_data(self, ctx: OnComponentDataContext) -> None:\n # Add extra template variable to all components when they are rendered\n ctx.template_data[\"my_template_var\"] = \"my_value\"\n
Called when a Component was triggered to render, but before a component's context and data methods are invoked.
Use this hook to modify or validate component inputs before they're processed.
This is the first hook that is called when rendering a component. As such this hook is called before Component.get_template_data(), Component.get_js_data(), and Component.get_css_data() methods, and the on_component_data hook.
This hook also allows to skip the rendering of a component altogether. If the hook returns a non-null value, this value will be used instead of rendering the component.
You can use this to implement a caching mechanism for components, or define components that will be rendered conditionally.
Example:
from django_components import ComponentExtension, OnComponentInputContext\n\nclass MyExtension(ComponentExtension):\n def on_component_input(self, ctx: OnComponentInputContext) -> None:\n # Add extra kwarg to all components when they are rendered\n ctx.kwargs[\"my_input\"] = \"my_value\"\n
Warning
In this hook, the components' inputs are still mutable.
As such, if a component defines Args, Kwargs, Slots types, these types are NOT yet instantiated.
Instead, component fields like Component.args, Component.kwargs, Component.slots are plain list / dict objects.
Called when a Component was rendered, including all its child components.
Use this hook to access or post-process the component's rendered output.
This hook works similarly to Component.on_render_after():
To modify the output, return a new string from this hook. The original output or error will be ignored.
To cause this component to return a new error, raise that error. The original output and error will be ignored.
If you neither raise nor return string, the original output or error will be used.
Examples:
Change the final output of a component:
from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n # Append a comment to the component's rendered output\n return ctx.result + \"<!-- MyExtension comment -->\"\n
Cause the component to raise a new exception:
from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n # Raise a new exception\n raise Exception(\"Error message\")\n
Return nothing (or None) to handle the result as usual:
from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n if ctx.error is not None:\n # The component raised an exception\n print(f\"Error: {ctx.error}\")\n else:\n # The component rendered successfully\n print(f\"Result: {ctx.result}\")\n
This hook is called after a new ComponentRegistry instance is initialized.
Use this hook to perform any initialization needed for the registry.
Example:
from django_components import ComponentExtension, OnRegistryCreatedContext\n\nclass MyExtension(ComponentExtension):\n def on_registry_created(self, ctx: OnRegistryCreatedContext) -> None:\n # Add a new attribute to the registry\n ctx.registry.my_attr = \"my_value\"\n
Use this hook to access or post-process the slot's rendered output.
To modify the output, return a new string from this hook.
Example:
from django_components import ComponentExtension, OnSlotRenderedContext\n\nclass MyExtension(ComponentExtension):\n def on_slot_rendered(self, ctx: OnSlotRenderedContext) -> Optional[str]:\n # Append a comment to the slot's rendered output\n return ctx.result + \"<!-- MyExtension comment -->\"\n
Access slot metadata:
You can access the {% slot %} tag node (SlotNode) and its metadata using ctx.slot_node.
For example, to find the Component class to which belongs the template where the {% slot %} tag is defined, you can use ctx.slot_node.template_component:
Configures whether the component should inherit the media files from the parent component.
If True, the component inherits the media files from the parent component.
If False, the component does not inherit the media files from the parent component.
If a list of components classes, the component inherits the media files ONLY from these specified components.
Read more in Media inheritance section.
Example:
Disable media inheritance:
class ParentComponent(Component):\n class Media:\n js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n class Media:\n extend = False # Don't inherit parent media\n js = [\"script.js\"]\n\nprint(MyComponent.media._js) # [\"script.js\"]\n
Specify which components to inherit from. In this case, the media files are inherited ONLY from the specified components, and NOT from the original parent components:
class ParentComponent(Component):\n class Media:\n js = [\"parent.js\"]\n\nclass MyComponent(ParentComponent):\n class Media:\n # Only inherit from these, ignoring the files from the parent\n extend = [OtherComponent1, OtherComponent2]\n\n js = [\"script.js\"]\n\nprint(MyComponent.media._js) # [\"script.js\", \"other1.js\", \"other2.js\"]\n
A type representing an entry in Media.js or Media.css.
If an entry is a SafeString (or has __html__ method), then entry is assumed to be a formatted HTML tag. Otherwise, it's assumed to be a path to a file.
By default, components behave similarly to Django's {% include %}, and the template inside the component has access to the variables defined in the outer template.
You can selectively isolate a component, using the only flag, so that the inner template can access only the data that was explicitly passed to it:
{% component \"name\" positional_arg keyword_arg=value ... only %}\n
Alternatively, you can set all components to be isolated by default, by setting context_behavior to \"isolated\" in your settings:
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(\"button\")\nregistry.has(\"button\")\n
"},{"location":"reference/api/#django_components.ComponentRegistry--using-registry-to-share-components","title":"Using registry to share components","text":"
You can use component registry for isolating or \"packaging\" components:
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
Deprecated. Will be removed in v1. Use component_vars.slots instead. Note that component_vars.slots no longer escapes the slot names.
Dictonary describing which component slots are filled (True) or are not (False).
New in version 0.70
Use as {{ component_vars.is_filled }}
Example:
{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n <div class=\"slot-wrapper\">\n {% slot \"my_slot\" / %}\n </div>\n{% endif %}\n
This is equivalent to checking if a given key is among the slot fills:
class MyTable(Component):\n def get_template_data(self, args, kwargs, slots, context):\n return {\n \"my_slot_filled\": \"my_slot\" in slots\n }\n
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:
DEPRECATED. Template caching will be removed in v1.
Configure the maximum amount of Django templates to be cached.
Defaults to 128.
Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.
By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding Component.get_template() to render many dynamic templates, you can increase this number.
This setting makes the component fills behave similar to Vue or React, where the fills use EXCLUSIVELY the context variables defined in Component.get_template_data().
Use this class to mark a field on the Component.Defaults class as a factory.
Read more about Component defaults.
Example:
from django_components import Default\n\nclass MyComponent(Component):\n class Defaults:\n # Plain value doesn't need a factory\n position = \"left\"\n # Lists and dicts need to be wrapped in `Default`\n # Otherwise all instances will share the same value\n selected_items = Default(lambda: [1, 2, 3])\n
ExtensionComponentConfig is the base class for all extension component configs.
Extensions can define nested classes on the component class, such as Component.View or Component.Cache:
class MyComp(Component):\n class View:\n def get(self, request):\n ...\n\n class Cache:\n ttl = 60\n
This allows users to configure extension behavior per component.
Behind the scenes, the nested classes that users define on their components are merged with the extension's \"base\" class.
So the example above is the same as:
class MyComp(Component):\n class View(ViewExtension.ComponentConfig):\n def get(self, request):\n ...\n\n class Cache(CacheExtension.ComponentConfig):\n ttl = 60\n
Where both ViewExtension.ComponentConfig and CacheExtension.ComponentConfig are subclasses of ExtensionComponentConfig.
When a Component is instantiated, also the nested extension classes (such as Component.View) are instantiated, receiving the component instance as an argument.
This attribute holds the owner Component instance that this extension is defined on.
This function is what is passed to Django's Library.tag() when registering the tag.
In other words, this method is called by Django's template parser when we encounter a tag that matches this node's tag, e.g. {% component %} or {% slot %}.
To register the tag, you can use BaseNode.register().
This is the signature of the Component.on_render() method if it yields (and thus returns a generator).
When on_render() is a generator then it:
Yields a rendered template (string or None)
Receives back a tuple of (final_output, error).
The final output is the rendered template that now has all its children rendered too. May be None if you yielded None earlier.
The error is None if the rendering was successful. Otherwise the error is set and the output is None.
At the end it may return a new string to override the final rendered output.
Example:
from django_components import Component, OnRenderGenerator\n\nclass MyTable(Component):\n def on_render(\n self,\n context: Context,\n template: Optional[Template],\n ) -> OnRenderGenerator:\n # Do something BEFORE rendering template\n # Same as `Component.on_render_before()`\n context[\"hello\"] = \"world\"\n\n # Yield rendered template to receive fully-rendered template or error\n html, error = yield template.render(context)\n\n # Do something AFTER rendering template, or post-process\n # the rendered template.\n # Same as `Component.on_render_after()`\n return html + \"<p>Hello</p>\"\n
Since the \"child\" component is used within the {% provide %} / {% endprovide %} tags, we can request the \"user_data\" using Component.inject(\"user_data\"):
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n User is: {{ user }}\n </div>\n \"\"\"\n\n def get_template_data(self, args, kwargs, slots, context):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n
Notice that the keys defined on the {% provide %} tag are then accessed as attributes when accessing them with Component.inject().
This function is what is passed to Django's Library.tag() when registering the tag.
In other words, this method is called by Django's template parser when we encounter a tag that matches this node's tag, e.g. {% component %} or {% slot %}.
To register the tag, you can use BaseNode.register().
If the slot was created from a {% fill %} tag, this will be the FillNode instance.
If the slot was a default slot created from a {% component %} tag, this will be the ComponentNode instance.
Otherwise, this will be None.
Extensions can use this info to handle slots differently based on their source.
See Slot metadata.
Example:
You can use this to find the Component in whose template the {% fill %} tag was defined:
class MyTable(Component):\n def get_template_data(self, args, kwargs, slots, context):\n footer_slot = slots.get(\"footer\")\n if footer_slot is not None and footer_slot.fill_node is not None:\n owner_component = footer_slot.fill_node.template_component\n # ...\n
Type representing all forms in which slot content can be passed to a component.
When rendering a component with Component.render() or Component.render_to_response(), the slots may be given a strings, functions, or Slot instances. This type describes that union.
Use this type when typing the slots in your component.
SlotInput accepts an optional type parameter to specify the data dictionary that will be passed to the slot content function.
Any extra kwargs will be considered as slot data, and will be accessible in the {% fill %} tag via fill's data kwarg:
Read more about Slot data.
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
The content between the {% slot %}..{% endslot %} tags is the fallback content that will be rendered if no fill is given for the slot.
This fallback content can then be accessed from within the {% fill %} tag using the fill's fallback kwarg. This is useful if you need to wrap / prepend / append the original slot's content.
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" %}\n This is fallback content!\n {% endslot %}\n </div>\n \"\"\"\n
This function is what is passed to Django's Library.tag() when registering the tag.
In other words, this method is called by Django's template parser when we encounter a tag that matches this node's tag, e.g. {% component %} or {% slot %}.
To register the tag, you can use BaseNode.register().
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.
Raises RuntimeError if the component is not public.
Read more about Component views and URLs.
get_component_url() optionally accepts query and fragment arguments.
Example:
from django_components import Component, get_component_url\n\nclass MyComponent(Component):\n class View:\n public = True\n\n# Get the URL for the component\nurl = get_component_url(\n MyComponent,\n query={\"foo\": \"bar\"},\n fragment=\"baz\",\n)\n# /components/ext/view/components/c1ab2c3?foo=bar#baz\n
The default and global component registry. Use this instance to directly register or remove components:
See Registering components.
# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get single\nregistry.get(\"button\")\n\n# Get all\nregistry.all()\n\n# Check if component is registered\nregistry.has(\"button\")\n\n# Unregister single\nregistry.unregister(\"button\")\n\n# Unregister all\nregistry.clear()\n
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 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.
Here are some examples of how you can use the command:
Creating a Component with Default Settings
To create a component with the default settings, you only need to provide the name of the component:
python manage.py components create my_component\n
This will create a new component named my_component in the components directory of your Django project. The JavaScript, CSS, and template files will be named script.js, style.css, and template.html, respectively.
Creating a Component with Custom Settings
You can also create a component with custom settings by providing additional arguments:
This will create a new component named new_component in the my_components directory. The JavaScript, CSS, and template files will be named my_script.js, my_style.css, and my_template.html, respectively.
Overwriting an Existing Component
If you want to overwrite an existing component, you can use the --force option:
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\".
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\".
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.
Title for the argument group in help output; by default \u201cpositional arguments\u201d if description is provided, otherwise uses title for positional arguments.
Usage information that will be displayed with sub-command help, by default the name of the program and any positional arguments before the subparser argument.
Title for the sub-parser group in help output; by default \u201csubcommands\u201d if description is provided, otherwise uses title for positional arguments.
name type description component_clsType[Component] The created Component class
Available data:
name type description component_clsType[Component] The to-be-deleted Component class
Available data:
name type description componentComponent The Component instance that is being rendered component_clsType[Component] The Component class component_idstr The unique identifier for this component instance context_dataDict Deprecated. Use template_data instead. Will be removed in v1.0. css_dataDict Dictionary of CSS data from Component.get_css_data()js_dataDict Dictionary of JavaScript data from Component.get_js_data()template_dataDict Dictionary of template data from Component.get_template_data()
Available data:
name type description argsList List of positional arguments passed to the component componentComponent The Component instance that received the input and is being rendered component_clsType[Component] The Component class component_idstr The unique identifier for this component instance contextContext The Django template Context object kwargsDict Dictionary of keyword arguments passed to the component slotsDict[str, Slot] Dictionary of slot definitions
Available data:
name type description component_clsType[Component] The registered Component class namestr The name the component was registered under registryComponentRegistry The registry the component was registered to
Available data:
name type description componentComponent The Component instance that is being rendered component_clsType[Component] The Component class component_idstr The unique identifier for this component instance errorOptional[Exception] The error that occurred during rendering, or None if rendering was successful resultOptional[str] The rendered component, or None if rendering failed
Available data:
name type description component_clsType[Component] The unregistered Component class namestr The name the component was registered under registryComponentRegistry The registry the component was unregistered from
Available data:
name type description component_clsType[Component] The Component class whose CSS was loaded contentstr The CSS content (string)
Available data:
name type description component_clsType[Component] The Component class whose JS was loaded contentstr The JS content (string)
Available data:
name type description registryComponentRegistry The created ComponentRegistry instance
Available data:
name type description registryComponentRegistry The to-be-deleted ComponentRegistry instance
Available data:
name type description componentComponent The Component instance that contains the {% slot %} tag component_clsType[Component] The Component class that contains the {% slot %} tag component_idstr The unique identifier for this component instance resultSlotResult The rendered result of the slot slotSlot The Slot instance that was rendered slot_is_defaultbool Whether the slot is default slot_is_requiredbool Whether the slot is required slot_namestr The name of the {% slot %} tag slot_nodeSlotNode The node instance of the {% slot %} tag
Available data:
name type description component_clsType[Component] The Component class whose template was loaded templatedjango.template.base.Template The compiled template object
Available data:
name type description component_clsType[Component] The Component class whose template was loaded contentstr The template string nameOptional[str] The name of the template originOptional[django.template.base.Origin] The origin of the template"},{"location":"reference/extension_hooks/#django_components.extension.ComponentExtension.on_component_class_created","title":"on_component_class_created","text":"
This hook is called after the Component class is fully defined but before it's registered.
Use this hook to perform any initialization or validation of the Component class.
Example:
from django_components import ComponentExtension, OnComponentClassCreatedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_class_created(self, ctx: OnComponentClassCreatedContext) -> None:\n # Add a new attribute to the Component class\n ctx.component_cls.my_attr = \"my_value\"\n
This hook is called before the Component class is deleted from memory.
Use this hook to perform any cleanup related to the Component class.
Example:
from django_components import ComponentExtension, OnComponentClassDeletedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_class_deleted(self, ctx: OnComponentClassDeletedContext) -> None:\n # Remove Component class from the extension's cache on deletion\n self.cache.pop(ctx.component_cls, None)\n
Called when a Component was triggered to render, after a component's context and data methods have been processed.
This hook is called after Component.get_template_data(), Component.get_js_data() and Component.get_css_data().
This hook runs after on_component_input.
Use this hook to modify or validate the component's data before rendering.
Example:
from django_components import ComponentExtension, OnComponentDataContext\n\nclass MyExtension(ComponentExtension):\n def on_component_data(self, ctx: OnComponentDataContext) -> None:\n # Add extra template variable to all components when they are rendered\n ctx.template_data[\"my_template_var\"] = \"my_value\"\n
Called when a Component was triggered to render, but before a component's context and data methods are invoked.
Use this hook to modify or validate component inputs before they're processed.
This is the first hook that is called when rendering a component. As such this hook is called before Component.get_template_data(), Component.get_js_data(), and Component.get_css_data() methods, and the on_component_data hook.
This hook also allows to skip the rendering of a component altogether. If the hook returns a non-null value, this value will be used instead of rendering the component.
You can use this to implement a caching mechanism for components, or define components that will be rendered conditionally.
Example:
from django_components import ComponentExtension, OnComponentInputContext\n\nclass MyExtension(ComponentExtension):\n def on_component_input(self, ctx: OnComponentInputContext) -> None:\n # Add extra kwarg to all components when they are rendered\n ctx.kwargs[\"my_input\"] = \"my_value\"\n
Warning
In this hook, the components' inputs are still mutable.
As such, if a component defines Args, Kwargs, Slots types, these types are NOT yet instantiated.
Instead, component fields like Component.args, Component.kwargs, Component.slots are plain list / dict objects.
Called when a Component was rendered, including all its child components.
Use this hook to access or post-process the component's rendered output.
This hook works similarly to Component.on_render_after():
To modify the output, return a new string from this hook. The original output or error will be ignored.
To cause this component to return a new error, raise that error. The original output and error will be ignored.
If you neither raise nor return string, the original output or error will be used.
Examples:
Change the final output of a component:
from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n # Append a comment to the component's rendered output\n return ctx.result + \"<!-- MyExtension comment -->\"\n
Cause the component to raise a new exception:
from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n # Raise a new exception\n raise Exception(\"Error message\")\n
Return nothing (or None) to handle the result as usual:
from django_components import ComponentExtension, OnComponentRenderedContext\n\nclass MyExtension(ComponentExtension):\n def on_component_rendered(self, ctx: OnComponentRenderedContext) -> Optional[str]:\n if ctx.error is not None:\n # The component raised an exception\n print(f\"Error: {ctx.error}\")\n else:\n # The component rendered successfully\n print(f\"Result: {ctx.result}\")\n
This hook is called after a new ComponentRegistry instance is initialized.
Use this hook to perform any initialization needed for the registry.
Example:
from django_components import ComponentExtension, OnRegistryCreatedContext\n\nclass MyExtension(ComponentExtension):\n def on_registry_created(self, ctx: OnRegistryCreatedContext) -> None:\n # Add a new attribute to the registry\n ctx.registry.my_attr = \"my_value\"\n
Use this hook to access or post-process the slot's rendered output.
To modify the output, return a new string from this hook.
Example:
from django_components import ComponentExtension, OnSlotRenderedContext\n\nclass MyExtension(ComponentExtension):\n def on_slot_rendered(self, ctx: OnSlotRenderedContext) -> Optional[str]:\n # Append a comment to the slot's rendered output\n return ctx.result + \"<!-- MyExtension comment -->\"\n
Access slot metadata:
You can access the {% slot %} tag node (SlotNode) and its metadata using ctx.slot_node.
For example, to find the Component class to which belongs the template where the {% slot %} tag is defined, you can use ctx.slot_node.template_component:
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:
DEPRECATED. Template caching will be removed in v1.
Configure the maximum amount of Django templates to be cached.
Defaults to 128.
Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.
By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding Component.get_template() to render many dynamic templates, you can increase this number.
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.
Marks location where CSS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted into the <head> tag of the HTML.
If the generated HTML does NOT contain any {% component_css_dependencies %} tags, CSS links are by default inserted into the <head> tag of the HTML. (See Default JS / CSS locations)
Note that there should be only one {% component_css_dependencies %} for the whole HTML document. If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.
Marks location where JS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted at the end of the <body> tag of the HTML.
If the generated HTML does NOT contain any {% component_js_dependencies %} tags, JS scripts are by default inserted at the end of the <body> tag of the HTML. (See Default JS / CSS locations)
Note that there should be only one {% component_js_dependencies %} for the whole HTML document. If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.
By default, components behave similarly to Django's {% include %}, and the template inside the component has access to the variables defined in the outer template.
You can selectively isolate a component, using the only flag, so that the inner template can access only the data that was explicitly passed to it:
{% component \"name\" positional_arg keyword_arg=value ... only %}\n
Alternatively, you can set all components to be isolated by default, by setting context_behavior to \"isolated\" in your settings:
Since the \"child\" component is used within the {% provide %} / {% endprovide %} tags, we can request the \"user_data\" using Component.inject(\"user_data\"):
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n User is: {{ user }}\n </div>\n \"\"\"\n\n def get_template_data(self, args, kwargs, slots, context):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n
Notice that the keys defined on the {% provide %} tag are then accessed as attributes when accessing them with Component.inject().
Any extra kwargs will be considered as slot data, and will be accessible in the {% fill %} tag via fill's data kwarg:
Read more about Slot data.
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \"\"\"\n
@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
The content between the {% slot %}..{% endslot %} tags is the fallback content that will be rendered if no fill is given for the slot.
This fallback content can then be accessed from within the {% fill %} tag using the fill's fallback kwarg. This is useful if you need to wrap / prepend / append the original slot's content.
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" %}\n This is fallback content!\n {% endslot %}\n </div>\n \"\"\"\n
Deprecated. Will be removed in v1. Use component_vars.slots instead. Note that component_vars.slots no longer escapes the slot names.
Dictonary describing which component slots are filled (True) or are not (False).
New in version 0.70
Use as {{ component_vars.is_filled }}
Example:
{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n <div class=\"slot-wrapper\">\n {% slot \"my_slot\" / %}\n </div>\n{% endif %}\n
This is equivalent to checking if a given key is among the slot fills:
class MyTable(Component):\n def get_template_data(self, args, kwargs, slots, context):\n return {\n \"my_slot_filled\": \"my_slot\" in slots\n }\n
Decorator for testing components from django-components.
@djc_test manages the global state of django-components, ensuring that each test is properly isolated and that components registered in one test do not affect other tests.
This decorator can be applied to a function, method, or a class. If applied to a class, it will search for all methods that start with test_, and apply the decorator to them. This is applied recursively to nested classes as well.
Examples:
Applying to a function:
from django_components.testing import djc_test\n\n@djc_test\ndef test_my_component():\n @register(\"my_component\")\n class MyComponent(Component):\n template = \"...\"\n ...\n
Applying to a class:
from django_components.testing import djc_test\n\n@djc_test\nclass TestMyComponent:\n def test_something(self):\n ...\n\n class Nested:\n def test_something_else(self):\n ...\n
Applying to a class is the same as applying the decorator to each test_ method individually:
from django_components.testing import djc_test\n\nclass TestMyComponent:\n @djc_test\n def test_something(self):\n ...\n\n class Nested:\n @djc_test\n def test_something_else(self):\n ...\n
django_settings: Django settings, a dictionary passed to Django's @override_settings. The test runs within the context of these overridden settings.
If django_settings contains django-components settings (COMPONENTS field), these are merged. Other Django settings are simply overridden.
components_settings: Instead of defining django-components settings under django_settings[\"COMPONENTS\"], you can simply set the Components settings here.
These settings are merged with the django-components settings from django_settings[\"COMPONENTS\"].
Fields in components_settings override fields in django_settings[\"COMPONENTS\"].
parametrize: Parametrize the test function with pytest.mark.parametrize. This requires pytest to be installed.
You can parametrize the Django or Components settings by setting up parameters called django_settings and components_settings. These will be merged with the respetive settings from the decorator.
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":"