@register.tag("html_attrs")
+def html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode:
+ """
+ This tag takes:
+ - Optional dictionary of attributes (`attrs`)
+ - Optional dictionary of defaults (`defaults`)
+ - Additional kwargs that are appended to the former two
+
+ The inputs are merged and resulting dict is rendered as HTML attributes
+ (`key="value"`).
+
+ Rules:
+ 1. Both `attrs` and `defaults` can be passed as positional args or as kwargs
+ 2. Both `attrs` and `defaults` are optional (can be omitted)
+ 3. Both `attrs` and `defaults` are dictionaries, and we can define them the same way
+ we define dictionaries for the `component` tag. So either as `attrs=attrs` or
+ `attrs:key=value`.
+ 4. All other kwargs (`key=value`) are appended and can be repeated.
+
+ Normal kwargs (`key=value`) are concatenated to existing keys. So if e.g. key
+ "class" is supplied with value "my-class", then adding `class="extra-class"`
+ will result in `class="my-class extra-class".
+
+ Example:
+ ```htmldjango
+ {% html_attrs attrs defaults:class="default-class" class="extra-class" data-id="123" %}
+ ```
+ """
tag = _parse_tag(
"html_attrs",
parser,
- bits,
+ token,
params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],
optional_params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],
flags=[],
diff --git a/dev/search/search_index.json b/dev/search/search_index.json
index 9f17ca09..de309602 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":"
","text":"Docs (Work in progress)
Create simple reusable template components in Django
"},{"location":"#features","title":"Features","text":" - \u2728 Reusable components: Create components that can be reused in different parts of your project, or even in different projects.
- \ud83d\udcc1 Single file components: Keep your Python, CSS, Javascript and HTML in one place (if you wish)
- \ud83c\udfb0 Slots: Define slots in your components to make them more flexible.
- \ud83d\udcbb CLI: A command line interface to help you create new components.
- \ud83d\ude80 Wide compatibility: Works with modern and LTS versions of Django.
- Load assets: Automatically load the right CSS and Javascript files for your components, with our middleware.
"},{"location":"#summary","title":"Summary","text":"It lets you create \"template components\", that contains both the template, the Javascript and the CSS needed to generate the front end code you need for a modern app. Use components like this:
{% component \"calendar\" date=\"2015-06-19\" %}{% endcomponent %}\n
And this is what gets rendered (plus the CSS and Javascript you've specified):
<div class=\"calendar-component\">Today's date is <span>2015-06-19</span></div>\n
See the example project or read on to learn about the details!
"},{"location":"#table-of-contents","title":"Table of Contents","text":" - Release notes
- Security notes \ud83d\udea8
- Installation
- Compatibility
- Create your first component
- Using single-file components
- Use components in templates
- Use components outside of templates
- Registering components
- Use components as views
- Autodiscovery
- Using slots in templates
- Passing data to components
- Rendering HTML attributes
- Template tag syntax
- Prop drilling and dependency injection (provide / inject)
- Component context and scope
- Customizing component tags with TagFormatter
- Defining HTML/JS/CSS files
- Rendering JS/CSS dependencies
- Available settings
- Logging and debugging
- Management Command
- Community examples
- Running django-components project locally
- Development guides
"},{"location":"#release-notes","title":"Release notes","text":"\ud83d\udea8\ud83d\udce2 Version 0.92 - BREAKING CHANGE: Component
class is no longer a subclass of View
. To configure the View
class, set the Component.View
nested class. HTTP methods like get
or post
can still be defined directly on Component
class, and Component.as_view()
internally calls Component.View.as_view()
. (See Modifying the View class)
-
The inputs (args, kwargs, slots, context, ...) that you pass to Component.render()
can be accessed from within get_context_data
, get_template_string
and get_template_name
via self.input
. (See Accessing data passed to the component)
-
Typing: Component
class supports generics that specify types for Component.render
(See Adding type hints with Generics)
Version 0.90 - All tags (component
, slot
, fill
, ...) now support \"self-closing\" or \"inline\" form, where you can omit the closing tag:
{# Before #}\n{% component \"button\" %}{% endcomponent %}\n{# After #}\n{% component \"button\" / %}\n
- All tags now support the \"dictionary key\" or \"aggregate\" syntax (kwarg:key=val
): {% component \"button\" attrs:class=\"hidden\" %}\n
- You can change how the components are written in the template with TagFormatter. The default is `django_components.component_formatter`:\n```django\n{% component \"button\" href=\"...\" disabled %}\n Click me!\n{% endcomponent %}\n```\n\nWhile `django_components.shorthand_component_formatter` allows you to write components like so:\n\n```django\n{% button href=\"...\" disabled %}\n Click me!\n{% endbutton %}\n
\ud83d\udea8\ud83d\udce2 Version 0.85 Autodiscovery module resolution changed. Following undocumented behavior was removed:
- Previously, autodiscovery also imported any
[app]/components.py
files, and used SETTINGS_MODULE
to search for component dirs. - To migrate from:
[app]/components.py
- Define each module in COMPONENTS.libraries
setting, or import each module inside the AppConfig.ready()
hook in respective apps.py
files. SETTINGS_MODULE
- Define component dirs using STATICFILES_DIRS
- Previously, autodiscovery handled relative files in
STATICFILES_DIRS
. To align with Django, STATICFILES_DIRS
now must be full paths (Django docs).
\ud83d\udea8\ud83d\udce2 Version 0.81 Aligned the render_to_response
method with the (now public) render
method of Component
class. Moreover, slots passed to these can now be rendered also as functions.
- BREAKING CHANGE: The order of arguments to
render_to_response
has changed.
Version 0.80 introduces dependency injection with the {% provide %}
tag and inject()
method.
\ud83d\udea8\ud83d\udce2 Version 0.79
- BREAKING CHANGE: Default value for the
COMPONENTS.context_behavior
setting was changes from \"isolated\"
to \"django\"
. If you did not set this value explicitly before, this may be a breaking change. See the rationale for change here.
\ud83d\udea8\ud83d\udce2 Version 0.77 CHANGED the syntax for accessing default slot content.
- Previously, the syntax was
{% fill \"my_slot\" as \"alias\" %}
and {{ alias.default }}
. - Now, the syntax is
{% fill \"my_slot\" default=\"alias\" %}
and {{ alias }}
.
Version 0.74 introduces html_attrs
tag and prefix:key=val
construct for passing dicts to components.
\ud83d\udea8\ud83d\udce2 Version 0.70
{% if_filled \"my_slot\" %}
tags were replaced with {{ component_vars.is_filled.my_slot }}
variables. - Simplified settings -
slot_context_behavior
and context_behavior
were merged. See the documentation for more details.
Version 0.67 CHANGED the default way how context variables are resolved in slots. See the documentation for more details.
\ud83d\udea8\ud83d\udce2 Version 0.5 CHANGES THE SYNTAX for components. component_block
is now component
, and component
blocks need an ending endcomponent
tag. The new python manage.py upgradecomponent
command can be used to upgrade a directory (use --path argument to point to each dir) of templates that use components to the new syntax automatically.
This change is done to simplify the API in anticipation of a 1.0 release of django_components. After 1.0 we intend to be stricter with big changes like this in point releases.
Version 0.34 adds components as views, which allows you to handle requests and render responses from within a component. See the documentation for more details.
Version 0.28 introduces 'implicit' slot filling and the default
option for slot
tags.
Version 0.27 adds a second installable app: django_components.safer_staticfiles. It provides the same behavior as django.contrib.staticfiles but with extra security guarantees (more info below in Security Notes).
Version 0.26 changes the syntax for {% slot %}
tags. From now on, we separate defining a slot ({% slot %}
) from filling a slot with content ({% fill %}
). This means you will likely need to change a lot of slot tags to fill. We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice featuPpre to have access to. Hoping that this will feel worth it!
Version 0.22 starts autoimporting all files inside components subdirectores, to simplify setup. An existing project might start to get AlreadyRegistered-errors because of this. To solve this, either remove your custom loading of components, or set \"autodiscover\": False in settings.COMPONENTS.
Version 0.17 renames Component.context
and Component.template
to get_context_data
and get_template_name
. The old methods still work, but emit a deprecation warning. This change was done to sync naming with Django's class based views, and make using django-components more familiar to Django users. Component.context
and Component.template
will be removed when version 1.0 is released.
"},{"location":"#security-notes","title":"Security notes \ud83d\udea8","text":"You are advised to read this section before using django-components in production.
"},{"location":"#static-files","title":"Static files","text":"Components can be organized however you prefer. That said, our prefered way is to keep the files of a component close together by bundling them in the same directory. This means that files containing backend logic, such as Python modules and HTML templates, live in the same directory as static files, e.g. JS and CSS.
If your are using django.contrib.staticfiles to collect static files, no distinction is 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.
As of v0.27, django-components ships with an additional installable app django_components.safer_staticfiles. It is a drop-in replacement for django.contrib.staticfiles. Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server. To use it, add it to INSTALLED_APPS and remove django.contrib.staticfiles.
INSTALLED_APPS = [\n # 'django.contrib.staticfiles', # <-- REMOVE\n 'django_components',\n 'django_components.safer_staticfiles' # <-- ADD\n]\n
If you are on an older version of django-components, your alternatives are a) passing --ignore <pattern>
options to the collecstatic CLI command, or b) defining a subclass of StaticFilesConfig. Both routes are described in the official docs of the staticfiles app.
Note that safer_staticfiles
excludes the .py
and .html
files for collectstatic command:
python manage.py collectstatic\n
but it is ignored on the development server:
python manage.py runserver\n
For a step-by-step guide on deploying production server with static files, see the demo project.
"},{"location":"#installation","title":"Installation","text":" - Install the app into your environment:
pip install django_components
- Then add the app into
INSTALLED_APPS
in settings.py
INSTALLED_APPS = [\n ...,\n 'django_components',\n]\n
- Ensure that
BASE_DIR
setting is defined in settings.py:
BASE_DIR = Path(__file__).resolve().parent.parent\n
-
Modify TEMPLATES
section of settings.py as follows:
-
Remove 'APP_DIRS': True,
- Add
loaders
to OPTIONS
list and set it to following value:
TEMPLATES = [\n {\n ...,\n 'OPTIONS': {\n 'context_processors': [\n ...\n ],\n 'loaders':[(\n 'django.template.loaders.cached.Loader', [\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n 'django_components.template_loader.Loader',\n ]\n )],\n },\n },\n]\n
- Modify
STATICFILES_DIRS
(or add it if you don't have it) so django can find your static JS and CSS files:
STATICFILES_DIRS = [\n ...,\n os.path.join(BASE_DIR, \"components\"),\n]\n
If STATICFILES_DIRS
is omitted or empty, django-components will by default look for {BASE_DIR}/components
NOTE: The paths in STATICFILES_DIRS
must be full paths. See Django docs.
"},{"location":"#optional","title":"Optional","text":"To avoid loading the app in each template using {% load component_tags %}
, you can add the tag as a 'builtin' in settings.py
TEMPLATES = [\n {\n ...,\n 'OPTIONS': {\n 'context_processors': [\n ...\n ],\n 'builtins': [\n 'django_components.templatetags.component_tags',\n ]\n },\n },\n]\n
Read on to find out how to build your first component!
"},{"location":"#compatibility","title":"Compatibility","text":"Django-components supports all supported combinations versions of Django and Python.
Python version Django version 3.8 4.2 3.9 4.2 3.10 4.2, 5.0 3.11 4.2, 5.0 3.12 4.2, 5.0"},{"location":"#create-your-first-component","title":"Create your first component","text":"A component in django-components is the combination of four things: CSS, Javascript, a Django template, and some Python code to put them all together.
sampleproject/\n \u251c\u2500\u2500 calendarapp/\n \u251c\u2500\u2500 components/ \ud83c\udd95\n \u2502 \u2514\u2500\u2500 calendar/ \ud83c\udd95\n \u2502 \u251c\u2500\u2500 calendar.py \ud83c\udd95\n \u2502 \u251c\u2500\u2500 script.js \ud83c\udd95\n \u2502 \u251c\u2500\u2500 style.css \ud83c\udd95\n \u2502 \u2514\u2500\u2500 template.html \ud83c\udd95\n \u251c\u2500\u2500 sampleproject/\n \u251c\u2500\u2500 manage.py\n \u2514\u2500\u2500 requirements.txt\n
Start by creating empty files in the structure above.
First, you need a CSS file. Be sure to prefix all rules with a unique class so they don't clash with other rules.
[project root]/components/calendar/style.css/* In a file called [project root]/components/calendar/style.css */\n.calendar-component {\n width: 200px;\n background: pink;\n}\n.calendar-component span {\n font-weight: bold;\n}\n
Then you need a javascript file that specifies how you interact with this component. You are free to use any javascript framework you want. A good way to make sure this component doesn't clash with other components is to define all code inside an anonymous function that calls itself. This makes all variables defined only be defined inside this component and not affect other components.
[project root]/components/calendar/script.js/* In a file called [project root]/components/calendar/script.js */\n(function () {\n if (document.querySelector(\".calendar-component\")) {\n document.querySelector(\".calendar-component\").onclick = function () {\n alert(\"Clicked calendar!\");\n };\n }\n})();\n
Now you need a Django template for your component. Feel free to define more variables like date
in this example. When creating an instance of this component we will send in the values for these variables. The template will be rendered with whatever template backend you've specified in your Django settings file.
[project root]/components/calendar/calendar.html{# In a file called [project root]/components/calendar/template.html #}\n<div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n
Finally, we use django-components to tie this together. Start by creating a file called calendar.py
in your component calendar directory. It will be auto-detected and loaded by the app.
Inside this file we create a Component by inheriting from the Component class and specifying the context method. We also register the global component registry so that we easily can render it anywhere in our templates.
[project root]/components/calendar/calendar.py# In a file called [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n # Templates inside `[your apps]/components` dir and `[project root]/components` dir\n # will be automatically found. To customize which template to use based on context\n # you can override method `get_template_name` instead of specifying `template_name`.\n #\n # `template_name` can be relative to dir where `calendar.py` is, or relative to STATICFILES_DIRS\n template_name = \"template.html\"\n\n # This component takes one parameter, a date string to show in the template\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n\n # Both `css` and `js` can be relative to dir where `calendar.py` is, or relative to STATICFILES_DIRS\n class Media:\n css = \"style.css\"\n js = \"script.js\"\n
And voil\u00e1!! We've created our first component.
"},{"location":"#using-single-file-components","title":"Using single-file components","text":"Components can also be defined in a single file, which is useful for small components. To do this, you can use the template
, js
, and css
class attributes instead of the template_name
and Media
. For example, here's the calendar component from above, defined in a single file:
[project root]/components/calendar.py# In a file called [project root]/components/calendar.py\nfrom django_components import Component, register, types\n\n@register(\"calendar\")\nclass Calendar(Component):\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n\n template: types.django_html = \"\"\"\n <div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n \"\"\"\n\n css: types.css = \"\"\"\n .calendar-component { width: 200px; background: pink; }\n .calendar-component span { font-weight: bold; }\n \"\"\"\n\n js: types.js = \"\"\"\n (function(){\n if (document.querySelector(\".calendar-component\")) {\n document.querySelector(\".calendar-component\").onclick = function(){ alert(\"Clicked calendar!\"); };\n }\n })()\n \"\"\"\n
This makes it easy to create small components without having to create a separate template, CSS, and JS file.
"},{"location":"#syntax-highlight-and-code-assistance","title":"Syntax highlight and code assistance","text":""},{"location":"#vscode","title":"VSCode","text":"Note, in the above example, that the t.django_html
, t.css
, and t.js
types are used to specify the type of the template, CSS, and JS files, respectively. This is not necessary, but if you're using VSCode with the Python Inline Source Syntax Highlighting extension, it will give you syntax highlighting for the template, CSS, and JS.
"},{"location":"#pycharm-or-other-jetbrains-ides","title":"Pycharm (or other Jetbrains IDEs)","text":"If you're a Pycharm user (or any other editor from Jetbrains), you can have coding assistance as well:
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n\n # language=HTML\n template= \"\"\"\n <div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n \"\"\"\n\n # language=CSS\n css = \"\"\"\n .calendar-component { width: 200px; background: pink; }\n .calendar-component span { font-weight: bold; }\n \"\"\"\n\n # language=JS\n js = \"\"\"\n (function(){\n if (document.querySelector(\".calendar-component\")) {\n document.querySelector(\".calendar-component\").onclick = function(){ alert(\"Clicked calendar!\"); };\n }\n })()\n \"\"\"\n
You don't need to use types.django_html
, types.css
, types.js
since Pycharm uses language injections. You only need to write the comments # language=<lang>
above the variables.
"},{"location":"#use-components-in-templates","title":"Use components in templates","text":"First load the component_tags
tag library, then use the component_[js/css]_dependencies
and component
tags to render the component to the page.
{% load component_tags %}\n<!DOCTYPE html>\n<html>\n<head>\n <title>My example calendar</title>\n {% component_css_dependencies %}\n</head>\n<body>\n {% component \"calendar\" date=\"2015-06-19\" %}{% endcomponent %}\n {% component_js_dependencies %}\n</body>\n<html>\n
NOTE: Instead of writing {% endcomponent %}
at the end, you can use a self-closing tag:
{% component \"calendar\" date=\"2015-06-19\" / %}
The output from the above template will be:
<!DOCTYPE html>\n<html>\n <head>\n <title>My example calendar</title>\n <link\n href=\"/static/calendar/style.css\"\n type=\"text/css\"\n media=\"all\"\n rel=\"stylesheet\"\n />\n </head>\n <body>\n <div class=\"calendar-component\">\n Today's date is <span>2015-06-19</span>\n </div>\n <script src=\"/static/calendar/script.js\"></script>\n </body>\n <html></html>\n</html>\n
This makes it possible to organize your front-end around reusable components. Instead of relying on template tags and keeping your CSS and Javascript in the static directory.
"},{"location":"#use-components-outside-of-templates","title":"Use components outside of templates","text":"New in version 0.81
Components can be rendered outside of Django templates, calling them as regular functions (\"React-style\").
The component class defines render
and render_to_response
class methods. These methods accept positional args, kwargs, and slots, offering the same flexibility as the {% component %}
tag:
class SimpleComponent(Component):\n template = \"\"\"\n {% load component_tags %}\n hello: {{ hello }}\n foo: {{ foo }}\n kwargs: {{ kwargs|safe }}\n slot_first: {% slot \"first\" required / %}\n \"\"\"\n\n def get_context_data(self, arg1, arg2, **kwargs):\n return {\n \"hello\": arg1,\n \"foo\": arg2,\n \"kwargs\": kwargs,\n }\n\nrendered = SimpleComponent.render(\n args=[\"world\", \"bar\"],\n kwargs={\"kw1\": \"test\", \"kw2\": \"ooo\"},\n slots={\"first\": \"FIRST_SLOT\"},\n context={\"from_context\": 98},\n)\n
Renders:
hello: world\nfoo: bar\nkwargs: {'kw1': 'test', 'kw2': 'ooo'}\nslot_first: FIRST_SLOT\n
"},{"location":"#inputs-of-render-and-render_to_response","title":"Inputs of render
and render_to_response
","text":"Both render
and render_to_response
accept the same input:
Component.render(\n context: Mapping | django.template.Context | None = None,\n args: List[Any] | None = None,\n kwargs: Dict[str, Any] | None = None,\n slots: Dict[str, str | SafeString | SlotFunc] | None = None,\n escape_slots_content: bool = True\n) -> str:\n
-
args
- Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %}
-
kwargs
- Keyword args for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %}
-
slots
- Component slot fills. This is the same as pasing {% fill %}
tags to the component. Accepts a dictionary of { slot_name: slot_content }
where slot_content
can be a string or SlotFunc
.
-
escape_slots_content
- Whether the content from slots
should be escaped. True
by default to prevent XSS attacks. If you disable escaping, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.
-
context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template.
- NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs.
"},{"location":"#slotfunc","title":"SlotFunc
","text":"When rendering components with slots in render
or render_to_response
, you can pass either a string or a function.
The function has following signature:
def render_func(\n context: Context,\n data: Dict[str, Any],\n slot_ref: SlotRef,\n) -> str | SafeString:\n return nodelist.render(ctx)\n
context
- Django's Context available to the Slot Node. data
- Data passed to the {% slot %}
tag. See Scoped Slots. slot_ref
- The default slot content. See Accessing original content of slots. - NOTE: The slot is lazily evaluated. To render the slot, convert it to string with
str(slot_ref)
.
Example:
def footer_slot(ctx, data, slot_ref):\n return f\"\"\"\n SLOT_DATA: {data['abc']}\n ORIGINAL: {slot_ref}\n \"\"\"\n\nMyComponent.render_to_response(\n slots={\n \"footer\": footer_slot,\n },\n)\n
"},{"location":"#adding-type-hints-with-generics","title":"Adding type hints with Generics","text":"The Component
class optionally accepts type parameters that allow you to specify the types of args, kwargs, slots, and data.
from typing import NotRequired, Tuple, TypedDict, SlotFunc\n\n# Positional inputs - Tuple\nArgs = Tuple[int, str]\n\n# Kwargs inputs - Mapping\nclass Kwargs(TypedDict):\n variable: str\n another: int\n maybe_var: NotRequired[int]\n\n# Data returned from `get_context_data` - Mapping\nclass Data(TypedDict):\n variable: str\n\n# The data available to the `my_slot` scoped slot\nclass MySlotData(TypedDict):\n value: int\n\n# Slot functions - Mapping\nclass Slots(TypedDict):\n # Use SlotFunc for slot functions.\n # The generic specifies the `data` dictionary\n my_slot: NotRequired[SlotFunc[MySlotData]]\n\nclass Button(Component[Args, Kwargs, Data, Slots]):\n def get_context_data(self, variable, another):\n return {\n \"variable\": variable,\n }\n
When you then call Component.render
or Component.render_to_response
, you will get type hints:
Button.render(\n # Error: First arg must be `int`, got `float`\n args=(1.25, \"abc\"),\n # Error: Key \"another\" is missing\n kwargs={\n \"variable\": \"text\",\n },\n)\n
"},{"location":"#response-class-of-render_to_response","title":"Response class of render_to_response
","text":"While render
method returns a plain string, render_to_response
wraps the rendered content in a \"Response\" class. By default, this is django.http.HttpResponse
.
If you want to use a different Response class in render_to_response
, set the Component.response_class
attribute:
class MyResponse(HttpResponse):\n def __init__(self, *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n # Configure response\n self.headers = ...\n self.status = ...\n\nclass SimpleComponent(Component):\n response_class = MyResponse\n template: types.django_html = \"HELLO\"\n\nresponse = SimpleComponent.render_to_response()\nassert isinstance(response, MyResponse)\n
"},{"location":"#use-components-as-views","title":"Use components as views","text":"New in version 0.34
Note: Since 0.92, Component no longer subclasses View. To configure the View class, set the nested Component.View
class
Components can now be used as views: - Components define the Component.as_view()
class method that can be used the same as View.as_view()
.
-
By default, you can define GET, POST or other HTTP handlers directly on the Component, same as you do with View. For example, you can override get
and post
to handle GET and POST requests, respectively.
-
In addition, Component
now has a render_to_response
method that renders the component template based on the provided context and slots' data and returns an HttpResponse
object.
"},{"location":"#component-as-view-example","title":"Component as view example","text":"Here's an example of a calendar component defined as a view:
# In a file called [project root]/components/calendar.py\nfrom django_components import Component, ComponentView, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n\n template = \"\"\"\n <div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" / %}\n </div>\n <div class=\"body\">\n Today's date is <span>{{ date }}</span>\n </div>\n </div>\n \"\"\"\n\n # Handle GET requests\n def get(self, request, *args, **kwargs):\n context = {\n \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n }\n slots = {\n \"header\": \"Calendar header\",\n }\n # Return HttpResponse with the rendered content\n return self.render_to_response(\n context=context,\n slots=slots,\n )\n
Then, to use this component as a view, you should create a urls.py
file in your components directory, and add a path to the component's view:
# In a file called [project root]/components/urls.py\nfrom django.urls import path\nfrom components.calendar.calendar import Calendar\n\nurlpatterns = [\n path(\"calendar/\", Calendar.as_view()),\n]\n
Component.as_view()
is a shorthand for calling View.as_view()
and passing the component instance as one of the arguments.
Remember to add __init__.py
to your components directory, so that Django can find the urls.py
file.
Finally, include the component's urls in your project's urls.py
file:
# In a file called [project root]/urls.py\nfrom django.urls import include, path\n\nurlpatterns = [\n path(\"components/\", include(\"components.urls\")),\n]\n
Note: Slots content are automatically escaped by default to prevent XSS attacks. To disable escaping, set escape_slots_content=False
in the render_to_response
method. If you do so, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.
If you're planning on passing an HTML string, check Django's use of format_html
and mark_safe
.
"},{"location":"#modifying-the-view-class","title":"Modifying the View class","text":"The View class that handles the requests is defined on Component.View
.
When you define a GET or POST handlers on the Component
class, like so:
class MyComponent(Component):\n def get(self, request, *args, **kwargs):\n return self.render_to_response(\n context={\n \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n },\n )\n\n def post(self, request, *args, **kwargs) -> HttpResponse:\n variable = request.POST.get(\"variable\")\n return self.render_to_response(\n kwargs={\"variable\": variable}\n )\n
Then the request is still handled by Component.View.get()
or Component.View.post()
methods. However, by default, Component.View.get()
points to Component.get()
, and so on.
class ComponentView(View):\n component: Component = None\n ...\n\n def get(self, request, *args, **kwargs):\n return self.component.get(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n return self.component.post(request, *args, **kwargs)\n\n ...\n
If you want to define your own View
class, you need to: 1. Set the class as Component.View
2. Subclass from ComponentView
, so the View instance has access to the component class.
In the example below, we added extra logic into View.setup()
.
Note that the POST handler is still defined at the top. This is because View
subclasses ComponentView
, which defines the post()
method that calls Component.post()
.
If you were to overwrite the View.post()
method, then Component.post()
would be ignored.
from django_components import Component, ComponentView\n\nclass MyComponent(Component):\n\n def post(self, request, *args, **kwargs) -> HttpResponse:\n variable = request.POST.get(\"variable\")\n return self.component.render_to_response(\n kwargs={\"variable\": variable}\n )\n\n class View(ComponentView):\n def setup(self, request, *args, **kwargs):\n super(request, *args, **kwargs)\n\n do_something_extra(request, *args, **kwargs)\n
"},{"location":"#registering-components","title":"Registering components","text":"In previous examples you could repeatedly see us using @register()
to \"register\" the components. In this section we dive deeper into what it actually means and how you can manage (add or remove) components.
As a reminder, we may have a component like this:
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"template.html\"\n\n # This component takes one parameter, a date string to show in the template\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n
which we then render in the template as:
{% component \"calendar\" date=\"1970-01-01\" %}\n{% endcomponent %}\n
As you can see, @register
links up the component class with the {% component %}
template tag. So when the template tag comes across a component called \"calendar\"
, it can look up it's class and instantiate it.
"},{"location":"#what-is-componentregistry","title":"What is ComponentRegistry","text":"The @register
decorator is a shortcut for working with the ComponentRegistry
.
ComponentRegistry
manages which components can be used in the template tags.
Each ComponentRegistry
instance is associated with an instance of Django's Library
. And Libraries are inserted into Django template using the {% load %}
tags.
The @register
decorator accepts an optional kwarg registry
, which specifies, the ComponentRegistry
to register components into. If omitted, the default ComponentRegistry
instance defined in django_components is used.
my_registry = ComponentRegistry()\n\n@register(registry=my_registry)\nclass MyComponent(Component):\n ...\n
The default ComponentRegistry
is associated with the Library
that you load when you call {% load component_tags %}
inside your template, or when you add django_components.templatetags.component_tags
to the template builtins.
So when you register or unregister a component to/from a component registry, then behind the scenes the registry automatically adds/removes the component's template tags to/from the Library, so you can call the component from within the templates such as {% component \"my_comp\" %}
.
"},{"location":"#working-with-componentregistry","title":"Working with ComponentRegistry","text":"The default ComponentRegistry
instance can be imported as:
from django_components import registry\n
You can use the registry to manually add/remove/get components:
from django_components import registry\n\n# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get all or single\nregistry.all() # {\"button\": ButtonComponent, \"card\": CardComponent}\nregistry.get(\"card\") # CardComponent\n\n# Unregister single component\nregistry.unregister(\"card\")\n\n# Unregister all components\nregistry.clear()\n
"},{"location":"#registering-components-to-custom-componentregistry","title":"Registering components to custom ComponentRegistry","text":"In rare cases, you may want to manage your own instance of ComponentRegistry
, or register components onto a different Library
instance than the default one.
The Library
instance can be set at instantiation of ComponentRegistry
. If omitted, then the default Library instance from django_components is used.
from django.template import Library\nfrom django_components import ComponentRegistry\n\nmy_library = Library(...)\nmy_registry = ComponentRegistry(library=my_library)\n
When you have defined your own ComponentRegistry
, you can either register the components with my_registry.register()
, or pass the registry to the @component.register()
decorator via the registry
kwarg:
from path.to.my.registry import my_registry\n\n@register(\"my_component\", registry=my_registry)\nclass MyComponent(Component):\n ...\n
NOTE: The Library instance can be accessed under library
attribute of ComponentRegistry
.
"},{"location":"#autodiscovery","title":"Autodiscovery","text":"Every component that you want to use in the template with the {% component %}
tag needs to be registered with the ComponentRegistry. Normally, we use the @register
decorator for that:
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n ...\n
But for the component to be registered, the code needs to be executed - the file needs to be imported as a module.
One way to do that is by importing all your components in apps.py
:
from django.apps import AppConfig\n\nclass MyAppConfig(AppConfig):\n name = \"my_app\"\n\n def ready(self) -> None:\n from components.card.card import Card\n from components.list.list import List\n from components.menu.menu import Menu\n from components.button.button import Button\n ...\n
However, there's a simpler way!
By default, the Python files in the STATICFILES_DIRS
directories are auto-imported in order to auto-register the components.
Autodiscovery occurs when Django is loaded, during the ready
hook of the apps.py
file.
If you are using autodiscovery, keep a few points in mind:
- Avoid defining any logic on the module-level inside the
components
dir, that you would not want to run anyway. - Components inside the auto-imported files still need to be registered with
@register()
- Auto-imported component files must be valid Python modules, they must use suffix
.py
, and module name should follow PEP-8.
Autodiscovery can be disabled in the settings.
"},{"location":"#manually-trigger-autodiscovery","title":"Manually trigger autodiscovery","text":"Autodiscovery can be also triggered manually as a function call. This is useful if you want to run autodiscovery at a custom point of the lifecycle:
from django_components import autodiscover\n\nautodiscover()\n
"},{"location":"#using-slots-in-templates","title":"Using slots in templates","text":"New in version 0.26:
- The
slot
tag now serves only to declare new slots inside the component template. - To override the content of a declared slot, use the newly introduced
fill
tag instead. - Whereas unfilled slots used to raise a warning, filling a slot is now optional by default.
- To indicate that a slot must be filled, the new
required
option should be added at the end of the slot
tag.
Components support something called 'slots'. When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content. This mechanism makes components more reusable and composable. This behavior is similar to slots in Vue.
In the example below we introduce two block tags that work hand in hand to make this work. These are...
{% slot <name> %}
/{% endslot %}
: Declares a new slot in the component template. {% fill <name> %}
/{% endfill %}
: (Used inside a component
tag pair.) Fills a declared slot with the specified content.
Let's update our calendar component to support more customization. We'll add slot
tag pairs to its template, template.html.
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" %}Calendar header{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"body\" %}Today's date is <span>{{ date }}</span>{% endslot %}\n </div>\n</div>\n
When using the component, you specify which slots you want to fill and where you want to use the defaults from the template. It looks like this:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"body\" %}Can you believe it's already <span>{{ date }}</span>??{% endfill %}\n{% endcomponent %}\n
Since the 'header' fill is unspecified, it's taken from the base template. If you put this in a template, and pass in date=2020-06-06
, this is what gets rendered:
<div class=\"calendar-component\">\n <div class=\"header\">\n Calendar header\n </div>\n <div class=\"body\">\n Can you believe it's already <span>2020-06-06</span>??\n </div>\n</div>\n
"},{"location":"#default-slot","title":"Default slot","text":"Added in version 0.28
As you can see, component slots lets you write reusable containers that you fill in when you use a component. This makes for highly reusable components that can be used in different circumstances.
It can become tedious to use fill
tags everywhere, especially when you're using a component that declares only one slot. To make things easier, slot
tags can be marked with an optional keyword: default
. When added to the end of the tag (as shown below), this option lets you pass filling content directly in the body of a component
tag pair \u2013 without using a fill
tag. Choose carefully, though: a component template may contain at most one slot that is marked as default
. The default
option can be combined with other slot options, e.g. required
.
Here's the same example as before, except with default slots and implicit filling.
The template:
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" %}Calendar header{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"body\" default %}Today's date is <span>{{ date }}</span>{% endslot %}\n </div>\n</div>\n
Including the component (notice how the fill
tag is omitted):
{% component \"calendar\" date=\"2020-06-06\" %}\n Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n
The rendered result (exactly the same as before):
<div class=\"calendar-component\">\n <div class=\"header\">Calendar header</div>\n <div class=\"body\">Can you believe it's already <span>2020-06-06</span>??</div>\n</div>\n
You may be tempted to combine implicit fills with explicit fill
tags. This will not work. The following component template will raise an error when compiled.
{# DON'T DO THIS #}\n{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}Totally new header!{% endfill %}\n Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n
By contrast, it is permitted to use fill
tags in nested components, e.g.:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% component \"beautiful-box\" %}\n {% fill \"content\" %} Can you believe it's already <span>{{ date }}</span>?? {% endfill %}\n {% endcomponent %}\n{% endcomponent %}\n
This is fine too:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}\n {% component \"calendar-header\" %}\n Super Special Calendar Header\n {% endcomponent %}\n {% endfill %}\n{% endcomponent %}\n
"},{"location":"#render-fill-in-multiple-places","title":"Render fill in multiple places","text":"Added in version 0.70
You can render the same content in multiple places by defining multiple slots with identical names:
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"image\" %}Image here{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"image\" %}Image here{% endslot %}\n </div>\n</div>\n
So if used like:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"image\" %}\n <img src=\"...\" />\n {% endfill %}\n{% endcomponent %}\n
This renders:
<div class=\"calendar-component\">\n <div class=\"header\">\n <img src=\"...\" />\n </div>\n <div class=\"body\">\n <img src=\"...\" />\n </div>\n</div>\n
"},{"location":"#default-and-required-slots","title":"Default and required slots","text":"If you use a slot multiple times, you can still mark the slot as default
or required
. For that, you must mark ONLY ONE of the identical slots.
We recommend to mark the first occurence for consistency, e.g.:
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"image\" default required %}Image here{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"image\" %}Image here{% endslot %}\n </div>\n</div>\n
Which you can then use are regular default slot:
{% component \"calendar\" date=\"2020-06-06\" %}\n <img src=\"...\" />\n{% endcomponent %}\n
"},{"location":"#accessing-original-content-of-slots","title":"Accessing original content of slots","text":"Added in version 0.26
NOTE: In version 0.77, the syntax was changed from
{% fill \"my_slot\" as \"alias\" %} {{ alias.default }}\n
to
{% fill \"my_slot\" default=\"slot_default\" %} {{ slot_default }}\n
Sometimes you may want to keep the original slot, but only wrap or prepend/append content to it. To do so, you can access the default slot via the default
kwarg.
Similarly to the data
attribute, you specify the variable name through which the default slot will be made available.
For instance, let's say you're filling a slot called 'body'. To render the original slot, assign it to a variable using the 'default'
keyword. You then render this variable to insert the default content:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"body\" default=\"body_default\" %}\n {{ body_default }}. Have a great day!\n {% endfill %}\n{% endcomponent %}\n
This produces:
<div class=\"calendar-component\">\n <div class=\"header\">\n Calendar header\n </div>\n <div class=\"body\">\n Today's date is <span>2020-06-06</span>. Have a great day!\n </div>\n</div>\n
"},{"location":"#conditional-slots","title":"Conditional slots","text":"Added in version 0.26.
NOTE: In version 0.70, {% if_filled %}
tags were replaced with {{ component_vars.is_filled }}
variables. If your slot name contained special characters, see the section \"Accessing slot names with special characters\".
In certain circumstances, you may want the behavior of slot filling to depend on whether or not a particular slot is filled.
For example, suppose we have the following component template:
<div class=\"frontmatter-component\">\n <div class=\"title\">\n {% slot \"title\" %}Title{% endslot %}\n </div>\n <div class=\"subtitle\">\n {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n </div>\n</div>\n
By default the slot named 'subtitle' is empty. Yet when the component is used without explicit fills, the div containing the slot is still rendered, as shown below:
<div class=\"frontmatter-component\">\n <div class=\"title\">Title</div>\n <div class=\"subtitle\"></div>\n</div>\n
This may not be what you want. What if instead the outer 'subtitle' div should only be included when the inner slot is in fact filled?
The answer is to use the {{ component_vars.is_filled.<name> }}
variable. You can use this together with Django's {% if/elif/else/endif %}
tags to define a block whose contents will be rendered only if the component slot with the corresponding 'name' is filled.
This is what our example looks like with component_vars.is_filled
.
<div class=\"frontmatter-component\">\n <div class=\"title\">\n {% slot \"title\" %}Title{% endslot %}\n </div>\n {% if component_vars.is_filled.subtitle %}\n <div class=\"subtitle\">\n {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n </div>\n {% endif %}\n</div>\n
Here's our example with more complex branching.
<div class=\"frontmatter-component\">\n <div class=\"title\">\n {% slot \"title\" %}Title{% endslot %}\n </div>\n {% if component_vars.is_filled.subtitle %}\n <div class=\"subtitle\">\n {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n </div>\n {% elif component_vars.is_filled.title %}\n ...\n {% elif component_vars.is_filled.<name> %}\n ...\n {% endif %}\n</div>\n
Sometimes you're not interested in whether a slot is filled, but rather that it isn't. To negate the meaning of component_vars.is_filled
, simply treat it as boolean and negate it with not
:
{% if not component_vars.is_filled.subtitle %}\n<div class=\"subtitle\">\n {% slot \"subtitle\" / %}\n</div>\n{% endif %}\n
"},{"location":"#accessing-is_filled-of-slot-names-with-special-characters","title":"Accessing is_filled
of slot names with special characters","text":"To be able to access a slot name via component_vars.is_filled
, the slot name needs to be composed of only alphanumeric characters and underscores (e.g. this__isvalid_123
).
However, you can still define slots with other special characters. In such case, the slot name in component_vars.is_filled
is modified to replace all invalid characters into _
.
So a slot named \"my super-slot :)\"
will be available as component_vars.is_filled.my_super_slot___
.
"},{"location":"#scoped-slots","title":"Scoped slots","text":"Added in version 0.76:
Consider a component with slot(s). This component may do some processing on the inputs, and then use the processed variable in the slot's default template:
@register(\"my_comp\")\nclass MyComp(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" default %}\n input: {{ input }}\n {% endslot %}\n </div>\n \"\"\"\n\n def get_context_data(self, input):\n processed_input = do_something(input)\n return {\"input\": processed_input}\n
You may want to design a component so that users of your component can still access the input
variable, so they don't have to recompute it.
This behavior is called \"scoped slots\". This is inspired by Vue scoped slots and scoped slots of django-web-components.
Using scoped slots consists of two steps:
- Passing data to
slot
tag - Accessing data in
fill
tag
"},{"location":"#passing-data-to-slots","title":"Passing data to slots","text":"To pass the data to the slot
tag, simply pass them as keyword attributes (key=value
):
@register(\"my_comp\")\nclass MyComp(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" default input=input %}\n input: {{ input }}\n {% endslot %}\n </div>\n \"\"\"\n\n def get_context_data(self, input):\n processed_input = do_something(input)\n return {\n \"input\": processed_input,\n }\n
"},{"location":"#accessing-slot-data-in-fill","title":"Accessing slot data in fill","text":"Next, we head over to where we define a fill for this slot. Here, to access the slot data we set the data
attribute to the name of the variable through which we want to access the slot data. In the example below, we set it to data
:
{% component \"my_comp\" %}\n {% fill \"content\" data=\"data\" %}\n {{ data.input }}\n {% endfill %}\n{% endcomponent %}\n
To access slot data on a default slot, you have to explictly define the {% fill %}
tags.
So this works:
{% component \"my_comp\" %}\n {% fill \"content\" data=\"data\" %}\n {{ data.input }}\n {% endfill %}\n{% endcomponent %}\n
While this does not:
{% component \"my_comp\" data=\"data\" %}\n {{ data.input }}\n{% endcomponent %}\n
Note: You cannot set the data
attribute and default
attribute) to the same name. This raises an error:
{% component \"my_comp\" %}\n {% fill \"content\" data=\"slot_var\" default=\"slot_var\" %}\n {{ slot_var.input }}\n {% endfill %}\n{% endcomponent %}\n
"},{"location":"#passing-data-to-components","title":"Passing data to components","text":"As seen above, you can pass arguments to components like so:
<body>\n {% component \"calendar\" date=\"2015-06-19\" %}\n {% endcomponent %}\n</body>\n
"},{"location":"#accessing-data-passed-to-the-component","title":"Accessing data passed to the component","text":"When you call Component.render
or Component.render_to_response
, the inputs to these methods can be accessed from within the instance under self.input
.
This means that you can use self.input
inside: - get_context_data
- get_template_name
- get_template_string
self.input
is defined only for the duration of Component.render
, and returns None
when called outside of this.
self.input
has the same fields as the input to Component.render
:
class TestComponent(Component):\n def get_context_data(self, var1, var2, variable, another, **attrs):\n assert self.input.args == (123, \"str\")\n assert self.input.kwargs == {\"variable\": \"test\", \"another\": 1}\n assert self.input.slots == {\"my_slot\": \"MY_SLOT\"}\n assert isinstance(self.input.context, Context)\n\n return {\n \"variable\": variable,\n }\n\nrendered = TestComponent.render(\n kwargs={\"variable\": \"test\", \"another\": 1},\n args=(123, \"str\"),\n slots={\"my_slot\": \"MY_SLOT\"},\n)\n
"},{"location":"#rendering-html-attributes","title":"Rendering HTML attributes","text":"New in version 0.74:
You can use the html_attrs
tag to render HTML attributes, given a dictionary of values.
So if you have a template:
<div class=\"{{ classes }}\" data-id=\"{{ my_id }}\">\n</div>\n
You can simplify it with html_attrs
tag:
<div {% html_attrs attrs %}>\n</div>\n
where attrs
is:
attrs = {\n \"class\": classes,\n \"data-id\": my_id,\n}\n
This feature is inspired by merge_attrs
tag of django-web-components and \"fallthrough attributes\" feature of Vue.
"},{"location":"#removing-atttributes","title":"Removing atttributes","text":"Attributes that are set to None
or False
are NOT rendered.
So given this input:
attrs = {\n \"class\": \"text-green\",\n \"required\": False,\n \"data-id\": None,\n}\n
And template:
<div {% html_attrs attrs %}>\n</div>\n
Then this renders:
<div class=\"text-green\"></div>\n
"},{"location":"#boolean-attributes","title":"Boolean attributes","text":"In HTML, boolean attributes are usually rendered with no value. Consider the example below where the first button is disabled and the second is not:
<button disabled>Click me!</button> <button>Click me!</button>\n
HTML rendering with html_attrs
tag or attributes_to_string
works the same way, where key=True
is rendered simply as key
, and key=False
is not render at all.
So given this input:
attrs = {\n \"disabled\": True,\n \"autofocus\": False,\n}\n
And template:
<div {% html_attrs attrs %}>\n</div>\n
Then this renders:
<div disabled></div>\n
"},{"location":"#default-attributes","title":"Default attributes","text":"Sometimes you may want to specify default values for attributes. You can pass a second argument (or kwarg defaults
) to set the defaults.
<div {% html_attrs attrs defaults %}>\n ...\n</div>\n
In the example above, if attrs
contains e.g. the class
key, html_attrs
will render:
class=\"{{ attrs.class }}\"
Otherwise, html_attrs
will render:
class=\"{{ defaults.class }}\"
"},{"location":"#appending-attributes","title":"Appending attributes","text":"For the class
HTML attribute, it's common that we want to join multiple values, instead of overriding them. For example, if you're authoring a component, you may want to ensure that the component will ALWAYS have a specific class. Yet, you may want to allow users of your component to supply their own classes.
We can achieve this by adding extra kwargs. These values will be appended, instead of overwriting the previous value.
So if we have a variable attrs
:
attrs = {\n \"class\": \"my-class pa-4\",\n}\n
And on html_attrs
tag, we set the key class
:
<div {% html_attrs attrs class=\"some-class\" %}>\n</div>\n
Then these will be merged and rendered as:
<div data-value=\"my-class pa-4 some-class\"></div>\n
To simplify merging of variables, you can supply the same key multiple times, and these will be all joined together:
{# my_var = \"class-from-var text-red\" #}\n<div {% html_attrs attrs class=\"some-class another-class\" class=my_var %}>\n</div>\n
Renders:
<div\n data-value=\"my-class pa-4 some-class another-class class-from-var text-red\"\n></div>\n
"},{"location":"#rules-for-html_attrs","title":"Rules for html_attrs
","text":" - Both
attrs
and defaults
can be passed as positional args
{% html_attrs attrs defaults key=val %}
or as kwargs
{% html_attrs key=val defaults=defaults attrs=attrs %}
-
Both attrs
and defaults
are optional (can be omitted)
-
Both attrs
and defaults
are dictionaries, and we can define them the same way we define dictionaries for the component
tag. So either as attrs=attrs
or attrs:key=value
.
-
All other kwargs are appended and can be repeated.
"},{"location":"#examples-for-html_attrs","title":"Examples for html_attrs
","text":"Assuming that:
class_from_var = \"from-var\"\n\nattrs = {\n \"class\": \"from-attrs\",\n \"type\": \"submit\",\n}\n\ndefaults = {\n \"class\": \"from-defaults\",\n \"role\": \"button\",\n}\n
Then:
- Empty tag
{% html_attr %}
renders (empty string):
- Only kwargs
{% html_attr class=\"some-class\" class=class_from_var data-id=\"123\" %}
renders: class=\"some-class from-var\" data-id=\"123\"
- Only attrs
{% html_attr attrs %}
renders: class=\"from-attrs\" type=\"submit\"
- Attrs as kwarg
{% html_attr attrs=attrs %}
renders: class=\"from-attrs\" type=\"submit\"
- Only defaults (as kwarg)
{% html_attr defaults=defaults %}
renders: class=\"from-defaults\" role=\"button\"
- Attrs using the
prefix:key=value
construct {% html_attr attrs:class=\"from-attrs\" attrs:type=\"submit\" %}
renders: class=\"from-attrs\" type=\"submit\"
- Defaults using the
prefix:key=value
construct {% html_attr defaults:class=\"from-defaults\" %}
renders: class=\"from-defaults\" role=\"button\"
- All together (1) - attrs and defaults as positional args:
{% html_attrs attrs defaults class=\"added_class\" class=class_from_var data-id=123 %}
renders: class=\"from-attrs added_class from-var\" type=\"submit\" role=\"button\" data-id=123
- All together (2) - attrs and defaults as kwargs args:
{% html_attrs class=\"added_class\" class=class_from_var data-id=123 attrs=attrs defaults=defaults %}
renders: class=\"from-attrs added_class from-var\" type=\"submit\" role=\"button\" data-id=123
- All together (3) - mixed:
{% html_attrs attrs defaults:class=\"default-class\" class=\"added_class\" class=class_from_var data-id=123 %}
renders: class=\"from-attrs added_class from-var\" type=\"submit\" data-id=123
"},{"location":"#full-example-for-html_attrs","title":"Full example for html_attrs
","text":"@register(\"my_comp\")\nclass MyComp(Component):\n template: t.django_html = \"\"\"\n <div\n {% html_attrs attrs\n defaults:class=\"pa-4 text-red\"\n class=\"my-comp-date\"\n class=class_from_var\n data-id=\"123\"\n %}\n >\n Today's date is <span>{{ date }}</span>\n </div>\n \"\"\"\n\n def get_context_data(self, date: Date, attrs: dict):\n return {\n \"date\": date,\n \"attrs\": attrs,\n \"class_from_var\": \"extra-class\"\n }\n\n@register(\"parent\")\nclass Parent(Component):\n template: t.django_html = \"\"\"\n {% component \"my_comp\"\n date=date\n attrs:class=\"pa-0 border-solid border-red\"\n attrs:data-json=json_data\n attrs:@click=\"(e) => onClick(e, 'from_parent')\"\n / %}\n \"\"\"\n\n def get_context_data(self, date: Date):\n return {\n \"date\": datetime.now(),\n \"json_data\": json.dumps({\"value\": 456})\n }\n
Note: For readability, we've split the tags across multiple lines.
Inside MyComp
, we defined a default attribute
defaults:class=\"pa-4 text-red\"
So if attrs
includes key class
, the default above will be ignored.
MyComp
also defines class
key twice. It means that whether the class
attribute is taken from attrs
or defaults
, the two class
values will be appended to it.
So by default, MyComp
renders:
<div class=\"pa-4 text-red my-comp-date extra-class\" data-id=\"123\">...</div>\n
Next, let's consider what will be rendered when we call MyComp
from Parent
component.
MyComp
accepts a attrs
dictionary, that is passed to html_attrs
, so the contents of that dictionary are rendered as the HTML attributes.
In Parent
, we make use of passing dictionary key-value pairs as kwargs to define individual attributes as if they were regular kwargs.
So all kwargs that start with attrs:
will be collected into an attrs
dict.
attrs:class=\"pa-0 border-solid border-red\"\n attrs:data-json=json_data\n attrs:@click=\"(e) => onClick(e, 'from_parent')\"\n
And get_context_data
of MyComp
will receive attrs
input with following keys:
attrs = {\n \"class\": \"pa-0 border-solid\",\n \"data-json\": '{\"value\": 456}',\n \"@click\": \"(e) => onClick(e, 'from_parent')\",\n}\n
attrs[\"class\"]
overrides the default value for class
, whereas other keys will be merged.
So in the end MyComp
will render:
<div\n class=\"pa-0 border-solid my-comp-date extra-class\"\n data-id=\"123\"\n data-json='{\"value\": 456}'\n @click=\"(e) => onClick(e, 'from_parent')\"\n>\n ...\n</div>\n
"},{"location":"#rendering-html-attributes-outside-of-templates","title":"Rendering HTML attributes outside of templates","text":"If you need to use serialize HTML attributes outside of Django template and the html_attrs
tag, you can use attributes_to_string
:
from django_components.attributes import attributes_to_string\n\nattrs = {\n \"class\": \"my-class text-red pa-4\",\n \"data-id\": 123,\n \"required\": True,\n \"disabled\": False,\n \"ignored-attr\": None,\n}\n\nattributes_to_string(attrs)\n# 'class=\"my-class text-red pa-4\" data-id=\"123\" required'\n
"},{"location":"#template-tag-syntax","title":"Template tag syntax","text":"All template tags in django_component, like {% component %}
or {% slot %}
, and so on, support extra syntax that makes it possible to write components like in Vue or React.
"},{"location":"#special-characters","title":"Special characters","text":"New in version 0.71:
Keyword arguments can contain special characters # @ . - _
, so keywords like so are still valid:
<body>\n {% component \"calendar\" my-date=\"2015-06-19\" @click.native=do_something #some_id=True / %}\n</body>\n
These can then be accessed inside get_context_data
so:
@register(\"calendar\")\nclass Calendar(Component):\n # Since # . @ - are not valid identifiers, we have to\n # use `**kwargs` so the method can accept these args.\n def get_context_data(self, **kwargs):\n return {\n \"date\": kwargs[\"my-date\"],\n \"id\": kwargs[\"#some_id\"],\n \"on_click\": kwargs[\"@click.native\"]\n }\n
"},{"location":"#spread-operator","title":"Spread operator","text":"New in version 0.93:
Instead of passing keyword arguments one-by-one:
{% component \"calendar\" title=\"How to abc\" date=\"2015-06-19\" author=\"John Wick\" / %}\n
You can use a spread operator ...dict
to apply key-value pairs from a dictionary:
post_data = {\n \"title\": \"How to...\",\n \"date\": \"2015-06-19\",\n \"author\": \"John Wick\",\n}\n
{% component \"calendar\" ...post_data / %}\n
This behaves similar to JSX's spread operator or Vue's v-bind
.
Spread operators are treated as keyword arguments, which means that: 1. Spread operators must come after positional arguments. 2. You cannot use spread operators for positional-only arguments.
Other than that, you can use spread operators multiple times, and even put keyword arguments in-between or after them:
{% component \"calendar\" ...post_data id=post.id ...extra / %}\n
In a case of conflicts, the values added later (right-most) overwrite previous values.
"},{"location":"#pass-dictonary-by-its-key-value-pairs","title":"Pass dictonary by its key-value pairs","text":"New in version 0.74:
Sometimes, a component may expect a dictionary as one of its inputs.
Most commonly, this happens when a component accepts a dictionary of HTML attributes (usually called attrs
) to pass to the underlying template.
In such cases, we may want to define some HTML attributes statically, and other dynamically. But for that, we need to define this dictionary on Python side:
@register(\"my_comp\")\nclass MyComp(Component):\n template = \"\"\"\n {% component \"other\" attrs=attrs / %}\n \"\"\"\n\n def get_context_data(self, some_id: str):\n attrs = {\n \"class\": \"pa-4 flex\",\n \"data-some-id\": some_id,\n \"@click.stop\": \"onClickHandler\",\n }\n return {\"attrs\": attrs}\n
But as you can see in the case above, the event handler @click.stop
and styling pa-4 flex
are disconnected from the template. If the component grew in size and we moved the HTML to a separate file, we would have hard time reasoning about the component's template.
Luckily, there's a better way.
When we want to pass a dictionary to a component, we can define individual key-value pairs as component kwargs, so we can keep all the relevant information in the template. For that, we prefix the key with the name of the dict and :
. So key class
of input attrs
becomes attrs:class
. And our example becomes:
@register(\"my_comp\")\nclass MyComp(Component):\n template = \"\"\"\n {% component \"other\"\n attrs:class=\"pa-4 flex\"\n attrs:data-some-id=some_id\n attrs:@click.stop=\"onClickHandler\"\n / %}\n \"\"\"\n\n def get_context_data(self, some_id: str):\n return {\"some_id\": some_id}\n
Sweet! Now all the relevant HTML is inside the template, and we can move it to a separate file with confidence:
{% component \"other\"\n attrs:class=\"pa-4 flex\"\n attrs:data-some-id=some_id\n attrs:@click.stop=\"onClickHandler\"\n/ %}\n
Note: It is NOT possible to define nested dictionaries, so attrs:my_key:two=2
would be interpreted as:
{\"attrs\": {\"my_key:two\": 2}}\n
"},{"location":"#prop-drilling-and-dependency-injection-provide-inject","title":"Prop drilling and dependency injection (provide / inject)","text":"New in version 0.80:
Django components supports dependency injection with the combination of:
{% provide %}
tag inject()
method of the Component
class
"},{"location":"#what-is-dependency-injection-and-prop-drilling","title":"What is \"dependency injection\" and \"prop drilling\"?","text":"Prop drilling refers to a scenario in UI development where you need to pass data through many layers of a component tree to reach the nested components that actually need the data.
Normally, you'd use props to send data from a parent component to its children. However, this straightforward method becomes cumbersome and inefficient if the data has to travel through many levels or if several components scattered at different depths all need the same piece of information.
This results in a situation where the intermediate components, which don't need the data for their own functioning, end up having to manage and pass along these props. This clutters the component tree and makes the code verbose and harder to manage.
A neat solution to avoid prop drilling is using the \"provide and inject\" technique, AKA dependency injection.
With dependency injection, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.
This feature is inspired by Vue's Provide / Inject and React's Context / useContext.
"},{"location":"#how-to-use-provide-inject","title":"How to use provide / inject","text":"As the name suggest, using provide / inject consists of 2 steps
- Providing data
- Injecting provided data
For examples of advanced uses of provide / inject, see this discussion.
"},{"location":"#using-provide-tag","title":"Using {% provide %}
tag","text":"First we use the {% provide %}
tag to define the data we want to \"provide\" (make available).
{% provide \"my_data\" key=\"hi\" another=123 %}\n {% component \"child\" / %} <--- Can access \"my_data\"\n{% endprovide %}\n\n{% component \"child\" / %} <--- Cannot access \"my_data\"\n
Notice that the provide
tag REQUIRES a name as a first argument. This is the key by which we can then access the data passed to this tag.
provide
tag key, similarly to the name argument in component
or slot
tags, has these requirements:
- The key must be a string literal
- It must be a valid identifier (AKA a valid Python variable name)
Once you've set the name, you define the data you want to \"provide\" by passing it as keyword arguments. This is similar to how you pass data to the {% with %}
tag.
NOTE: Kwargs passed to {% provide %}
are NOT added to the context. In the example below, the {{ key }}
won't render anything:
{% provide \"my_data\" key=\"hi\" another=123 %}\n {{ key }}\n{% endprovide %}\n
"},{"location":"#using-inject-method","title":"Using inject()
method","text":"To \"inject\" (access) the data defined on the provide
tag, you can use the inject()
method inside of get_context_data()
.
For a component to be able to \"inject\" some data, the component ({% component %}
tag) must be nested inside the {% provide %}
tag.
In the example from previous section, we've defined two kwargs: key=\"hi\" another=123
. That means that if we now inject \"my_data\"
, we get an object with 2 attributes - key
and another
.
class ChildComponent(Component):\n def get_context_data(self):\n my_data = self.inject(\"my_data\")\n print(my_data.key) # hi\n print(my_data.another) # 123\n return {}\n
First argument to inject
is the key of the provided data. This must match the string that you used in the provide
tag. If no provider with given key is found, inject
raises a KeyError
.
To avoid the error, you can pass a second argument to inject
to which will act as a default value, similar to dict.get(key, default)
:
class ChildComponent(Component):\n def get_context_data(self):\n my_data = self.inject(\"invalid_key\", DEFAULT_DATA)\n assert my_data == DEFAUKT_DATA\n return {}\n
The instance returned from inject()
is a subclass of NamedTuple
, so the instance is immutable. This ensures that the data returned from inject
will always have all the keys that were passed to the provide
tag.
NOTE: inject()
works strictly only in get_context_data
. If you try to call it from elsewhere, it will raise an error.
"},{"location":"#full-example","title":"Full example","text":"@register(\"child\")\nclass ChildComponent(Component):\n template = \"\"\"\n <div> {{ my_data.key }} </div>\n <div> {{ my_data.another }} </div>\n \"\"\"\n\n def get_context_data(self):\n my_data = self.inject(\"my_data\", \"default\")\n return {\"my_data\": my_data}\n\ntemplate_str = \"\"\"\n {% load component_tags %}\n {% provide \"my_data\" key=\"hi\" another=123 %}\n {% component \"child\" / %}\n {% endprovide %}\n\"\"\"\n
renders:
<div>hi</div>\n<div>123</div>\n
"},{"location":"#component-context-and-scope","title":"Component context and scope","text":"By default, context variables are passed down the template as in regular Django - deeper scopes can access the variables from the outer scopes. So if you have several nested forloops, then inside the deep-most loop you can access variables defined by all previous loops.
With this in mind, the {% component %}
tag behaves similarly to {% include %}
tag - inside the component tag, you can access all variables that were defined outside of it.
And just like with {% include %}
, if you don't want a specific component template to have access to the parent context, add only
to the {% component %}
tag:
{% component \"calendar\" date=\"2015-06-19\" only %}{% endcomponent %}\n
NOTE: {% csrf_token %}
tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the only
modifier.
If you find yourself using the only
modifier often, you can set the context_behavior option to \"isolated\"
, which automatically applies the only
modifier. This is useful if you want to make sure that components don't accidentally access the outer context.
Components can also access the outer context in their context methods like get_context_data
by accessing the property self.outer_context
.
"},{"location":"#customizing-component-tags-with-tagformatter","title":"Customizing component tags with TagFormatter","text":"New in version 0.89
By default, components are rendered using the pair of {% component %}
/ {% endcomponent %}
template tags:
{% component \"button\" href=\"...\" disabled %}\nClick me!\n{% endcomponent %}\n\n{# or #}\n\n{% component \"button\" href=\"...\" disabled / %}\n
You can change this behaviour in the settings under the COMPONENTS.tag_formatter
.
For example, if you set the tag formatter to django_components.shorthand_component_formatter
, the components will use their name as the template tags:
{% button href=\"...\" disabled %}\n Click me!\n{% endbutton %}\n\n{# or #}\n\n{% button href=\"...\" disabled / %}\n
"},{"location":"#available-tagformatters","title":"Available TagFormatters","text":"django_components provides following predefined TagFormatters:
-
ComponentFormatter
(django_components.component_formatter
)
Default
Uses the component
and endcomponent
tags, and the component name is gives as the first positional argument.
Example as block:
{% component \"button\" href=\"...\" %}\n {% fill \"content\" %}\n ...\n {% endfill %}\n{% endcomponent %}\n
Example as inlined tag:
{% component \"button\" href=\"...\" / %}\n
-
ShorthandComponentFormatter
(django_components.shorthand_component_formatter
)
Uses the component name as start tag, and end<component_name>
as an end tag.
Example as block:
{% button href=\"...\" %}\n Click me!\n{% endbutton %}\n
Example as inlined tag:
{% button href=\"...\" / %}\n
"},{"location":"#writing-your-own-tagformatter","title":"Writing your own TagFormatter","text":""},{"location":"#background","title":"Background","text":"First, let's discuss how TagFormatters work, and how components are rendered in django_components.
When you render a component with {% component %}
(or your own tag), the following happens: 1. component
must be registered as a Django's template tag 2. Django triggers django_components's tag handler for tag component
. 3. The tag handler passes the tag contents for pre-processing to TagFormatter.parse()
.
So if you render this:\n```django\n{% component \"button\" href=\"...\" disabled %}\n{% endcomponent %}\n```\n\nThen `TagFormatter.parse()` will receive a following input:\n```py\n[\"component\", '\"button\"', 'href=\"...\"', 'disabled']\n```\n
-
TagFormatter
extracts the component name and the remaining input.
So, given the above, TagFormatter.parse()
returns the following:
TagResult(\n component_name=\"button\",\n tokens=['href=\"...\"', 'disabled']\n)\n
5. The tag handler resumes, using the tokens returned from TagFormatter
. So, continuing the example, at this point the tag handler practically behaves as if you rendered:
{% component href=\"...\" disabled %}\n
6. Tag handler looks up the component button
, and passes the args, kwargs, and slots to it.
"},{"location":"#tagformatter","title":"TagFormatter","text":"TagFormatter
handles following parts of the process above: - Generates start/end tags, given a component. This is what you then call from within your template as {% component %}
.
- When you
{% component %}
, tag formatter pre-processes the tag contents, so it can link back the custom template tag to the right component.
To do so, subclass from TagFormatterABC
and implement following method: - start_tag
- end_tag
- parse
For example, this is the implementation of ShorthandComponentFormatter
class ShorthandComponentFormatter(TagFormatterABC):\n # Given a component name, generate the start template tag\n def start_tag(self, name: str) -> str:\n return name # e.g. 'button'\n\n # Given a component name, generate the start template tag\n def end_tag(self, name: str) -> str:\n return f\"end{name}\" # e.g. 'endbutton'\n\n # Given a tag, e.g.\n # `{% button href=\"...\" disabled %}`\n #\n # The parser receives:\n # `['button', 'href=\"...\"', 'disabled']`\n def parse(self, tokens: List[str]) -> TagResult:\n tokens = [*tokens]\n name = tokens.pop(0)\n return TagResult(\n name, # e.g. 'button'\n tokens # e.g. ['href=\"...\"', 'disabled']\n )\n
That's it! And once your TagFormatter
is ready, don't forget to update the settings!
"},{"location":"#defining-htmljscss-files","title":"Defining HTML/JS/CSS files","text":"django_component's management of files builds on top of Django's Media
class.
To be familiar with how Django handles static files, we recommend reading also:
- How to manage static files (e.g. images, JavaScript, CSS)
"},{"location":"#defining-file-paths-relative-to-component-or-static-dirs","title":"Defining file paths relative to component or static dirs","text":"As seen in the getting started example, to associate HTML/JS/CSS files with a component, you set them as template_name
, Media.js
and Media.css
respectively:
# In a file [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"template.html\"\n\n class Media:\n css = \"style.css\"\n js = \"script.js\"\n
In the example above, the files are defined relative to the directory where component.py
is.
Alternatively, you can specify the file paths relative to the directories set in STATICFILES_DIRS
.
Assuming that STATICFILES_DIRS
contains path [project root]/components
, we can rewrite the example as:
# In a file [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"calendar/template.html\"\n\n class Media:\n css = \"calendar/style.css\"\n js = \"calendar/script.js\"\n
NOTE: In case of conflict, the preference goes to resolving the files relative to the component's directory.
"},{"location":"#defining-multiple-paths","title":"Defining multiple paths","text":"Each component can have only a single template. However, you can define as many JS or CSS files as you want using a list.
class MyComponent(Component):\n class Media:\n js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n
"},{"location":"#configuring-css-media-types","title":"Configuring CSS Media Types","text":"You can define which stylesheets will be associated with which CSS Media types. You do so by defining CSS files as a dictionary.
See the corresponding Django Documentation.
Again, you can set either a single file or a list of files per media type:
class MyComponent(Component):\n class Media:\n css = {\n \"all\": \"path/to/style1.css\",\n \"print\": \"path/to/style2.css\",\n }\n
class MyComponent(Component):\n class Media:\n css = {\n \"all\": [\"path/to/style1.css\", \"path/to/style2.css\"],\n \"print\": [\"path/to/style3.css\", \"path/to/style4.css\"],\n }\n
NOTE: When you define CSS as a string or a list, the all
media type is implied.
"},{"location":"#supported-types-for-file-paths","title":"Supported types for file paths","text":"File paths can be any of:
str
bytes
PathLike
(__fspath__
method) SafeData
(__html__
method) Callable
that returns any of the above, evaluated at class creation (__new__
)
from pathlib import Path\n\nfrom django.utils.safestring import mark_safe\n\nclass SimpleComponent(Component):\n class Media:\n css = [\n mark_safe('<link href=\"/static/calendar/style.css\" rel=\"stylesheet\" />'),\n Path(\"calendar/style1.css\"),\n \"calendar/style2.css\",\n b\"calendar/style3.css\",\n lambda: \"calendar/style4.css\",\n ]\n js = [\n mark_safe('<script src=\"/static/calendar/script.js\"></script>'),\n Path(\"calendar/script1.js\"),\n \"calendar/script2.js\",\n b\"calendar/script3.js\",\n lambda: \"calendar/script4.js\",\n ]\n
"},{"location":"#path-as-objects","title":"Path as objects","text":"In the example above, you could see that when we used mark_safe
to mark a string as a SafeString
, we had to define the full <script>
/<link>
tag.
This is an extension of Django's Paths as objects feature, where \"safe\" strings are taken as is, and accessed only at render time.
Because of that, the paths defined as \"safe\" strings are NEVER resolved, neither relative to component's directory, nor relative to STATICFILES_DIRS
.
\"Safe\" strings can be used to lazily resolve a path, or to customize the <script>
or <link>
tag for individual paths:
class LazyJsPath:\n def __init__(self, static_path: str) -> None:\n self.static_path = static_path\n\n def __html__(self):\n full_path = static(self.static_path)\n return format_html(\n f'<script type=\"module\" src=\"{full_path}\"></script>'\n )\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"calendar/template.html\"\n\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n\n class Media:\n css = \"calendar/style.css\"\n js = [\n # <script> tag constructed by Media class\n \"calendar/script1.js\",\n # Custom <script> tag\n LazyJsPath(\"calendar/script2.js\"),\n ]\n
"},{"location":"#customize-how-paths-are-rendered-into-html-tags-with-media_class","title":"Customize how paths are rendered into HTML tags with media_class
","text":"Sometimes you may need to change how all CSS <link>
or JS <script>
tags are rendered for a given component. You can achieve this by providing your own subclass of Django's Media
class to component's media_class
attribute.
Normally, the JS and CSS paths are passed to Media
class, which decides how the paths are resolved and how the <link>
and <script>
tags are constructed.
To change how the tags are constructed, you can override the Media.render_js
and Media.render_css
methods:
from django.forms.widgets import Media\nfrom django_components import Component, register\n\nclass MyMedia(Media):\n # Same as original Media.render_js, except\n # the `<script>` tag has also `type=\"module\"`\n def render_js(self):\n tags = []\n for path in self._js:\n if hasattr(path, \"__html__\"):\n tag = path.__html__()\n else:\n tag = format_html(\n '<script type=\"module\" src=\"{}\"></script>',\n self.absolute_path(path)\n )\n return tags\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"calendar/template.html\"\n\n class Media:\n css = \"calendar/style.css\"\n js = \"calendar/script.js\"\n\n # Override the behavior of Media class\n media_class = MyMedia\n
NOTE: The instance of the Media
class (or it's subclass) is available under Component.media
after the class creation (__new__
).
"},{"location":"#rendering-jscss-dependencies","title":"Rendering JS/CSS dependencies","text":"The JS and CSS files included in components are not automatically rendered. Instead, use the following tags to specify where to render the dependencies:
component_dependencies
- Renders both JS and CSS component_js_dependencies
- Renders only JS component_css_dependencies
- Reneders only CSS
JS files are rendered as <script>
tags. CSS files are rendered as <style>
tags.
"},{"location":"#setting-up-componentdependencymiddleware","title":"Setting Up ComponentDependencyMiddleware
","text":"ComponentDependencyMiddleware
is a Django middleware designed to manage and inject CSS/JS dependencies for rendered components dynamically. It ensures that only the necessary stylesheets and scripts are loaded in your HTML responses, based on the components used in your Django templates.
To set it up, add the middleware to your MIDDLEWARE
in settings.py:
MIDDLEWARE = [\n # ... other middleware classes ...\n 'django_components.middleware.ComponentDependencyMiddleware'\n # ... other middleware classes ...\n]\n
Then, enable RENDER_DEPENDENCIES
in setting.py:
COMPONENTS = {\n \"RENDER_DEPENDENCIES\": True,\n # ... other component settings ...\n}\n
"},{"location":"#available-settings","title":"Available settings","text":"All library settings are handled from a global COMPONENTS
variable that is read from settings.py
. By default you don't need it set, there are resonable defaults.
"},{"location":"#configure-the-module-where-components-are-loaded-from","title":"Configure the module where components are loaded from","text":"Configure the location where components are loaded. To do this, add a COMPONENTS
variable to you settings.py
with a list of python paths to load. This allows you to build a structure of components that are independent from your apps.
COMPONENTS = {\n \"libraries\": [\n \"mysite.components.forms\",\n \"mysite.components.buttons\",\n \"mysite.components.cards\",\n ],\n}\n
Where mysite/components/forms.py
may look like this:
@register(\"form_simple\")\nclass FormSimple(Component):\n template = \"\"\"\n <form>\n ...\n </form>\n \"\"\"\n\n@register(\"form_other\")\nclass FormOther(Component):\n template = \"\"\"\n <form>\n ...\n </form>\n \"\"\"\n
In the rare cases when you need to manually trigger the import of libraries, you can use the import_libraries
function:
from django_components import import_libraries\n\nimport_libraries()\n
"},{"location":"#disable-autodiscovery","title":"Disable autodiscovery","text":"If you specify all the component locations with the setting above and have a lot of apps, you can (very) slightly speed things up by disabling autodiscovery.
COMPONENTS = {\n \"autodiscover\": False,\n}\n
"},{"location":"#tune-the-template-cache","title":"Tune the template cache","text":"Each time a template is rendered it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up. By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are using the template
method of a component to render lots of dynamic templates, you can increase this number. To remove the cache limit altogether and cache everything, set template_cache_size to None
.
COMPONENTS = {\n \"template_cache_size\": 256,\n}\n
"},{"location":"#context-behavior-setting","title":"Context behavior setting","text":"NOTE: context_behavior
and slot_context_behavior
options were merged in v0.70.
If you are migrating from BEFORE v0.67, set context_behavior
to \"django\"
. From v0.67 to v0.78 (incl) the default value was \"isolated\"
.
For v0.79 and later, the default is again \"django\"
. See the rationale for change here.
You can configure what variables are available inside the {% fill %}
tags. See Component context and scope.
This has two modes:
\"django\"
- Default - The default Django template behavior.
Inside the {% fill %}
tag, the context variables you can access are a union of:
- All the variables that were OUTSIDE the fill tag, including any loops or with tag
-
Data returned from get_context_data()
of the component that wraps the fill tag.
-
\"isolated\"
- Similar behavior to Vue or React, this is useful if you want to make sure that components don't accidentally access variables defined outside of the component.
Inside the {% fill %}
tag, you can ONLY access variables from 2 places:
get_context_data()
of the component which defined the template (AKA the \"root\" component) - Any loops (
{% for ... %}
) that the {% fill %}
tag is part of.
COMPONENTS = {\n \"context_behavior\": \"isolated\",\n}\n
"},{"location":"#example-django","title":"Example \"django\"","text":"Given this template:
class RootComp(Component):\n template = \"\"\"\n {% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n {% endwith %}\n \"\"\"\n def get_context_data(self):\n return { \"my_var\": 123 }\n
Then if get_context_data()
of the component \"my_comp\"
returns following data:
{ \"my_var\": 456 }\n
Then the template will be rendered as:
456 # my_var\nfeta # cheese\n
Because \"my_comp\"
overshadows the variable \"my_var\"
, so {{ my_var }}
equals 456
.
And variable \"cheese\"
equals feta
, because the fill CAN access all the data defined in the outer layers, like the {% with %}
tag.
"},{"location":"#example-isolated","title":"Example \"isolated\"","text":"Given this template:
class RootComp(Component):\n template = \"\"\"\n {% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n {% endwith %}\n \"\"\"\n def get_context_data(self):\n return { \"my_var\": 123 }\n
Then if get_context_data()
of the component \"my_comp\"
returns following data:
{ \"my_var\": 456 }\n
Then the template will be rendered as:
123 # my_var\n # cheese\n
Because variables \"my_var\"
and \"cheese\"
are searched only inside RootComponent.get_context_data()
. But since \"cheese\"
is not defined there, it's empty.
Notice that the variables defined with the {% with %}
tag are ignored inside the {% fill %}
tag with the \"isolated\"
mode.
"},{"location":"#tag-formatter-setting","title":"Tag formatter setting","text":"Set the TagFormatter
instance.
Can be set either as direct reference, or as an import string;
COMPONENTS = {\n \"tag_formatter\": \"django_components.component_formatter\"\n}\n
Or
from django_components import component_formatter\n\nCOMPONENTS = {\n \"tag_formatter\": component_formatter\n}\n
"},{"location":"#logging-and-debugging","title":"Logging and debugging","text":"Django components supports logging with Django. This can help with troubleshooting.
To configure logging for Django components, set the django_components
logger in LOGGING
in settings.py
(below).
Also see the settings.py
file in sampleproject for a real-life example.
import logging\nimport sys\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n \"handlers\": {\n \"console\": {\n 'class': 'logging.StreamHandler',\n 'stream': sys.stdout,\n },\n },\n \"loggers\": {\n \"django_components\": {\n \"level\": logging.DEBUG,\n \"handlers\": [\"console\"],\n },\n },\n}\n
"},{"location":"#management-command","title":"Management Command","text":"You can use the built-in management command startcomponent
to create a django component. The command accepts the following arguments and options:
-
name
: The name of the component to create. This is a required argument.
-
--path
: The path to the components directory. This is an optional argument. If not provided, the command will use the BASE_DIR
setting from your Django settings.
-
--js
: The name of the JavaScript file. This is an optional argument. The default value is script.js
.
-
--css
: The name of the CSS file. This is an optional argument. The default value is style.css
.
-
--template
: The name of the template file. This is an optional argument. The default value is template.html
.
-
--force
: This option allows you to overwrite existing files if they exist. This is an optional argument.
-
--verbose
: This option allows the command to print additional information during component creation. This is an optional argument.
-
--dry-run
: This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False
.
"},{"location":"#management-command-usage","title":"Management Command Usage","text":"To use the command, run the following command in your terminal:
python manage.py startcomponent <name> --path <path> --js <js_filename> --css <css_filename> --template <template_filename> --force --verbose --dry-run\n
Replace <name>
, <path>
, <js_filename>
, <css_filename>
, and <template_filename>
with your desired values.
"},{"location":"#management-command-examples","title":"Management Command Examples","text":"Here are some examples of how you can use the command:
"},{"location":"#creating-a-component-with-default-settings","title":"Creating a Component with Default Settings","text":"To create a component with the default settings, you only need to provide the name of the component:
python manage.py startcomponent my_component\n
This will create a new component named my_component
in the components
directory of your Django project. The JavaScript, CSS, and template files will be named script.js
, style.css
, and template.html
, respectively.
"},{"location":"#creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"You can also create a component with custom settings by providing additional arguments:
python manage.py startcomponent new_component --path my_components --js my_script.js --css my_style.css --template my_template.html\n
This will create a new component named new_component
in the my_components
directory. The JavaScript, CSS, and template files will be named my_script.js
, my_style.css
, and my_template.html
, respectively.
"},{"location":"#overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"If you want to overwrite an existing component, you can use the --force
option:
python manage.py startcomponent my_component --force\n
This will overwrite the existing my_component
if it exists.
"},{"location":"#simulating-component-creation","title":"Simulating Component Creation","text":"If you want to simulate the creation of a component without actually creating any files, you can use the --dry-run
option:
python manage.py startcomponent my_component --dry-run\n
This will simulate the creation of my_component
without creating any files.
"},{"location":"#community-examples","title":"Community examples","text":"One of our goals with django-components
is to make it easy to share components between projects. If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.
- django-htmx-components: A set of components for use with htmx. Try out the live demo.
"},{"location":"#running-django-components-project-locally","title":"Running django-components project locally","text":""},{"location":"#install-locally-and-run-the-tests","title":"Install locally and run the tests","text":"Start by forking the project by clicking the Fork button up in the right corner in the GitHub . This makes a copy of the repository in your own name. Now you can clone this repository locally and start adding features:
git clone https://github.com/<your GitHub username>/django-components.git\n
To quickly run the tests install the local dependencies by running:
pip install -r requirements-dev.txt\n
Now you can run the tests to make sure everything works as expected:
pytest\n
The library is also tested across many versions of Python and Django. To run tests that way:
pyenv install -s 3.8\npyenv install -s 3.9\npyenv install -s 3.10\npyenv install -s 3.11\npyenv install -s 3.12\npyenv local 3.8 3.9 3.10 3.11 3.12\ntox -p\n
"},{"location":"#developing-against-live-django-app","title":"Developing against live Django app","text":"How do you check that your changes to django-components project will work in an actual Django project?
Use the sampleproject demo project to validate the changes:
- Navigate to sampleproject directory:
cd sampleproject\n
- Install dependencies from the requirements.txt file:
pip install -r requirements.txt\n
- Link to your local version of django-components:
pip install -e ..\n
NOTE: The path (in this case ..
) must point to the directory that has the setup.py
file.
- Start Django server
python manage.py runserver\n
Once the server is up, it should be available at http://127.0.0.1:8000.
To display individual components, add them to the urls.py
, like in the case of http://127.0.0.1:8000/greeting
"},{"location":"#development-guides","title":"Development guides","text":""},{"location":"CHANGELOG/","title":"Release notes","text":"\ud83d\udea8\ud83d\udce2 Version 0.92 - BREAKING CHANGE: Component
class is no longer a subclass of View
. To configure the View
class, set the Component.View
nested class. HTTP methods like get
or post
can still be defined directly on Component
class, and Component.as_view()
internally calls Component.View.as_view()
. (See Modifying the View class)
-
The inputs (args, kwargs, slots, context, ...) that you pass to Component.render()
can be accessed from within get_context_data
, get_template_string
and get_template_name
via self.input
. (See Accessing data passed to the component)
-
Typing: Component
class supports generics that specify types for Component.render
(See Adding type hints with Generics)
Version 0.90 - All tags (component
, slot
, fill
, ...) now support \"self-closing\" or \"inline\" form, where you can omit the closing tag:
{# Before #}\n{% component \"button\" %}{% endcomponent %}\n{# After #}\n{% component \"button\" / %}\n
- All tags now support the \"dictionary key\" or \"aggregate\" syntax (kwarg:key=val
): {% component \"button\" attrs:class=\"hidden\" %}\n
- You can change how the components are written in the template with TagFormatter. The default is `django_components.component_formatter`:\n```django\n{% component \"button\" href=\"...\" disabled %}\n Click me!\n{% endcomponent %}\n```\n\nWhile `django_components.shorthand_component_formatter` allows you to write components like so:\n\n```django\n{% button href=\"...\" disabled %}\n Click me!\n{% endbutton %}\n
\ud83d\udea8\ud83d\udce2 Version 0.85 Autodiscovery module resolution changed. Following undocumented behavior was removed:
- Previously, autodiscovery also imported any
[app]/components.py
files, and used SETTINGS_MODULE
to search for component dirs. - To migrate from:
[app]/components.py
- Define each module in COMPONENTS.libraries
setting, or import each module inside the AppConfig.ready()
hook in respective apps.py
files. SETTINGS_MODULE
- Define component dirs using STATICFILES_DIRS
- Previously, autodiscovery handled relative files in
STATICFILES_DIRS
. To align with Django, STATICFILES_DIRS
now must be full paths (Django docs).
\ud83d\udea8\ud83d\udce2 Version 0.81 Aligned the render_to_response
method with the (now public) render
method of Component
class. Moreover, slots passed to these can now be rendered also as functions.
- BREAKING CHANGE: The order of arguments to
render_to_response
has changed.
Version 0.80 introduces dependency injection with the {% provide %}
tag and inject()
method.
\ud83d\udea8\ud83d\udce2 Version 0.79
- BREAKING CHANGE: Default value for the
COMPONENTS.context_behavior
setting was changes from \"isolated\"
to \"django\"
. If you did not set this value explicitly before, this may be a breaking change. See the rationale for change here.
\ud83d\udea8\ud83d\udce2 Version 0.77 CHANGED the syntax for accessing default slot content.
- Previously, the syntax was
{% fill \"my_slot\" as \"alias\" %}
and {{ alias.default }}
. - Now, the syntax is
{% fill \"my_slot\" default=\"alias\" %}
and {{ alias }}
.
Version 0.74 introduces html_attrs
tag and prefix:key=val
construct for passing dicts to components.
\ud83d\udea8\ud83d\udce2 Version 0.70
{% if_filled \"my_slot\" %}
tags were replaced with {{ component_vars.is_filled.my_slot }}
variables. - Simplified settings -
slot_context_behavior
and context_behavior
were merged. See the documentation for more details.
Version 0.67 CHANGED the default way how context variables are resolved in slots. See the documentation for more details.
\ud83d\udea8\ud83d\udce2 Version 0.5 CHANGES THE SYNTAX for components. component_block
is now component
, and component
blocks need an ending endcomponent
tag. The new python manage.py upgradecomponent
command can be used to upgrade a directory (use --path argument to point to each dir) of templates that use components to the new syntax automatically.
This change is done to simplify the API in anticipation of a 1.0 release of django_components. After 1.0 we intend to be stricter with big changes like this in point releases.
Version 0.34 adds components as views, which allows you to handle requests and render responses from within a component. See the documentation for more details.
Version 0.28 introduces 'implicit' slot filling and the default
option for slot
tags.
Version 0.27 adds a second installable app: django_components.safer_staticfiles. It provides the same behavior as django.contrib.staticfiles but with extra security guarantees (more info below in Security Notes).
Version 0.26 changes the syntax for {% slot %}
tags. From now on, we separate defining a slot ({% slot %}
) from filling a slot with content ({% fill %}
). This means you will likely need to change a lot of slot tags to fill. We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice featuPpre to have access to. Hoping that this will feel worth it!
Version 0.22 starts autoimporting all files inside components subdirectores, to simplify setup. An existing project might start to get AlreadyRegistered-errors because of this. To solve this, either remove your custom loading of components, or set \"autodiscover\": False in settings.COMPONENTS.
Version 0.17 renames Component.context
and Component.template
to get_context_data
and get_template_name
. The old methods still work, but emit a deprecation warning. This change was done to sync naming with Django's class based views, and make using django-components more familiar to Django users. Component.context
and Component.template
will be removed when version 1.0 is released.
Static files
Components can be organized however you prefer. That said, our prefered way is to keep the files of a component close together by bundling them in the same directory. This means that files containing backend logic, such as Python modules and HTML templates, live in the same directory as static files, e.g. JS and CSS.
If your are using django.contrib.staticfiles to collect static files, no distinction is 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.
As of v0.27, django-components ships with an additional installable app django_components.safer_staticfiles. It is a drop-in replacement for django.contrib.staticfiles. Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server. To use it, add it to INSTALLED_APPS and remove django.contrib.staticfiles.
INSTALLED_APPS = [\n # 'django.contrib.staticfiles', # <-- REMOVE\n 'django_components',\n 'django_components.safer_staticfiles' # <-- ADD\n]\n
If you are on an older version of django-components, your alternatives are a) passing --ignore <pattern>
options to the collecstatic CLI command, or b) defining a subclass of StaticFilesConfig. Both routes are described in the official docs of the staticfiles app.
Note that safer_staticfiles
excludes the .py
and .html
files for collectstatic command:
python manage.py collectstatic\n
but it is ignored on the development server:
python manage.py runserver\n
For a step-by-step guide on deploying production server with static files, see the demo project.
Optional
To avoid loading the app in each template using {% load component_tags %}
, you can add the tag as a 'builtin' in settings.py
TEMPLATES = [\n {\n ...,\n 'OPTIONS': {\n 'context_processors': [\n ...\n ],\n 'builtins': [\n 'django_components.templatetags.component_tags',\n ]\n },\n },\n]\n
Read on to find out how to build your first component!
Create your first component
A component in django-components is the combination of four things: CSS, Javascript, a Django template, and some Python code to put them all together.
sampleproject/\n \u251c\u2500\u2500 calendarapp/\n \u251c\u2500\u2500 components/ \ud83c\udd95\n \u2502 \u2514\u2500\u2500 calendar/ \ud83c\udd95\n \u2502 \u251c\u2500\u2500 calendar.py \ud83c\udd95\n \u2502 \u251c\u2500\u2500 script.js \ud83c\udd95\n \u2502 \u251c\u2500\u2500 style.css \ud83c\udd95\n \u2502 \u2514\u2500\u2500 template.html \ud83c\udd95\n \u251c\u2500\u2500 sampleproject/\n \u251c\u2500\u2500 manage.py\n \u2514\u2500\u2500 requirements.txt\n
Start by creating empty files in the structure above.
First, you need a CSS file. Be sure to prefix all rules with a unique class so they don't clash with other rules.
[project root]/components/calendar/style.css/* In a file called [project root]/components/calendar/style.css */\n.calendar-component {\n width: 200px;\n background: pink;\n}\n.calendar-component span {\n font-weight: bold;\n}\n
Then you need a javascript file that specifies how you interact with this component. You are free to use any javascript framework you want. A good way to make sure this component doesn't clash with other components is to define all code inside an anonymous function that calls itself. This makes all variables defined only be defined inside this component and not affect other components.
[project root]/components/calendar/script.js/* In a file called [project root]/components/calendar/script.js */\n(function () {\n if (document.querySelector(\".calendar-component\")) {\n document.querySelector(\".calendar-component\").onclick = function () {\n alert(\"Clicked calendar!\");\n };\n }\n})();\n
Now you need a Django template for your component. Feel free to define more variables like date
in this example. When creating an instance of this component we will send in the values for these variables. The template will be rendered with whatever template backend you've specified in your Django settings file.
[project root]/components/calendar/calendar.html{# In a file called [project root]/components/calendar/template.html #}\n<div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n
Finally, we use django-components to tie this together. Start by creating a file called calendar.py
in your component calendar directory. It will be auto-detected and loaded by the app.
Inside this file we create a Component by inheriting from the Component class and specifying the context method. We also register the global component registry so that we easily can render it anywhere in our templates.
[project root]/components/calendar/calendar.py## In a file called [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n # Templates inside `[your apps]/components` dir and `[project root]/components` dir\n # will be automatically found. To customize which template to use based on context\n # you can override method `get_template_name` instead of specifying `template_name`.\n #\n # `template_name` can be relative to dir where `calendar.py` is, or relative to STATICFILES_DIRS\n template_name = \"template.html\"\n\n # This component takes one parameter, a date string to show in the template\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n\n # Both `css` and `js` can be relative to dir where `calendar.py` is, or relative to STATICFILES_DIRS\n class Media:\n css = \"style.css\"\n js = \"script.js\"\n
And voil\u00e1!! We've created our first component.
Syntax highlight and code assistance
"},{"location":"CHANGELOG/#pycharm-or-other-jetbrains-ides","title":"Pycharm (or other Jetbrains IDEs)","text":"If you're a Pycharm user (or any other editor from Jetbrains), you can have coding assistance as well:
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n\n # language=HTML\n template= \"\"\"\n <div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n \"\"\"\n\n # language=CSS\n css = \"\"\"\n .calendar-component { width: 200px; background: pink; }\n .calendar-component span { font-weight: bold; }\n \"\"\"\n\n # language=JS\n js = \"\"\"\n (function(){\n if (document.querySelector(\".calendar-component\")) {\n document.querySelector(\".calendar-component\").onclick = function(){ alert(\"Clicked calendar!\"); };\n }\n })()\n \"\"\"\n
You don't need to use types.django_html
, types.css
, types.js
since Pycharm uses language injections. You only need to write the comments # language=<lang>
above the variables.
Use components outside of templates
New in version 0.81
Components can be rendered outside of Django templates, calling them as regular functions (\"React-style\").
The component class defines render
and render_to_response
class methods. These methods accept positional args, kwargs, and slots, offering the same flexibility as the {% component %}
tag:
class SimpleComponent(Component):\n template = \"\"\"\n {% load component_tags %}\n hello: {{ hello }}\n foo: {{ foo }}\n kwargs: {{ kwargs|safe }}\n slot_first: {% slot \"first\" required / %}\n \"\"\"\n\n def get_context_data(self, arg1, arg2, **kwargs):\n return {\n \"hello\": arg1,\n \"foo\": arg2,\n \"kwargs\": kwargs,\n }\n\nrendered = SimpleComponent.render(\n args=[\"world\", \"bar\"],\n kwargs={\"kw1\": \"test\", \"kw2\": \"ooo\"},\n slots={\"first\": \"FIRST_SLOT\"},\n context={\"from_context\": 98},\n)\n
Renders:
hello: world\nfoo: bar\nkwargs: {'kw1': 'test', 'kw2': 'ooo'}\nslot_first: FIRST_SLOT\n
"},{"location":"CHANGELOG/#slotfunc","title":"SlotFunc
","text":"When rendering components with slots in render
or render_to_response
, you can pass either a string or a function.
The function has following signature:
def render_func(\n context: Context,\n data: Dict[str, Any],\n slot_ref: SlotRef,\n) -> str | SafeString:\n return nodelist.render(ctx)\n
context
- Django's Context available to the Slot Node. data
- Data passed to the {% slot %}
tag. See Scoped Slots. slot_ref
- The default slot content. See Accessing original content of slots. - NOTE: The slot is lazily evaluated. To render the slot, convert it to string with
str(slot_ref)
.
Example:
def footer_slot(ctx, data, slot_ref):\n return f\"\"\"\n SLOT_DATA: {data['abc']}\n ORIGINAL: {slot_ref}\n \"\"\"\n\nMyComponent.render_to_response(\n slots={\n \"footer\": footer_slot,\n },\n)\n
"},{"location":"CHANGELOG/#response-class-of-render_to_response","title":"Response class of render_to_response
","text":"While render
method returns a plain string, render_to_response
wraps the rendered content in a \"Response\" class. By default, this is django.http.HttpResponse
.
If you want to use a different Response class in render_to_response
, set the Component.response_class
attribute:
class MyResponse(HttpResponse):\n def __init__(self, *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n # Configure response\n self.headers = ...\n self.status = ...\n\nclass SimpleComponent(Component):\n response_class = MyResponse\n template: types.django_html = \"HELLO\"\n\nresponse = SimpleComponent.render_to_response()\nassert isinstance(response, MyResponse)\n
Component as view example
Here's an example of a calendar component defined as a view:
## In a file called [project root]/components/calendar.py\nfrom django_components import Component, ComponentView, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n\n template = \"\"\"\n <div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" / %}\n </div>\n <div class=\"body\">\n Today's date is <span>{{ date }}</span>\n </div>\n </div>\n \"\"\"\n\n # Handle GET requests\n def get(self, request, *args, **kwargs):\n context = {\n \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n }\n slots = {\n \"header\": \"Calendar header\",\n }\n # Return HttpResponse with the rendered content\n return self.render_to_response(\n context=context,\n slots=slots,\n )\n
Then, to use this component as a view, you should create a urls.py
file in your components directory, and add a path to the component's view:
## In a file called [project root]/components/urls.py\nfrom django.urls import path\nfrom components.calendar.calendar import Calendar\n\nurlpatterns = [\n path(\"calendar/\", Calendar.as_view()),\n]\n
Component.as_view()
is a shorthand for calling View.as_view()
and passing the component instance as one of the arguments.
Remember to add __init__.py
to your components directory, so that Django can find the urls.py
file.
Finally, include the component's urls in your project's urls.py
file:
## In a file called [project root]/urls.py\nfrom django.urls import include, path\n\nurlpatterns = [\n path(\"components/\", include(\"components.urls\")),\n]\n
Note: Slots content are automatically escaped by default to prevent XSS attacks. To disable escaping, set escape_slots_content=False
in the render_to_response
method. If you do so, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.
If you're planning on passing an HTML string, check Django's use of format_html
and mark_safe
.
"},{"location":"CHANGELOG/#registering-components","title":"Registering components","text":"In previous examples you could repeatedly see us using @register()
to \"register\" the components. In this section we dive deeper into what it actually means and how you can manage (add or remove) components.
As a reminder, we may have a component like this:
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"template.html\"\n\n # This component takes one parameter, a date string to show in the template\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n
which we then render in the template as:
{% component \"calendar\" date=\"1970-01-01\" %}\n{% endcomponent %}\n
As you can see, @register
links up the component class with the {% component %}
template tag. So when the template tag comes across a component called \"calendar\"
, it can look up it's class and instantiate it.
"},{"location":"CHANGELOG/#working-with-componentregistry","title":"Working with ComponentRegistry","text":"The default ComponentRegistry
instance can be imported as:
from django_components import registry\n
You can use the registry to manually add/remove/get components:
from django_components import registry\n\n## Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n## Get all or single\nregistry.all() # {\"button\": ButtonComponent, \"card\": CardComponent}\nregistry.get(\"card\") # CardComponent\n\n## Unregister single component\nregistry.unregister(\"card\")\n\n## Unregister all components\nregistry.clear()\n
"},{"location":"CHANGELOG/#autodiscovery","title":"Autodiscovery","text":"Every component that you want to use in the template with the {% component %}
tag needs to be registered with the ComponentRegistry. Normally, we use the @register
decorator for that:
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n ...\n
But for the component to be registered, the code needs to be executed - the file needs to be imported as a module.
One way to do that is by importing all your components in apps.py
:
from django.apps import AppConfig\n\nclass MyAppConfig(AppConfig):\n name = \"my_app\"\n\n def ready(self) -> None:\n from components.card.card import Card\n from components.list.list import List\n from components.menu.menu import Menu\n from components.button.button import Button\n ...\n
However, there's a simpler way!
By default, the Python files in the STATICFILES_DIRS
directories are auto-imported in order to auto-register the components.
Autodiscovery occurs when Django is loaded, during the ready
hook of the apps.py
file.
If you are using autodiscovery, keep a few points in mind:
- Avoid defining any logic on the module-level inside the
components
dir, that you would not want to run anyway. - Components inside the auto-imported files still need to be registered with
@register()
- Auto-imported component files must be valid Python modules, they must use suffix
.py
, and module name should follow PEP-8.
Autodiscovery can be disabled in the settings.
"},{"location":"CHANGELOG/#using-slots-in-templates","title":"Using slots in templates","text":"New in version 0.26:
- The
slot
tag now serves only to declare new slots inside the component template. - To override the content of a declared slot, use the newly introduced
fill
tag instead. - Whereas unfilled slots used to raise a warning, filling a slot is now optional by default.
- To indicate that a slot must be filled, the new
required
option should be added at the end of the slot
tag.
Components support something called 'slots'. When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content. This mechanism makes components more reusable and composable. This behavior is similar to slots in Vue.
In the example below we introduce two block tags that work hand in hand to make this work. These are...
{% slot <name> %}
/{% endslot %}
: Declares a new slot in the component template. {% fill <name> %}
/{% endfill %}
: (Used inside a component
tag pair.) Fills a declared slot with the specified content.
Let's update our calendar component to support more customization. We'll add slot
tag pairs to its template, template.html.
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" %}Calendar header{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"body\" %}Today's date is <span>{{ date }}</span>{% endslot %}\n </div>\n</div>\n
When using the component, you specify which slots you want to fill and where you want to use the defaults from the template. It looks like this:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"body\" %}Can you believe it's already <span>{{ date }}</span>??{% endfill %}\n{% endcomponent %}\n
Since the 'header' fill is unspecified, it's taken from the base template. If you put this in a template, and pass in date=2020-06-06
, this is what gets rendered:
<div class=\"calendar-component\">\n <div class=\"header\">\n Calendar header\n </div>\n <div class=\"body\">\n Can you believe it's already <span>2020-06-06</span>??\n </div>\n</div>\n
"},{"location":"CHANGELOG/#render-fill-in-multiple-places","title":"Render fill in multiple places","text":"Added in version 0.70
You can render the same content in multiple places by defining multiple slots with identical names:
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"image\" %}Image here{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"image\" %}Image here{% endslot %}\n </div>\n</div>\n
So if used like:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"image\" %}\n <img src=\"...\" />\n {% endfill %}\n{% endcomponent %}\n
This renders:
<div class=\"calendar-component\">\n <div class=\"header\">\n <img src=\"...\" />\n </div>\n <div class=\"body\">\n <img src=\"...\" />\n </div>\n</div>\n
"},{"location":"CHANGELOG/#accessing-original-content-of-slots","title":"Accessing original content of slots","text":"Added in version 0.26
NOTE: In version 0.77, the syntax was changed from
{% fill \"my_slot\" as \"alias\" %} {{ alias.default }}\n
to
{% fill \"my_slot\" default=\"slot_default\" %} {{ slot_default }}\n
Sometimes you may want to keep the original slot, but only wrap or prepend/append content to it. To do so, you can access the default slot via the default
kwarg.
Similarly to the data
attribute, you specify the variable name through which the default slot will be made available.
For instance, let's say you're filling a slot called 'body'. To render the original slot, assign it to a variable using the 'default'
keyword. You then render this variable to insert the default content:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"body\" default=\"body_default\" %}\n {{ body_default }}. Have a great day!\n {% endfill %}\n{% endcomponent %}\n
This produces:
<div class=\"calendar-component\">\n <div class=\"header\">\n Calendar header\n </div>\n <div class=\"body\">\n Today's date is <span>2020-06-06</span>. Have a great day!\n </div>\n</div>\n
"},{"location":"CHANGELOG/#accessing-is_filled-of-slot-names-with-special-characters","title":"Accessing is_filled
of slot names with special characters","text":"To be able to access a slot name via component_vars.is_filled
, the slot name needs to be composed of only alphanumeric characters and underscores (e.g. this__isvalid_123
).
However, you can still define slots with other special characters. In such case, the slot name in component_vars.is_filled
is modified to replace all invalid characters into _
.
So a slot named \"my super-slot :)\"
will be available as component_vars.is_filled.my_super_slot___
.
"},{"location":"CHANGELOG/#passing-data-to-slots","title":"Passing data to slots","text":"To pass the data to the slot
tag, simply pass them as keyword attributes (key=value
):
@register(\"my_comp\")\nclass MyComp(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" default input=input %}\n input: {{ input }}\n {% endslot %}\n </div>\n \"\"\"\n\n def get_context_data(self, input):\n processed_input = do_something(input)\n return {\n \"input\": processed_input,\n }\n
"},{"location":"CHANGELOG/#passing-data-to-components","title":"Passing data to components","text":"As seen above, you can pass arguments to components like so:
<body>\n {% component \"calendar\" date=\"2015-06-19\" %}\n {% endcomponent %}\n</body>\n
"},{"location":"CHANGELOG/#rendering-html-attributes","title":"Rendering HTML attributes","text":"New in version 0.74:
You can use the html_attrs
tag to render HTML attributes, given a dictionary of values.
So if you have a template:
<div class=\"{{ classes }}\" data-id=\"{{ my_id }}\">\n</div>\n
You can simplify it with html_attrs
tag:
<div {% html_attrs attrs %}>\n</div>\n
where attrs
is:
attrs = {\n \"class\": classes,\n \"data-id\": my_id,\n}\n
This feature is inspired by merge_attrs
tag of django-web-components and \"fallthrough attributes\" feature of Vue.
"},{"location":"CHANGELOG/#boolean-attributes","title":"Boolean attributes","text":"In HTML, boolean attributes are usually rendered with no value. Consider the example below where the first button is disabled and the second is not:
<button disabled>Click me!</button> <button>Click me!</button>\n
HTML rendering with html_attrs
tag or attributes_to_string
works the same way, where key=True
is rendered simply as key
, and key=False
is not render at all.
So given this input:
attrs = {\n \"disabled\": True,\n \"autofocus\": False,\n}\n
And template:
<div {% html_attrs attrs %}>\n</div>\n
Then this renders:
<div disabled></div>\n
"},{"location":"CHANGELOG/#appending-attributes","title":"Appending attributes","text":"For the class
HTML attribute, it's common that we want to join multiple values, instead of overriding them. For example, if you're authoring a component, you may want to ensure that the component will ALWAYS have a specific class. Yet, you may want to allow users of your component to supply their own classes.
We can achieve this by adding extra kwargs. These values will be appended, instead of overwriting the previous value.
So if we have a variable attrs
:
attrs = {\n \"class\": \"my-class pa-4\",\n}\n
And on html_attrs
tag, we set the key class
:
<div {% html_attrs attrs class=\"some-class\" %}>\n</div>\n
Then these will be merged and rendered as:
<div data-value=\"my-class pa-4 some-class\"></div>\n
To simplify merging of variables, you can supply the same key multiple times, and these will be all joined together:
{# my_var = \"class-from-var text-red\" #}\n<div {% html_attrs attrs class=\"some-class another-class\" class=my_var %}>\n</div>\n
Renders:
<div\n data-value=\"my-class pa-4 some-class another-class class-from-var text-red\"\n></div>\n
"},{"location":"CHANGELOG/#examples-for-html_attrs","title":"Examples for html_attrs
","text":"Assuming that:
class_from_var = \"from-var\"\n\nattrs = {\n \"class\": \"from-attrs\",\n \"type\": \"submit\",\n}\n\ndefaults = {\n \"class\": \"from-defaults\",\n \"role\": \"button\",\n}\n
Then:
- Empty tag
{% html_attr %}
renders (empty string):
- Only kwargs
{% html_attr class=\"some-class\" class=class_from_var data-id=\"123\" %}
renders: class=\"some-class from-var\" data-id=\"123\"
- Only attrs
{% html_attr attrs %}
renders: class=\"from-attrs\" type=\"submit\"
- Attrs as kwarg
{% html_attr attrs=attrs %}
renders: class=\"from-attrs\" type=\"submit\"
- Only defaults (as kwarg)
{% html_attr defaults=defaults %}
renders: class=\"from-defaults\" role=\"button\"
- Attrs using the
prefix:key=value
construct {% html_attr attrs:class=\"from-attrs\" attrs:type=\"submit\" %}
renders: class=\"from-attrs\" type=\"submit\"
- Defaults using the
prefix:key=value
construct {% html_attr defaults:class=\"from-defaults\" %}
renders: class=\"from-defaults\" role=\"button\"
- All together (1) - attrs and defaults as positional args:
{% html_attrs attrs defaults class=\"added_class\" class=class_from_var data-id=123 %}
renders: class=\"from-attrs added_class from-var\" type=\"submit\" role=\"button\" data-id=123
- All together (2) - attrs and defaults as kwargs args:
{% html_attrs class=\"added_class\" class=class_from_var data-id=123 attrs=attrs defaults=defaults %}
renders: class=\"from-attrs added_class from-var\" type=\"submit\" role=\"button\" data-id=123
- All together (3) - mixed:
{% html_attrs attrs defaults:class=\"default-class\" class=\"added_class\" class=class_from_var data-id=123 %}
renders: class=\"from-attrs added_class from-var\" type=\"submit\" data-id=123
"},{"location":"CHANGELOG/#rendering-html-attributes-outside-of-templates","title":"Rendering HTML attributes outside of templates","text":"If you need to use serialize HTML attributes outside of Django template and the html_attrs
tag, you can use attributes_to_string
:
from django_components.attributes import attributes_to_string\n\nattrs = {\n \"class\": \"my-class text-red pa-4\",\n \"data-id\": 123,\n \"required\": True,\n \"disabled\": False,\n \"ignored-attr\": None,\n}\n\nattributes_to_string(attrs)\n## 'class=\"my-class text-red pa-4\" data-id=\"123\" required'\n
Special characters
New in version 0.71:
Keyword arguments can contain special characters # @ . - _
, so keywords like so are still valid:
<body>\n {% component \"calendar\" my-date=\"2015-06-19\" @click.native=do_something #some_id=True / %}\n</body>\n
These can then be accessed inside get_context_data
so:
@register(\"calendar\")\nclass Calendar(Component):\n # Since # . @ - are not valid identifiers, we have to\n # use `**kwargs` so the method can accept these args.\n def get_context_data(self, **kwargs):\n return {\n \"date\": kwargs[\"my-date\"],\n \"id\": kwargs[\"#some_id\"],\n \"on_click\": kwargs[\"@click.native\"]\n }\n
"},{"location":"CHANGELOG/#pass-dictonary-by-its-key-value-pairs","title":"Pass dictonary by its key-value pairs","text":"New in version 0.74:
Sometimes, a component may expect a dictionary as one of its inputs.
Most commonly, this happens when a component accepts a dictionary of HTML attributes (usually called attrs
) to pass to the underlying template.
In such cases, we may want to define some HTML attributes statically, and other dynamically. But for that, we need to define this dictionary on Python side:
@register(\"my_comp\")\nclass MyComp(Component):\n template = \"\"\"\n {% component \"other\" attrs=attrs / %}\n \"\"\"\n\n def get_context_data(self, some_id: str):\n attrs = {\n \"class\": \"pa-4 flex\",\n \"data-some-id\": some_id,\n \"@click.stop\": \"onClickHandler\",\n }\n return {\"attrs\": attrs}\n
But as you can see in the case above, the event handler @click.stop
and styling pa-4 flex
are disconnected from the template. If the component grew in size and we moved the HTML to a separate file, we would have hard time reasoning about the component's template.
Luckily, there's a better way.
When we want to pass a dictionary to a component, we can define individual key-value pairs as component kwargs, so we can keep all the relevant information in the template. For that, we prefix the key with the name of the dict and :
. So key class
of input attrs
becomes attrs:class
. And our example becomes:
@register(\"my_comp\")\nclass MyComp(Component):\n template = \"\"\"\n {% component \"other\"\n attrs:class=\"pa-4 flex\"\n attrs:data-some-id=some_id\n attrs:@click.stop=\"onClickHandler\"\n / %}\n \"\"\"\n\n def get_context_data(self, some_id: str):\n return {\"some_id\": some_id}\n
Sweet! Now all the relevant HTML is inside the template, and we can move it to a separate file with confidence:
{% component \"other\"\n attrs:class=\"pa-4 flex\"\n attrs:data-some-id=some_id\n attrs:@click.stop=\"onClickHandler\"\n/ %}\n
Note: It is NOT possible to define nested dictionaries, so attrs:my_key:two=2
would be interpreted as:
{\"attrs\": {\"my_key:two\": 2}}\n
What is \"dependency injection\" and \"prop drilling\"?
Prop drilling refers to a scenario in UI development where you need to pass data through many layers of a component tree to reach the nested components that actually need the data.
Normally, you'd use props to send data from a parent component to its children. However, this straightforward method becomes cumbersome and inefficient if the data has to travel through many levels or if several components scattered at different depths all need the same piece of information.
This results in a situation where the intermediate components, which don't need the data for their own functioning, end up having to manage and pass along these props. This clutters the component tree and makes the code verbose and harder to manage.
A neat solution to avoid prop drilling is using the \"provide and inject\" technique, AKA dependency injection.
With dependency injection, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.
This feature is inspired by Vue's Provide / Inject and React's Context / useContext.
"},{"location":"CHANGELOG/#using-provide-tag","title":"Using {% provide %}
tag","text":"First we use the {% provide %}
tag to define the data we want to \"provide\" (make available).
{% provide \"my_data\" key=\"hi\" another=123 %}\n {% component \"child\" / %} <--- Can access \"my_data\"\n{% endprovide %}\n\n{% component \"child\" / %} <--- Cannot access \"my_data\"\n
Notice that the provide
tag REQUIRES a name as a first argument. This is the key by which we can then access the data passed to this tag.
provide
tag key, similarly to the name argument in component
or slot
tags, has these requirements:
- The key must be a string literal
- It must be a valid identifier (AKA a valid Python variable name)
Once you've set the name, you define the data you want to \"provide\" by passing it as keyword arguments. This is similar to how you pass data to the {% with %}
tag.
NOTE: Kwargs passed to {% provide %}
are NOT added to the context. In the example below, the {{ key }}
won't render anything:
{% provide \"my_data\" key=\"hi\" another=123 %}\n {{ key }}\n{% endprovide %}\n
"},{"location":"CHANGELOG/#full-example","title":"Full example","text":"@register(\"child\")\nclass ChildComponent(Component):\n template = \"\"\"\n <div> {{ my_data.key }} </div>\n <div> {{ my_data.another }} </div>\n \"\"\"\n\n def get_context_data(self):\n my_data = self.inject(\"my_data\", \"default\")\n return {\"my_data\": my_data}\n\ntemplate_str = \"\"\"\n {% load component_tags %}\n {% provide \"my_data\" key=\"hi\" another=123 %}\n {% component \"child\" / %}\n {% endprovide %}\n\"\"\"\n
renders:
<div>hi</div>\n<div>123</div>\n
Customizing component tags with TagFormatter
New in version 0.89
By default, components are rendered using the pair of {% component %}
/ {% endcomponent %}
template tags:
{% component \"button\" href=\"...\" disabled %}\nClick me!\n{% endcomponent %}\n\n{# or #}\n\n{% component \"button\" href=\"...\" disabled / %}\n
You can change this behaviour in the settings under the COMPONENTS.tag_formatter
.
For example, if you set the tag formatter to django_components.shorthand_component_formatter
, the components will use their name as the template tags:
{% button href=\"...\" disabled %}\n Click me!\n{% endbutton %}\n\n{# or #}\n\n{% button href=\"...\" disabled / %}\n
"},{"location":"CHANGELOG/#writing-your-own-tagformatter","title":"Writing your own TagFormatter","text":""},{"location":"CHANGELOG/#tagformatter","title":"TagFormatter","text":"TagFormatter
handles following parts of the process above: - Generates start/end tags, given a component. This is what you then call from within your template as {% component %}
.
- When you
{% component %}
, tag formatter pre-processes the tag contents, so it can link back the custom template tag to the right component.
To do so, subclass from TagFormatterABC
and implement following method: - start_tag
- end_tag
- parse
For example, this is the implementation of ShorthandComponentFormatter
class ShorthandComponentFormatter(TagFormatterABC):\n # Given a component name, generate the start template tag\n def start_tag(self, name: str) -> str:\n return name # e.g. 'button'\n\n # Given a component name, generate the start template tag\n def end_tag(self, name: str) -> str:\n return f\"end{name}\" # e.g. 'endbutton'\n\n # Given a tag, e.g.\n # `{% button href=\"...\" disabled %}`\n #\n # The parser receives:\n # `['button', 'href=\"...\"', 'disabled']`\n def parse(self, tokens: List[str]) -> TagResult:\n tokens = [*tokens]\n name = tokens.pop(0)\n return TagResult(\n name, # e.g. 'button'\n tokens # e.g. ['href=\"...\"', 'disabled']\n )\n
That's it! And once your TagFormatter
is ready, don't forget to update the settings!
Defining file paths relative to component or static dirs
As seen in the getting started example, to associate HTML/JS/CSS files with a component, you set them as template_name
, Media.js
and Media.css
respectively:
## In a file [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"template.html\"\n\n class Media:\n css = \"style.css\"\n js = \"script.js\"\n
In the example above, the files are defined relative to the directory where component.py
is.
Alternatively, you can specify the file paths relative to the directories set in STATICFILES_DIRS
.
Assuming that STATICFILES_DIRS
contains path [project root]/components
, we can rewrite the example as:
## In a file [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"calendar/template.html\"\n\n class Media:\n css = \"calendar/style.css\"\n js = \"calendar/script.js\"\n
NOTE: In case of conflict, the preference goes to resolving the files relative to the component's directory.
"},{"location":"CHANGELOG/#configuring-css-media-types","title":"Configuring CSS Media Types","text":"You can define which stylesheets will be associated with which CSS Media types. You do so by defining CSS files as a dictionary.
See the corresponding Django Documentation.
Again, you can set either a single file or a list of files per media type:
class MyComponent(Component):\n class Media:\n css = {\n \"all\": \"path/to/style1.css\",\n \"print\": \"path/to/style2.css\",\n }\n
class MyComponent(Component):\n class Media:\n css = {\n \"all\": [\"path/to/style1.css\", \"path/to/style2.css\"],\n \"print\": [\"path/to/style3.css\", \"path/to/style4.css\"],\n }\n
NOTE: When you define CSS as a string or a list, the all
media type is implied.
"},{"location":"CHANGELOG/#path-as-objects","title":"Path as objects","text":"In the example above, you could see that when we used mark_safe
to mark a string as a SafeString
, we had to define the full <script>
/<link>
tag.
This is an extension of Django's Paths as objects feature, where \"safe\" strings are taken as is, and accessed only at render time.
Because of that, the paths defined as \"safe\" strings are NEVER resolved, neither relative to component's directory, nor relative to STATICFILES_DIRS
.
\"Safe\" strings can be used to lazily resolve a path, or to customize the <script>
or <link>
tag for individual paths:
class LazyJsPath:\n def __init__(self, static_path: str) -> None:\n self.static_path = static_path\n\n def __html__(self):\n full_path = static(self.static_path)\n return format_html(\n f'<script type=\"module\" src=\"{full_path}\"></script>'\n )\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"calendar/template.html\"\n\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n\n class Media:\n css = \"calendar/style.css\"\n js = [\n # <script> tag constructed by Media class\n \"calendar/script1.js\",\n # Custom <script> tag\n LazyJsPath(\"calendar/script2.js\"),\n ]\n
"},{"location":"CHANGELOG/#rendering-jscss-dependencies","title":"Rendering JS/CSS dependencies","text":"The JS and CSS files included in components are not automatically rendered. Instead, use the following tags to specify where to render the dependencies:
component_dependencies
- Renders both JS and CSS component_js_dependencies
- Renders only JS component_css_dependencies
- Reneders only CSS
JS files are rendered as <script>
tags. CSS files are rendered as <style>
tags.
"},{"location":"CHANGELOG/#available-settings","title":"Available settings","text":"All library settings are handled from a global COMPONENTS
variable that is read from settings.py
. By default you don't need it set, there are resonable defaults.
"},{"location":"CHANGELOG/#disable-autodiscovery","title":"Disable autodiscovery","text":"If you specify all the component locations with the setting above and have a lot of apps, you can (very) slightly speed things up by disabling autodiscovery.
COMPONENTS = {\n \"autodiscover\": False,\n}\n
"},{"location":"CHANGELOG/#context-behavior-setting","title":"Context behavior setting","text":"NOTE: context_behavior
and slot_context_behavior
options were merged in v0.70.
If you are migrating from BEFORE v0.67, set context_behavior
to \"django\"
. From v0.67 to v0.78 (incl) the default value was \"isolated\"
.
For v0.79 and later, the default is again \"django\"
. See the rationale for change here.
You can configure what variables are available inside the {% fill %}
tags. See Component context and scope.
This has two modes:
\"django\"
- Default - The default Django template behavior.
Inside the {% fill %}
tag, the context variables you can access are a union of:
- All the variables that were OUTSIDE the fill tag, including any loops or with tag
-
Data returned from get_context_data()
of the component that wraps the fill tag.
-
\"isolated\"
- Similar behavior to Vue or React, this is useful if you want to make sure that components don't accidentally access variables defined outside of the component.
Inside the {% fill %}
tag, you can ONLY access variables from 2 places:
get_context_data()
of the component which defined the template (AKA the \"root\" component) - Any loops (
{% for ... %}
) that the {% fill %}
tag is part of.
COMPONENTS = {\n \"context_behavior\": \"isolated\",\n}\n
"},{"location":"CHANGELOG/#example-isolated","title":"Example \"isolated\"","text":"Given this template:
class RootComp(Component):\n template = \"\"\"\n {% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n {% endwith %}\n \"\"\"\n def get_context_data(self):\n return { \"my_var\": 123 }\n
Then if get_context_data()
of the component \"my_comp\"
returns following data:
{ \"my_var\": 456 }\n
Then the template will be rendered as:
123 # my_var\n # cheese\n
Because variables \"my_var\"
and \"cheese\"
are searched only inside RootComponent.get_context_data()
. But since \"cheese\"
is not defined there, it's empty.
Notice that the variables defined with the {% with %}
tag are ignored inside the {% fill %}
tag with the \"isolated\"
mode.
"},{"location":"CHANGELOG/#logging-and-debugging","title":"Logging and debugging","text":"Django components supports logging with Django. This can help with troubleshooting.
To configure logging for Django components, set the django_components
logger in LOGGING
in settings.py
(below).
Also see the settings.py
file in sampleproject for a real-life example.
import logging\nimport sys\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n \"handlers\": {\n \"console\": {\n 'class': 'logging.StreamHandler',\n 'stream': sys.stdout,\n },\n },\n \"loggers\": {\n \"django_components\": {\n \"level\": logging.DEBUG,\n \"handlers\": [\"console\"],\n },\n },\n}\n
Management Command Usage
To use the command, run the following command in your terminal:
python manage.py startcomponent <name> --path <path> --js <js_filename> --css <css_filename> --template <template_filename> --force --verbose --dry-run\n
Replace <name>
, <path>
, <js_filename>
, <css_filename>
, and <template_filename>
with your desired values.
"},{"location":"CHANGELOG/#creating-a-component-with-default-settings","title":"Creating a Component with Default Settings","text":"To create a component with the default settings, you only need to provide the name of the component:
python manage.py startcomponent my_component\n
This will create a new component named my_component
in the components
directory of your Django project. The JavaScript, CSS, and template files will be named script.js
, style.css
, and template.html
, respectively.
"},{"location":"CHANGELOG/#overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"If you want to overwrite an existing component, you can use the --force
option:
python manage.py startcomponent my_component --force\n
This will overwrite the existing my_component
if it exists.
"},{"location":"CHANGELOG/#community-examples","title":"Community examples","text":"One of our goals with django-components
is to make it easy to share components between projects. If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.
- django-htmx-components: A set of components for use with htmx. Try out the live demo.
Install locally and run the tests
Start by forking the project by clicking the Fork button up in the right corner in the GitHub . This makes a copy of the repository in your own name. Now you can clone this repository locally and start adding features:
git clone https://github.com/<your GitHub username>/django-components.git\n
To quickly run the tests install the local dependencies by running:
pip install -r requirements-dev.txt\n
Now you can run the tests to make sure everything works as expected:
pytest\n
The library is also tested across many versions of Python and Django. To run tests that way:
pyenv install -s 3.8\npyenv install -s 3.9\npyenv install -s 3.10\npyenv install -s 3.11\npyenv install -s 3.12\npyenv local 3.8 3.9 3.10 3.11 3.12\ntox -p\n
"},{"location":"CHANGELOG/#development-guides","title":"Development guides","text":""},{"location":"CODE_OF_CONDUCT/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"CODE_OF_CONDUCT/#our-pledge","title":"Our Pledge","text":"In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
"},{"location":"CODE_OF_CONDUCT/#our-standards","title":"Our Standards","text":"Examples of behavior that contributes to creating a positive environment include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
"},{"location":"CODE_OF_CONDUCT/#our-responsibilities","title":"Our Responsibilities","text":"Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
"},{"location":"CODE_OF_CONDUCT/#scope","title":"Scope","text":"This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
"},{"location":"CODE_OF_CONDUCT/#enforcement","title":"Enforcement","text":"Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at emil@emilstenstrom.se. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
"},{"location":"CODE_OF_CONDUCT/#attribution","title":"Attribution","text":"This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq
"},{"location":"SUMMARY/","title":"SUMMARY","text":" - README
- Changelog
- Code of Conduct
- License
- Reference
- API Reference
"},{"location":"license/","title":"License","text":"MIT License
Copyright (c) 2019 Emil Stenstr\u00f6m
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"},{"location":"slot_rendering/","title":"Slot rendering","text":"This doc serves as a primer on how component slots and fills are resolved.
"},{"location":"slot_rendering/#flow","title":"Flow","text":" -
Imagine you have a template. Some kind of text, maybe HTML:
| ------\n| ---------\n| ----\n| -------\n
-
The template may contain some vars, tags, etc
| -- {{ my_var }} --\n| ---------\n| ----\n| -------\n
-
The template also contains some slots, etc
| -- {{ my_var }} --\n| ---------\n| -- {% slot \"myslot\" %} ---\n| -- {% endslot %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| -- {% endslot %} ---\n| -------\n
-
Slots may be nested
| -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %} ---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- JKL {{ my_var }}\n| -- {% endslot %} ---\n| -------\n
-
Some slots may be inside fills for other components
| -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %}---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ------\n| -- {% component \"mycomp\" %} ---\n| ---- {% slot \"myslot\" %} ---\n| ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n| ---- {% endslot %} ---\n| -- {% endcomponent %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- PQR {{ my_var }}\n| -- {% endslot %} ---\n| -------\n
-
I want to render the slots with {% fill %}
tag that were defined OUTSIDE of this template. How do I do that?
-
Traverse the template to collect ALL slots
- NOTE: I will also look inside
{% slot %}
and {% fill %}
tags, since they are all still defined within the same TEMPLATE.
I should end up with a list like this:
- Name: \"myslot\"\n ID 0001\n Content:\n | ----- DEF {{ my_var }}\n | ----- {% slot \"myslot_inner\" %}\n | -------- GHI {{ my_var }}\n | ----- {% endslot %}\n- Name: \"myslot_inner\"\n ID 0002\n Content:\n | -------- GHI {{ my_var }}\n- Name: \"myslot\"\n ID 0003\n Content:\n | ------- JKL {{ my_var }}\n | ------- {% slot \"myslot_inner\" %}\n | ---------- MNO {{ my_var }}\n | ------- {% endslot %}\n- Name: \"myslot_inner\"\n ID 0004\n Content:\n | ---------- MNO {{ my_var }}\n- Name: \"myslot2\"\n ID 0005\n Content:\n | ---- PQR {{ my_var }}\n
-
Note the relationships - which slot is nested in which one
I should end up with a graph-like data like:
- 0001: [0002]\n- 0002: []\n- 0003: [0004]\n- 0004: []\n- 0005: []\n
In other words, the data tells us that slot ID 0001
is PARENT of slot 0002
.
This is important, because, IF parent template provides slot fill for slot 0001, then we DON'T NEED TO render it's children, AKA slot 0002.
-
Find roots of the slot relationships
The data from previous step can be understood also as a collection of directled acyclig graphs (DAG), e.g.:
0001 --> 0002\n0003 --> 0004\n0005\n
So we find the roots (0001
, 0003
, 0005
), AKA slots that are NOT nested in other slots. We do so by going over ALL entries from previous step. Those IDs which are NOT mentioned in ANY of the lists are the roots.
Because of the nature of nested structures, there cannot be any cycles.
-
Recursively render slots, starting from roots.
-
First we take each of the roots.
-
Then we check if there is a slot fill for given slot name.
-
If YES we replace the slot node with the fill node.
-
If NO, then we will replace slot nodes with their children, e.g.:
| ---- {% slot \"myslot\" %} ---\n| ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n| ---- {% endslot %} ---\n
Becomes | ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n
-
We check if the slot includes any children {% slot %}
tags. If YES, then continue with step 4. for them, and wait until they finish.
-
At this point, ALL slots should be rendered and we should have something like this:
| -- {{ my_var }} --\n| -- ABC\n| ----- DEF {{ my_var }}\n| -------- GHI {{ my_var }}\n| ------\n| -- {% component \"mycomp\" %} ---\n| ------- JKL {{ my_var }}\n| ---- {% component \"mycomp\" %} ---\n| ---------- MNO {{ my_var }}\n| ---- {% endcomponent %} ---\n| -- {% endcomponent %} ---\n| ----\n| -- {% component \"mycomp2\" %} ---\n| ---- PQR {{ my_var }}\n| -- {% endcomponent %} ---\n| ----\n
- NOTE: Inserting fills into {% slots %} should NOT introduce new {% slots %}, as the fills should be already rendered!
"},{"location":"slot_rendering/#using-the-correct-context-in-slotfill-tags","title":"Using the correct context in {% slot/fill %} tags","text":"In previous section, we said that the {% fill %}
tags should be already rendered by the time they are inserted into the {% slot %}
tags.
This is not quite true. To help you understand, consider this complex case:
| -- {% for var in [1, 2, 3] %} ---\n| ---- {% component \"mycomp2\" %} ---\n| ------ {% fill \"first\" %}\n| ------- STU {{ my_var }}\n| ------- {{ var }}\n| ------ {% endfill %}\n| ------ {% fill \"second\" %}\n| -------- {% component var=var my_var=my_var %}\n| ---------- VWX {{ my_var }}\n| -------- {% endcomponent %}\n| ------ {% endfill %}\n| ---- {% endcomponent %} ---\n| -- {% endfor %} ---\n| -------\n
We want the forloop variables to be available inside the {% fill %}
tags. Because of that, however, we CANNOT render the fills/slots in advance.
Instead, our solution is closer to how Vue handles slots. In Vue, slots are effectively functions that accept a context variables and render some content.
While we do not wrap the logic in a function, we do PREPARE IN ADVANCE: 1. The content that should be rendered for each slot 2. The context variables from get_context_data()
Thus, once we reach the {% slot %}
node, in it's render()
method, we access the data above, and, depending on the context_behavior
setting, include the current context or not. For more info, see SlotNode.render()
.
"},{"location":"slots_and_blocks/","title":"Using slot
and block
tags","text":" -
First let's clarify how include
and extends
tags work inside components. So when component template includes include
or extends
tags, it's as if the \"included\" template was inlined. So if the \"included\" template contains slot
tags, then the component uses those slots.
So if you have a template `abc.html`:\n```django\n<div>\n hello\n {% slot \"body\" %}{% endslot %}\n</div>\n```\n\nAnd components that make use of `abc.html` via `include` or `extends`:\n```py\nfrom django_components import Component, register\n\n@register(\"my_comp_extends\")\nclass MyCompWithExtends(Component):\n template = \"\"\"{% extends \"abc.html\" %}\"\"\"\n\n@register(\"my_comp_include\")\nclass MyCompWithInclude(Component):\n template = \"\"\"{% include \"abc.html\" %}\"\"\"\n```\n\nThen you can set slot fill for the slot imported via `include/extends`:\n\n```django\n{% component \"my_comp_extends\" %}\n {% fill \"body\" %}\n 123\n {% endfill %}\n{% endcomponent %}\n```\n\nAnd it will render:\n```html\n<div>\n hello\n 123\n</div>\n```\n
-
Slot and block
So if you have a template abc.html
like so:
<div>\n hello\n {% block inner %}\n 1\n {% slot \"body\" %}\n 2\n {% endslot %}\n {% endblock %}\n</div>\n
and component my_comp
:
@register(\"my_comp\")\nclass MyComp(Component):\n template_name = \"abc.html\"\n
Then:
-
Since the block
wasn't overriden, you can use the body
slot:
{% component \"my_comp\" %}\n {% fill \"body\" %}\n XYZ\n {% endfill %}\n{% endcomponent %}\n
And we get:
<div>hello 1 XYZ</div>\n
-
blocks
CANNOT be overriden through the component
tag, so something like this:
{% component \"my_comp\" %}\n {% fill \"body\" %}\n XYZ\n {% endfill %}\n{% endcomponent %}\n{% block \"inner\" %}\n 456\n{% endblock %}\n
Will still render the component content just the same:
<div>hello 1 XYZ</div>\n
-
You CAN override the block
tags of abc.html
if my component template uses extends
. In that case, just as you would expect, the block inner
inside abc.html
will render OVERRIDEN
:
@register(\"my_comp\")\nclass MyComp(Component):\ntemplate_name = \"\"\"\n{% extends \"abc.html\" %}\n\n {% block inner %}\n OVERRIDEN\n {% endblock %}\n \"\"\"\n ```\n
-
This is where it gets interesting (but still intuitive). You can insert even new slots
inside these \"overriding\" blocks:
@register(\"my_comp\")\nclass MyComp(Component):\n template_name = \"\"\"\n {% extends \"abc.html\" %}\n\n {% load component_tags %}\n {% block \"inner\" %}\n OVERRIDEN\n {% slot \"new_slot\" %}\n hello\n {% endslot %}\n {% endblock %}\n \"\"\"\n
And you can then pass fill for this new_slot
when rendering the component:
{% component \"my_comp\" %}\n {% fill \"new_slot\" %}\n XYZ\n {% endfill %}\n{% endcomponent %}\n
NOTE: Currently you can supply fills for both new_slot
and body
slots, and you will not get an error for an invalid/unknown slot name. But since body
slot is not rendered, it just won't do anything. So this renders the same as above:
{% component \"my_comp\" %}\n {% fill \"new_slot\" %}\n XYZ\n {% endfill %}\n {% fill \"body\" %}\n www\n {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/SUMMARY/","title":"SUMMARY","text":" - django_components
- app_settings
- apps
- attributes
- autodiscover
- component
- component_media
- component_registry
- context
- expression
- library
- logger
- management
- commands
- startcomponent
- upgradecomponent
- middleware
- node
- provide
- safer_staticfiles
- slots
- tag_formatter
- template_loader
- template_parser
- templatetags
- types
- utils
"},{"location":"reference/django_components/","title":"Index","text":""},{"location":"reference/django_components/#django_components","title":"django_components","text":"Main package for Django Components.
"},{"location":"reference/django_components/#django_components.app_settings","title":"app_settings","text":""},{"location":"reference/django_components/#django_components.app_settings.ContextBehavior","title":"ContextBehavior","text":" Bases: str
, Enum
"},{"location":"reference/django_components/#django_components.app_settings.ContextBehavior.DJANGO","title":"DJANGO class-attribute
instance-attribute
","text":"DJANGO = 'django'\n
With this setting, component fills behave as usual Django tags. That is, they enrich the context, and pass it along.
- Component fills use the context of the component they are within.
- Variables from
get_context_data
are available to the component fill.
Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the get_context_data()
method
{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
456 # my_var\nfeta # cheese\n
Because \"my_comp\" overrides the variable \"my_var\", so {{ my_var }}
equals 456
.
And variable \"cheese\" will equal feta
, because the fill CAN access the current context.
"},{"location":"reference/django_components/#django_components.app_settings.ContextBehavior.ISOLATED","title":"ISOLATED class-attribute
instance-attribute
","text":"ISOLATED = 'isolated'\n
This setting makes the component fills behave similar to Vue or React, where the fills use EXCLUSIVELY the context variables defined in get_context_data
.
Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the get_context_data()
method
{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
123 # my_var\n # cheese\n
Because both variables \"my_var\" and \"cheese\" are taken from the root context. Since \"cheese\" is not defined in root context, it's empty.
"},{"location":"reference/django_components/#django_components.attributes","title":"attributes","text":""},{"location":"reference/django_components/#django_components.attributes.append_attributes","title":"append_attributes","text":"append_attributes(*args: Tuple[str, Any]) -> Dict\n
Merges the key-value pairs and returns a new dictionary.
If a key is present multiple times, its values are concatenated with a space character as separator in the final dictionary.
Source code in src/django_components/attributes.py
def append_attributes(*args: Tuple[str, Any]) -> Dict:\n \"\"\"\n Merges the key-value pairs and returns a new dictionary.\n\n If a key is present multiple times, its values are concatenated with a space\n character as separator in the final dictionary.\n \"\"\"\n result: Dict = {}\n\n for key, value in args:\n if key in result:\n result[key] += \" \" + value\n else:\n result[key] = value\n\n return result\n
"},{"location":"reference/django_components/#django_components.attributes.attributes_to_string","title":"attributes_to_string","text":"attributes_to_string(attributes: Mapping[str, Any]) -> str\n
Convert a dict of attributes to a string.
Source code in src/django_components/attributes.py
def attributes_to_string(attributes: Mapping[str, Any]) -> str:\n \"\"\"Convert a dict of attributes to a string.\"\"\"\n attr_list = []\n\n for key, value in attributes.items():\n if value is None or value is False:\n continue\n if value is True:\n attr_list.append(conditional_escape(key))\n else:\n attr_list.append(format_html('{}=\"{}\"', key, value))\n\n return mark_safe(SafeString(\" \").join(attr_list))\n
"},{"location":"reference/django_components/#django_components.autodiscover","title":"autodiscover","text":""},{"location":"reference/django_components/#django_components.autodiscover.autodiscover","title":"autodiscover","text":"autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Search for component files and import them. Returns a list of module paths of imported files.
Autodiscover searches in the locations as defined by Loader.get_dirs
.
You can map the module paths with map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Source code in src/django_components/autodiscover.py
def autodiscover(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Search for component files and import them. Returns a list of module\n paths of imported files.\n\n Autodiscover searches in the locations as defined by `Loader.get_dirs`.\n\n You can map the module paths with `map_module` function. This serves\n as an escape hatch for when you need to use this function in tests.\n \"\"\"\n dirs = get_dirs()\n component_filepaths = search_dirs(dirs, \"**/*.py\")\n logger.debug(f\"Autodiscover found {len(component_filepaths)} files in component directories.\")\n\n modules = [_filepath_to_python_module(filepath) for filepath in component_filepaths]\n return _import_modules(modules, map_module)\n
"},{"location":"reference/django_components/#django_components.autodiscover.get_dirs","title":"get_dirs","text":"get_dirs(engine: Optional[Engine] = None) -> List[Path]\n
Helper for using django_component's FilesystemLoader class to obtain a list of directories where component python files may be defined.
Source code in src/django_components/autodiscover.py
def get_dirs(engine: Optional[Engine] = None) -> List[Path]:\n \"\"\"\n Helper for using django_component's FilesystemLoader class to obtain a list\n of directories where component python files may be defined.\n \"\"\"\n current_engine = engine\n if current_engine is None:\n current_engine = Engine.get_default()\n\n loader = Loader(current_engine)\n return loader.get_dirs()\n
"},{"location":"reference/django_components/#django_components.autodiscover.import_libraries","title":"import_libraries","text":"import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Import modules set in COMPONENTS.libraries
setting.
You can map the module paths with map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Source code in src/django_components/autodiscover.py
def import_libraries(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Import modules set in `COMPONENTS.libraries` setting.\n\n You can map the module paths with `map_module` function. This serves\n as an escape hatch for when you need to use this function in tests.\n \"\"\"\n from django_components.app_settings import app_settings\n\n return _import_modules(app_settings.LIBRARIES, map_module)\n
"},{"location":"reference/django_components/#django_components.autodiscover.search_dirs","title":"search_dirs","text":"search_dirs(dirs: List[Path], search_glob: str) -> List[Path]\n
Search the directories for the given glob pattern. Glob search results are returned as a flattened list.
Source code in src/django_components/autodiscover.py
def search_dirs(dirs: List[Path], search_glob: str) -> List[Path]:\n \"\"\"\n Search the directories for the given glob pattern. Glob search results are returned\n as a flattened list.\n \"\"\"\n matched_files: List[Path] = []\n for directory in dirs:\n for path in glob.iglob(str(Path(directory) / search_glob), recursive=True):\n matched_files.append(Path(path))\n\n return matched_files\n
"},{"location":"reference/django_components/#django_components.component","title":"component","text":""},{"location":"reference/django_components/#django_components.component.Component","title":"Component","text":"Component(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n fill_content: Optional[Dict[str, FillContent]] = None,\n)\n
Bases: Generic[ArgsType, KwargsType, DataType, SlotsType]
Source code in src/django_components/component.py
def __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n fill_content: Optional[Dict[str, FillContent]] = None,\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.fill_content = fill_content or {}\n self.component_id = component_id or gen_id()\n self._render_stack: Deque[RenderInput[ArgsType, KwargsType, SlotsType]] = deque()\n
"},{"location":"reference/django_components/#django_components.component.Component.Media","title":"Media class-attribute
instance-attribute
","text":"Media = ComponentMediaInput\n
Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/#django_components.component.Component.css","title":"css class-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/#django_components.component.Component.input","title":"input property
","text":"input: Optional[RenderInput[ArgsType, KwargsType, SlotsType]]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the render
method.
"},{"location":"reference/django_components/#django_components.component.Component.js","title":"js class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/#django_components.component.Component.media","title":"media instance-attribute
","text":"media: Media\n
Normalized definition of JS and CSS media files associated with this component.
NOTE: This field is generated from Component.Media class.
"},{"location":"reference/django_components/#django_components.component.Component.response_class","title":"response_class class-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from render_to_response
"},{"location":"reference/django_components/#django_components.component.Component.template","title":"template class-attribute
instance-attribute
","text":"template: Optional[str] = None\n
Inlined Django template associated with this component.
"},{"location":"reference/django_components/#django_components.component.Component.template_name","title":"template_name class-attribute
","text":"template_name: Optional[str] = None\n
Relative filepath to the Django template associated with this component.
"},{"location":"reference/django_components/#django_components.component.Component.as_view","title":"as_view classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling Component.View.as_view
and passing component instance to it.
Source code in src/django_components/component.py
@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # Allow the View class to access this component via `self.component`\n component = cls()\n return component.View.as_view(**initkwargs, component=component)\n
"},{"location":"reference/django_components/#django_components.component.Component.inject","title":"inject","text":"inject(key: str, default: Optional[Any] = None) -> Any\n
Use this method to retrieve the data that was passed to a {% provide %}
tag with the corresponding key.
To retrieve the data, inject()
must be called inside a component that's inside the {% provide %}
tag.
You may also pass a default that will be used if the provide
tag with given key was NOT found.
This method mut be used inside the get_context_data()
method and raises an error if called elsewhere.
Example:
Given this template:
{% provide \"provider\" hello=\"world\" %}\n {% component \"my_comp\" %}\n {% endcomponent %}\n{% endprovide %}\n
And given this definition of \"my_comp\" component:
from django_components import Component, register\n\n@register(\"my_comp\")\nclass MyComp(Component):\n template = \"hi {{ data.hello }}!\"\n def get_context_data(self):\n data = self.inject(\"provider\")\n return {\"data\": data}\n
This renders into:
hi world!\n
As the {{ data.hello }}
is taken from the \"provider\".
Source code in src/django_components/component.py
def inject(self, key: str, default: Optional[Any] = None) -> Any:\n \"\"\"\n Use this method to retrieve the data that was passed to a `{% provide %}` tag\n with the corresponding key.\n\n To retrieve the data, `inject()` must be called inside a component that's\n inside the `{% provide %}` tag.\n\n You may also pass a default that will be used if the `provide` tag with given\n key was NOT found.\n\n This method mut be used inside the `get_context_data()` method and raises\n an error if called elsewhere.\n\n Example:\n\n Given this template:\n ```django\n {% provide \"provider\" hello=\"world\" %}\n {% component \"my_comp\" %}\n {% endcomponent %}\n {% endprovide %}\n ```\n\n And given this definition of \"my_comp\" component:\n ```py\n from django_components import Component, register\n\n @register(\"my_comp\")\n class MyComp(Component):\n template = \"hi {{ data.hello }}!\"\n def get_context_data(self):\n data = self.inject(\"provider\")\n return {\"data\": data}\n ```\n\n This renders into:\n ```\n hi world!\n ```\n\n As the `{{ data.hello }}` is taken from the \"provider\".\n \"\"\"\n if self.input is None:\n raise RuntimeError(\n f\"Method 'inject()' of component '{self.name}' was called outside of 'get_context_data()'\"\n )\n\n return get_injected_context_var(self.name, self.input.context, key, default)\n
"},{"location":"reference/django_components/#django_components.component.Component.render","title":"render classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n) -> str\n
Render the component into a string.
Inputs: - args
- Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %}
- kwargs
- Kwargs for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %}
- slots
- Component slot fills. This is the same as pasing {% fill %}
tags to the component. Accepts a dictionary of { slot_name: slot_content }
where slot_content
can be a string or render function. - escape_slots_content
- Whether the content from slots
should be escaped. - context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs.
Example:
MyComponent.render(\n args=[1, \"two\", {}],\n kwargs={\n \"key\": 123,\n },\n slots={\n \"header\": 'STATIC TEXT HERE',\n \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n },\n escape_slots_content=False,\n)\n
Source code in src/django_components/component.py
@classmethod\ndef render(\n cls,\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n) -> str:\n \"\"\"\n Render the component into a string.\n\n Inputs:\n - `args` - Positional args for the component. This is the same as calling the component\n as `{% component \"my_comp\" arg1 arg2 ... %}`\n - `kwargs` - Kwargs for the component. This is the same as calling the component\n as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n or render function.\n - `escape_slots_content` - Whether the content from `slots` should be escaped.\n - `context` - A context (dictionary or Django's Context) within which the component\n is rendered. The keys on the context can be accessed from within the template.\n - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n component's args and kwargs.\n\n Example:\n ```py\n MyComponent.render(\n args=[1, \"two\", {}],\n kwargs={\n \"key\": 123,\n },\n slots={\n \"header\": 'STATIC TEXT HERE',\n \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n },\n escape_slots_content=False,\n )\n ```\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n return comp._render(context, args, kwargs, slots, escape_slots_content)\n
"},{"location":"reference/django_components/#django_components.component.Component.render_css_dependencies","title":"render_css_dependencies","text":"render_css_dependencies() -> SafeString\n
Render only CSS dependencies available in the media class or provided as a string.
Source code in src/django_components/component.py
def render_css_dependencies(self) -> SafeString:\n \"\"\"Render only CSS dependencies available in the media class or provided as a string.\"\"\"\n if self.css is not None:\n return mark_safe(f\"<style>{self.css}</style>\")\n return mark_safe(\"\\n\".join(self.media.render_css()))\n
"},{"location":"reference/django_components/#django_components.component.Component.render_dependencies","title":"render_dependencies","text":"render_dependencies() -> SafeString\n
Helper function to render all dependencies for a component.
Source code in src/django_components/component.py
def render_dependencies(self) -> SafeString:\n \"\"\"Helper function to render all dependencies for a component.\"\"\"\n dependencies = []\n\n css_deps = self.render_css_dependencies()\n if css_deps:\n dependencies.append(css_deps)\n\n js_deps = self.render_js_dependencies()\n if js_deps:\n dependencies.append(js_deps)\n\n return mark_safe(\"\\n\".join(dependencies))\n
"},{"location":"reference/django_components/#django_components.component.Component.render_js_dependencies","title":"render_js_dependencies","text":"render_js_dependencies() -> SafeString\n
Render only JS dependencies available in the media class or provided as a string.
Source code in src/django_components/component.py
def render_js_dependencies(self) -> SafeString:\n \"\"\"Render only JS dependencies available in the media class or provided as a string.\"\"\"\n if self.js is not None:\n return mark_safe(f\"<script>{self.js}</script>\")\n return mark_safe(\"\\n\".join(self.media.render_js()))\n
"},{"location":"reference/django_components/#django_components.component.Component.render_to_response","title":"render_to_response classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n *response_args: Any,\n **response_kwargs: Any\n) -> HttpResponse\n
Render the component and wrap the content in the response class.
The response class is taken from Component.response_class
. Defaults to django.http.HttpResponse
.
This is the interface for the django.views.View
class which allows us to use components as Django views with component.as_view()
.
Inputs: - args
- Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %}
- kwargs
- Kwargs for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %}
- slots
- Component slot fills. This is the same as pasing {% fill %}
tags to the component. Accepts a dictionary of { slot_name: slot_content }
where slot_content
can be a string or render function. - escape_slots_content
- Whether the content from slots
should be escaped. - context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs.
Any additional args and kwargs are passed to the response_class
.
Example:
MyComponent.render_to_response(\n args=[1, \"two\", {}],\n kwargs={\n \"key\": 123,\n },\n slots={\n \"header\": 'STATIC TEXT HERE',\n \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n },\n escape_slots_content=False,\n # HttpResponse input\n status=201,\n headers={...},\n)\n# HttpResponse(content=..., status=201, headers=...)\n
Source code in src/django_components/component.py
@classmethod\ndef render_to_response(\n cls,\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n *response_args: Any,\n **response_kwargs: Any,\n) -> HttpResponse:\n \"\"\"\n Render the component and wrap the content in the response class.\n\n The response class is taken from `Component.response_class`. Defaults to `django.http.HttpResponse`.\n\n This is the interface for the `django.views.View` class which allows us to\n use components as Django views with `component.as_view()`.\n\n Inputs:\n - `args` - Positional args for the component. This is the same as calling the component\n as `{% component \"my_comp\" arg1 arg2 ... %}`\n - `kwargs` - Kwargs for the component. This is the same as calling the component\n as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n or render function.\n - `escape_slots_content` - Whether the content from `slots` should be escaped.\n - `context` - A context (dictionary or Django's Context) within which the component\n is rendered. The keys on the context can be accessed from within the template.\n - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n component's args and kwargs.\n\n Any additional args and kwargs are passed to the `response_class`.\n\n Example:\n ```py\n MyComponent.render_to_response(\n args=[1, \"two\", {}],\n kwargs={\n \"key\": 123,\n },\n slots={\n \"header\": 'STATIC TEXT HERE',\n \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n },\n escape_slots_content=False,\n # HttpResponse input\n status=201,\n headers={...},\n )\n # HttpResponse(content=..., status=201, headers=...)\n ```\n \"\"\"\n content = cls.render(\n args=args,\n kwargs=kwargs,\n context=context,\n slots=slots,\n escape_slots_content=escape_slots_content,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
"},{"location":"reference/django_components/#django_components.component.ComponentNode","title":"ComponentNode","text":"ComponentNode(\n name: str,\n args: List[Expression],\n kwargs: RuntimeKwargs,\n isolated_context: bool = False,\n fill_nodes: Optional[List[FillNode]] = None,\n node_id: Optional[str] = None,\n)\n
Bases: BaseNode
Django.template.Node subclass that renders a django-components component
Source code in src/django_components/component.py
def __init__(\n self,\n name: str,\n args: List[Expression],\n kwargs: RuntimeKwargs,\n isolated_context: bool = False,\n fill_nodes: Optional[List[FillNode]] = None,\n node_id: Optional[str] = None,\n) -> None:\n super().__init__(nodelist=NodeList(fill_nodes), args=args, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.isolated_context = isolated_context\n self.fill_nodes = fill_nodes or []\n
"},{"location":"reference/django_components/#django_components.component.ComponentView","title":"ComponentView","text":"ComponentView(component: Component, **kwargs: Any)\n
Bases: View
Subclass of django.views.View
where the Component
instance is available via self.component
.
Source code in src/django_components/component.py
def __init__(self, component: \"Component\", **kwargs: Any) -> None:\n super().__init__(**kwargs)\n self.component = component\n
"},{"location":"reference/django_components/#django_components.component_media","title":"component_media","text":""},{"location":"reference/django_components/#django_components.component_media.ComponentMediaInput","title":"ComponentMediaInput","text":"Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/#django_components.component_media.MediaMeta","title":"MediaMeta","text":" Bases: MediaDefiningClass
Metaclass for handling media files for components.
Similar to MediaDefiningClass
, this class supports the use of Media
attribute to define associated JS/CSS files, which are then available under media
attribute as a instance of Media
class.
This subclass has following changes:
"},{"location":"reference/django_components/#django_components.component_media.MediaMeta--1-support-for-multiple-interfaces-of-jscss","title":"1. Support for multiple interfaces of JS/CSS","text":" -
As plain strings
class MyComponent(Component):\n class Media:\n js = \"path/to/script.js\"\n css = \"path/to/style.css\"\n
-
As lists
class MyComponent(Component):\n class Media:\n js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n
-
[CSS ONLY] Dicts of strings
class MyComponent(Component):\n class Media:\n css = {\n \"all\": \"path/to/style1.css\",\n \"print\": \"path/to/style2.css\",\n }\n
-
[CSS ONLY] Dicts of lists
class MyComponent(Component):\n class Media:\n css = {\n \"all\": [\"path/to/style1.css\"],\n \"print\": [\"path/to/style2.css\"],\n }\n
"},{"location":"reference/django_components/#django_components.component_media.MediaMeta--2-media-are-first-resolved-relative-to-class-definition-file","title":"2. Media are first resolved relative to class definition file","text":"E.g. if in a directory my_comp
you have script.js
and my_comp.py
, and my_comp.py
looks like this:
class MyComponent(Component):\n class Media:\n js = \"script.js\"\n
Then script.js
will be resolved as my_comp/script.js
.
"},{"location":"reference/django_components/#django_components.component_media.MediaMeta--3-media-can-be-defined-as-str-bytes-pathlike-safestring-or-function-of-thereof","title":"3. Media can be defined as str, bytes, PathLike, SafeString, or function of thereof","text":"E.g.:
def lazy_eval_css():\n # do something\n return path\n\nclass MyComponent(Component):\n class Media:\n js = b\"script.js\"\n css = lazy_eval_css\n
"},{"location":"reference/django_components/#django_components.component_media.MediaMeta--4-subclass-media-class-with-media_class","title":"4. Subclass Media
class with media_class
","text":"Normal MediaDefiningClass
creates an instance of Media
class under the media
attribute. This class allows to override which class will be instantiated with media_class
attribute:
class MyMedia(Media):\n def render_js(self):\n ...\n\nclass MyComponent(Component):\n media_class = MyMedia\n def get_context_data(self):\n assert isinstance(self.media, MyMedia)\n
"},{"location":"reference/django_components/#django_components.component_registry","title":"component_registry","text":""},{"location":"reference/django_components/#django_components.component_registry.registry","title":"registry module-attribute
","text":"registry: ComponentRegistry = ComponentRegistry()\n
The default and global component registry. Use this instance to directly register or remove components:
# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Get single\nregistry.get(\"button\")\n# Get all\nregistry.all()\n# Unregister single\nregistry.unregister(\"button\")\n# Unregister all\nregistry.clear()\n
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry","title":"ComponentRegistry","text":"ComponentRegistry(library: Optional[Library] = None)\n
Manages which components can be used in the template tags.
Each ComponentRegistry instance is associated with an instance of Django's Library. So when you register or unregister a component to/from a component registry, behind the scenes the registry automatically adds/removes the component's template tag to/from the Library.
The Library instance can be set at instantiation. If omitted, then the default Library instance from django_components is used. The Library instance can be accessed under library
attribute.
Example:
# Use with default Library\nregistry = ComponentRegistry()\n\n# Or a custom one\nmy_lib = Library()\nregistry = ComponentRegistry(library=my_lib)\n\n# Usage\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\nregistry.all()\nregistry.clear()\nregistry.get()\n
Source code in src/django_components/component_registry.py
def __init__(self, library: Optional[Library] = None) -> None:\n self._registry: Dict[str, ComponentRegistryEntry] = {} # component name -> component_entry mapping\n self._tags: Dict[str, Set[str]] = {} # tag -> list[component names]\n self._library = library\n
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.library","title":"library property
","text":"library: Library\n
The template tag library with which the component registry is associated.
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.all","title":"all","text":"all() -> Dict[str, Type[Component]]\n
Retrieve all registered component classes.
Example:
# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then get all\nregistry.all()\n# > {\n# > \"button\": ButtonComponent,\n# > \"card\": CardComponent,\n# > }\n
Source code in src/django_components/component_registry.py
def all(self) -> Dict[str, Type[\"Component\"]]:\n \"\"\"\n Retrieve all registered component classes.\n\n Example:\n\n ```py\n # First register components\n registry.register(\"button\", ButtonComponent)\n registry.register(\"card\", CardComponent)\n # Then get all\n registry.all()\n # > {\n # > \"button\": ButtonComponent,\n # > \"card\": CardComponent,\n # > }\n ```\n \"\"\"\n comps = {key: entry.cls for key, entry in self._registry.items()}\n return comps\n
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.clear","title":"clear","text":"clear() -> None\n
Clears the registry, unregistering all components.
Example:
# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then clear\nregistry.clear()\n# Then get all\nregistry.all()\n# > {}\n
Source code in src/django_components/component_registry.py
def clear(self) -> None:\n \"\"\"\n Clears the registry, unregistering all components.\n\n Example:\n\n ```py\n # First register components\n registry.register(\"button\", ButtonComponent)\n registry.register(\"card\", CardComponent)\n # Then clear\n registry.clear()\n # Then get all\n registry.all()\n # > {}\n ```\n \"\"\"\n all_comp_names = list(self._registry.keys())\n for comp_name in all_comp_names:\n self.unregister(comp_name)\n\n self._registry = {}\n self._tags = {}\n
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.get","title":"get","text":"get(name: str) -> Type[Component]\n
Retrieve a component class registered under the given name.
Raises NotRegistered
if the given name is not registered.
Example:
# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then get\nregistry.get(\"button\")\n# > ButtonComponent\n
Source code in src/django_components/component_registry.py
def get(self, name: str) -> Type[\"Component\"]:\n \"\"\"\n Retrieve a component class registered under the given name.\n\n Raises `NotRegistered` if the given name is not registered.\n\n Example:\n\n ```py\n # First register component\n registry.register(\"button\", ButtonComponent)\n # Then get\n registry.get(\"button\")\n # > ButtonComponent\n ```\n \"\"\"\n if name not in self._registry:\n raise NotRegistered('The component \"%s\" is not registered' % name)\n\n return self._registry[name].cls\n
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.register","title":"register","text":"register(name: str, component: Type[Component]) -> None\n
Register a component with this registry under the given name.
A component MUST be registered before it can be used in a template such as:
{% component \"my_comp\" %}{% endcomponent %}\n
Raises AlreadyRegistered
if a different component was already registered under the same name.
Example:
registry.register(\"button\", ButtonComponent)\n
Source code in src/django_components/component_registry.py
def register(self, name: str, component: Type[\"Component\"]) -> None:\n \"\"\"\n Register a component with this registry under the given name.\n\n A component MUST be registered before it can be used in a template such as:\n ```django\n {% component \"my_comp\" %}{% endcomponent %}\n ```\n\n Raises `AlreadyRegistered` if a different component was already registered\n under the same name.\n\n Example:\n\n ```py\n registry.register(\"button\", ButtonComponent)\n ```\n \"\"\"\n existing_component = self._registry.get(name)\n if existing_component and existing_component.cls._class_hash != component._class_hash:\n raise AlreadyRegistered('The component \"%s\" has already been registered' % name)\n\n entry = self._register_to_library(name, component)\n\n # Keep track of which components use which tags, because multiple components may\n # use the same tag.\n tag = entry.tag\n if tag not in self._tags:\n self._tags[tag] = set()\n self._tags[tag].add(name)\n\n self._registry[name] = entry\n
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.unregister","title":"unregister","text":"unregister(name: str) -> None\n
Unlinks a previously-registered component from the registry under the given name.
Once a component is unregistered, it CANNOT be used in a template anymore. Following would raise an error:
{% component \"my_comp\" %}{% endcomponent %}\n
Raises NotRegistered
if the given name is not registered.
Example:
# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
Source code in src/django_components/component_registry.py
def unregister(self, name: str) -> None:\n \"\"\"\n Unlinks a previously-registered component from the registry under the given name.\n\n Once a component is unregistered, it CANNOT be used in a template anymore.\n Following would raise an error:\n ```django\n {% component \"my_comp\" %}{% endcomponent %}\n ```\n\n Raises `NotRegistered` if the given name is not registered.\n\n Example:\n\n ```py\n # First register component\n registry.register(\"button\", ButtonComponent)\n # Then unregister\n registry.unregister(\"button\")\n ```\n \"\"\"\n # Validate\n self.get(name)\n\n entry = self._registry[name]\n tag = entry.tag\n\n # Unregister the tag from library if this was the last component using this tag\n # Unlink component from tag\n self._tags[tag].remove(name)\n\n # Cleanup\n is_tag_empty = not len(self._tags[tag])\n if is_tag_empty:\n del self._tags[tag]\n\n # Only unregister a tag if it's NOT protected\n is_protected = is_tag_protected(self.library, tag)\n if not is_protected:\n # Unregister the tag from library if this was the last component using this tag\n if is_tag_empty and tag in self.library.tags:\n del self.library.tags[tag]\n\n del self._registry[name]\n
"},{"location":"reference/django_components/#django_components.component_registry.register","title":"register","text":"register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]\n
Class decorator to register a component.
Usage:
@register(\"my_component\")\nclass MyComponent(Component):\n ...\n
Optionally specify which ComponentRegistry
the component should be registered to by setting the registry
kwarg:
my_lib = django.template.Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n ...\n
Source code in src/django_components/component_registry.py
def register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]:\n \"\"\"\n Class decorator to register a component.\n\n Usage:\n\n ```py\n @register(\"my_component\")\n class MyComponent(Component):\n ...\n ```\n\n Optionally specify which `ComponentRegistry` the component should be registered to by\n setting the `registry` kwarg:\n\n ```py\n my_lib = django.template.Library()\n my_reg = ComponentRegistry(library=my_lib)\n\n @register(\"my_component\", registry=my_reg)\n class MyComponent(Component):\n ...\n ```\n \"\"\"\n if registry is None:\n registry = _the_registry\n\n def decorator(component: _TComp) -> _TComp:\n registry.register(name=name, component=component)\n return component\n\n return decorator\n
"},{"location":"reference/django_components/#django_components.context","title":"context","text":"This file centralizes various ways we use Django's Context class pass data across components, nodes, slots, and contexts.
You can think of the Context as our storage system.
"},{"location":"reference/django_components/#django_components.context.copy_forloop_context","title":"copy_forloop_context","text":"copy_forloop_context(from_context: Context, to_context: Context) -> None\n
Forward the info about the current loop
Source code in src/django_components/context.py
def copy_forloop_context(from_context: Context, to_context: Context) -> None:\n \"\"\"Forward the info about the current loop\"\"\"\n # Note that the ForNode (which implements for loop behavior) does not\n # only add the `forloop` key, but also keys corresponding to the loop elements\n # So if the loop syntax is `{% for my_val in my_lists %}`, then ForNode also\n # sets a `my_val` key.\n # For this reason, instead of copying individual keys, we copy the whole stack layer\n # set by ForNode.\n if \"forloop\" in from_context:\n forloop_dict_index = find_last_index(from_context.dicts, lambda d: \"forloop\" in d)\n to_context.update(from_context.dicts[forloop_dict_index])\n
"},{"location":"reference/django_components/#django_components.context.get_injected_context_var","title":"get_injected_context_var","text":"get_injected_context_var(component_name: str, context: Context, key: str, default: Optional[Any] = None) -> Any\n
Retrieve a 'provided' field. The field MUST have been previously 'provided' by the component's ancestors using the {% provide %}
template tag.
Source code in src/django_components/context.py
def get_injected_context_var(\n component_name: str,\n context: Context,\n key: str,\n default: Optional[Any] = None,\n) -> Any:\n \"\"\"\n Retrieve a 'provided' field. The field MUST have been previously 'provided'\n by the component's ancestors using the `{% provide %}` template tag.\n \"\"\"\n # NOTE: For simplicity, we keep the provided values directly on the context.\n # This plays nicely with Django's Context, which behaves like a stack, so \"newer\"\n # values overshadow the \"older\" ones.\n internal_key = _INJECT_CONTEXT_KEY_PREFIX + key\n\n # Return provided value if found\n if internal_key in context:\n return context[internal_key]\n\n # If a default was given, return that\n if default is not None:\n return default\n\n # Otherwise raise error\n raise KeyError(\n f\"Component '{component_name}' tried to inject a variable '{key}' before it was provided.\"\n f\" To fix this, make sure that at least one ancestor of component '{component_name}' has\"\n f\" the variable '{key}' in their 'provide' attribute.\"\n )\n
"},{"location":"reference/django_components/#django_components.context.prepare_context","title":"prepare_context","text":"prepare_context(context: Context, component_id: str) -> None\n
Initialize the internal context state.
Source code in src/django_components/context.py
def prepare_context(\n context: Context,\n component_id: str,\n) -> None:\n \"\"\"Initialize the internal context state.\"\"\"\n # Initialize mapping dicts within this rendering run.\n # This is shared across the whole render chain, thus we set it only once.\n if _FILLED_SLOTS_CONTENT_CONTEXT_KEY not in context:\n context[_FILLED_SLOTS_CONTENT_CONTEXT_KEY] = {}\n\n set_component_id(context, component_id)\n
"},{"location":"reference/django_components/#django_components.context.set_component_id","title":"set_component_id","text":"set_component_id(context: Context, component_id: str) -> None\n
We use the Context object to pass down info on inside of which component we are currently rendering.
Source code in src/django_components/context.py
def set_component_id(context: Context, component_id: str) -> None:\n \"\"\"\n We use the Context object to pass down info on inside of which component\n we are currently rendering.\n \"\"\"\n # Store the previous component so we can detect if the current component\n # is the top-most or not. If it is, then \"_parent_component_id\" is None\n context[_PARENT_COMP_CONTEXT_KEY] = context.get(_CURRENT_COMP_CONTEXT_KEY, None)\n context[_CURRENT_COMP_CONTEXT_KEY] = component_id\n
"},{"location":"reference/django_components/#django_components.context.set_provided_context_var","title":"set_provided_context_var","text":"set_provided_context_var(context: Context, key: str, provided_kwargs: Dict[str, Any]) -> None\n
'Provide' given data under given key. In other words, this data can be retrieved using self.inject(key)
inside of get_context_data()
method of components that are nested inside the {% provide %}
tag.
Source code in src/django_components/context.py
def set_provided_context_var(\n context: Context,\n key: str,\n provided_kwargs: Dict[str, Any],\n) -> None:\n \"\"\"\n 'Provide' given data under given key. In other words, this data can be retrieved\n using `self.inject(key)` inside of `get_context_data()` method of components that\n are nested inside the `{% provide %}` tag.\n \"\"\"\n # NOTE: We raise TemplateSyntaxError since this func should be called only from\n # within template.\n if not key:\n raise TemplateSyntaxError(\n \"Provide tag received an empty string. Key must be non-empty and a valid identifier.\"\n )\n if not key.isidentifier():\n raise TemplateSyntaxError(\n \"Provide tag received a non-identifier string. Key must be non-empty and a valid identifier.\"\n )\n\n # We turn the kwargs into a NamedTuple so that the object that's \"provided\"\n # is immutable. This ensures that the data returned from `inject` will always\n # have all the keys that were passed to the `provide` tag.\n tpl_cls = namedtuple(\"DepInject\", provided_kwargs.keys()) # type: ignore[misc]\n payload = tpl_cls(**provided_kwargs)\n\n internal_key = _INJECT_CONTEXT_KEY_PREFIX + key\n context[internal_key] = payload\n
"},{"location":"reference/django_components/#django_components.expression","title":"expression","text":""},{"location":"reference/django_components/#django_components.expression.Operator","title":"Operator","text":" Bases: ABC
Operator describes something that somehow changes the inputs to template tags (the {% %}
).
For example, a SpreadOperator inserts one or more kwargs at the specified location.
"},{"location":"reference/django_components/#django_components.expression.SpreadOperator","title":"SpreadOperator","text":"SpreadOperator(expr: Expression)\n
Bases: Operator
Operator that inserts one or more kwargs at the specified location.
Source code in src/django_components/expression.py
def __init__(self, expr: Expression) -> None:\n self.expr = expr\n
"},{"location":"reference/django_components/#django_components.expression.process_aggregate_kwargs","title":"process_aggregate_kwargs","text":"process_aggregate_kwargs(kwargs: Mapping[str, Any]) -> Dict[str, Any]\n
This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs start with some prefix delimited with :
(e.g. attrs:
).
Example:
process_component_kwargs({\"abc:one\": 1, \"abc:two\": 2, \"def:three\": 3, \"four\": 4})\n# {\"abc\": {\"one\": 1, \"two\": 2}, \"def\": {\"three\": 3}, \"four\": 4}\n
We want to support a use case similar to Vue's fallthrough attributes. In other words, where a component author can designate a prop (input) which is a dict and which will be rendered as HTML attributes.
This is useful for allowing component users to tweak styling or add event handling to the underlying HTML. E.g.:
class=\"pa-4 d-flex text-black\"
or @click.stop=\"alert('clicked!')\"
So if the prop is attrs
, and the component is called like so:
{% component \"my_comp\" attrs=attrs %}\n
then, if attrs
is:
{\"class\": \"text-red pa-4\", \"@click\": \"dispatch('my_event', 123)\"}\n
and the component template is:
<div {% html_attrs attrs add:class=\"extra-class\" %}></div>\n
Then this renders:
<div class=\"text-red pa-4 extra-class\" @click=\"dispatch('my_event', 123)\" ></div>\n
However, this way it is difficult for the component user to define the attrs
variable, especially if they want to combine static and dynamic values. Because they will need to pre-process the attrs
dict.
So, instead, we allow to \"aggregate\" props into a dict. So all props that start with attrs:
, like attrs:class=\"text-red\"
, will be collected into a dict at key attrs
.
This provides sufficient flexiblity to make it easy for component users to provide \"fallthrough attributes\", and sufficiently easy for component authors to process that input while still being able to provide their own keys.
Source code in src/django_components/expression.py
def process_aggregate_kwargs(kwargs: Mapping[str, Any]) -> Dict[str, Any]:\n \"\"\"\n This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs\n start with some prefix delimited with `:` (e.g. `attrs:`).\n\n Example:\n ```py\n process_component_kwargs({\"abc:one\": 1, \"abc:two\": 2, \"def:three\": 3, \"four\": 4})\n # {\"abc\": {\"one\": 1, \"two\": 2}, \"def\": {\"three\": 3}, \"four\": 4}\n ```\n\n ---\n\n We want to support a use case similar to Vue's fallthrough attributes.\n In other words, where a component author can designate a prop (input)\n which is a dict and which will be rendered as HTML attributes.\n\n This is useful for allowing component users to tweak styling or add\n event handling to the underlying HTML. E.g.:\n\n `class=\"pa-4 d-flex text-black\"` or `@click.stop=\"alert('clicked!')\"`\n\n So if the prop is `attrs`, and the component is called like so:\n ```django\n {% component \"my_comp\" attrs=attrs %}\n ```\n\n then, if `attrs` is:\n ```py\n {\"class\": \"text-red pa-4\", \"@click\": \"dispatch('my_event', 123)\"}\n ```\n\n and the component template is:\n ```django\n <div {% html_attrs attrs add:class=\"extra-class\" %}></div>\n ```\n\n Then this renders:\n ```html\n <div class=\"text-red pa-4 extra-class\" @click=\"dispatch('my_event', 123)\" ></div>\n ```\n\n However, this way it is difficult for the component user to define the `attrs`\n variable, especially if they want to combine static and dynamic values. Because\n they will need to pre-process the `attrs` dict.\n\n So, instead, we allow to \"aggregate\" props into a dict. So all props that start\n with `attrs:`, like `attrs:class=\"text-red\"`, will be collected into a dict\n at key `attrs`.\n\n This provides sufficient flexiblity to make it easy for component users to provide\n \"fallthrough attributes\", and sufficiently easy for component authors to process\n that input while still being able to provide their own keys.\n \"\"\"\n processed_kwargs = {}\n nested_kwargs: Dict[str, Dict[str, Any]] = {}\n for key, val in kwargs.items():\n if not is_aggregate_key(key):\n processed_kwargs[key] = val\n continue\n\n # NOTE: Trim off the prefix from keys\n prefix, sub_key = key.split(\":\", 1)\n if prefix not in nested_kwargs:\n nested_kwargs[prefix] = {}\n nested_kwargs[prefix][sub_key] = val\n\n # Assign aggregated values into normal input\n for key, val in nested_kwargs.items():\n if key in processed_kwargs:\n raise TemplateSyntaxError(\n f\"Received argument '{key}' both as a regular input ({key}=...)\"\n f\" and as an aggregate dict ('{key}:key=...'). Must be only one of the two\"\n )\n processed_kwargs[key] = val\n\n return processed_kwargs\n
"},{"location":"reference/django_components/#django_components.library","title":"library","text":"Module for interfacing with Django's Library (django.template.library
)
"},{"location":"reference/django_components/#django_components.library.PROTECTED_TAGS","title":"PROTECTED_TAGS module-attribute
","text":"PROTECTED_TAGS = [\n \"component_dependencies\",\n \"component_css_dependencies\",\n \"component_js_dependencies\",\n \"fill\",\n \"html_attrs\",\n \"provide\",\n \"slot\",\n]\n
These are the names that users cannot choose for their components, as they would conflict with other tags in the Library.
"},{"location":"reference/django_components/#django_components.logger","title":"logger","text":""},{"location":"reference/django_components/#django_components.logger.trace","title":"trace","text":"trace(logger: Logger, message: str, *args: Any, **kwargs: Any) -> None\n
TRACE level logger.
To display TRACE logs, set the logging level to 5.
Example:
LOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"handlers\": {\n \"console\": {\n \"class\": \"logging.StreamHandler\",\n \"stream\": sys.stdout,\n },\n },\n \"loggers\": {\n \"django_components\": {\n \"level\": 5,\n \"handlers\": [\"console\"],\n },\n },\n}\n
Source code in src/django_components/logger.py
def trace(logger: logging.Logger, message: str, *args: Any, **kwargs: Any) -> None:\n \"\"\"\n TRACE level logger.\n\n To display TRACE logs, set the logging level to 5.\n\n Example:\n ```py\n LOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"handlers\": {\n \"console\": {\n \"class\": \"logging.StreamHandler\",\n \"stream\": sys.stdout,\n },\n },\n \"loggers\": {\n \"django_components\": {\n \"level\": 5,\n \"handlers\": [\"console\"],\n },\n },\n }\n ```\n \"\"\"\n if actual_trace_level_num == -1:\n setup_logging()\n if logger.isEnabledFor(actual_trace_level_num):\n logger.log(actual_trace_level_num, message, *args, **kwargs)\n
"},{"location":"reference/django_components/#django_components.logger.trace_msg","title":"trace_msg","text":"trace_msg(\n action: Literal[\"PARSE\", \"ASSOC\", \"RENDR\", \"GET\", \"SET\"],\n node_type: Literal[\"COMP\", \"FILL\", \"SLOT\", \"PROVIDE\", \"N/A\"],\n node_name: str,\n node_id: str,\n msg: str = \"\",\n component_id: Optional[str] = None,\n) -> None\n
TRACE level logger with opinionated format for tracing interaction of components, nodes, and slots. Formats messages like so:
\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"
Source code in src/django_components/logger.py
def trace_msg(\n action: Literal[\"PARSE\", \"ASSOC\", \"RENDR\", \"GET\", \"SET\"],\n node_type: Literal[\"COMP\", \"FILL\", \"SLOT\", \"PROVIDE\", \"N/A\"],\n node_name: str,\n node_id: str,\n msg: str = \"\",\n component_id: Optional[str] = None,\n) -> None:\n \"\"\"\n TRACE level logger with opinionated format for tracing interaction of components,\n nodes, and slots. Formats messages like so:\n\n `\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"`\n \"\"\"\n msg_prefix = \"\"\n if action == \"ASSOC\":\n if not component_id:\n raise ValueError(\"component_id must be set for the ASSOC action\")\n msg_prefix = f\"TO COMP {component_id}\"\n elif action == \"RENDR\" and node_type == \"FILL\":\n if not component_id:\n raise ValueError(\"component_id must be set for the RENDER action\")\n msg_prefix = f\"FOR COMP {component_id}\"\n\n msg_parts = [f\"{action} {node_type} {node_name} ID {node_id}\", *([msg_prefix] if msg_prefix else []), msg]\n full_msg = \" \".join(msg_parts)\n\n # NOTE: When debugging tests during development, it may be easier to change\n # this to `print()`\n trace(logger, full_msg)\n
"},{"location":"reference/django_components/#django_components.management","title":"management","text":""},{"location":"reference/django_components/#django_components.management.commands","title":"commands","text":""},{"location":"reference/django_components/#django_components.management.commands.upgradecomponent","title":"upgradecomponent","text":""},{"location":"reference/django_components/#django_components.middleware","title":"middleware","text":""},{"location":"reference/django_components/#django_components.middleware.ComponentDependencyMiddleware","title":"ComponentDependencyMiddleware","text":"ComponentDependencyMiddleware(get_response: Callable[[HttpRequest], HttpResponse])\n
Middleware that inserts CSS/JS dependencies for all rendered components at points marked with template tags.
Source code in src/django_components/middleware.py
def __init__(self, get_response: \"Callable[[HttpRequest], HttpResponse]\") -> None:\n self.get_response = get_response\n\n if iscoroutinefunction(self.get_response):\n markcoroutinefunction(self)\n
"},{"location":"reference/django_components/#django_components.middleware.DependencyReplacer","title":"DependencyReplacer","text":"DependencyReplacer(css_string: bytes, js_string: bytes)\n
Replacer for use in re.sub that replaces the first placeholder CSS and JS tags it encounters and removes any subsequent ones.
Source code in src/django_components/middleware.py
def __init__(self, css_string: bytes, js_string: bytes) -> None:\n self.js_string = js_string\n self.css_string = css_string\n
"},{"location":"reference/django_components/#django_components.middleware.join_media","title":"join_media","text":"join_media(components: Iterable[Component]) -> Media\n
Return combined media object for iterable of components.
Source code in src/django_components/middleware.py
def join_media(components: Iterable[\"Component\"]) -> Media:\n \"\"\"Return combined media object for iterable of components.\"\"\"\n\n return sum([component.media for component in components], Media())\n
"},{"location":"reference/django_components/#django_components.node","title":"node","text":""},{"location":"reference/django_components/#django_components.node.BaseNode","title":"BaseNode","text":"BaseNode(\n nodelist: Optional[NodeList] = None,\n node_id: Optional[str] = None,\n args: Optional[List[Expression]] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n)\n
Bases: Node
Shared behavior for our subclasses of Django's Node
Source code in src/django_components/node.py
def __init__(\n self,\n nodelist: Optional[NodeList] = None,\n node_id: Optional[str] = None,\n args: Optional[List[Expression]] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n):\n self.nodelist = nodelist or NodeList()\n self.node_id = node_id or gen_id()\n self.args = args or []\n self.kwargs = kwargs or RuntimeKwargs({})\n
"},{"location":"reference/django_components/#django_components.node.get_node_children","title":"get_node_children","text":"get_node_children(node: Node, context: Optional[Context] = None) -> NodeList\n
Get child Nodes from Node's nodelist atribute.
This function is taken from get_nodes_by_type
method of django.template.base.Node
.
Source code in src/django_components/node.py
def get_node_children(node: Node, context: Optional[Context] = None) -> NodeList:\n \"\"\"\n Get child Nodes from Node's nodelist atribute.\n\n This function is taken from `get_nodes_by_type` method of `django.template.base.Node`.\n \"\"\"\n # Special case - {% extends %} tag - Load the template and go deeper\n if isinstance(node, ExtendsNode):\n # NOTE: When {% extends %} node is being parsed, it collects all remaining template\n # under node.nodelist.\n # Hence, when we come across ExtendsNode in the template, we:\n # 1. Go over all nodes in the template using `node.nodelist`\n # 2. Go over all nodes in the \"parent\" template, via `node.get_parent`\n nodes = NodeList()\n nodes.extend(node.nodelist)\n template = node.get_parent(context)\n nodes.extend(template.nodelist)\n return nodes\n\n # Special case - {% include %} tag - Load the template and go deeper\n elif isinstance(node, IncludeNode):\n template = get_template_for_include_node(node, context)\n return template.nodelist\n\n nodes = NodeList()\n for attr in node.child_nodelists:\n nodelist = getattr(node, attr, [])\n if nodelist:\n nodes.extend(nodelist)\n return nodes\n
"},{"location":"reference/django_components/#django_components.node.get_template_for_include_node","title":"get_template_for_include_node","text":"get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template\n
This snippet is taken directly from IncludeNode.render()
. Unfortunately the render logic doesn't separate out template loading logic from rendering, so we have to copy the method.
Source code in src/django_components/node.py
def get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template:\n \"\"\"\n This snippet is taken directly from `IncludeNode.render()`. Unfortunately the\n render logic doesn't separate out template loading logic from rendering, so we\n have to copy the method.\n \"\"\"\n template = include_node.template.resolve(context)\n # Does this quack like a Template?\n if not callable(getattr(template, \"render\", None)):\n # If not, try the cache and select_template().\n template_name = template or ()\n if isinstance(template_name, str):\n template_name = (\n construct_relative_path(\n include_node.origin.template_name,\n template_name,\n ),\n )\n else:\n template_name = tuple(template_name)\n cache = context.render_context.dicts[0].setdefault(include_node, {})\n template = cache.get(template_name)\n if template is None:\n template = context.template.engine.select_template(template_name)\n cache[template_name] = template\n # Use the base.Template of a backends.django.Template.\n elif hasattr(template, \"template\"):\n template = template.template\n return template\n
"},{"location":"reference/django_components/#django_components.node.walk_nodelist","title":"walk_nodelist","text":"walk_nodelist(nodes: NodeList, callback: Callable[[Node], Optional[str]], context: Optional[Context] = None) -> None\n
Recursively walk a NodeList, calling callback
for each Node.
Source code in src/django_components/node.py
def walk_nodelist(\n nodes: NodeList,\n callback: Callable[[Node], Optional[str]],\n context: Optional[Context] = None,\n) -> None:\n \"\"\"Recursively walk a NodeList, calling `callback` for each Node.\"\"\"\n node_queue: List[NodeTraverse] = [NodeTraverse(node=node, parent=None) for node in nodes]\n while len(node_queue):\n traverse = node_queue.pop()\n callback(traverse)\n child_nodes = get_node_children(traverse.node, context)\n child_traverses = [NodeTraverse(node=child_node, parent=traverse) for child_node in child_nodes]\n node_queue.extend(child_traverses)\n
"},{"location":"reference/django_components/#django_components.provide","title":"provide","text":""},{"location":"reference/django_components/#django_components.provide.ProvideNode","title":"ProvideNode","text":"ProvideNode(name: str, nodelist: NodeList, node_id: Optional[str] = None, kwargs: Optional[RuntimeKwargs] = None)\n
Bases: BaseNode
Implementation of the {% provide %}
tag. For more info see Component.inject
.
Source code in src/django_components/provide.py
def __init__(\n self,\n name: str,\n nodelist: NodeList,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.nodelist = nodelist\n self.node_id = node_id or gen_id()\n self.kwargs = kwargs or RuntimeKwargs({})\n
"},{"location":"reference/django_components/#django_components.safer_staticfiles","title":"safer_staticfiles","text":""},{"location":"reference/django_components/#django_components.safer_staticfiles.apps","title":"apps","text":""},{"location":"reference/django_components/#django_components.safer_staticfiles.apps.SaferStaticFilesConfig","title":"SaferStaticFilesConfig","text":" Bases: StaticFilesConfig
Extend the ignore_patterns
class attr of StaticFilesConfig to include Python modules and HTML files.
When this class is registered as an installed app, $ ./manage.py collectstatic
will ignore .py and .html files, preventing potentially sensitive backend logic from being leaked by the static file server.
See https://docs.djangoproject.com/en/5.0/ref/contrib/staticfiles/#customizing-the-ignored-pattern-list
"},{"location":"reference/django_components/#django_components.slots","title":"slots","text":""},{"location":"reference/django_components/#django_components.slots.FillContent","title":"FillContent dataclass
","text":"FillContent(content_func: SlotFunc[TSlotData], slot_default_var: Optional[SlotDefaultName], slot_data_var: Optional[SlotDataName])\n
Bases: Generic[TSlotData]
This represents content set with the {% fill %}
tag, e.g.:
{% component \"my_comp\" %}\n {% fill \"first_slot\" %} <--- This\n hi\n {{ my_var }}\n hello\n {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/django_components/#django_components.slots.FillNode","title":"FillNode","text":"FillNode(name: FilterExpression, nodelist: NodeList, kwargs: RuntimeKwargs, node_id: Optional[str] = None, is_implicit: bool = False)\n
Bases: BaseNode
Set when a component
tag pair is passed template content that excludes fill
tags. Nodes of this type contribute their nodelists to slots marked as 'default'.
Source code in src/django_components/slots.py
def __init__(\n self,\n name: FilterExpression,\n nodelist: NodeList,\n kwargs: RuntimeKwargs,\n node_id: Optional[str] = None,\n is_implicit: bool = False,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.is_implicit = is_implicit\n self.component_id: Optional[str] = None\n
"},{"location":"reference/django_components/#django_components.slots.Slot","title":"Slot","text":" Bases: NamedTuple
This represents content set with the {% slot %}
tag, e.g.:
{% slot \"my_comp\" default %} <--- This\n hi\n {{ my_var }}\n hello\n{% endslot %}\n
"},{"location":"reference/django_components/#django_components.slots.SlotFill","title":"SlotFill dataclass
","text":"SlotFill(\n name: str,\n escaped_name: str,\n is_filled: bool,\n content_func: SlotFunc[TSlotData],\n context_data: Mapping,\n slot_default_var: Optional[SlotDefaultName],\n slot_data_var: Optional[SlotDataName],\n)\n
Bases: Generic[TSlotData]
SlotFill describes what WILL be rendered.
It is a Slot that has been resolved against FillContents passed to a Component.
"},{"location":"reference/django_components/#django_components.slots.SlotNode","title":"SlotNode","text":"SlotNode(\n name: str,\n nodelist: NodeList,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n is_required: bool = False,\n is_default: bool = False,\n)\n
Bases: BaseNode
Source code in src/django_components/slots.py
def __init__(\n self,\n name: str,\n nodelist: NodeList,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n is_required: bool = False,\n is_default: bool = False,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.is_required = is_required\n self.is_default = is_default\n
"},{"location":"reference/django_components/#django_components.slots.SlotRef","title":"SlotRef","text":"SlotRef(slot: SlotNode, context: Context)\n
SlotRef allows to treat a slot as a variable. The slot is rendered only once the instance is coerced to string.
This is used to access slots as variables inside the templates. When a SlotRef is rendered in the template with {{ my_lazy_slot }}
, it will output the contents of the slot.
Source code in src/django_components/slots.py
def __init__(self, slot: \"SlotNode\", context: Context):\n self._slot = slot\n self._context = context\n
"},{"location":"reference/django_components/#django_components.slots.parse_slot_fill_nodes_from_component_nodelist","title":"parse_slot_fill_nodes_from_component_nodelist","text":"parse_slot_fill_nodes_from_component_nodelist(component_nodelist: NodeList, ComponentNodeCls: Type[Node]) -> List[FillNode]\n
Given a component body (django.template.NodeList
), find all slot fills, whether defined explicitly with {% fill %}
or implicitly.
So if we have a component body:
{% component \"mycomponent\" %}\n {% fill \"first_fill\" %}\n Hello!\n {% endfill %}\n {% fill \"second_fill\" %}\n Hello too!\n {% endfill %}\n{% endcomponent %}\n
Then this function returns the nodes (django.template.Node
) for fill \"first_fill\"
and fill \"second_fill\"
. Source code in src/django_components/slots.py
def parse_slot_fill_nodes_from_component_nodelist(\n component_nodelist: NodeList,\n ComponentNodeCls: Type[Node],\n) -> List[FillNode]:\n \"\"\"\n Given a component body (`django.template.NodeList`), find all slot fills,\n whether defined explicitly with `{% fill %}` or implicitly.\n\n So if we have a component body:\n ```django\n {% component \"mycomponent\" %}\n {% fill \"first_fill\" %}\n Hello!\n {% endfill %}\n {% fill \"second_fill\" %}\n Hello too!\n {% endfill %}\n {% endcomponent %}\n ```\n Then this function returns the nodes (`django.template.Node`) for `fill \"first_fill\"`\n and `fill \"second_fill\"`.\n \"\"\"\n fill_nodes: List[FillNode] = []\n if nodelist_has_content(component_nodelist):\n for parse_fn in (\n _try_parse_as_default_fill,\n _try_parse_as_named_fill_tag_set,\n ):\n curr_fill_nodes = parse_fn(component_nodelist, ComponentNodeCls)\n if curr_fill_nodes:\n fill_nodes = curr_fill_nodes\n break\n else:\n raise TemplateSyntaxError(\n \"Illegal content passed to 'component' tag pair. \"\n \"Possible causes: 1) Explicit 'fill' tags cannot occur alongside other \"\n \"tags except comment tags; 2) Default (default slot-targeting) content \"\n \"is mixed with explict 'fill' tags.\"\n )\n return fill_nodes\n
"},{"location":"reference/django_components/#django_components.slots.resolve_slots","title":"resolve_slots","text":"resolve_slots(\n context: Context,\n template: Template,\n component_name: Optional[str],\n context_data: Mapping[str, Any],\n fill_content: Dict[SlotName, FillContent],\n) -> Tuple[Dict[SlotId, Slot], Dict[SlotId, SlotFill]]\n
Search the template for all SlotNodes, and associate the slots with the given fills.
Returns tuple of: - Slots defined in the component's Template with {% slot %}
tag - SlotFills (AKA slots matched with fills) describing what will be rendered for each slot.
Source code in src/django_components/slots.py
def resolve_slots(\n context: Context,\n template: Template,\n component_name: Optional[str],\n context_data: Mapping[str, Any],\n fill_content: Dict[SlotName, FillContent],\n) -> Tuple[Dict[SlotId, Slot], Dict[SlotId, SlotFill]]:\n \"\"\"\n Search the template for all SlotNodes, and associate the slots\n with the given fills.\n\n Returns tuple of:\n - Slots defined in the component's Template with `{% slot %}` tag\n - SlotFills (AKA slots matched with fills) describing what will be rendered for each slot.\n \"\"\"\n slot_fills = {\n name: SlotFill(\n name=name,\n escaped_name=_escape_slot_name(name),\n is_filled=True,\n content_func=fill.content_func,\n context_data=context_data,\n slot_default_var=fill.slot_default_var,\n slot_data_var=fill.slot_data_var,\n )\n for name, fill in fill_content.items()\n }\n\n slots: Dict[SlotId, Slot] = {}\n # This holds info on which slot (key) has which slots nested in it (value list)\n slot_children: Dict[SlotId, List[SlotId]] = {}\n\n def on_node(entry: NodeTraverse) -> None:\n node = entry.node\n if not isinstance(node, SlotNode):\n return\n\n # 1. Collect slots\n # Basically we take all the important info form the SlotNode, so the logic is\n # less coupled to Django's Template/Node. Plain tuples should also help with\n # troubleshooting.\n slot = Slot(\n id=node.node_id,\n name=node.name,\n nodelist=node.nodelist,\n is_default=node.is_default,\n is_required=node.is_required,\n )\n slots[node.node_id] = slot\n\n # 2. Figure out which Slots are nested in other Slots, so we can render\n # them from outside-inwards, so we can skip inner Slots if fills are provided.\n # We should end up with a graph-like data like:\n # - 0001: [0002]\n # - 0002: []\n # - 0003: [0004]\n # In other words, the data tells us that slot ID 0001 is PARENT of slot 0002.\n curr_entry = entry.parent\n while curr_entry and curr_entry.parent is not None:\n if not isinstance(curr_entry.node, SlotNode):\n curr_entry = curr_entry.parent\n continue\n\n parent_slot_id = curr_entry.node.node_id\n if parent_slot_id not in slot_children:\n slot_children[parent_slot_id] = []\n slot_children[parent_slot_id].append(node.node_id)\n break\n\n walk_nodelist(template.nodelist, on_node, context)\n\n # 3. Figure out which slot the default/implicit fill belongs to\n slot_fills = _resolve_default_slot(\n template_name=template.name,\n component_name=component_name,\n slots=slots,\n slot_fills=slot_fills,\n )\n\n # 4. Detect any errors with slots/fills\n _report_slot_errors(slots, slot_fills, component_name)\n\n # 5. Find roots of the slot relationships\n top_level_slot_ids: List[SlotId] = []\n for node_id, slot in slots.items():\n if node_id not in slot_children or not slot_children[node_id]:\n top_level_slot_ids.append(node_id)\n\n # 6. Walk from out-most slots inwards, and decide whether and how\n # we will render each slot.\n resolved_slots: Dict[SlotId, SlotFill] = {}\n slot_ids_queue = deque([*top_level_slot_ids])\n while len(slot_ids_queue):\n slot_id = slot_ids_queue.pop()\n slot = slots[slot_id]\n\n # Check if there is a slot fill for given slot name\n if slot.name in slot_fills:\n # If yes, we remember which slot we want to replace with already-rendered fills\n resolved_slots[slot_id] = slot_fills[slot.name]\n # Since the fill cannot include other slots, we can leave this path\n continue\n else:\n # If no, then the slot is NOT filled, and we will render the slot's default (what's\n # between the slot tags)\n resolved_slots[slot_id] = SlotFill(\n name=slot.name,\n escaped_name=_escape_slot_name(slot.name),\n is_filled=False,\n content_func=_nodelist_to_slot_render_func(slot.nodelist),\n context_data=context_data,\n slot_default_var=None,\n slot_data_var=None,\n )\n # Since the slot's default CAN include other slots (because it's defined in\n # the same template), we need to enqueue the slot's children\n if slot_id in slot_children and slot_children[slot_id]:\n slot_ids_queue.extend(slot_children[slot_id])\n\n # By the time we get here, we should know, for each slot, how it will be rendered\n # -> Whether it will be replaced with a fill, or whether we render slot's defaults.\n return slots, resolved_slots\n
"},{"location":"reference/django_components/#django_components.tag_formatter","title":"tag_formatter","text":""},{"location":"reference/django_components/#django_components.tag_formatter.ComponentFormatter","title":"ComponentFormatter","text":"ComponentFormatter(tag: str)\n
Bases: TagFormatterABC
The original django_component's component tag formatter, it uses the component
and endcomponent
tags, and the component name is gives as the first positional arg.
Example as block:
{% component \"mycomp\" abc=123 %}\n {% fill \"myfill\" %}\n ...\n {% endfill %}\n{% endcomponent %}\n
Example as inlined tag:
{% component \"mycomp\" abc=123 / %}\n
Source code in src/django_components/tag_formatter.py
def __init__(self, tag: str):\n self.tag = tag\n
"},{"location":"reference/django_components/#django_components.tag_formatter.InternalTagFormatter","title":"InternalTagFormatter","text":"InternalTagFormatter(tag_formatter: TagFormatterABC)\n
Internal wrapper around user-provided TagFormatters, so that we validate the outputs.
Source code in src/django_components/tag_formatter.py
def __init__(self, tag_formatter: TagFormatterABC):\n self.tag_formatter = tag_formatter\n
"},{"location":"reference/django_components/#django_components.tag_formatter.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":" Bases: TagFormatterABC
The component tag formatter that uses <name>
/ end<name>
tags.
This is similar to django-web-components and django-slippers syntax.
Example as block:
{% mycomp abc=123 %}\n {% fill \"myfill\" %}\n ...\n {% endfill %}\n{% endmycomp %}\n
Example as inlined tag:
{% mycomp abc=123 / %}\n
"},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC","title":"TagFormatterABC","text":" Bases: ABC
"},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC.end_tag","title":"end_tag abstractmethod
","text":"end_tag(name: str) -> str\n
Formats the end tag of a block component.
Source code in src/django_components/tag_formatter.py
@abc.abstractmethod\ndef end_tag(self, name: str) -> str:\n \"\"\"Formats the end tag of a block component.\"\"\"\n ...\n
"},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC.parse","title":"parse abstractmethod
","text":"parse(tokens: List[str]) -> TagResult\n
Given the tokens (words) of a component start tag, this function extracts the component name from the tokens list, and returns TagResult
, which is a tuple of (component_name, remaining_tokens)
.
Example:
Given a component declarations:
{% component \"my_comp\" key=val key2=val2 %}
This function receives a list of tokens
['component', '\"my_comp\"', 'key=val', 'key2=val2']
component
is the tag name, which we drop. \"my_comp\"
is the component name, but we must remove the extra quotes. And we pass remaining tokens unmodified, as that's the input to the component.
So in the end, we return a tuple:
('my_comp', ['key=val', 'key2=val2'])
Source code in src/django_components/tag_formatter.py
@abc.abstractmethod\ndef parse(self, tokens: List[str]) -> TagResult:\n \"\"\"\n Given the tokens (words) of a component start tag, this function extracts\n the component name from the tokens list, and returns `TagResult`, which\n is a tuple of `(component_name, remaining_tokens)`.\n\n Example:\n\n Given a component declarations:\n\n `{% component \"my_comp\" key=val key2=val2 %}`\n\n This function receives a list of tokens\n\n `['component', '\"my_comp\"', 'key=val', 'key2=val2']`\n\n `component` is the tag name, which we drop. `\"my_comp\"` is the component name,\n but we must remove the extra quotes. And we pass remaining tokens unmodified,\n as that's the input to the component.\n\n So in the end, we return a tuple:\n\n `('my_comp', ['key=val', 'key2=val2'])`\n \"\"\"\n ...\n
"},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC.start_tag","title":"start_tag abstractmethod
","text":"start_tag(name: str) -> str\n
Formats the start tag of a component.
Source code in src/django_components/tag_formatter.py
@abc.abstractmethod\ndef start_tag(self, name: str) -> str:\n \"\"\"Formats the start tag of a component.\"\"\"\n ...\n
"},{"location":"reference/django_components/#django_components.tag_formatter.TagResult","title":"TagResult","text":" Bases: NamedTuple
The return value from TagFormatter.parse()
"},{"location":"reference/django_components/#django_components.tag_formatter.TagResult.component_name","title":"component_name instance-attribute
","text":"component_name: str\n
Component name extracted from the template tag
"},{"location":"reference/django_components/#django_components.tag_formatter.TagResult.tokens","title":"tokens instance-attribute
","text":"tokens: List[str]\n
Remaining tokens (words) that were passed to the tag, with component name removed
"},{"location":"reference/django_components/#django_components.tag_formatter.get_tag_formatter","title":"get_tag_formatter","text":"get_tag_formatter() -> InternalTagFormatter\n
Returns an instance of the currently configured component tag formatter.
Source code in src/django_components/tag_formatter.py
def get_tag_formatter() -> InternalTagFormatter:\n \"\"\"Returns an instance of the currently configured component tag formatter.\"\"\"\n # Allow users to configure the component TagFormatter\n formatter_cls_or_str = app_settings.TAG_FORMATTER\n\n if isinstance(formatter_cls_or_str, str):\n tag_formatter: TagFormatterABC = import_string(formatter_cls_or_str)\n else:\n tag_formatter = formatter_cls_or_str\n\n return InternalTagFormatter(tag_formatter)\n
"},{"location":"reference/django_components/#django_components.template_loader","title":"template_loader","text":"Template loader that loads templates from each Django app's \"components\" directory.
"},{"location":"reference/django_components/#django_components.template_loader.Loader","title":"Loader","text":" Bases: Loader
"},{"location":"reference/django_components/#django_components.template_loader.Loader.get_dirs","title":"get_dirs","text":"get_dirs() -> List[Path]\n
Prepare directories that may contain component files:
Searches for dirs set in STATICFILES_DIRS
settings. If none set, defaults to searching for a \"components\" app. The dirs in STATICFILES_DIRS
must be absolute paths.
Paths are accepted only if they resolve to a directory. E.g. /path/to/django_project/my_app/components/
.
If STATICFILES_DIRS
is not set or empty, then BASE_DIR
is required.
Source code in src/django_components/template_loader.py
def get_dirs(self) -> List[Path]:\n \"\"\"\n Prepare directories that may contain component files:\n\n Searches for dirs set in `STATICFILES_DIRS` settings. If none set, defaults to searching\n for a \"components\" app. The dirs in `STATICFILES_DIRS` must be absolute paths.\n\n Paths are accepted only if they resolve to a directory.\n E.g. `/path/to/django_project/my_app/components/`.\n\n If `STATICFILES_DIRS` is not set or empty, then `BASE_DIR` is required.\n \"\"\"\n # Allow to configure from settings which dirs should be checked for components\n if hasattr(settings, \"STATICFILES_DIRS\") and settings.STATICFILES_DIRS:\n component_dirs = settings.STATICFILES_DIRS\n else:\n component_dirs = [settings.BASE_DIR / \"components\"]\n\n logger.debug(\n \"Template loader will search for valid template dirs from following options:\\n\"\n + \"\\n\".join([f\" - {str(d)}\" for d in component_dirs])\n )\n\n directories: Set[Path] = set()\n for component_dir in component_dirs:\n # Consider tuples for STATICFILES_DIRS (See #489)\n # See https://docs.djangoproject.com/en/5.0/ref/settings/#prefixes-optional\n if isinstance(component_dir, (tuple, list)) and len(component_dir) == 2:\n component_dir = component_dir[1]\n try:\n Path(component_dir)\n except TypeError:\n logger.warning(\n f\"STATICFILES_DIRS expected str, bytes or os.PathLike object, or tuple/list of length 2. \"\n f\"See Django documentation. Got {type(component_dir)} : {component_dir}\"\n )\n continue\n\n if not Path(component_dir).is_absolute():\n raise ValueError(f\"STATICFILES_DIRS must contain absolute paths, got '{component_dir}'\")\n else:\n directories.add(Path(component_dir).resolve())\n\n logger.debug(\n \"Template loader matched following template dirs:\\n\" + \"\\n\".join([f\" - {str(d)}\" for d in directories])\n )\n return list(directories)\n
"},{"location":"reference/django_components/#django_components.template_parser","title":"template_parser","text":"Overrides for the Django Template system to allow finer control over template parsing.
Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py
"},{"location":"reference/django_components/#django_components.template_parser.parse_bits","title":"parse_bits","text":"parse_bits(\n parser: Parser, bits: List[str], params: List[str], name: str\n) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]\n
Parse bits for template tag helpers simple_tag and inclusion_tag, in particular by detecting syntax errors and by extracting positional and keyword arguments.
This is a simplified version of django.template.library.parse_bits
where we use custom regex to handle special characters in keyword names.
Furthermore, our version allows duplicate keys, and instead of return kwargs as a dict, we return it as a list of key-value pairs. So it is up to the user of this function to decide whether they support duplicate keys or not.
Source code in src/django_components/template_parser.py
def parse_bits(\n parser: Parser,\n bits: List[str],\n params: List[str],\n name: str,\n) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]:\n \"\"\"\n Parse bits for template tag helpers simple_tag and inclusion_tag, in\n particular by detecting syntax errors and by extracting positional and\n keyword arguments.\n\n This is a simplified version of `django.template.library.parse_bits`\n where we use custom regex to handle special characters in keyword names.\n\n Furthermore, our version allows duplicate keys, and instead of return kwargs\n as a dict, we return it as a list of key-value pairs. So it is up to the\n user of this function to decide whether they support duplicate keys or not.\n \"\"\"\n args: List[FilterExpression] = []\n kwargs: List[Tuple[str, FilterExpression]] = []\n unhandled_params = list(params)\n for bit in bits:\n # First we try to extract a potential kwarg from the bit\n kwarg = token_kwargs([bit], parser)\n if kwarg:\n # The kwarg was successfully extracted\n param, value = kwarg.popitem()\n # All good, record the keyword argument\n kwargs.append((str(param), value))\n if param in unhandled_params:\n # If using the keyword syntax for a positional arg, then\n # consume it.\n unhandled_params.remove(param)\n else:\n if kwargs:\n raise TemplateSyntaxError(\n \"'%s' received some positional argument(s) after some \" \"keyword argument(s)\" % name\n )\n else:\n # Record the positional argument\n args.append(parser.compile_filter(bit))\n try:\n # Consume from the list of expected positional arguments\n unhandled_params.pop(0)\n except IndexError:\n pass\n if unhandled_params:\n # Some positional arguments were not supplied\n raise TemplateSyntaxError(\n \"'%s' did not receive value(s) for the argument(s): %s\"\n % (name, \", \".join(\"'%s'\" % p for p in unhandled_params))\n )\n return args, kwargs\n
"},{"location":"reference/django_components/#django_components.template_parser.token_kwargs","title":"token_kwargs","text":"token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]\n
Parse token keyword arguments and return a dictionary of the arguments retrieved from the bits
token list.
bits
is a list containing the remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments are removed from this list.
There is no requirement for all remaining token bits
to be keyword arguments, so return the dictionary as soon as an invalid argument format is reached.
Source code in src/django_components/template_parser.py
def token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]:\n \"\"\"\n Parse token keyword arguments and return a dictionary of the arguments\n retrieved from the ``bits`` token list.\n\n `bits` is a list containing the remainder of the token (split by spaces)\n that is to be checked for arguments. Valid arguments are removed from this\n list.\n\n There is no requirement for all remaining token ``bits`` to be keyword\n arguments, so return the dictionary as soon as an invalid argument format\n is reached.\n \"\"\"\n if not bits:\n return {}\n match = kwarg_re.match(bits[0])\n kwarg_format = match and match[1]\n if not kwarg_format:\n return {}\n\n kwargs: Dict[str, FilterExpression] = {}\n while bits:\n if kwarg_format:\n match = kwarg_re.match(bits[0])\n if not match or not match[1]:\n return kwargs\n key, value = match.groups()\n del bits[:1]\n else:\n if len(bits) < 3 or bits[1] != \"as\":\n return kwargs\n key, value = bits[2], bits[0]\n del bits[:3]\n\n # This is the only difference from the original token_kwargs. We use\n # the ComponentsFilterExpression instead of the original FilterExpression.\n kwargs[key] = ComponentsFilterExpression(value, parser)\n if bits and not kwarg_format:\n if bits[0] != \"and\":\n return kwargs\n del bits[:1]\n return kwargs\n
"},{"location":"reference/django_components/#django_components.templatetags","title":"templatetags","text":""},{"location":"reference/django_components/#django_components.templatetags.component_tags","title":"component_tags","text":""},{"location":"reference/django_components/#django_components.templatetags.component_tags.component","title":"component","text":"component(parser: Parser, token: Token, tag_name: str) -> ComponentNode\n
To give the component access to the template context {% component \"name\" positional_arg keyword_arg=value ... %}
To render the component in an isolated context {% component \"name\" positional_arg keyword_arg=value ... only %}
Positional and keyword arguments can be literals or template variables. The component name must be a single- or double-quotes string and must be either the first positional argument or, if there are no positional arguments, passed as 'name'.
Source code in src/django_components/templatetags/component_tags.py
def component(parser: Parser, token: Token, tag_name: str) -> ComponentNode:\n \"\"\"\n To give the component access to the template context:\n ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... %}```\n\n To render the component in an isolated context:\n ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... only %}```\n\n Positional and keyword arguments can be literals or template variables.\n The component name must be a single- or double-quotes string and must\n be either the first positional argument or, if there are no positional\n arguments, passed as 'name'.\n \"\"\"\n bits = token.split_contents()\n\n # Let the TagFormatter pre-process the tokens\n formatter = get_tag_formatter()\n result = formatter.parse([*bits])\n end_tag = formatter.end_tag(result.component_name)\n\n # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n bits = [bits[0], *result.tokens]\n\n tag = _parse_tag(\n tag_name,\n parser,\n bits,\n params=True, # Allow many args\n flags=[\"only\"],\n keywordonly_kwargs=True,\n repeatable_kwargs=False,\n end_tag=end_tag,\n )\n\n # Check for isolated context keyword\n isolated_context = tag.flags[\"only\"] or app_settings.CONTEXT_BEHAVIOR == ContextBehavior.ISOLATED\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n body = tag.parse_body()\n fill_nodes = parse_slot_fill_nodes_from_component_nodelist(body, ComponentNode)\n\n # Tag all fill nodes as children of this particular component instance\n for node in fill_nodes:\n trace_msg(\"ASSOC\", \"FILL\", node.name, node.node_id, component_id=tag.id)\n node.component_id = tag.id\n\n component_node = ComponentNode(\n name=result.component_name,\n args=tag.args,\n kwargs=tag.kwargs,\n isolated_context=isolated_context,\n fill_nodes=fill_nodes,\n node_id=tag.id,\n )\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n return component_node\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"component_css_dependencies(preload: str = '') -> SafeString\n
Marks location where CSS link tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_css_dependencies\")\ndef component_css_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where CSS link tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_css_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.component_dependencies","title":"component_dependencies","text":"component_dependencies(preload: str = '') -> SafeString\n
Marks location where CSS link and JS script tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_dependencies\")\ndef component_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where CSS link and JS script tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER + JS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"component_js_dependencies(preload: str = '') -> SafeString\n
Marks location where JS script tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_js_dependencies\")\ndef component_js_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where JS script tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + JS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_js_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.fill","title":"fill","text":"fill(parser: Parser, token: Token) -> FillNode\n
Block tag whose contents 'fill' (are inserted into) an identically named 'slot'-block in the component template referred to by a parent component. It exists to make component nesting easier.
This tag is available only within a {% component %}..{% endcomponent %} block. Runtime checks should prohibit other usages.
Source code in src/django_components/templatetags/component_tags.py
@register.tag(\"fill\")\ndef fill(parser: Parser, token: Token) -> FillNode:\n \"\"\"\n Block tag whose contents 'fill' (are inserted into) an identically named\n 'slot'-block in the component template referred to by a parent component.\n It exists to make component nesting easier.\n\n This tag is available only within a {% component %}..{% endcomponent %} block.\n Runtime checks should prohibit other usages.\n \"\"\"\n bits = token.split_contents()\n tag = _parse_tag(\n \"fill\",\n parser,\n bits,\n params=[\"name\"],\n keywordonly_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n repeatable_kwargs=False,\n end_tag=\"endfill\",\n )\n slot_name = tag.named_args[\"name\"]\n\n trace_msg(\"PARSE\", \"FILL\", str(slot_name), tag.id)\n\n body = tag.parse_body()\n fill_node = FillNode(\n nodelist=body,\n name=slot_name,\n node_id=tag.id,\n kwargs=tag.kwargs,\n )\n\n trace_msg(\"PARSE\", \"FILL\", str(slot_name), tag.id, \"...Done!\")\n return fill_node\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode\n
This tag takes: - Optional dictionary of attributes (attrs
) - Optional dictionary of defaults (defaults
) - Additional kwargs that are appended to the former two
The inputs are merged and resulting dict is rendered as HTML attributes (key=\"value\"
).
Rules: 1. Both attrs
and defaults
can be passed as positional args or as kwargs 2. Both attrs
and defaults
are optional (can be omitted) 3. Both attrs
and defaults
are dictionaries, and we can define them the same way we define dictionaries for the component
tag. So either as attrs=attrs
or attrs:key=value
. 4. All other kwargs (key=value
) are appended and can be repeated.
Normal kwargs (key=value
) are concatenated to existing keys. So if e.g. key \"class\" is supplied with value \"my-class\", then adding class=\"extra-class\"
will result in `class=\"my-class extra-class\".
Example:
{% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n
Source code in src/django_components/templatetags/component_tags.py
@register.tag(\"html_attrs\")\ndef html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode:\n \"\"\"\n This tag takes:\n - Optional dictionary of attributes (`attrs`)\n - Optional dictionary of defaults (`defaults`)\n - Additional kwargs that are appended to the former two\n\n The inputs are merged and resulting dict is rendered as HTML attributes\n (`key=\"value\"`).\n\n Rules:\n 1. Both `attrs` and `defaults` can be passed as positional args or as kwargs\n 2. Both `attrs` and `defaults` are optional (can be omitted)\n 3. Both `attrs` and `defaults` are dictionaries, and we can define them the same way\n we define dictionaries for the `component` tag. So either as `attrs=attrs` or\n `attrs:key=value`.\n 4. All other kwargs (`key=value`) are appended and can be repeated.\n\n Normal kwargs (`key=value`) are concatenated to existing keys. So if e.g. key\n \"class\" is supplied with value \"my-class\", then adding `class=\"extra-class\"`\n will result in `class=\"my-class extra-class\".\n\n Example:\n ```htmldjango\n {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n ```\n \"\"\"\n bits = token.split_contents()\n\n tag = _parse_tag(\n \"html_attrs\",\n parser,\n bits,\n params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n optional_params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n flags=[],\n keywordonly_kwargs=True,\n repeatable_kwargs=True,\n )\n\n return HtmlAttrsNode(\n kwargs=tag.kwargs,\n kwarg_pairs=tag.kwarg_pairs,\n )\n
"},{"location":"reference/django_components/#django_components.types","title":"types","text":"Helper types for IDEs.
"},{"location":"reference/django_components/#django_components.utils","title":"utils","text":""},{"location":"reference/django_components/#django_components.utils.gen_id","title":"gen_id","text":"gen_id(length: int = 5) -> str\n
Generate a unique ID that can be associated with a Node
Source code in src/django_components/utils.py
def gen_id(length: int = 5) -> str:\n \"\"\"Generate a unique ID that can be associated with a Node\"\"\"\n # Global counter to avoid conflicts\n global _id\n _id += 1\n\n # Pad the ID with `0`s up to 4 digits, e.g. `0007`\n return f\"{_id:04}\"\n
"},{"location":"reference/django_components/app_settings/","title":"
app_settings","text":""},{"location":"reference/django_components/app_settings/#django_components.app_settings","title":"app_settings","text":""},{"location":"reference/django_components/app_settings/#django_components.app_settings.ContextBehavior","title":"ContextBehavior","text":" Bases: str
, Enum
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ContextBehavior.DJANGO","title":"DJANGO class-attribute
instance-attribute
","text":"DJANGO = 'django'\n
With this setting, component fills behave as usual Django tags. That is, they enrich the context, and pass it along.
- Component fills use the context of the component they are within.
- Variables from
get_context_data
are available to the component fill.
Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the get_context_data()
method
{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
456 # my_var\nfeta # cheese\n
Because \"my_comp\" overrides the variable \"my_var\", so {{ my_var }}
equals 456
.
And variable \"cheese\" will equal feta
, because the fill CAN access the current context.
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ContextBehavior.ISOLATED","title":"ISOLATED class-attribute
instance-attribute
","text":"ISOLATED = 'isolated'\n
This setting makes the component fills behave similar to Vue or React, where the fills use EXCLUSIVELY the context variables defined in get_context_data
.
Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the get_context_data()
method
{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
123 # my_var\n # cheese\n
Because both variables \"my_var\" and \"cheese\" are taken from the root context. Since \"cheese\" is not defined in root context, it's empty.
"},{"location":"reference/django_components/apps/","title":"
apps","text":""},{"location":"reference/django_components/apps/#django_components.apps","title":"apps","text":""},{"location":"reference/django_components/attributes/","title":"
attributes","text":""},{"location":"reference/django_components/attributes/#django_components.attributes","title":"attributes","text":""},{"location":"reference/django_components/attributes/#django_components.attributes.append_attributes","title":"append_attributes","text":"append_attributes(*args: Tuple[str, Any]) -> Dict\n
Merges the key-value pairs and returns a new dictionary.
If a key is present multiple times, its values are concatenated with a space character as separator in the final dictionary.
Source code in src/django_components/attributes.py
def append_attributes(*args: Tuple[str, Any]) -> Dict:\n \"\"\"\n Merges the key-value pairs and returns a new dictionary.\n\n If a key is present multiple times, its values are concatenated with a space\n character as separator in the final dictionary.\n \"\"\"\n result: Dict = {}\n\n for key, value in args:\n if key in result:\n result[key] += \" \" + value\n else:\n result[key] = value\n\n return result\n
"},{"location":"reference/django_components/attributes/#django_components.attributes.attributes_to_string","title":"attributes_to_string","text":"attributes_to_string(attributes: Mapping[str, Any]) -> str\n
Convert a dict of attributes to a string.
Source code in src/django_components/attributes.py
def attributes_to_string(attributes: Mapping[str, Any]) -> str:\n \"\"\"Convert a dict of attributes to a string.\"\"\"\n attr_list = []\n\n for key, value in attributes.items():\n if value is None or value is False:\n continue\n if value is True:\n attr_list.append(conditional_escape(key))\n else:\n attr_list.append(format_html('{}=\"{}\"', key, value))\n\n return mark_safe(SafeString(\" \").join(attr_list))\n
"},{"location":"reference/django_components/autodiscover/","title":"
autodiscover","text":""},{"location":"reference/django_components/autodiscover/#django_components.autodiscover","title":"autodiscover","text":""},{"location":"reference/django_components/autodiscover/#django_components.autodiscover.autodiscover","title":"autodiscover","text":"autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Search for component files and import them. Returns a list of module paths of imported files.
Autodiscover searches in the locations as defined by Loader.get_dirs
.
You can map the module paths with map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Source code in src/django_components/autodiscover.py
def autodiscover(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Search for component files and import them. Returns a list of module\n paths of imported files.\n\n Autodiscover searches in the locations as defined by `Loader.get_dirs`.\n\n You can map the module paths with `map_module` function. This serves\n as an escape hatch for when you need to use this function in tests.\n \"\"\"\n dirs = get_dirs()\n component_filepaths = search_dirs(dirs, \"**/*.py\")\n logger.debug(f\"Autodiscover found {len(component_filepaths)} files in component directories.\")\n\n modules = [_filepath_to_python_module(filepath) for filepath in component_filepaths]\n return _import_modules(modules, map_module)\n
"},{"location":"reference/django_components/autodiscover/#django_components.autodiscover.get_dirs","title":"get_dirs","text":"get_dirs(engine: Optional[Engine] = None) -> List[Path]\n
Helper for using django_component's FilesystemLoader class to obtain a list of directories where component python files may be defined.
Source code in src/django_components/autodiscover.py
def get_dirs(engine: Optional[Engine] = None) -> List[Path]:\n \"\"\"\n Helper for using django_component's FilesystemLoader class to obtain a list\n of directories where component python files may be defined.\n \"\"\"\n current_engine = engine\n if current_engine is None:\n current_engine = Engine.get_default()\n\n loader = Loader(current_engine)\n return loader.get_dirs()\n
"},{"location":"reference/django_components/autodiscover/#django_components.autodiscover.import_libraries","title":"import_libraries","text":"import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Import modules set in COMPONENTS.libraries
setting.
You can map the module paths with map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Source code in src/django_components/autodiscover.py
def import_libraries(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Import modules set in `COMPONENTS.libraries` setting.\n\n You can map the module paths with `map_module` function. This serves\n as an escape hatch for when you need to use this function in tests.\n \"\"\"\n from django_components.app_settings import app_settings\n\n return _import_modules(app_settings.LIBRARIES, map_module)\n
"},{"location":"reference/django_components/autodiscover/#django_components.autodiscover.search_dirs","title":"search_dirs","text":"search_dirs(dirs: List[Path], search_glob: str) -> List[Path]\n
Search the directories for the given glob pattern. Glob search results are returned as a flattened list.
Source code in src/django_components/autodiscover.py
def search_dirs(dirs: List[Path], search_glob: str) -> List[Path]:\n \"\"\"\n Search the directories for the given glob pattern. Glob search results are returned\n as a flattened list.\n \"\"\"\n matched_files: List[Path] = []\n for directory in dirs:\n for path in glob.iglob(str(Path(directory) / search_glob), recursive=True):\n matched_files.append(Path(path))\n\n return matched_files\n
"},{"location":"reference/django_components/component/","title":"
component","text":""},{"location":"reference/django_components/component/#django_components.component","title":"component","text":""},{"location":"reference/django_components/component/#django_components.component.Component","title":"Component","text":"Component(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n fill_content: Optional[Dict[str, FillContent]] = None,\n)\n
Bases: Generic[ArgsType, KwargsType, DataType, SlotsType]
Source code in src/django_components/component.py
def __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n fill_content: Optional[Dict[str, FillContent]] = None,\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.fill_content = fill_content or {}\n self.component_id = component_id or gen_id()\n self._render_stack: Deque[RenderInput[ArgsType, KwargsType, SlotsType]] = deque()\n
"},{"location":"reference/django_components/component/#django_components.component.Component.Media","title":"Media class-attribute
instance-attribute
","text":"Media = ComponentMediaInput\n
Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/component/#django_components.component.Component.css","title":"css class-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/component/#django_components.component.Component.input","title":"input property
","text":"input: Optional[RenderInput[ArgsType, KwargsType, SlotsType]]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the render
method.
"},{"location":"reference/django_components/component/#django_components.component.Component.js","title":"js class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/component/#django_components.component.Component.media","title":"media instance-attribute
","text":"media: Media\n
Normalized definition of JS and CSS media files associated with this component.
NOTE: This field is generated from Component.Media class.
"},{"location":"reference/django_components/component/#django_components.component.Component.response_class","title":"response_class class-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from render_to_response
"},{"location":"reference/django_components/component/#django_components.component.Component.template","title":"template class-attribute
instance-attribute
","text":"template: Optional[str] = None\n
Inlined Django template associated with this component.
"},{"location":"reference/django_components/component/#django_components.component.Component.template_name","title":"template_name class-attribute
","text":"template_name: Optional[str] = None\n
Relative filepath to the Django template associated with this component.
"},{"location":"reference/django_components/component/#django_components.component.Component.as_view","title":"as_view classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling Component.View.as_view
and passing component instance to it.
Source code in src/django_components/component.py
@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # Allow the View class to access this component via `self.component`\n component = cls()\n return component.View.as_view(**initkwargs, component=component)\n
"},{"location":"reference/django_components/component/#django_components.component.Component.inject","title":"inject","text":"inject(key: str, default: Optional[Any] = None) -> Any\n
Use this method to retrieve the data that was passed to a {% provide %}
tag with the corresponding key.
To retrieve the data, inject()
must be called inside a component that's inside the {% provide %}
tag.
You may also pass a default that will be used if the provide
tag with given key was NOT found.
This method mut be used inside the get_context_data()
method and raises an error if called elsewhere.
Example:
Given this template:
{% provide \"provider\" hello=\"world\" %}\n {% component \"my_comp\" %}\n {% endcomponent %}\n{% endprovide %}\n
And given this definition of \"my_comp\" component:
from django_components import Component, register\n\n@register(\"my_comp\")\nclass MyComp(Component):\n template = \"hi {{ data.hello }}!\"\n def get_context_data(self):\n data = self.inject(\"provider\")\n return {\"data\": data}\n
This renders into:
hi world!\n
As the {{ data.hello }}
is taken from the \"provider\".
Source code in src/django_components/component.py
def inject(self, key: str, default: Optional[Any] = None) -> Any:\n \"\"\"\n Use this method to retrieve the data that was passed to a `{% provide %}` tag\n with the corresponding key.\n\n To retrieve the data, `inject()` must be called inside a component that's\n inside the `{% provide %}` tag.\n\n You may also pass a default that will be used if the `provide` tag with given\n key was NOT found.\n\n This method mut be used inside the `get_context_data()` method and raises\n an error if called elsewhere.\n\n Example:\n\n Given this template:\n ```django\n {% provide \"provider\" hello=\"world\" %}\n {% component \"my_comp\" %}\n {% endcomponent %}\n {% endprovide %}\n ```\n\n And given this definition of \"my_comp\" component:\n ```py\n from django_components import Component, register\n\n @register(\"my_comp\")\n class MyComp(Component):\n template = \"hi {{ data.hello }}!\"\n def get_context_data(self):\n data = self.inject(\"provider\")\n return {\"data\": data}\n ```\n\n This renders into:\n ```\n hi world!\n ```\n\n As the `{{ data.hello }}` is taken from the \"provider\".\n \"\"\"\n if self.input is None:\n raise RuntimeError(\n f\"Method 'inject()' of component '{self.name}' was called outside of 'get_context_data()'\"\n )\n\n return get_injected_context_var(self.name, self.input.context, key, default)\n
"},{"location":"reference/django_components/component/#django_components.component.Component.render","title":"render classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n) -> str\n
Render the component into a string.
Inputs: - args
- Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %}
- kwargs
- Kwargs for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %}
- slots
- Component slot fills. This is the same as pasing {% fill %}
tags to the component. Accepts a dictionary of { slot_name: slot_content }
where slot_content
can be a string or render function. - escape_slots_content
- Whether the content from slots
should be escaped. - context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs.
Example:
MyComponent.render(\n args=[1, \"two\", {}],\n kwargs={\n \"key\": 123,\n },\n slots={\n \"header\": 'STATIC TEXT HERE',\n \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n },\n escape_slots_content=False,\n)\n
Source code in src/django_components/component.py
@classmethod\ndef render(\n cls,\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n) -> str:\n \"\"\"\n Render the component into a string.\n\n Inputs:\n - `args` - Positional args for the component. This is the same as calling the component\n as `{% component \"my_comp\" arg1 arg2 ... %}`\n - `kwargs` - Kwargs for the component. This is the same as calling the component\n as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n or render function.\n - `escape_slots_content` - Whether the content from `slots` should be escaped.\n - `context` - A context (dictionary or Django's Context) within which the component\n is rendered. The keys on the context can be accessed from within the template.\n - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n component's args and kwargs.\n\n Example:\n ```py\n MyComponent.render(\n args=[1, \"two\", {}],\n kwargs={\n \"key\": 123,\n },\n slots={\n \"header\": 'STATIC TEXT HERE',\n \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n },\n escape_slots_content=False,\n )\n ```\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n return comp._render(context, args, kwargs, slots, escape_slots_content)\n
"},{"location":"reference/django_components/component/#django_components.component.Component.render_css_dependencies","title":"render_css_dependencies","text":"render_css_dependencies() -> SafeString\n
Render only CSS dependencies available in the media class or provided as a string.
Source code in src/django_components/component.py
def render_css_dependencies(self) -> SafeString:\n \"\"\"Render only CSS dependencies available in the media class or provided as a string.\"\"\"\n if self.css is not None:\n return mark_safe(f\"<style>{self.css}</style>\")\n return mark_safe(\"\\n\".join(self.media.render_css()))\n
"},{"location":"reference/django_components/component/#django_components.component.Component.render_dependencies","title":"render_dependencies","text":"render_dependencies() -> SafeString\n
Helper function to render all dependencies for a component.
Source code in src/django_components/component.py
def render_dependencies(self) -> SafeString:\n \"\"\"Helper function to render all dependencies for a component.\"\"\"\n dependencies = []\n\n css_deps = self.render_css_dependencies()\n if css_deps:\n dependencies.append(css_deps)\n\n js_deps = self.render_js_dependencies()\n if js_deps:\n dependencies.append(js_deps)\n\n return mark_safe(\"\\n\".join(dependencies))\n
"},{"location":"reference/django_components/component/#django_components.component.Component.render_js_dependencies","title":"render_js_dependencies","text":"render_js_dependencies() -> SafeString\n
Render only JS dependencies available in the media class or provided as a string.
Source code in src/django_components/component.py
def render_js_dependencies(self) -> SafeString:\n \"\"\"Render only JS dependencies available in the media class or provided as a string.\"\"\"\n if self.js is not None:\n return mark_safe(f\"<script>{self.js}</script>\")\n return mark_safe(\"\\n\".join(self.media.render_js()))\n
"},{"location":"reference/django_components/component/#django_components.component.Component.render_to_response","title":"render_to_response classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n *response_args: Any,\n **response_kwargs: Any\n) -> HttpResponse\n
Render the component and wrap the content in the response class.
The response class is taken from Component.response_class
. Defaults to django.http.HttpResponse
.
This is the interface for the django.views.View
class which allows us to use components as Django views with component.as_view()
.
Inputs: - args
- Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %}
- kwargs
- Kwargs for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %}
- slots
- Component slot fills. This is the same as pasing {% fill %}
tags to the component. Accepts a dictionary of { slot_name: slot_content }
where slot_content
can be a string or render function. - escape_slots_content
- Whether the content from slots
should be escaped. - context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs.
Any additional args and kwargs are passed to the response_class
.
Example:
MyComponent.render_to_response(\n args=[1, \"two\", {}],\n kwargs={\n \"key\": 123,\n },\n slots={\n \"header\": 'STATIC TEXT HERE',\n \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n },\n escape_slots_content=False,\n # HttpResponse input\n status=201,\n headers={...},\n)\n# HttpResponse(content=..., status=201, headers=...)\n
Source code in src/django_components/component.py
@classmethod\ndef render_to_response(\n cls,\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n *response_args: Any,\n **response_kwargs: Any,\n) -> HttpResponse:\n \"\"\"\n Render the component and wrap the content in the response class.\n\n The response class is taken from `Component.response_class`. Defaults to `django.http.HttpResponse`.\n\n This is the interface for the `django.views.View` class which allows us to\n use components as Django views with `component.as_view()`.\n\n Inputs:\n - `args` - Positional args for the component. This is the same as calling the component\n as `{% component \"my_comp\" arg1 arg2 ... %}`\n - `kwargs` - Kwargs for the component. This is the same as calling the component\n as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n or render function.\n - `escape_slots_content` - Whether the content from `slots` should be escaped.\n - `context` - A context (dictionary or Django's Context) within which the component\n is rendered. The keys on the context can be accessed from within the template.\n - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n component's args and kwargs.\n\n Any additional args and kwargs are passed to the `response_class`.\n\n Example:\n ```py\n MyComponent.render_to_response(\n args=[1, \"two\", {}],\n kwargs={\n \"key\": 123,\n },\n slots={\n \"header\": 'STATIC TEXT HERE',\n \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n },\n escape_slots_content=False,\n # HttpResponse input\n status=201,\n headers={...},\n )\n # HttpResponse(content=..., status=201, headers=...)\n ```\n \"\"\"\n content = cls.render(\n args=args,\n kwargs=kwargs,\n context=context,\n slots=slots,\n escape_slots_content=escape_slots_content,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
"},{"location":"reference/django_components/component/#django_components.component.ComponentNode","title":"ComponentNode","text":"ComponentNode(\n name: str,\n args: List[Expression],\n kwargs: RuntimeKwargs,\n isolated_context: bool = False,\n fill_nodes: Optional[List[FillNode]] = None,\n node_id: Optional[str] = None,\n)\n
Bases: BaseNode
Django.template.Node subclass that renders a django-components component
Source code in src/django_components/component.py
def __init__(\n self,\n name: str,\n args: List[Expression],\n kwargs: RuntimeKwargs,\n isolated_context: bool = False,\n fill_nodes: Optional[List[FillNode]] = None,\n node_id: Optional[str] = None,\n) -> None:\n super().__init__(nodelist=NodeList(fill_nodes), args=args, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.isolated_context = isolated_context\n self.fill_nodes = fill_nodes or []\n
"},{"location":"reference/django_components/component/#django_components.component.ComponentView","title":"ComponentView","text":"ComponentView(component: Component, **kwargs: Any)\n
Bases: View
Subclass of django.views.View
where the Component
instance is available via self.component
.
Source code in src/django_components/component.py
def __init__(self, component: \"Component\", **kwargs: Any) -> None:\n super().__init__(**kwargs)\n self.component = component\n
"},{"location":"reference/django_components/component_media/","title":"
component_media","text":""},{"location":"reference/django_components/component_media/#django_components.component_media","title":"component_media","text":""},{"location":"reference/django_components/component_media/#django_components.component_media.ComponentMediaInput","title":"ComponentMediaInput","text":"Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta","title":"MediaMeta","text":" Bases: MediaDefiningClass
Metaclass for handling media files for components.
Similar to MediaDefiningClass
, this class supports the use of Media
attribute to define associated JS/CSS files, which are then available under media
attribute as a instance of Media
class.
This subclass has following changes:
"},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--1-support-for-multiple-interfaces-of-jscss","title":"1. Support for multiple interfaces of JS/CSS","text":" -
As plain strings
class MyComponent(Component):\n class Media:\n js = \"path/to/script.js\"\n css = \"path/to/style.css\"\n
-
As lists
class MyComponent(Component):\n class Media:\n js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n
-
[CSS ONLY] Dicts of strings
class MyComponent(Component):\n class Media:\n css = {\n \"all\": \"path/to/style1.css\",\n \"print\": \"path/to/style2.css\",\n }\n
-
[CSS ONLY] Dicts of lists
class MyComponent(Component):\n class Media:\n css = {\n \"all\": [\"path/to/style1.css\"],\n \"print\": [\"path/to/style2.css\"],\n }\n
"},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--2-media-are-first-resolved-relative-to-class-definition-file","title":"2. Media are first resolved relative to class definition file","text":"E.g. if in a directory my_comp
you have script.js
and my_comp.py
, and my_comp.py
looks like this:
class MyComponent(Component):\n class Media:\n js = \"script.js\"\n
Then script.js
will be resolved as my_comp/script.js
.
"},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--3-media-can-be-defined-as-str-bytes-pathlike-safestring-or-function-of-thereof","title":"3. Media can be defined as str, bytes, PathLike, SafeString, or function of thereof","text":"E.g.:
def lazy_eval_css():\n # do something\n return path\n\nclass MyComponent(Component):\n class Media:\n js = b\"script.js\"\n css = lazy_eval_css\n
"},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--4-subclass-media-class-with-media_class","title":"4. Subclass Media
class with media_class
","text":"Normal MediaDefiningClass
creates an instance of Media
class under the media
attribute. This class allows to override which class will be instantiated with media_class
attribute:
class MyMedia(Media):\n def render_js(self):\n ...\n\nclass MyComponent(Component):\n media_class = MyMedia\n def get_context_data(self):\n assert isinstance(self.media, MyMedia)\n
"},{"location":"reference/django_components/component_registry/","title":"
component_registry","text":""},{"location":"reference/django_components/component_registry/#django_components.component_registry","title":"component_registry","text":""},{"location":"reference/django_components/component_registry/#django_components.component_registry.registry","title":"registry module-attribute
","text":"registry: ComponentRegistry = ComponentRegistry()\n
The default and global component registry. Use this instance to directly register or remove components:
# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Get single\nregistry.get(\"button\")\n# Get all\nregistry.all()\n# Unregister single\nregistry.unregister(\"button\")\n# Unregister all\nregistry.clear()\n
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry","title":"ComponentRegistry","text":"ComponentRegistry(library: Optional[Library] = None)\n
Manages which components can be used in the template tags.
Each ComponentRegistry instance is associated with an instance of Django's Library. So when you register or unregister a component to/from a component registry, behind the scenes the registry automatically adds/removes the component's template tag to/from the Library.
The Library instance can be set at instantiation. If omitted, then the default Library instance from django_components is used. The Library instance can be accessed under library
attribute.
Example:
# Use with default Library\nregistry = ComponentRegistry()\n\n# Or a custom one\nmy_lib = Library()\nregistry = ComponentRegistry(library=my_lib)\n\n# Usage\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\nregistry.all()\nregistry.clear()\nregistry.get()\n
Source code in src/django_components/component_registry.py
def __init__(self, library: Optional[Library] = None) -> None:\n self._registry: Dict[str, ComponentRegistryEntry] = {} # component name -> component_entry mapping\n self._tags: Dict[str, Set[str]] = {} # tag -> list[component names]\n self._library = library\n
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.library","title":"library property
","text":"library: Library\n
The template tag library with which the component registry is associated.
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.all","title":"all","text":"all() -> Dict[str, Type[Component]]\n
Retrieve all registered component classes.
Example:
# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then get all\nregistry.all()\n# > {\n# > \"button\": ButtonComponent,\n# > \"card\": CardComponent,\n# > }\n
Source code in src/django_components/component_registry.py
def all(self) -> Dict[str, Type[\"Component\"]]:\n \"\"\"\n Retrieve all registered component classes.\n\n Example:\n\n ```py\n # First register components\n registry.register(\"button\", ButtonComponent)\n registry.register(\"card\", CardComponent)\n # Then get all\n registry.all()\n # > {\n # > \"button\": ButtonComponent,\n # > \"card\": CardComponent,\n # > }\n ```\n \"\"\"\n comps = {key: entry.cls for key, entry in self._registry.items()}\n return comps\n
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.clear","title":"clear","text":"clear() -> None\n
Clears the registry, unregistering all components.
Example:
# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then clear\nregistry.clear()\n# Then get all\nregistry.all()\n# > {}\n
Source code in src/django_components/component_registry.py
def clear(self) -> None:\n \"\"\"\n Clears the registry, unregistering all components.\n\n Example:\n\n ```py\n # First register components\n registry.register(\"button\", ButtonComponent)\n registry.register(\"card\", CardComponent)\n # Then clear\n registry.clear()\n # Then get all\n registry.all()\n # > {}\n ```\n \"\"\"\n all_comp_names = list(self._registry.keys())\n for comp_name in all_comp_names:\n self.unregister(comp_name)\n\n self._registry = {}\n self._tags = {}\n
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.get","title":"get","text":"get(name: str) -> Type[Component]\n
Retrieve a component class registered under the given name.
Raises NotRegistered
if the given name is not registered.
Example:
# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then get\nregistry.get(\"button\")\n# > ButtonComponent\n
Source code in src/django_components/component_registry.py
def get(self, name: str) -> Type[\"Component\"]:\n \"\"\"\n Retrieve a component class registered under the given name.\n\n Raises `NotRegistered` if the given name is not registered.\n\n Example:\n\n ```py\n # First register component\n registry.register(\"button\", ButtonComponent)\n # Then get\n registry.get(\"button\")\n # > ButtonComponent\n ```\n \"\"\"\n if name not in self._registry:\n raise NotRegistered('The component \"%s\" is not registered' % name)\n\n return self._registry[name].cls\n
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.register","title":"register","text":"register(name: str, component: Type[Component]) -> None\n
Register a component with this registry under the given name.
A component MUST be registered before it can be used in a template such as:
{% component \"my_comp\" %}{% endcomponent %}\n
Raises AlreadyRegistered
if a different component was already registered under the same name.
Example:
registry.register(\"button\", ButtonComponent)\n
Source code in src/django_components/component_registry.py
def register(self, name: str, component: Type[\"Component\"]) -> None:\n \"\"\"\n Register a component with this registry under the given name.\n\n A component MUST be registered before it can be used in a template such as:\n ```django\n {% component \"my_comp\" %}{% endcomponent %}\n ```\n\n Raises `AlreadyRegistered` if a different component was already registered\n under the same name.\n\n Example:\n\n ```py\n registry.register(\"button\", ButtonComponent)\n ```\n \"\"\"\n existing_component = self._registry.get(name)\n if existing_component and existing_component.cls._class_hash != component._class_hash:\n raise AlreadyRegistered('The component \"%s\" has already been registered' % name)\n\n entry = self._register_to_library(name, component)\n\n # Keep track of which components use which tags, because multiple components may\n # use the same tag.\n tag = entry.tag\n if tag not in self._tags:\n self._tags[tag] = set()\n self._tags[tag].add(name)\n\n self._registry[name] = entry\n
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.unregister","title":"unregister","text":"unregister(name: str) -> None\n
Unlinks a previously-registered component from the registry under the given name.
Once a component is unregistered, it CANNOT be used in a template anymore. Following would raise an error:
{% component \"my_comp\" %}{% endcomponent %}\n
Raises NotRegistered
if the given name is not registered.
Example:
# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
Source code in src/django_components/component_registry.py
def unregister(self, name: str) -> None:\n \"\"\"\n Unlinks a previously-registered component from the registry under the given name.\n\n Once a component is unregistered, it CANNOT be used in a template anymore.\n Following would raise an error:\n ```django\n {% component \"my_comp\" %}{% endcomponent %}\n ```\n\n Raises `NotRegistered` if the given name is not registered.\n\n Example:\n\n ```py\n # First register component\n registry.register(\"button\", ButtonComponent)\n # Then unregister\n registry.unregister(\"button\")\n ```\n \"\"\"\n # Validate\n self.get(name)\n\n entry = self._registry[name]\n tag = entry.tag\n\n # Unregister the tag from library if this was the last component using this tag\n # Unlink component from tag\n self._tags[tag].remove(name)\n\n # Cleanup\n is_tag_empty = not len(self._tags[tag])\n if is_tag_empty:\n del self._tags[tag]\n\n # Only unregister a tag if it's NOT protected\n is_protected = is_tag_protected(self.library, tag)\n if not is_protected:\n # Unregister the tag from library if this was the last component using this tag\n if is_tag_empty and tag in self.library.tags:\n del self.library.tags[tag]\n\n del self._registry[name]\n
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.register","title":"register","text":"register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]\n
Class decorator to register a component.
Usage:
@register(\"my_component\")\nclass MyComponent(Component):\n ...\n
Optionally specify which ComponentRegistry
the component should be registered to by setting the registry
kwarg:
my_lib = django.template.Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n ...\n
Source code in src/django_components/component_registry.py
def register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]:\n \"\"\"\n Class decorator to register a component.\n\n Usage:\n\n ```py\n @register(\"my_component\")\n class MyComponent(Component):\n ...\n ```\n\n Optionally specify which `ComponentRegistry` the component should be registered to by\n setting the `registry` kwarg:\n\n ```py\n my_lib = django.template.Library()\n my_reg = ComponentRegistry(library=my_lib)\n\n @register(\"my_component\", registry=my_reg)\n class MyComponent(Component):\n ...\n ```\n \"\"\"\n if registry is None:\n registry = _the_registry\n\n def decorator(component: _TComp) -> _TComp:\n registry.register(name=name, component=component)\n return component\n\n return decorator\n
"},{"location":"reference/django_components/context/","title":"
context","text":""},{"location":"reference/django_components/context/#django_components.context","title":"context","text":"This file centralizes various ways we use Django's Context class pass data across components, nodes, slots, and contexts.
You can think of the Context as our storage system.
"},{"location":"reference/django_components/context/#django_components.context.copy_forloop_context","title":"copy_forloop_context","text":"copy_forloop_context(from_context: Context, to_context: Context) -> None\n
Forward the info about the current loop
Source code in src/django_components/context.py
def copy_forloop_context(from_context: Context, to_context: Context) -> None:\n \"\"\"Forward the info about the current loop\"\"\"\n # Note that the ForNode (which implements for loop behavior) does not\n # only add the `forloop` key, but also keys corresponding to the loop elements\n # So if the loop syntax is `{% for my_val in my_lists %}`, then ForNode also\n # sets a `my_val` key.\n # For this reason, instead of copying individual keys, we copy the whole stack layer\n # set by ForNode.\n if \"forloop\" in from_context:\n forloop_dict_index = find_last_index(from_context.dicts, lambda d: \"forloop\" in d)\n to_context.update(from_context.dicts[forloop_dict_index])\n
"},{"location":"reference/django_components/context/#django_components.context.get_injected_context_var","title":"get_injected_context_var","text":"get_injected_context_var(component_name: str, context: Context, key: str, default: Optional[Any] = None) -> Any\n
Retrieve a 'provided' field. The field MUST have been previously 'provided' by the component's ancestors using the {% provide %}
template tag.
Source code in src/django_components/context.py
def get_injected_context_var(\n component_name: str,\n context: Context,\n key: str,\n default: Optional[Any] = None,\n) -> Any:\n \"\"\"\n Retrieve a 'provided' field. The field MUST have been previously 'provided'\n by the component's ancestors using the `{% provide %}` template tag.\n \"\"\"\n # NOTE: For simplicity, we keep the provided values directly on the context.\n # This plays nicely with Django's Context, which behaves like a stack, so \"newer\"\n # values overshadow the \"older\" ones.\n internal_key = _INJECT_CONTEXT_KEY_PREFIX + key\n\n # Return provided value if found\n if internal_key in context:\n return context[internal_key]\n\n # If a default was given, return that\n if default is not None:\n return default\n\n # Otherwise raise error\n raise KeyError(\n f\"Component '{component_name}' tried to inject a variable '{key}' before it was provided.\"\n f\" To fix this, make sure that at least one ancestor of component '{component_name}' has\"\n f\" the variable '{key}' in their 'provide' attribute.\"\n )\n
"},{"location":"reference/django_components/context/#django_components.context.prepare_context","title":"prepare_context","text":"prepare_context(context: Context, component_id: str) -> None\n
Initialize the internal context state.
Source code in src/django_components/context.py
def prepare_context(\n context: Context,\n component_id: str,\n) -> None:\n \"\"\"Initialize the internal context state.\"\"\"\n # Initialize mapping dicts within this rendering run.\n # This is shared across the whole render chain, thus we set it only once.\n if _FILLED_SLOTS_CONTENT_CONTEXT_KEY not in context:\n context[_FILLED_SLOTS_CONTENT_CONTEXT_KEY] = {}\n\n set_component_id(context, component_id)\n
"},{"location":"reference/django_components/context/#django_components.context.set_component_id","title":"set_component_id","text":"set_component_id(context: Context, component_id: str) -> None\n
We use the Context object to pass down info on inside of which component we are currently rendering.
Source code in src/django_components/context.py
def set_component_id(context: Context, component_id: str) -> None:\n \"\"\"\n We use the Context object to pass down info on inside of which component\n we are currently rendering.\n \"\"\"\n # Store the previous component so we can detect if the current component\n # is the top-most or not. If it is, then \"_parent_component_id\" is None\n context[_PARENT_COMP_CONTEXT_KEY] = context.get(_CURRENT_COMP_CONTEXT_KEY, None)\n context[_CURRENT_COMP_CONTEXT_KEY] = component_id\n
"},{"location":"reference/django_components/context/#django_components.context.set_provided_context_var","title":"set_provided_context_var","text":"set_provided_context_var(context: Context, key: str, provided_kwargs: Dict[str, Any]) -> None\n
'Provide' given data under given key. In other words, this data can be retrieved using self.inject(key)
inside of get_context_data()
method of components that are nested inside the {% provide %}
tag.
Source code in src/django_components/context.py
def set_provided_context_var(\n context: Context,\n key: str,\n provided_kwargs: Dict[str, Any],\n) -> None:\n \"\"\"\n 'Provide' given data under given key. In other words, this data can be retrieved\n using `self.inject(key)` inside of `get_context_data()` method of components that\n are nested inside the `{% provide %}` tag.\n \"\"\"\n # NOTE: We raise TemplateSyntaxError since this func should be called only from\n # within template.\n if not key:\n raise TemplateSyntaxError(\n \"Provide tag received an empty string. Key must be non-empty and a valid identifier.\"\n )\n if not key.isidentifier():\n raise TemplateSyntaxError(\n \"Provide tag received a non-identifier string. Key must be non-empty and a valid identifier.\"\n )\n\n # We turn the kwargs into a NamedTuple so that the object that's \"provided\"\n # is immutable. This ensures that the data returned from `inject` will always\n # have all the keys that were passed to the `provide` tag.\n tpl_cls = namedtuple(\"DepInject\", provided_kwargs.keys()) # type: ignore[misc]\n payload = tpl_cls(**provided_kwargs)\n\n internal_key = _INJECT_CONTEXT_KEY_PREFIX + key\n context[internal_key] = payload\n
"},{"location":"reference/django_components/expression/","title":"
expression","text":""},{"location":"reference/django_components/expression/#django_components.expression","title":"expression","text":""},{"location":"reference/django_components/expression/#django_components.expression.Operator","title":"Operator","text":" Bases: ABC
Operator describes something that somehow changes the inputs to template tags (the {% %}
).
For example, a SpreadOperator inserts one or more kwargs at the specified location.
"},{"location":"reference/django_components/expression/#django_components.expression.SpreadOperator","title":"SpreadOperator","text":"SpreadOperator(expr: Expression)\n
Bases: Operator
Operator that inserts one or more kwargs at the specified location.
Source code in src/django_components/expression.py
def __init__(self, expr: Expression) -> None:\n self.expr = expr\n
"},{"location":"reference/django_components/expression/#django_components.expression.process_aggregate_kwargs","title":"process_aggregate_kwargs","text":"process_aggregate_kwargs(kwargs: Mapping[str, Any]) -> Dict[str, Any]\n
This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs start with some prefix delimited with :
(e.g. attrs:
).
Example:
process_component_kwargs({\"abc:one\": 1, \"abc:two\": 2, \"def:three\": 3, \"four\": 4})\n# {\"abc\": {\"one\": 1, \"two\": 2}, \"def\": {\"three\": 3}, \"four\": 4}\n
We want to support a use case similar to Vue's fallthrough attributes. In other words, where a component author can designate a prop (input) which is a dict and which will be rendered as HTML attributes.
This is useful for allowing component users to tweak styling or add event handling to the underlying HTML. E.g.:
class=\"pa-4 d-flex text-black\"
or @click.stop=\"alert('clicked!')\"
So if the prop is attrs
, and the component is called like so:
{% component \"my_comp\" attrs=attrs %}\n
then, if attrs
is:
{\"class\": \"text-red pa-4\", \"@click\": \"dispatch('my_event', 123)\"}\n
and the component template is:
<div {% html_attrs attrs add:class=\"extra-class\" %}></div>\n
Then this renders:
<div class=\"text-red pa-4 extra-class\" @click=\"dispatch('my_event', 123)\" ></div>\n
However, this way it is difficult for the component user to define the attrs
variable, especially if they want to combine static and dynamic values. Because they will need to pre-process the attrs
dict.
So, instead, we allow to \"aggregate\" props into a dict. So all props that start with attrs:
, like attrs:class=\"text-red\"
, will be collected into a dict at key attrs
.
This provides sufficient flexiblity to make it easy for component users to provide \"fallthrough attributes\", and sufficiently easy for component authors to process that input while still being able to provide their own keys.
Source code in src/django_components/expression.py
def process_aggregate_kwargs(kwargs: Mapping[str, Any]) -> Dict[str, Any]:\n \"\"\"\n This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs\n start with some prefix delimited with `:` (e.g. `attrs:`).\n\n Example:\n ```py\n process_component_kwargs({\"abc:one\": 1, \"abc:two\": 2, \"def:three\": 3, \"four\": 4})\n # {\"abc\": {\"one\": 1, \"two\": 2}, \"def\": {\"three\": 3}, \"four\": 4}\n ```\n\n ---\n\n We want to support a use case similar to Vue's fallthrough attributes.\n In other words, where a component author can designate a prop (input)\n which is a dict and which will be rendered as HTML attributes.\n\n This is useful for allowing component users to tweak styling or add\n event handling to the underlying HTML. E.g.:\n\n `class=\"pa-4 d-flex text-black\"` or `@click.stop=\"alert('clicked!')\"`\n\n So if the prop is `attrs`, and the component is called like so:\n ```django\n {% component \"my_comp\" attrs=attrs %}\n ```\n\n then, if `attrs` is:\n ```py\n {\"class\": \"text-red pa-4\", \"@click\": \"dispatch('my_event', 123)\"}\n ```\n\n and the component template is:\n ```django\n <div {% html_attrs attrs add:class=\"extra-class\" %}></div>\n ```\n\n Then this renders:\n ```html\n <div class=\"text-red pa-4 extra-class\" @click=\"dispatch('my_event', 123)\" ></div>\n ```\n\n However, this way it is difficult for the component user to define the `attrs`\n variable, especially if they want to combine static and dynamic values. Because\n they will need to pre-process the `attrs` dict.\n\n So, instead, we allow to \"aggregate\" props into a dict. So all props that start\n with `attrs:`, like `attrs:class=\"text-red\"`, will be collected into a dict\n at key `attrs`.\n\n This provides sufficient flexiblity to make it easy for component users to provide\n \"fallthrough attributes\", and sufficiently easy for component authors to process\n that input while still being able to provide their own keys.\n \"\"\"\n processed_kwargs = {}\n nested_kwargs: Dict[str, Dict[str, Any]] = {}\n for key, val in kwargs.items():\n if not is_aggregate_key(key):\n processed_kwargs[key] = val\n continue\n\n # NOTE: Trim off the prefix from keys\n prefix, sub_key = key.split(\":\", 1)\n if prefix not in nested_kwargs:\n nested_kwargs[prefix] = {}\n nested_kwargs[prefix][sub_key] = val\n\n # Assign aggregated values into normal input\n for key, val in nested_kwargs.items():\n if key in processed_kwargs:\n raise TemplateSyntaxError(\n f\"Received argument '{key}' both as a regular input ({key}=...)\"\n f\" and as an aggregate dict ('{key}:key=...'). Must be only one of the two\"\n )\n processed_kwargs[key] = val\n\n return processed_kwargs\n
"},{"location":"reference/django_components/library/","title":"
library","text":""},{"location":"reference/django_components/library/#django_components.library","title":"library","text":"Module for interfacing with Django's Library (django.template.library
)
"},{"location":"reference/django_components/library/#django_components.library.PROTECTED_TAGS","title":"PROTECTED_TAGS module-attribute
","text":"PROTECTED_TAGS = [\n \"component_dependencies\",\n \"component_css_dependencies\",\n \"component_js_dependencies\",\n \"fill\",\n \"html_attrs\",\n \"provide\",\n \"slot\",\n]\n
These are the names that users cannot choose for their components, as they would conflict with other tags in the Library.
"},{"location":"reference/django_components/logger/","title":"
logger","text":""},{"location":"reference/django_components/logger/#django_components.logger","title":"logger","text":""},{"location":"reference/django_components/logger/#django_components.logger.trace","title":"trace","text":"trace(logger: Logger, message: str, *args: Any, **kwargs: Any) -> None\n
TRACE level logger.
To display TRACE logs, set the logging level to 5.
Example:
LOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"handlers\": {\n \"console\": {\n \"class\": \"logging.StreamHandler\",\n \"stream\": sys.stdout,\n },\n },\n \"loggers\": {\n \"django_components\": {\n \"level\": 5,\n \"handlers\": [\"console\"],\n },\n },\n}\n
Source code in src/django_components/logger.py
def trace(logger: logging.Logger, message: str, *args: Any, **kwargs: Any) -> None:\n \"\"\"\n TRACE level logger.\n\n To display TRACE logs, set the logging level to 5.\n\n Example:\n ```py\n LOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"handlers\": {\n \"console\": {\n \"class\": \"logging.StreamHandler\",\n \"stream\": sys.stdout,\n },\n },\n \"loggers\": {\n \"django_components\": {\n \"level\": 5,\n \"handlers\": [\"console\"],\n },\n },\n }\n ```\n \"\"\"\n if actual_trace_level_num == -1:\n setup_logging()\n if logger.isEnabledFor(actual_trace_level_num):\n logger.log(actual_trace_level_num, message, *args, **kwargs)\n
"},{"location":"reference/django_components/logger/#django_components.logger.trace_msg","title":"trace_msg","text":"trace_msg(\n action: Literal[\"PARSE\", \"ASSOC\", \"RENDR\", \"GET\", \"SET\"],\n node_type: Literal[\"COMP\", \"FILL\", \"SLOT\", \"PROVIDE\", \"N/A\"],\n node_name: str,\n node_id: str,\n msg: str = \"\",\n component_id: Optional[str] = None,\n) -> None\n
TRACE level logger with opinionated format for tracing interaction of components, nodes, and slots. Formats messages like so:
\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"
Source code in src/django_components/logger.py
def trace_msg(\n action: Literal[\"PARSE\", \"ASSOC\", \"RENDR\", \"GET\", \"SET\"],\n node_type: Literal[\"COMP\", \"FILL\", \"SLOT\", \"PROVIDE\", \"N/A\"],\n node_name: str,\n node_id: str,\n msg: str = \"\",\n component_id: Optional[str] = None,\n) -> None:\n \"\"\"\n TRACE level logger with opinionated format for tracing interaction of components,\n nodes, and slots. Formats messages like so:\n\n `\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"`\n \"\"\"\n msg_prefix = \"\"\n if action == \"ASSOC\":\n if not component_id:\n raise ValueError(\"component_id must be set for the ASSOC action\")\n msg_prefix = f\"TO COMP {component_id}\"\n elif action == \"RENDR\" and node_type == \"FILL\":\n if not component_id:\n raise ValueError(\"component_id must be set for the RENDER action\")\n msg_prefix = f\"FOR COMP {component_id}\"\n\n msg_parts = [f\"{action} {node_type} {node_name} ID {node_id}\", *([msg_prefix] if msg_prefix else []), msg]\n full_msg = \" \".join(msg_parts)\n\n # NOTE: When debugging tests during development, it may be easier to change\n # this to `print()`\n trace(logger, full_msg)\n
"},{"location":"reference/django_components/management/","title":"Index","text":""},{"location":"reference/django_components/management/#django_components.management","title":"management","text":""},{"location":"reference/django_components/management/#django_components.management.commands","title":"commands","text":""},{"location":"reference/django_components/management/#django_components.management.commands.upgradecomponent","title":"upgradecomponent","text":""},{"location":"reference/django_components/management/commands/","title":"Index","text":""},{"location":"reference/django_components/management/commands/#django_components.management.commands","title":"commands","text":""},{"location":"reference/django_components/management/commands/#django_components.management.commands.upgradecomponent","title":"upgradecomponent","text":""},{"location":"reference/django_components/management/commands/startcomponent/","title":"
startcomponent","text":""},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent","title":"startcomponent","text":""},{"location":"reference/django_components/management/commands/upgradecomponent/","title":"
upgradecomponent","text":""},{"location":"reference/django_components/management/commands/upgradecomponent/#django_components.management.commands.upgradecomponent","title":"upgradecomponent","text":""},{"location":"reference/django_components/middleware/","title":"
middleware","text":""},{"location":"reference/django_components/middleware/#django_components.middleware","title":"middleware","text":""},{"location":"reference/django_components/middleware/#django_components.middleware.ComponentDependencyMiddleware","title":"ComponentDependencyMiddleware","text":"ComponentDependencyMiddleware(get_response: Callable[[HttpRequest], HttpResponse])\n
Middleware that inserts CSS/JS dependencies for all rendered components at points marked with template tags.
Source code in src/django_components/middleware.py
def __init__(self, get_response: \"Callable[[HttpRequest], HttpResponse]\") -> None:\n self.get_response = get_response\n\n if iscoroutinefunction(self.get_response):\n markcoroutinefunction(self)\n
"},{"location":"reference/django_components/middleware/#django_components.middleware.DependencyReplacer","title":"DependencyReplacer","text":"DependencyReplacer(css_string: bytes, js_string: bytes)\n
Replacer for use in re.sub that replaces the first placeholder CSS and JS tags it encounters and removes any subsequent ones.
Source code in src/django_components/middleware.py
def __init__(self, css_string: bytes, js_string: bytes) -> None:\n self.js_string = js_string\n self.css_string = css_string\n
"},{"location":"reference/django_components/middleware/#django_components.middleware.join_media","title":"join_media","text":"join_media(components: Iterable[Component]) -> Media\n
Return combined media object for iterable of components.
Source code in src/django_components/middleware.py
def join_media(components: Iterable[\"Component\"]) -> Media:\n \"\"\"Return combined media object for iterable of components.\"\"\"\n\n return sum([component.media for component in components], Media())\n
"},{"location":"reference/django_components/node/","title":"
node","text":""},{"location":"reference/django_components/node/#django_components.node","title":"node","text":""},{"location":"reference/django_components/node/#django_components.node.BaseNode","title":"BaseNode","text":"BaseNode(\n nodelist: Optional[NodeList] = None,\n node_id: Optional[str] = None,\n args: Optional[List[Expression]] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n)\n
Bases: Node
Shared behavior for our subclasses of Django's Node
Source code in src/django_components/node.py
def __init__(\n self,\n nodelist: Optional[NodeList] = None,\n node_id: Optional[str] = None,\n args: Optional[List[Expression]] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n):\n self.nodelist = nodelist or NodeList()\n self.node_id = node_id or gen_id()\n self.args = args or []\n self.kwargs = kwargs or RuntimeKwargs({})\n
"},{"location":"reference/django_components/node/#django_components.node.get_node_children","title":"get_node_children","text":"get_node_children(node: Node, context: Optional[Context] = None) -> NodeList\n
Get child Nodes from Node's nodelist atribute.
This function is taken from get_nodes_by_type
method of django.template.base.Node
.
Source code in src/django_components/node.py
def get_node_children(node: Node, context: Optional[Context] = None) -> NodeList:\n \"\"\"\n Get child Nodes from Node's nodelist atribute.\n\n This function is taken from `get_nodes_by_type` method of `django.template.base.Node`.\n \"\"\"\n # Special case - {% extends %} tag - Load the template and go deeper\n if isinstance(node, ExtendsNode):\n # NOTE: When {% extends %} node is being parsed, it collects all remaining template\n # under node.nodelist.\n # Hence, when we come across ExtendsNode in the template, we:\n # 1. Go over all nodes in the template using `node.nodelist`\n # 2. Go over all nodes in the \"parent\" template, via `node.get_parent`\n nodes = NodeList()\n nodes.extend(node.nodelist)\n template = node.get_parent(context)\n nodes.extend(template.nodelist)\n return nodes\n\n # Special case - {% include %} tag - Load the template and go deeper\n elif isinstance(node, IncludeNode):\n template = get_template_for_include_node(node, context)\n return template.nodelist\n\n nodes = NodeList()\n for attr in node.child_nodelists:\n nodelist = getattr(node, attr, [])\n if nodelist:\n nodes.extend(nodelist)\n return nodes\n
"},{"location":"reference/django_components/node/#django_components.node.get_template_for_include_node","title":"get_template_for_include_node","text":"get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template\n
This snippet is taken directly from IncludeNode.render()
. Unfortunately the render logic doesn't separate out template loading logic from rendering, so we have to copy the method.
Source code in src/django_components/node.py
def get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template:\n \"\"\"\n This snippet is taken directly from `IncludeNode.render()`. Unfortunately the\n render logic doesn't separate out template loading logic from rendering, so we\n have to copy the method.\n \"\"\"\n template = include_node.template.resolve(context)\n # Does this quack like a Template?\n if not callable(getattr(template, \"render\", None)):\n # If not, try the cache and select_template().\n template_name = template or ()\n if isinstance(template_name, str):\n template_name = (\n construct_relative_path(\n include_node.origin.template_name,\n template_name,\n ),\n )\n else:\n template_name = tuple(template_name)\n cache = context.render_context.dicts[0].setdefault(include_node, {})\n template = cache.get(template_name)\n if template is None:\n template = context.template.engine.select_template(template_name)\n cache[template_name] = template\n # Use the base.Template of a backends.django.Template.\n elif hasattr(template, \"template\"):\n template = template.template\n return template\n
"},{"location":"reference/django_components/node/#django_components.node.walk_nodelist","title":"walk_nodelist","text":"walk_nodelist(nodes: NodeList, callback: Callable[[Node], Optional[str]], context: Optional[Context] = None) -> None\n
Recursively walk a NodeList, calling callback
for each Node.
Source code in src/django_components/node.py
def walk_nodelist(\n nodes: NodeList,\n callback: Callable[[Node], Optional[str]],\n context: Optional[Context] = None,\n) -> None:\n \"\"\"Recursively walk a NodeList, calling `callback` for each Node.\"\"\"\n node_queue: List[NodeTraverse] = [NodeTraverse(node=node, parent=None) for node in nodes]\n while len(node_queue):\n traverse = node_queue.pop()\n callback(traverse)\n child_nodes = get_node_children(traverse.node, context)\n child_traverses = [NodeTraverse(node=child_node, parent=traverse) for child_node in child_nodes]\n node_queue.extend(child_traverses)\n
"},{"location":"reference/django_components/provide/","title":"
provide","text":""},{"location":"reference/django_components/provide/#django_components.provide","title":"provide","text":""},{"location":"reference/django_components/provide/#django_components.provide.ProvideNode","title":"ProvideNode","text":"ProvideNode(name: str, nodelist: NodeList, node_id: Optional[str] = None, kwargs: Optional[RuntimeKwargs] = None)\n
Bases: BaseNode
Implementation of the {% provide %}
tag. For more info see Component.inject
.
Source code in src/django_components/provide.py
def __init__(\n self,\n name: str,\n nodelist: NodeList,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.nodelist = nodelist\n self.node_id = node_id or gen_id()\n self.kwargs = kwargs or RuntimeKwargs({})\n
"},{"location":"reference/django_components/safer_staticfiles/","title":"Index","text":""},{"location":"reference/django_components/safer_staticfiles/#django_components.safer_staticfiles","title":"safer_staticfiles","text":""},{"location":"reference/django_components/safer_staticfiles/#django_components.safer_staticfiles.apps","title":"apps","text":""},{"location":"reference/django_components/safer_staticfiles/#django_components.safer_staticfiles.apps.SaferStaticFilesConfig","title":"SaferStaticFilesConfig","text":" Bases: StaticFilesConfig
Extend the ignore_patterns
class attr of StaticFilesConfig to include Python modules and HTML files.
When this class is registered as an installed app, $ ./manage.py collectstatic
will ignore .py and .html files, preventing potentially sensitive backend logic from being leaked by the static file server.
See https://docs.djangoproject.com/en/5.0/ref/contrib/staticfiles/#customizing-the-ignored-pattern-list
"},{"location":"reference/django_components/safer_staticfiles/apps/","title":"
apps","text":""},{"location":"reference/django_components/safer_staticfiles/apps/#django_components.safer_staticfiles.apps","title":"apps","text":""},{"location":"reference/django_components/safer_staticfiles/apps/#django_components.safer_staticfiles.apps.SaferStaticFilesConfig","title":"SaferStaticFilesConfig","text":" Bases: StaticFilesConfig
Extend the ignore_patterns
class attr of StaticFilesConfig to include Python modules and HTML files.
When this class is registered as an installed app, $ ./manage.py collectstatic
will ignore .py and .html files, preventing potentially sensitive backend logic from being leaked by the static file server.
See https://docs.djangoproject.com/en/5.0/ref/contrib/staticfiles/#customizing-the-ignored-pattern-list
"},{"location":"reference/django_components/slots/","title":"
slots","text":""},{"location":"reference/django_components/slots/#django_components.slots","title":"slots","text":""},{"location":"reference/django_components/slots/#django_components.slots.FillContent","title":"FillContent dataclass
","text":"FillContent(content_func: SlotFunc[TSlotData], slot_default_var: Optional[SlotDefaultName], slot_data_var: Optional[SlotDataName])\n
Bases: Generic[TSlotData]
This represents content set with the {% fill %}
tag, e.g.:
{% component \"my_comp\" %}\n {% fill \"first_slot\" %} <--- This\n hi\n {{ my_var }}\n hello\n {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/django_components/slots/#django_components.slots.FillNode","title":"FillNode","text":"FillNode(name: FilterExpression, nodelist: NodeList, kwargs: RuntimeKwargs, node_id: Optional[str] = None, is_implicit: bool = False)\n
Bases: BaseNode
Set when a component
tag pair is passed template content that excludes fill
tags. Nodes of this type contribute their nodelists to slots marked as 'default'.
Source code in src/django_components/slots.py
def __init__(\n self,\n name: FilterExpression,\n nodelist: NodeList,\n kwargs: RuntimeKwargs,\n node_id: Optional[str] = None,\n is_implicit: bool = False,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.is_implicit = is_implicit\n self.component_id: Optional[str] = None\n
"},{"location":"reference/django_components/slots/#django_components.slots.Slot","title":"Slot","text":" Bases: NamedTuple
This represents content set with the {% slot %}
tag, e.g.:
{% slot \"my_comp\" default %} <--- This\n hi\n {{ my_var }}\n hello\n{% endslot %}\n
"},{"location":"reference/django_components/slots/#django_components.slots.SlotFill","title":"SlotFill dataclass
","text":"SlotFill(\n name: str,\n escaped_name: str,\n is_filled: bool,\n content_func: SlotFunc[TSlotData],\n context_data: Mapping,\n slot_default_var: Optional[SlotDefaultName],\n slot_data_var: Optional[SlotDataName],\n)\n
Bases: Generic[TSlotData]
SlotFill describes what WILL be rendered.
It is a Slot that has been resolved against FillContents passed to a Component.
"},{"location":"reference/django_components/slots/#django_components.slots.SlotNode","title":"SlotNode","text":"SlotNode(\n name: str,\n nodelist: NodeList,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n is_required: bool = False,\n is_default: bool = False,\n)\n
Bases: BaseNode
Source code in src/django_components/slots.py
def __init__(\n self,\n name: str,\n nodelist: NodeList,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n is_required: bool = False,\n is_default: bool = False,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.is_required = is_required\n self.is_default = is_default\n
"},{"location":"reference/django_components/slots/#django_components.slots.SlotRef","title":"SlotRef","text":"SlotRef(slot: SlotNode, context: Context)\n
SlotRef allows to treat a slot as a variable. The slot is rendered only once the instance is coerced to string.
This is used to access slots as variables inside the templates. When a SlotRef is rendered in the template with {{ my_lazy_slot }}
, it will output the contents of the slot.
Source code in src/django_components/slots.py
def __init__(self, slot: \"SlotNode\", context: Context):\n self._slot = slot\n self._context = context\n
"},{"location":"reference/django_components/slots/#django_components.slots.parse_slot_fill_nodes_from_component_nodelist","title":"parse_slot_fill_nodes_from_component_nodelist","text":"parse_slot_fill_nodes_from_component_nodelist(component_nodelist: NodeList, ComponentNodeCls: Type[Node]) -> List[FillNode]\n
Given a component body (django.template.NodeList
), find all slot fills, whether defined explicitly with {% fill %}
or implicitly.
So if we have a component body:
{% component \"mycomponent\" %}\n {% fill \"first_fill\" %}\n Hello!\n {% endfill %}\n {% fill \"second_fill\" %}\n Hello too!\n {% endfill %}\n{% endcomponent %}\n
Then this function returns the nodes (django.template.Node
) for fill \"first_fill\"
and fill \"second_fill\"
. Source code in src/django_components/slots.py
def parse_slot_fill_nodes_from_component_nodelist(\n component_nodelist: NodeList,\n ComponentNodeCls: Type[Node],\n) -> List[FillNode]:\n \"\"\"\n Given a component body (`django.template.NodeList`), find all slot fills,\n whether defined explicitly with `{% fill %}` or implicitly.\n\n So if we have a component body:\n ```django\n {% component \"mycomponent\" %}\n {% fill \"first_fill\" %}\n Hello!\n {% endfill %}\n {% fill \"second_fill\" %}\n Hello too!\n {% endfill %}\n {% endcomponent %}\n ```\n Then this function returns the nodes (`django.template.Node`) for `fill \"first_fill\"`\n and `fill \"second_fill\"`.\n \"\"\"\n fill_nodes: List[FillNode] = []\n if nodelist_has_content(component_nodelist):\n for parse_fn in (\n _try_parse_as_default_fill,\n _try_parse_as_named_fill_tag_set,\n ):\n curr_fill_nodes = parse_fn(component_nodelist, ComponentNodeCls)\n if curr_fill_nodes:\n fill_nodes = curr_fill_nodes\n break\n else:\n raise TemplateSyntaxError(\n \"Illegal content passed to 'component' tag pair. \"\n \"Possible causes: 1) Explicit 'fill' tags cannot occur alongside other \"\n \"tags except comment tags; 2) Default (default slot-targeting) content \"\n \"is mixed with explict 'fill' tags.\"\n )\n return fill_nodes\n
"},{"location":"reference/django_components/slots/#django_components.slots.resolve_slots","title":"resolve_slots","text":"resolve_slots(\n context: Context,\n template: Template,\n component_name: Optional[str],\n context_data: Mapping[str, Any],\n fill_content: Dict[SlotName, FillContent],\n) -> Tuple[Dict[SlotId, Slot], Dict[SlotId, SlotFill]]\n
Search the template for all SlotNodes, and associate the slots with the given fills.
Returns tuple of: - Slots defined in the component's Template with {% slot %}
tag - SlotFills (AKA slots matched with fills) describing what will be rendered for each slot.
Source code in src/django_components/slots.py
def resolve_slots(\n context: Context,\n template: Template,\n component_name: Optional[str],\n context_data: Mapping[str, Any],\n fill_content: Dict[SlotName, FillContent],\n) -> Tuple[Dict[SlotId, Slot], Dict[SlotId, SlotFill]]:\n \"\"\"\n Search the template for all SlotNodes, and associate the slots\n with the given fills.\n\n Returns tuple of:\n - Slots defined in the component's Template with `{% slot %}` tag\n - SlotFills (AKA slots matched with fills) describing what will be rendered for each slot.\n \"\"\"\n slot_fills = {\n name: SlotFill(\n name=name,\n escaped_name=_escape_slot_name(name),\n is_filled=True,\n content_func=fill.content_func,\n context_data=context_data,\n slot_default_var=fill.slot_default_var,\n slot_data_var=fill.slot_data_var,\n )\n for name, fill in fill_content.items()\n }\n\n slots: Dict[SlotId, Slot] = {}\n # This holds info on which slot (key) has which slots nested in it (value list)\n slot_children: Dict[SlotId, List[SlotId]] = {}\n\n def on_node(entry: NodeTraverse) -> None:\n node = entry.node\n if not isinstance(node, SlotNode):\n return\n\n # 1. Collect slots\n # Basically we take all the important info form the SlotNode, so the logic is\n # less coupled to Django's Template/Node. Plain tuples should also help with\n # troubleshooting.\n slot = Slot(\n id=node.node_id,\n name=node.name,\n nodelist=node.nodelist,\n is_default=node.is_default,\n is_required=node.is_required,\n )\n slots[node.node_id] = slot\n\n # 2. Figure out which Slots are nested in other Slots, so we can render\n # them from outside-inwards, so we can skip inner Slots if fills are provided.\n # We should end up with a graph-like data like:\n # - 0001: [0002]\n # - 0002: []\n # - 0003: [0004]\n # In other words, the data tells us that slot ID 0001 is PARENT of slot 0002.\n curr_entry = entry.parent\n while curr_entry and curr_entry.parent is not None:\n if not isinstance(curr_entry.node, SlotNode):\n curr_entry = curr_entry.parent\n continue\n\n parent_slot_id = curr_entry.node.node_id\n if parent_slot_id not in slot_children:\n slot_children[parent_slot_id] = []\n slot_children[parent_slot_id].append(node.node_id)\n break\n\n walk_nodelist(template.nodelist, on_node, context)\n\n # 3. Figure out which slot the default/implicit fill belongs to\n slot_fills = _resolve_default_slot(\n template_name=template.name,\n component_name=component_name,\n slots=slots,\n slot_fills=slot_fills,\n )\n\n # 4. Detect any errors with slots/fills\n _report_slot_errors(slots, slot_fills, component_name)\n\n # 5. Find roots of the slot relationships\n top_level_slot_ids: List[SlotId] = []\n for node_id, slot in slots.items():\n if node_id not in slot_children or not slot_children[node_id]:\n top_level_slot_ids.append(node_id)\n\n # 6. Walk from out-most slots inwards, and decide whether and how\n # we will render each slot.\n resolved_slots: Dict[SlotId, SlotFill] = {}\n slot_ids_queue = deque([*top_level_slot_ids])\n while len(slot_ids_queue):\n slot_id = slot_ids_queue.pop()\n slot = slots[slot_id]\n\n # Check if there is a slot fill for given slot name\n if slot.name in slot_fills:\n # If yes, we remember which slot we want to replace with already-rendered fills\n resolved_slots[slot_id] = slot_fills[slot.name]\n # Since the fill cannot include other slots, we can leave this path\n continue\n else:\n # If no, then the slot is NOT filled, and we will render the slot's default (what's\n # between the slot tags)\n resolved_slots[slot_id] = SlotFill(\n name=slot.name,\n escaped_name=_escape_slot_name(slot.name),\n is_filled=False,\n content_func=_nodelist_to_slot_render_func(slot.nodelist),\n context_data=context_data,\n slot_default_var=None,\n slot_data_var=None,\n )\n # Since the slot's default CAN include other slots (because it's defined in\n # the same template), we need to enqueue the slot's children\n if slot_id in slot_children and slot_children[slot_id]:\n slot_ids_queue.extend(slot_children[slot_id])\n\n # By the time we get here, we should know, for each slot, how it will be rendered\n # -> Whether it will be replaced with a fill, or whether we render slot's defaults.\n return slots, resolved_slots\n
"},{"location":"reference/django_components/tag_formatter/","title":"
tag_formatter","text":""},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter","title":"tag_formatter","text":""},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.ComponentFormatter","title":"ComponentFormatter","text":"ComponentFormatter(tag: str)\n
Bases: TagFormatterABC
The original django_component's component tag formatter, it uses the component
and endcomponent
tags, and the component name is gives as the first positional arg.
Example as block:
{% component \"mycomp\" abc=123 %}\n {% fill \"myfill\" %}\n ...\n {% endfill %}\n{% endcomponent %}\n
Example as inlined tag:
{% component \"mycomp\" abc=123 / %}\n
Source code in src/django_components/tag_formatter.py
def __init__(self, tag: str):\n self.tag = tag\n
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.InternalTagFormatter","title":"InternalTagFormatter","text":"InternalTagFormatter(tag_formatter: TagFormatterABC)\n
Internal wrapper around user-provided TagFormatters, so that we validate the outputs.
Source code in src/django_components/tag_formatter.py
def __init__(self, tag_formatter: TagFormatterABC):\n self.tag_formatter = tag_formatter\n
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":" Bases: TagFormatterABC
The component tag formatter that uses <name>
/ end<name>
tags.
This is similar to django-web-components and django-slippers syntax.
Example as block:
{% mycomp abc=123 %}\n {% fill \"myfill\" %}\n ...\n {% endfill %}\n{% endmycomp %}\n
Example as inlined tag:
{% mycomp abc=123 / %}\n
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC","title":"TagFormatterABC","text":" Bases: ABC
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC.end_tag","title":"end_tag abstractmethod
","text":"end_tag(name: str) -> str\n
Formats the end tag of a block component.
Source code in src/django_components/tag_formatter.py
@abc.abstractmethod\ndef end_tag(self, name: str) -> str:\n \"\"\"Formats the end tag of a block component.\"\"\"\n ...\n
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC.parse","title":"parse abstractmethod
","text":"parse(tokens: List[str]) -> TagResult\n
Given the tokens (words) of a component start tag, this function extracts the component name from the tokens list, and returns TagResult
, which is a tuple of (component_name, remaining_tokens)
.
Example:
Given a component declarations:
{% component \"my_comp\" key=val key2=val2 %}
This function receives a list of tokens
['component', '\"my_comp\"', 'key=val', 'key2=val2']
component
is the tag name, which we drop. \"my_comp\"
is the component name, but we must remove the extra quotes. And we pass remaining tokens unmodified, as that's the input to the component.
So in the end, we return a tuple:
('my_comp', ['key=val', 'key2=val2'])
Source code in src/django_components/tag_formatter.py
@abc.abstractmethod\ndef parse(self, tokens: List[str]) -> TagResult:\n \"\"\"\n Given the tokens (words) of a component start tag, this function extracts\n the component name from the tokens list, and returns `TagResult`, which\n is a tuple of `(component_name, remaining_tokens)`.\n\n Example:\n\n Given a component declarations:\n\n `{% component \"my_comp\" key=val key2=val2 %}`\n\n This function receives a list of tokens\n\n `['component', '\"my_comp\"', 'key=val', 'key2=val2']`\n\n `component` is the tag name, which we drop. `\"my_comp\"` is the component name,\n but we must remove the extra quotes. And we pass remaining tokens unmodified,\n as that's the input to the component.\n\n So in the end, we return a tuple:\n\n `('my_comp', ['key=val', 'key2=val2'])`\n \"\"\"\n ...\n
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC.start_tag","title":"start_tag abstractmethod
","text":"start_tag(name: str) -> str\n
Formats the start tag of a component.
Source code in src/django_components/tag_formatter.py
@abc.abstractmethod\ndef start_tag(self, name: str) -> str:\n \"\"\"Formats the start tag of a component.\"\"\"\n ...\n
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagResult","title":"TagResult","text":" Bases: NamedTuple
The return value from TagFormatter.parse()
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagResult.component_name","title":"component_name instance-attribute
","text":"component_name: str\n
Component name extracted from the template tag
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagResult.tokens","title":"tokens instance-attribute
","text":"tokens: List[str]\n
Remaining tokens (words) that were passed to the tag, with component name removed
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.get_tag_formatter","title":"get_tag_formatter","text":"get_tag_formatter() -> InternalTagFormatter\n
Returns an instance of the currently configured component tag formatter.
Source code in src/django_components/tag_formatter.py
def get_tag_formatter() -> InternalTagFormatter:\n \"\"\"Returns an instance of the currently configured component tag formatter.\"\"\"\n # Allow users to configure the component TagFormatter\n formatter_cls_or_str = app_settings.TAG_FORMATTER\n\n if isinstance(formatter_cls_or_str, str):\n tag_formatter: TagFormatterABC = import_string(formatter_cls_or_str)\n else:\n tag_formatter = formatter_cls_or_str\n\n return InternalTagFormatter(tag_formatter)\n
"},{"location":"reference/django_components/template_loader/","title":"
template_loader","text":""},{"location":"reference/django_components/template_loader/#django_components.template_loader","title":"template_loader","text":"Template loader that loads templates from each Django app's \"components\" directory.
"},{"location":"reference/django_components/template_loader/#django_components.template_loader.Loader","title":"Loader","text":" Bases: Loader
"},{"location":"reference/django_components/template_loader/#django_components.template_loader.Loader.get_dirs","title":"get_dirs","text":"get_dirs() -> List[Path]\n
Prepare directories that may contain component files:
Searches for dirs set in STATICFILES_DIRS
settings. If none set, defaults to searching for a \"components\" app. The dirs in STATICFILES_DIRS
must be absolute paths.
Paths are accepted only if they resolve to a directory. E.g. /path/to/django_project/my_app/components/
.
If STATICFILES_DIRS
is not set or empty, then BASE_DIR
is required.
Source code in src/django_components/template_loader.py
def get_dirs(self) -> List[Path]:\n \"\"\"\n Prepare directories that may contain component files:\n\n Searches for dirs set in `STATICFILES_DIRS` settings. If none set, defaults to searching\n for a \"components\" app. The dirs in `STATICFILES_DIRS` must be absolute paths.\n\n Paths are accepted only if they resolve to a directory.\n E.g. `/path/to/django_project/my_app/components/`.\n\n If `STATICFILES_DIRS` is not set or empty, then `BASE_DIR` is required.\n \"\"\"\n # Allow to configure from settings which dirs should be checked for components\n if hasattr(settings, \"STATICFILES_DIRS\") and settings.STATICFILES_DIRS:\n component_dirs = settings.STATICFILES_DIRS\n else:\n component_dirs = [settings.BASE_DIR / \"components\"]\n\n logger.debug(\n \"Template loader will search for valid template dirs from following options:\\n\"\n + \"\\n\".join([f\" - {str(d)}\" for d in component_dirs])\n )\n\n directories: Set[Path] = set()\n for component_dir in component_dirs:\n # Consider tuples for STATICFILES_DIRS (See #489)\n # See https://docs.djangoproject.com/en/5.0/ref/settings/#prefixes-optional\n if isinstance(component_dir, (tuple, list)) and len(component_dir) == 2:\n component_dir = component_dir[1]\n try:\n Path(component_dir)\n except TypeError:\n logger.warning(\n f\"STATICFILES_DIRS expected str, bytes or os.PathLike object, or tuple/list of length 2. \"\n f\"See Django documentation. Got {type(component_dir)} : {component_dir}\"\n )\n continue\n\n if not Path(component_dir).is_absolute():\n raise ValueError(f\"STATICFILES_DIRS must contain absolute paths, got '{component_dir}'\")\n else:\n directories.add(Path(component_dir).resolve())\n\n logger.debug(\n \"Template loader matched following template dirs:\\n\" + \"\\n\".join([f\" - {str(d)}\" for d in directories])\n )\n return list(directories)\n
"},{"location":"reference/django_components/template_parser/","title":"
template_parser","text":""},{"location":"reference/django_components/template_parser/#django_components.template_parser","title":"template_parser","text":"Overrides for the Django Template system to allow finer control over template parsing.
Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py
"},{"location":"reference/django_components/template_parser/#django_components.template_parser.parse_bits","title":"parse_bits","text":"parse_bits(\n parser: Parser, bits: List[str], params: List[str], name: str\n) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]\n
Parse bits for template tag helpers simple_tag and inclusion_tag, in particular by detecting syntax errors and by extracting positional and keyword arguments.
This is a simplified version of django.template.library.parse_bits
where we use custom regex to handle special characters in keyword names.
Furthermore, our version allows duplicate keys, and instead of return kwargs as a dict, we return it as a list of key-value pairs. So it is up to the user of this function to decide whether they support duplicate keys or not.
Source code in src/django_components/template_parser.py
def parse_bits(\n parser: Parser,\n bits: List[str],\n params: List[str],\n name: str,\n) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]:\n \"\"\"\n Parse bits for template tag helpers simple_tag and inclusion_tag, in\n particular by detecting syntax errors and by extracting positional and\n keyword arguments.\n\n This is a simplified version of `django.template.library.parse_bits`\n where we use custom regex to handle special characters in keyword names.\n\n Furthermore, our version allows duplicate keys, and instead of return kwargs\n as a dict, we return it as a list of key-value pairs. So it is up to the\n user of this function to decide whether they support duplicate keys or not.\n \"\"\"\n args: List[FilterExpression] = []\n kwargs: List[Tuple[str, FilterExpression]] = []\n unhandled_params = list(params)\n for bit in bits:\n # First we try to extract a potential kwarg from the bit\n kwarg = token_kwargs([bit], parser)\n if kwarg:\n # The kwarg was successfully extracted\n param, value = kwarg.popitem()\n # All good, record the keyword argument\n kwargs.append((str(param), value))\n if param in unhandled_params:\n # If using the keyword syntax for a positional arg, then\n # consume it.\n unhandled_params.remove(param)\n else:\n if kwargs:\n raise TemplateSyntaxError(\n \"'%s' received some positional argument(s) after some \" \"keyword argument(s)\" % name\n )\n else:\n # Record the positional argument\n args.append(parser.compile_filter(bit))\n try:\n # Consume from the list of expected positional arguments\n unhandled_params.pop(0)\n except IndexError:\n pass\n if unhandled_params:\n # Some positional arguments were not supplied\n raise TemplateSyntaxError(\n \"'%s' did not receive value(s) for the argument(s): %s\"\n % (name, \", \".join(\"'%s'\" % p for p in unhandled_params))\n )\n return args, kwargs\n
"},{"location":"reference/django_components/template_parser/#django_components.template_parser.token_kwargs","title":"token_kwargs","text":"token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]\n
Parse token keyword arguments and return a dictionary of the arguments retrieved from the bits
token list.
bits
is a list containing the remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments are removed from this list.
There is no requirement for all remaining token bits
to be keyword arguments, so return the dictionary as soon as an invalid argument format is reached.
Source code in src/django_components/template_parser.py
def token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]:\n \"\"\"\n Parse token keyword arguments and return a dictionary of the arguments\n retrieved from the ``bits`` token list.\n\n `bits` is a list containing the remainder of the token (split by spaces)\n that is to be checked for arguments. Valid arguments are removed from this\n list.\n\n There is no requirement for all remaining token ``bits`` to be keyword\n arguments, so return the dictionary as soon as an invalid argument format\n is reached.\n \"\"\"\n if not bits:\n return {}\n match = kwarg_re.match(bits[0])\n kwarg_format = match and match[1]\n if not kwarg_format:\n return {}\n\n kwargs: Dict[str, FilterExpression] = {}\n while bits:\n if kwarg_format:\n match = kwarg_re.match(bits[0])\n if not match or not match[1]:\n return kwargs\n key, value = match.groups()\n del bits[:1]\n else:\n if len(bits) < 3 or bits[1] != \"as\":\n return kwargs\n key, value = bits[2], bits[0]\n del bits[:3]\n\n # This is the only difference from the original token_kwargs. We use\n # the ComponentsFilterExpression instead of the original FilterExpression.\n kwargs[key] = ComponentsFilterExpression(value, parser)\n if bits and not kwarg_format:\n if bits[0] != \"and\":\n return kwargs\n del bits[:1]\n return kwargs\n
"},{"location":"reference/django_components/templatetags/","title":"Index","text":""},{"location":"reference/django_components/templatetags/#django_components.templatetags","title":"templatetags","text":""},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags","title":"component_tags","text":""},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component","title":"component","text":"component(parser: Parser, token: Token, tag_name: str) -> ComponentNode\n
To give the component access to the template context {% component \"name\" positional_arg keyword_arg=value ... %}
To render the component in an isolated context {% component \"name\" positional_arg keyword_arg=value ... only %}
Positional and keyword arguments can be literals or template variables. The component name must be a single- or double-quotes string and must be either the first positional argument or, if there are no positional arguments, passed as 'name'.
Source code in src/django_components/templatetags/component_tags.py
def component(parser: Parser, token: Token, tag_name: str) -> ComponentNode:\n \"\"\"\n To give the component access to the template context:\n ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... %}```\n\n To render the component in an isolated context:\n ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... only %}```\n\n Positional and keyword arguments can be literals or template variables.\n The component name must be a single- or double-quotes string and must\n be either the first positional argument or, if there are no positional\n arguments, passed as 'name'.\n \"\"\"\n bits = token.split_contents()\n\n # Let the TagFormatter pre-process the tokens\n formatter = get_tag_formatter()\n result = formatter.parse([*bits])\n end_tag = formatter.end_tag(result.component_name)\n\n # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n bits = [bits[0], *result.tokens]\n\n tag = _parse_tag(\n tag_name,\n parser,\n bits,\n params=True, # Allow many args\n flags=[\"only\"],\n keywordonly_kwargs=True,\n repeatable_kwargs=False,\n end_tag=end_tag,\n )\n\n # Check for isolated context keyword\n isolated_context = tag.flags[\"only\"] or app_settings.CONTEXT_BEHAVIOR == ContextBehavior.ISOLATED\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n body = tag.parse_body()\n fill_nodes = parse_slot_fill_nodes_from_component_nodelist(body, ComponentNode)\n\n # Tag all fill nodes as children of this particular component instance\n for node in fill_nodes:\n trace_msg(\"ASSOC\", \"FILL\", node.name, node.node_id, component_id=tag.id)\n node.component_id = tag.id\n\n component_node = ComponentNode(\n name=result.component_name,\n args=tag.args,\n kwargs=tag.kwargs,\n isolated_context=isolated_context,\n fill_nodes=fill_nodes,\n node_id=tag.id,\n )\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n return component_node\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"component_css_dependencies(preload: str = '') -> SafeString\n
Marks location where CSS link tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_css_dependencies\")\ndef component_css_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where CSS link tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_css_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component_dependencies","title":"component_dependencies","text":"component_dependencies(preload: str = '') -> SafeString\n
Marks location where CSS link and JS script tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_dependencies\")\ndef component_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where CSS link and JS script tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER + JS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"component_js_dependencies(preload: str = '') -> SafeString\n
Marks location where JS script tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_js_dependencies\")\ndef component_js_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where JS script tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + JS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_js_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.fill","title":"fill","text":"fill(parser: Parser, token: Token) -> FillNode\n
Block tag whose contents 'fill' (are inserted into) an identically named 'slot'-block in the component template referred to by a parent component. It exists to make component nesting easier.
This tag is available only within a {% component %}..{% endcomponent %} block. Runtime checks should prohibit other usages.
Source code in src/django_components/templatetags/component_tags.py
@register.tag(\"fill\")\ndef fill(parser: Parser, token: Token) -> FillNode:\n \"\"\"\n Block tag whose contents 'fill' (are inserted into) an identically named\n 'slot'-block in the component template referred to by a parent component.\n It exists to make component nesting easier.\n\n This tag is available only within a {% component %}..{% endcomponent %} block.\n Runtime checks should prohibit other usages.\n \"\"\"\n bits = token.split_contents()\n tag = _parse_tag(\n \"fill\",\n parser,\n bits,\n params=[\"name\"],\n keywordonly_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n repeatable_kwargs=False,\n end_tag=\"endfill\",\n )\n slot_name = tag.named_args[\"name\"]\n\n trace_msg(\"PARSE\", \"FILL\", str(slot_name), tag.id)\n\n body = tag.parse_body()\n fill_node = FillNode(\n nodelist=body,\n name=slot_name,\n node_id=tag.id,\n kwargs=tag.kwargs,\n )\n\n trace_msg(\"PARSE\", \"FILL\", str(slot_name), tag.id, \"...Done!\")\n return fill_node\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode\n
This tag takes: - Optional dictionary of attributes (attrs
) - Optional dictionary of defaults (defaults
) - Additional kwargs that are appended to the former two
The inputs are merged and resulting dict is rendered as HTML attributes (key=\"value\"
).
Rules: 1. Both attrs
and defaults
can be passed as positional args or as kwargs 2. Both attrs
and defaults
are optional (can be omitted) 3. Both attrs
and defaults
are dictionaries, and we can define them the same way we define dictionaries for the component
tag. So either as attrs=attrs
or attrs:key=value
. 4. All other kwargs (key=value
) are appended and can be repeated.
Normal kwargs (key=value
) are concatenated to existing keys. So if e.g. key \"class\" is supplied with value \"my-class\", then adding class=\"extra-class\"
will result in `class=\"my-class extra-class\".
Example:
{% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n
Source code in src/django_components/templatetags/component_tags.py
@register.tag(\"html_attrs\")\ndef html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode:\n \"\"\"\n This tag takes:\n - Optional dictionary of attributes (`attrs`)\n - Optional dictionary of defaults (`defaults`)\n - Additional kwargs that are appended to the former two\n\n The inputs are merged and resulting dict is rendered as HTML attributes\n (`key=\"value\"`).\n\n Rules:\n 1. Both `attrs` and `defaults` can be passed as positional args or as kwargs\n 2. Both `attrs` and `defaults` are optional (can be omitted)\n 3. Both `attrs` and `defaults` are dictionaries, and we can define them the same way\n we define dictionaries for the `component` tag. So either as `attrs=attrs` or\n `attrs:key=value`.\n 4. All other kwargs (`key=value`) are appended and can be repeated.\n\n Normal kwargs (`key=value`) are concatenated to existing keys. So if e.g. key\n \"class\" is supplied with value \"my-class\", then adding `class=\"extra-class\"`\n will result in `class=\"my-class extra-class\".\n\n Example:\n ```htmldjango\n {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n ```\n \"\"\"\n bits = token.split_contents()\n\n tag = _parse_tag(\n \"html_attrs\",\n parser,\n bits,\n params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n optional_params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n flags=[],\n keywordonly_kwargs=True,\n repeatable_kwargs=True,\n )\n\n return HtmlAttrsNode(\n kwargs=tag.kwargs,\n kwarg_pairs=tag.kwarg_pairs,\n )\n
"},{"location":"reference/django_components/templatetags/component_tags/","title":"
component_tags","text":""},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags","title":"component_tags","text":""},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component","title":"component","text":"component(parser: Parser, token: Token, tag_name: str) -> ComponentNode\n
To give the component access to the template context {% component \"name\" positional_arg keyword_arg=value ... %}
To render the component in an isolated context {% component \"name\" positional_arg keyword_arg=value ... only %}
Positional and keyword arguments can be literals or template variables. The component name must be a single- or double-quotes string and must be either the first positional argument or, if there are no positional arguments, passed as 'name'.
Source code in src/django_components/templatetags/component_tags.py
def component(parser: Parser, token: Token, tag_name: str) -> ComponentNode:\n \"\"\"\n To give the component access to the template context:\n ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... %}```\n\n To render the component in an isolated context:\n ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... only %}```\n\n Positional and keyword arguments can be literals or template variables.\n The component name must be a single- or double-quotes string and must\n be either the first positional argument or, if there are no positional\n arguments, passed as 'name'.\n \"\"\"\n bits = token.split_contents()\n\n # Let the TagFormatter pre-process the tokens\n formatter = get_tag_formatter()\n result = formatter.parse([*bits])\n end_tag = formatter.end_tag(result.component_name)\n\n # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n bits = [bits[0], *result.tokens]\n\n tag = _parse_tag(\n tag_name,\n parser,\n bits,\n params=True, # Allow many args\n flags=[\"only\"],\n keywordonly_kwargs=True,\n repeatable_kwargs=False,\n end_tag=end_tag,\n )\n\n # Check for isolated context keyword\n isolated_context = tag.flags[\"only\"] or app_settings.CONTEXT_BEHAVIOR == ContextBehavior.ISOLATED\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n body = tag.parse_body()\n fill_nodes = parse_slot_fill_nodes_from_component_nodelist(body, ComponentNode)\n\n # Tag all fill nodes as children of this particular component instance\n for node in fill_nodes:\n trace_msg(\"ASSOC\", \"FILL\", node.name, node.node_id, component_id=tag.id)\n node.component_id = tag.id\n\n component_node = ComponentNode(\n name=result.component_name,\n args=tag.args,\n kwargs=tag.kwargs,\n isolated_context=isolated_context,\n fill_nodes=fill_nodes,\n node_id=tag.id,\n )\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n return component_node\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"component_css_dependencies(preload: str = '') -> SafeString\n
Marks location where CSS link tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_css_dependencies\")\ndef component_css_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where CSS link tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_css_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component_dependencies","title":"component_dependencies","text":"component_dependencies(preload: str = '') -> SafeString\n
Marks location where CSS link and JS script tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_dependencies\")\ndef component_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where CSS link and JS script tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER + JS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"component_js_dependencies(preload: str = '') -> SafeString\n
Marks location where JS script tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_js_dependencies\")\ndef component_js_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where JS script tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + JS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_js_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.fill","title":"fill","text":"fill(parser: Parser, token: Token) -> FillNode\n
Block tag whose contents 'fill' (are inserted into) an identically named 'slot'-block in the component template referred to by a parent component. It exists to make component nesting easier.
This tag is available only within a {% component %}..{% endcomponent %} block. Runtime checks should prohibit other usages.
Source code in src/django_components/templatetags/component_tags.py
@register.tag(\"fill\")\ndef fill(parser: Parser, token: Token) -> FillNode:\n \"\"\"\n Block tag whose contents 'fill' (are inserted into) an identically named\n 'slot'-block in the component template referred to by a parent component.\n It exists to make component nesting easier.\n\n This tag is available only within a {% component %}..{% endcomponent %} block.\n Runtime checks should prohibit other usages.\n \"\"\"\n bits = token.split_contents()\n tag = _parse_tag(\n \"fill\",\n parser,\n bits,\n params=[\"name\"],\n keywordonly_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n repeatable_kwargs=False,\n end_tag=\"endfill\",\n )\n slot_name = tag.named_args[\"name\"]\n\n trace_msg(\"PARSE\", \"FILL\", str(slot_name), tag.id)\n\n body = tag.parse_body()\n fill_node = FillNode(\n nodelist=body,\n name=slot_name,\n node_id=tag.id,\n kwargs=tag.kwargs,\n )\n\n trace_msg(\"PARSE\", \"FILL\", str(slot_name), tag.id, \"...Done!\")\n return fill_node\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode\n
This tag takes: - Optional dictionary of attributes (attrs
) - Optional dictionary of defaults (defaults
) - Additional kwargs that are appended to the former two
The inputs are merged and resulting dict is rendered as HTML attributes (key=\"value\"
).
Rules: 1. Both attrs
and defaults
can be passed as positional args or as kwargs 2. Both attrs
and defaults
are optional (can be omitted) 3. Both attrs
and defaults
are dictionaries, and we can define them the same way we define dictionaries for the component
tag. So either as attrs=attrs
or attrs:key=value
. 4. All other kwargs (key=value
) are appended and can be repeated.
Normal kwargs (key=value
) are concatenated to existing keys. So if e.g. key \"class\" is supplied with value \"my-class\", then adding class=\"extra-class\"
will result in `class=\"my-class extra-class\".
Example:
{% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n
Source code in src/django_components/templatetags/component_tags.py
@register.tag(\"html_attrs\")\ndef html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode:\n \"\"\"\n This tag takes:\n - Optional dictionary of attributes (`attrs`)\n - Optional dictionary of defaults (`defaults`)\n - Additional kwargs that are appended to the former two\n\n The inputs are merged and resulting dict is rendered as HTML attributes\n (`key=\"value\"`).\n\n Rules:\n 1. Both `attrs` and `defaults` can be passed as positional args or as kwargs\n 2. Both `attrs` and `defaults` are optional (can be omitted)\n 3. Both `attrs` and `defaults` are dictionaries, and we can define them the same way\n we define dictionaries for the `component` tag. So either as `attrs=attrs` or\n `attrs:key=value`.\n 4. All other kwargs (`key=value`) are appended and can be repeated.\n\n Normal kwargs (`key=value`) are concatenated to existing keys. So if e.g. key\n \"class\" is supplied with value \"my-class\", then adding `class=\"extra-class\"`\n will result in `class=\"my-class extra-class\".\n\n Example:\n ```htmldjango\n {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n ```\n \"\"\"\n bits = token.split_contents()\n\n tag = _parse_tag(\n \"html_attrs\",\n parser,\n bits,\n params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n optional_params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n flags=[],\n keywordonly_kwargs=True,\n repeatable_kwargs=True,\n )\n\n return HtmlAttrsNode(\n kwargs=tag.kwargs,\n kwarg_pairs=tag.kwarg_pairs,\n )\n
"},{"location":"reference/django_components/types/","title":"
types","text":""},{"location":"reference/django_components/types/#django_components.types","title":"types","text":"Helper types for IDEs.
"},{"location":"reference/django_components/utils/","title":"
utils","text":""},{"location":"reference/django_components/utils/#django_components.utils","title":"utils","text":""},{"location":"reference/django_components/utils/#django_components.utils.gen_id","title":"gen_id","text":"gen_id(length: int = 5) -> str\n
Generate a unique ID that can be associated with a Node
Source code in src/django_components/utils.py
def gen_id(length: int = 5) -> str:\n \"\"\"Generate a unique ID that can be associated with a Node\"\"\"\n # Global counter to avoid conflicts\n global _id\n _id += 1\n\n # Pad the ID with `0`s up to 4 digits, e.g. `0007`\n return f\"{_id:04}\"\n
"}]}
\ No newline at end of file
+{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"
","text":"Docs (Work in progress)
Create simple reusable template components in Django
"},{"location":"#features","title":"Features","text":" - \u2728 Reusable components: Create components that can be reused in different parts of your project, or even in different projects.
- \ud83d\udcc1 Single file components: Keep your Python, CSS, Javascript and HTML in one place (if you wish)
- \ud83c\udfb0 Slots: Define slots in your components to make them more flexible.
- \ud83d\udcbb CLI: A command line interface to help you create new components.
- \ud83d\ude80 Wide compatibility: Works with modern and LTS versions of Django.
- Load assets: Automatically load the right CSS and Javascript files for your components, with our middleware.
"},{"location":"#summary","title":"Summary","text":"It lets you create \"template components\", that contains both the template, the Javascript and the CSS needed to generate the front end code you need for a modern app. Use components like this:
{% component \"calendar\" date=\"2015-06-19\" %}{% endcomponent %}\n
And this is what gets rendered (plus the CSS and Javascript you've specified):
<div class=\"calendar-component\">Today's date is <span>2015-06-19</span></div>\n
See the example project or read on to learn about the details!
"},{"location":"#table-of-contents","title":"Table of Contents","text":" - Release notes
- Security notes \ud83d\udea8
- Installation
- Compatibility
- Create your first component
- Using single-file components
- Use components in templates
- Use components outside of templates
- Registering components
- Use components as views
- Autodiscovery
- Using slots in templates
- Passing data to components
- Rendering HTML attributes
- Template tag syntax
- Prop drilling and dependency injection (provide / inject)
- Component context and scope
- Customizing component tags with TagFormatter
- Defining HTML/JS/CSS files
- Rendering JS/CSS dependencies
- Available settings
- Logging and debugging
- Management Command
- Community examples
- Running django-components project locally
- Development guides
"},{"location":"#release-notes","title":"Release notes","text":"Version 0.93 - Spread operator ...dict
inside template tags. See Spread operator) - Use template tags inside string literals in component inputs. See Use template tags inside component inputs)
\ud83d\udea8\ud83d\udce2 Version 0.92 - BREAKING CHANGE: Component
class is no longer a subclass of View
. To configure the View
class, set the Component.View
nested class. HTTP methods like get
or post
can still be defined directly on Component
class, and Component.as_view()
internally calls Component.View.as_view()
. (See Modifying the View class)
-
The inputs (args, kwargs, slots, context, ...) that you pass to Component.render()
can be accessed from within get_context_data
, get_template_string
and get_template_name
via self.input
. (See Accessing data passed to the component)
-
Typing: Component
class supports generics that specify types for Component.render
(See Adding type hints with Generics)
Version 0.90 - All tags (component
, slot
, fill
, ...) now support \"self-closing\" or \"inline\" form, where you can omit the closing tag:
{# Before #}\n{% component \"button\" %}{% endcomponent %}\n{# After #}\n{% component \"button\" / %}\n
- All tags now support the \"dictionary key\" or \"aggregate\" syntax (kwarg:key=val
): {% component \"button\" attrs:class=\"hidden\" %}\n
- You can change how the components are written in the template with TagFormatter. The default is `django_components.component_formatter`:\n```django\n{% component \"button\" href=\"...\" disabled %}\n Click me!\n{% endcomponent %}\n```\n\nWhile `django_components.shorthand_component_formatter` allows you to write components like so:\n\n```django\n{% button href=\"...\" disabled %}\n Click me!\n{% endbutton %}\n
\ud83d\udea8\ud83d\udce2 Version 0.85 Autodiscovery module resolution changed. Following undocumented behavior was removed:
- Previously, autodiscovery also imported any
[app]/components.py
files, and used SETTINGS_MODULE
to search for component dirs. - To migrate from:
[app]/components.py
- Define each module in COMPONENTS.libraries
setting, or import each module inside the AppConfig.ready()
hook in respective apps.py
files. SETTINGS_MODULE
- Define component dirs using STATICFILES_DIRS
- Previously, autodiscovery handled relative files in
STATICFILES_DIRS
. To align with Django, STATICFILES_DIRS
now must be full paths (Django docs).
\ud83d\udea8\ud83d\udce2 Version 0.81 Aligned the render_to_response
method with the (now public) render
method of Component
class. Moreover, slots passed to these can now be rendered also as functions.
- BREAKING CHANGE: The order of arguments to
render_to_response
has changed.
Version 0.80 introduces dependency injection with the {% provide %}
tag and inject()
method.
\ud83d\udea8\ud83d\udce2 Version 0.79
- BREAKING CHANGE: Default value for the
COMPONENTS.context_behavior
setting was changes from \"isolated\"
to \"django\"
. If you did not set this value explicitly before, this may be a breaking change. See the rationale for change here.
\ud83d\udea8\ud83d\udce2 Version 0.77 CHANGED the syntax for accessing default slot content.
- Previously, the syntax was
{% fill \"my_slot\" as \"alias\" %}
and {{ alias.default }}
. - Now, the syntax is
{% fill \"my_slot\" default=\"alias\" %}
and {{ alias }}
.
Version 0.74 introduces html_attrs
tag and prefix:key=val
construct for passing dicts to components.
\ud83d\udea8\ud83d\udce2 Version 0.70
{% if_filled \"my_slot\" %}
tags were replaced with {{ component_vars.is_filled.my_slot }}
variables. - Simplified settings -
slot_context_behavior
and context_behavior
were merged. See the documentation for more details.
Version 0.67 CHANGED the default way how context variables are resolved in slots. See the documentation for more details.
\ud83d\udea8\ud83d\udce2 Version 0.5 CHANGES THE SYNTAX for components. component_block
is now component
, and component
blocks need an ending endcomponent
tag. The new python manage.py upgradecomponent
command can be used to upgrade a directory (use --path argument to point to each dir) of templates that use components to the new syntax automatically.
This change is done to simplify the API in anticipation of a 1.0 release of django_components. After 1.0 we intend to be stricter with big changes like this in point releases.
Version 0.34 adds components as views, which allows you to handle requests and render responses from within a component. See the documentation for more details.
Version 0.28 introduces 'implicit' slot filling and the default
option for slot
tags.
Version 0.27 adds a second installable app: django_components.safer_staticfiles. It provides the same behavior as django.contrib.staticfiles but with extra security guarantees (more info below in Security Notes).
Version 0.26 changes the syntax for {% slot %}
tags. From now on, we separate defining a slot ({% slot %}
) from filling a slot with content ({% fill %}
). This means you will likely need to change a lot of slot tags to fill. We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice featuPpre to have access to. Hoping that this will feel worth it!
Version 0.22 starts autoimporting all files inside components subdirectores, to simplify setup. An existing project might start to get AlreadyRegistered-errors because of this. To solve this, either remove your custom loading of components, or set \"autodiscover\": False in settings.COMPONENTS.
Version 0.17 renames Component.context
and Component.template
to get_context_data
and get_template_name
. The old methods still work, but emit a deprecation warning. This change was done to sync naming with Django's class based views, and make using django-components more familiar to Django users. Component.context
and Component.template
will be removed when version 1.0 is released.
"},{"location":"#security-notes","title":"Security notes \ud83d\udea8","text":"You are advised to read this section before using django-components in production.
"},{"location":"#static-files","title":"Static files","text":"Components can be organized however you prefer. That said, our prefered way is to keep the files of a component close together by bundling them in the same directory. This means that files containing backend logic, such as Python modules and HTML templates, live in the same directory as static files, e.g. JS and CSS.
If your are using django.contrib.staticfiles to collect static files, no distinction is 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.
As of v0.27, django-components ships with an additional installable app django_components.safer_staticfiles. It is a drop-in replacement for django.contrib.staticfiles. Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server. To use it, add it to INSTALLED_APPS and remove django.contrib.staticfiles.
INSTALLED_APPS = [\n # 'django.contrib.staticfiles', # <-- REMOVE\n 'django_components',\n 'django_components.safer_staticfiles' # <-- ADD\n]\n
If you are on an older version of django-components, your alternatives are a) passing --ignore <pattern>
options to the collecstatic CLI command, or b) defining a subclass of StaticFilesConfig. Both routes are described in the official docs of the staticfiles app.
Note that safer_staticfiles
excludes the .py
and .html
files for collectstatic command:
python manage.py collectstatic\n
but it is ignored on the development server:
python manage.py runserver\n
For a step-by-step guide on deploying production server with static files, see the demo project.
"},{"location":"#installation","title":"Installation","text":" - Install the app into your environment:
pip install django_components
- Then add the app into
INSTALLED_APPS
in settings.py
INSTALLED_APPS = [\n ...,\n 'django_components',\n]\n
- Ensure that
BASE_DIR
setting is defined in settings.py:
BASE_DIR = Path(__file__).resolve().parent.parent\n
-
Modify TEMPLATES
section of settings.py as follows:
-
Remove 'APP_DIRS': True,
- Add
loaders
to OPTIONS
list and set it to following value:
TEMPLATES = [\n {\n ...,\n 'OPTIONS': {\n 'context_processors': [\n ...\n ],\n 'loaders':[(\n 'django.template.loaders.cached.Loader', [\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n 'django_components.template_loader.Loader',\n ]\n )],\n },\n },\n]\n
- Modify
STATICFILES_DIRS
(or add it if you don't have it) so django can find your static JS and CSS files:
STATICFILES_DIRS = [\n ...,\n os.path.join(BASE_DIR, \"components\"),\n]\n
If STATICFILES_DIRS
is omitted or empty, django-components will by default look for {BASE_DIR}/components
NOTE: The paths in STATICFILES_DIRS
must be full paths. See Django docs.
"},{"location":"#optional","title":"Optional","text":"To avoid loading the app in each template using {% load component_tags %}
, you can add the tag as a 'builtin' in settings.py
TEMPLATES = [\n {\n ...,\n 'OPTIONS': {\n 'context_processors': [\n ...\n ],\n 'builtins': [\n 'django_components.templatetags.component_tags',\n ]\n },\n },\n]\n
Read on to find out how to build your first component!
"},{"location":"#compatibility","title":"Compatibility","text":"Django-components supports all supported combinations versions of Django and Python.
Python version Django version 3.8 4.2 3.9 4.2 3.10 4.2, 5.0 3.11 4.2, 5.0 3.12 4.2, 5.0"},{"location":"#create-your-first-component","title":"Create your first component","text":"A component in django-components is the combination of four things: CSS, Javascript, a Django template, and some Python code to put them all together.
sampleproject/\n \u251c\u2500\u2500 calendarapp/\n \u251c\u2500\u2500 components/ \ud83c\udd95\n \u2502 \u2514\u2500\u2500 calendar/ \ud83c\udd95\n \u2502 \u251c\u2500\u2500 calendar.py \ud83c\udd95\n \u2502 \u251c\u2500\u2500 script.js \ud83c\udd95\n \u2502 \u251c\u2500\u2500 style.css \ud83c\udd95\n \u2502 \u2514\u2500\u2500 template.html \ud83c\udd95\n \u251c\u2500\u2500 sampleproject/\n \u251c\u2500\u2500 manage.py\n \u2514\u2500\u2500 requirements.txt\n
Start by creating empty files in the structure above.
First, you need a CSS file. Be sure to prefix all rules with a unique class so they don't clash with other rules.
[project root]/components/calendar/style.css/* In a file called [project root]/components/calendar/style.css */\n.calendar-component {\n width: 200px;\n background: pink;\n}\n.calendar-component span {\n font-weight: bold;\n}\n
Then you need a javascript file that specifies how you interact with this component. You are free to use any javascript framework you want. A good way to make sure this component doesn't clash with other components is to define all code inside an anonymous function that calls itself. This makes all variables defined only be defined inside this component and not affect other components.
[project root]/components/calendar/script.js/* In a file called [project root]/components/calendar/script.js */\n(function () {\n if (document.querySelector(\".calendar-component\")) {\n document.querySelector(\".calendar-component\").onclick = function () {\n alert(\"Clicked calendar!\");\n };\n }\n})();\n
Now you need a Django template for your component. Feel free to define more variables like date
in this example. When creating an instance of this component we will send in the values for these variables. The template will be rendered with whatever template backend you've specified in your Django settings file.
[project root]/components/calendar/calendar.html{# In a file called [project root]/components/calendar/template.html #}\n<div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n
Finally, we use django-components to tie this together. Start by creating a file called calendar.py
in your component calendar directory. It will be auto-detected and loaded by the app.
Inside this file we create a Component by inheriting from the Component class and specifying the context method. We also register the global component registry so that we easily can render it anywhere in our templates.
[project root]/components/calendar/calendar.py# In a file called [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n # Templates inside `[your apps]/components` dir and `[project root]/components` dir\n # will be automatically found. To customize which template to use based on context\n # you can override method `get_template_name` instead of specifying `template_name`.\n #\n # `template_name` can be relative to dir where `calendar.py` is, or relative to STATICFILES_DIRS\n template_name = \"template.html\"\n\n # This component takes one parameter, a date string to show in the template\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n\n # Both `css` and `js` can be relative to dir where `calendar.py` is, or relative to STATICFILES_DIRS\n class Media:\n css = \"style.css\"\n js = \"script.js\"\n
And voil\u00e1!! We've created our first component.
"},{"location":"#using-single-file-components","title":"Using single-file components","text":"Components can also be defined in a single file, which is useful for small components. To do this, you can use the template
, js
, and css
class attributes instead of the template_name
and Media
. For example, here's the calendar component from above, defined in a single file:
[project root]/components/calendar.py# In a file called [project root]/components/calendar.py\nfrom django_components import Component, register, types\n\n@register(\"calendar\")\nclass Calendar(Component):\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n\n template: types.django_html = \"\"\"\n <div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n \"\"\"\n\n css: types.css = \"\"\"\n .calendar-component { width: 200px; background: pink; }\n .calendar-component span { font-weight: bold; }\n \"\"\"\n\n js: types.js = \"\"\"\n (function(){\n if (document.querySelector(\".calendar-component\")) {\n document.querySelector(\".calendar-component\").onclick = function(){ alert(\"Clicked calendar!\"); };\n }\n })()\n \"\"\"\n
This makes it easy to create small components without having to create a separate template, CSS, and JS file.
"},{"location":"#syntax-highlight-and-code-assistance","title":"Syntax highlight and code assistance","text":""},{"location":"#vscode","title":"VSCode","text":"Note, in the above example, that the t.django_html
, t.css
, and t.js
types are used to specify the type of the template, CSS, and JS files, respectively. This is not necessary, but if you're using VSCode with the Python Inline Source Syntax Highlighting extension, it will give you syntax highlighting for the template, CSS, and JS.
"},{"location":"#pycharm-or-other-jetbrains-ides","title":"Pycharm (or other Jetbrains IDEs)","text":"If you're a Pycharm user (or any other editor from Jetbrains), you can have coding assistance as well:
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n\n # language=HTML\n template= \"\"\"\n <div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n \"\"\"\n\n # language=CSS\n css = \"\"\"\n .calendar-component { width: 200px; background: pink; }\n .calendar-component span { font-weight: bold; }\n \"\"\"\n\n # language=JS\n js = \"\"\"\n (function(){\n if (document.querySelector(\".calendar-component\")) {\n document.querySelector(\".calendar-component\").onclick = function(){ alert(\"Clicked calendar!\"); };\n }\n })()\n \"\"\"\n
You don't need to use types.django_html
, types.css
, types.js
since Pycharm uses language injections. You only need to write the comments # language=<lang>
above the variables.
"},{"location":"#use-components-in-templates","title":"Use components in templates","text":"First load the component_tags
tag library, then use the component_[js/css]_dependencies
and component
tags to render the component to the page.
{% load component_tags %}\n<!DOCTYPE html>\n<html>\n<head>\n <title>My example calendar</title>\n {% component_css_dependencies %}\n</head>\n<body>\n {% component \"calendar\" date=\"2015-06-19\" %}{% endcomponent %}\n {% component_js_dependencies %}\n</body>\n<html>\n
NOTE: Instead of writing {% endcomponent %}
at the end, you can use a self-closing tag:
{% component \"calendar\" date=\"2015-06-19\" / %}
The output from the above template will be:
<!DOCTYPE html>\n<html>\n <head>\n <title>My example calendar</title>\n <link\n href=\"/static/calendar/style.css\"\n type=\"text/css\"\n media=\"all\"\n rel=\"stylesheet\"\n />\n </head>\n <body>\n <div class=\"calendar-component\">\n Today's date is <span>2015-06-19</span>\n </div>\n <script src=\"/static/calendar/script.js\"></script>\n </body>\n <html></html>\n</html>\n
This makes it possible to organize your front-end around reusable components. Instead of relying on template tags and keeping your CSS and Javascript in the static directory.
"},{"location":"#use-components-outside-of-templates","title":"Use components outside of templates","text":"New in version 0.81
Components can be rendered outside of Django templates, calling them as regular functions (\"React-style\").
The component class defines render
and render_to_response
class methods. These methods accept positional args, kwargs, and slots, offering the same flexibility as the {% component %}
tag:
class SimpleComponent(Component):\n template = \"\"\"\n {% load component_tags %}\n hello: {{ hello }}\n foo: {{ foo }}\n kwargs: {{ kwargs|safe }}\n slot_first: {% slot \"first\" required / %}\n \"\"\"\n\n def get_context_data(self, arg1, arg2, **kwargs):\n return {\n \"hello\": arg1,\n \"foo\": arg2,\n \"kwargs\": kwargs,\n }\n\nrendered = SimpleComponent.render(\n args=[\"world\", \"bar\"],\n kwargs={\"kw1\": \"test\", \"kw2\": \"ooo\"},\n slots={\"first\": \"FIRST_SLOT\"},\n context={\"from_context\": 98},\n)\n
Renders:
hello: world\nfoo: bar\nkwargs: {'kw1': 'test', 'kw2': 'ooo'}\nslot_first: FIRST_SLOT\n
"},{"location":"#inputs-of-render-and-render_to_response","title":"Inputs of render
and render_to_response
","text":"Both render
and render_to_response
accept the same input:
Component.render(\n context: Mapping | django.template.Context | None = None,\n args: List[Any] | None = None,\n kwargs: Dict[str, Any] | None = None,\n slots: Dict[str, str | SafeString | SlotFunc] | None = None,\n escape_slots_content: bool = True\n) -> str:\n
-
args
- Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %}
-
kwargs
- Keyword args for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %}
-
slots
- Component slot fills. This is the same as pasing {% fill %}
tags to the component. Accepts a dictionary of { slot_name: slot_content }
where slot_content
can be a string or SlotFunc
.
-
escape_slots_content
- Whether the content from slots
should be escaped. True
by default to prevent XSS attacks. If you disable escaping, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.
-
context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template.
- NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs.
"},{"location":"#slotfunc","title":"SlotFunc
","text":"When rendering components with slots in render
or render_to_response
, you can pass either a string or a function.
The function has following signature:
def render_func(\n context: Context,\n data: Dict[str, Any],\n slot_ref: SlotRef,\n) -> str | SafeString:\n return nodelist.render(ctx)\n
context
- Django's Context available to the Slot Node. data
- Data passed to the {% slot %}
tag. See Scoped Slots. slot_ref
- The default slot content. See Accessing original content of slots. - NOTE: The slot is lazily evaluated. To render the slot, convert it to string with
str(slot_ref)
.
Example:
def footer_slot(ctx, data, slot_ref):\n return f\"\"\"\n SLOT_DATA: {data['abc']}\n ORIGINAL: {slot_ref}\n \"\"\"\n\nMyComponent.render_to_response(\n slots={\n \"footer\": footer_slot,\n },\n)\n
"},{"location":"#adding-type-hints-with-generics","title":"Adding type hints with Generics","text":"The Component
class optionally accepts type parameters that allow you to specify the types of args, kwargs, slots, and data.
from typing import NotRequired, Tuple, TypedDict, SlotFunc\n\n# Positional inputs - Tuple\nArgs = Tuple[int, str]\n\n# Kwargs inputs - Mapping\nclass Kwargs(TypedDict):\n variable: str\n another: int\n maybe_var: NotRequired[int]\n\n# Data returned from `get_context_data` - Mapping\nclass Data(TypedDict):\n variable: str\n\n# The data available to the `my_slot` scoped slot\nclass MySlotData(TypedDict):\n value: int\n\n# Slot functions - Mapping\nclass Slots(TypedDict):\n # Use SlotFunc for slot functions.\n # The generic specifies the `data` dictionary\n my_slot: NotRequired[SlotFunc[MySlotData]]\n\nclass Button(Component[Args, Kwargs, Data, Slots]):\n def get_context_data(self, variable, another):\n return {\n \"variable\": variable,\n }\n
When you then call Component.render
or Component.render_to_response
, you will get type hints:
Button.render(\n # Error: First arg must be `int`, got `float`\n args=(1.25, \"abc\"),\n # Error: Key \"another\" is missing\n kwargs={\n \"variable\": \"text\",\n },\n)\n
"},{"location":"#response-class-of-render_to_response","title":"Response class of render_to_response
","text":"While render
method returns a plain string, render_to_response
wraps the rendered content in a \"Response\" class. By default, this is django.http.HttpResponse
.
If you want to use a different Response class in render_to_response
, set the Component.response_class
attribute:
class MyResponse(HttpResponse):\n def __init__(self, *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n # Configure response\n self.headers = ...\n self.status = ...\n\nclass SimpleComponent(Component):\n response_class = MyResponse\n template: types.django_html = \"HELLO\"\n\nresponse = SimpleComponent.render_to_response()\nassert isinstance(response, MyResponse)\n
"},{"location":"#use-components-as-views","title":"Use components as views","text":"New in version 0.34
Note: Since 0.92, Component no longer subclasses View. To configure the View class, set the nested Component.View
class
Components can now be used as views: - Components define the Component.as_view()
class method that can be used the same as View.as_view()
.
-
By default, you can define GET, POST or other HTTP handlers directly on the Component, same as you do with View. For example, you can override get
and post
to handle GET and POST requests, respectively.
-
In addition, Component
now has a render_to_response
method that renders the component template based on the provided context and slots' data and returns an HttpResponse
object.
"},{"location":"#component-as-view-example","title":"Component as view example","text":"Here's an example of a calendar component defined as a view:
# In a file called [project root]/components/calendar.py\nfrom django_components import Component, ComponentView, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n\n template = \"\"\"\n <div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" / %}\n </div>\n <div class=\"body\">\n Today's date is <span>{{ date }}</span>\n </div>\n </div>\n \"\"\"\n\n # Handle GET requests\n def get(self, request, *args, **kwargs):\n context = {\n \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n }\n slots = {\n \"header\": \"Calendar header\",\n }\n # Return HttpResponse with the rendered content\n return self.render_to_response(\n context=context,\n slots=slots,\n )\n
Then, to use this component as a view, you should create a urls.py
file in your components directory, and add a path to the component's view:
# In a file called [project root]/components/urls.py\nfrom django.urls import path\nfrom components.calendar.calendar import Calendar\n\nurlpatterns = [\n path(\"calendar/\", Calendar.as_view()),\n]\n
Component.as_view()
is a shorthand for calling View.as_view()
and passing the component instance as one of the arguments.
Remember to add __init__.py
to your components directory, so that Django can find the urls.py
file.
Finally, include the component's urls in your project's urls.py
file:
# In a file called [project root]/urls.py\nfrom django.urls import include, path\n\nurlpatterns = [\n path(\"components/\", include(\"components.urls\")),\n]\n
Note: Slots content are automatically escaped by default to prevent XSS attacks. To disable escaping, set escape_slots_content=False
in the render_to_response
method. If you do so, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.
If you're planning on passing an HTML string, check Django's use of format_html
and mark_safe
.
"},{"location":"#modifying-the-view-class","title":"Modifying the View class","text":"The View class that handles the requests is defined on Component.View
.
When you define a GET or POST handlers on the Component
class, like so:
class MyComponent(Component):\n def get(self, request, *args, **kwargs):\n return self.render_to_response(\n context={\n \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n },\n )\n\n def post(self, request, *args, **kwargs) -> HttpResponse:\n variable = request.POST.get(\"variable\")\n return self.render_to_response(\n kwargs={\"variable\": variable}\n )\n
Then the request is still handled by Component.View.get()
or Component.View.post()
methods. However, by default, Component.View.get()
points to Component.get()
, and so on.
class ComponentView(View):\n component: Component = None\n ...\n\n def get(self, request, *args, **kwargs):\n return self.component.get(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n return self.component.post(request, *args, **kwargs)\n\n ...\n
If you want to define your own View
class, you need to: 1. Set the class as Component.View
2. Subclass from ComponentView
, so the View instance has access to the component class.
In the example below, we added extra logic into View.setup()
.
Note that the POST handler is still defined at the top. This is because View
subclasses ComponentView
, which defines the post()
method that calls Component.post()
.
If you were to overwrite the View.post()
method, then Component.post()
would be ignored.
from django_components import Component, ComponentView\n\nclass MyComponent(Component):\n\n def post(self, request, *args, **kwargs) -> HttpResponse:\n variable = request.POST.get(\"variable\")\n return self.component.render_to_response(\n kwargs={\"variable\": variable}\n )\n\n class View(ComponentView):\n def setup(self, request, *args, **kwargs):\n super(request, *args, **kwargs)\n\n do_something_extra(request, *args, **kwargs)\n
"},{"location":"#registering-components","title":"Registering components","text":"In previous examples you could repeatedly see us using @register()
to \"register\" the components. In this section we dive deeper into what it actually means and how you can manage (add or remove) components.
As a reminder, we may have a component like this:
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"template.html\"\n\n # This component takes one parameter, a date string to show in the template\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n
which we then render in the template as:
{% component \"calendar\" date=\"1970-01-01\" %}\n{% endcomponent %}\n
As you can see, @register
links up the component class with the {% component %}
template tag. So when the template tag comes across a component called \"calendar\"
, it can look up it's class and instantiate it.
"},{"location":"#what-is-componentregistry","title":"What is ComponentRegistry","text":"The @register
decorator is a shortcut for working with the ComponentRegistry
.
ComponentRegistry
manages which components can be used in the template tags.
Each ComponentRegistry
instance is associated with an instance of Django's Library
. And Libraries are inserted into Django template using the {% load %}
tags.
The @register
decorator accepts an optional kwarg registry
, which specifies, the ComponentRegistry
to register components into. If omitted, the default ComponentRegistry
instance defined in django_components is used.
my_registry = ComponentRegistry()\n\n@register(registry=my_registry)\nclass MyComponent(Component):\n ...\n
The default ComponentRegistry
is associated with the Library
that you load when you call {% load component_tags %}
inside your template, or when you add django_components.templatetags.component_tags
to the template builtins.
So when you register or unregister a component to/from a component registry, then behind the scenes the registry automatically adds/removes the component's template tags to/from the Library, so you can call the component from within the templates such as {% component \"my_comp\" %}
.
"},{"location":"#working-with-componentregistry","title":"Working with ComponentRegistry","text":"The default ComponentRegistry
instance can be imported as:
from django_components import registry\n
You can use the registry to manually add/remove/get components:
from django_components import registry\n\n# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get all or single\nregistry.all() # {\"button\": ButtonComponent, \"card\": CardComponent}\nregistry.get(\"card\") # CardComponent\n\n# Unregister single component\nregistry.unregister(\"card\")\n\n# Unregister all components\nregistry.clear()\n
"},{"location":"#registering-components-to-custom-componentregistry","title":"Registering components to custom ComponentRegistry","text":"In rare cases, you may want to manage your own instance of ComponentRegistry
, or register components onto a different Library
instance than the default one.
The Library
instance can be set at instantiation of ComponentRegistry
. If omitted, then the default Library instance from django_components is used.
from django.template import Library\nfrom django_components import ComponentRegistry\n\nmy_library = Library(...)\nmy_registry = ComponentRegistry(library=my_library)\n
When you have defined your own ComponentRegistry
, you can either register the components with my_registry.register()
, or pass the registry to the @component.register()
decorator via the registry
kwarg:
from path.to.my.registry import my_registry\n\n@register(\"my_component\", registry=my_registry)\nclass MyComponent(Component):\n ...\n
NOTE: The Library instance can be accessed under library
attribute of ComponentRegistry
.
"},{"location":"#autodiscovery","title":"Autodiscovery","text":"Every component that you want to use in the template with the {% component %}
tag needs to be registered with the ComponentRegistry. Normally, we use the @register
decorator for that:
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n ...\n
But for the component to be registered, the code needs to be executed - the file needs to be imported as a module.
One way to do that is by importing all your components in apps.py
:
from django.apps import AppConfig\n\nclass MyAppConfig(AppConfig):\n name = \"my_app\"\n\n def ready(self) -> None:\n from components.card.card import Card\n from components.list.list import List\n from components.menu.menu import Menu\n from components.button.button import Button\n ...\n
However, there's a simpler way!
By default, the Python files in the STATICFILES_DIRS
directories are auto-imported in order to auto-register the components.
Autodiscovery occurs when Django is loaded, during the ready
hook of the apps.py
file.
If you are using autodiscovery, keep a few points in mind:
- Avoid defining any logic on the module-level inside the
components
dir, that you would not want to run anyway. - Components inside the auto-imported files still need to be registered with
@register()
- Auto-imported component files must be valid Python modules, they must use suffix
.py
, and module name should follow PEP-8.
Autodiscovery can be disabled in the settings.
"},{"location":"#manually-trigger-autodiscovery","title":"Manually trigger autodiscovery","text":"Autodiscovery can be also triggered manually as a function call. This is useful if you want to run autodiscovery at a custom point of the lifecycle:
from django_components import autodiscover\n\nautodiscover()\n
"},{"location":"#using-slots-in-templates","title":"Using slots in templates","text":"New in version 0.26:
- The
slot
tag now serves only to declare new slots inside the component template. - To override the content of a declared slot, use the newly introduced
fill
tag instead. - Whereas unfilled slots used to raise a warning, filling a slot is now optional by default.
- To indicate that a slot must be filled, the new
required
option should be added at the end of the slot
tag.
Components support something called 'slots'. When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content. This mechanism makes components more reusable and composable. This behavior is similar to slots in Vue.
In the example below we introduce two block tags that work hand in hand to make this work. These are...
{% slot <name> %}
/{% endslot %}
: Declares a new slot in the component template. {% fill <name> %}
/{% endfill %}
: (Used inside a component
tag pair.) Fills a declared slot with the specified content.
Let's update our calendar component to support more customization. We'll add slot
tag pairs to its template, template.html.
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" %}Calendar header{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"body\" %}Today's date is <span>{{ date }}</span>{% endslot %}\n </div>\n</div>\n
When using the component, you specify which slots you want to fill and where you want to use the defaults from the template. It looks like this:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"body\" %}Can you believe it's already <span>{{ date }}</span>??{% endfill %}\n{% endcomponent %}\n
Since the 'header' fill is unspecified, it's taken from the base template. If you put this in a template, and pass in date=2020-06-06
, this is what gets rendered:
<div class=\"calendar-component\">\n <div class=\"header\">\n Calendar header\n </div>\n <div class=\"body\">\n Can you believe it's already <span>2020-06-06</span>??\n </div>\n</div>\n
"},{"location":"#default-slot","title":"Default slot","text":"Added in version 0.28
As you can see, component slots lets you write reusable containers that you fill in when you use a component. This makes for highly reusable components that can be used in different circumstances.
It can become tedious to use fill
tags everywhere, especially when you're using a component that declares only one slot. To make things easier, slot
tags can be marked with an optional keyword: default
. When added to the end of the tag (as shown below), this option lets you pass filling content directly in the body of a component
tag pair \u2013 without using a fill
tag. Choose carefully, though: a component template may contain at most one slot that is marked as default
. The default
option can be combined with other slot options, e.g. required
.
Here's the same example as before, except with default slots and implicit filling.
The template:
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" %}Calendar header{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"body\" default %}Today's date is <span>{{ date }}</span>{% endslot %}\n </div>\n</div>\n
Including the component (notice how the fill
tag is omitted):
{% component \"calendar\" date=\"2020-06-06\" %}\n Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n
The rendered result (exactly the same as before):
<div class=\"calendar-component\">\n <div class=\"header\">Calendar header</div>\n <div class=\"body\">Can you believe it's already <span>2020-06-06</span>??</div>\n</div>\n
You may be tempted to combine implicit fills with explicit fill
tags. This will not work. The following component template will raise an error when compiled.
{# DON'T DO THIS #}\n{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}Totally new header!{% endfill %}\n Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n
By contrast, it is permitted to use fill
tags in nested components, e.g.:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% component \"beautiful-box\" %}\n {% fill \"content\" %} Can you believe it's already <span>{{ date }}</span>?? {% endfill %}\n {% endcomponent %}\n{% endcomponent %}\n
This is fine too:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}\n {% component \"calendar-header\" %}\n Super Special Calendar Header\n {% endcomponent %}\n {% endfill %}\n{% endcomponent %}\n
"},{"location":"#render-fill-in-multiple-places","title":"Render fill in multiple places","text":"Added in version 0.70
You can render the same content in multiple places by defining multiple slots with identical names:
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"image\" %}Image here{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"image\" %}Image here{% endslot %}\n </div>\n</div>\n
So if used like:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"image\" %}\n <img src=\"...\" />\n {% endfill %}\n{% endcomponent %}\n
This renders:
<div class=\"calendar-component\">\n <div class=\"header\">\n <img src=\"...\" />\n </div>\n <div class=\"body\">\n <img src=\"...\" />\n </div>\n</div>\n
"},{"location":"#default-and-required-slots","title":"Default and required slots","text":"If you use a slot multiple times, you can still mark the slot as default
or required
. For that, you must mark ONLY ONE of the identical slots.
We recommend to mark the first occurence for consistency, e.g.:
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"image\" default required %}Image here{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"image\" %}Image here{% endslot %}\n </div>\n</div>\n
Which you can then use are regular default slot:
{% component \"calendar\" date=\"2020-06-06\" %}\n <img src=\"...\" />\n{% endcomponent %}\n
"},{"location":"#accessing-original-content-of-slots","title":"Accessing original content of slots","text":"Added in version 0.26
NOTE: In version 0.77, the syntax was changed from
{% fill \"my_slot\" as \"alias\" %} {{ alias.default }}\n
to
{% fill \"my_slot\" default=\"slot_default\" %} {{ slot_default }}\n
Sometimes you may want to keep the original slot, but only wrap or prepend/append content to it. To do so, you can access the default slot via the default
kwarg.
Similarly to the data
attribute, you specify the variable name through which the default slot will be made available.
For instance, let's say you're filling a slot called 'body'. To render the original slot, assign it to a variable using the 'default'
keyword. You then render this variable to insert the default content:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"body\" default=\"body_default\" %}\n {{ body_default }}. Have a great day!\n {% endfill %}\n{% endcomponent %}\n
This produces:
<div class=\"calendar-component\">\n <div class=\"header\">\n Calendar header\n </div>\n <div class=\"body\">\n Today's date is <span>2020-06-06</span>. Have a great day!\n </div>\n</div>\n
"},{"location":"#conditional-slots","title":"Conditional slots","text":"Added in version 0.26.
NOTE: In version 0.70, {% if_filled %}
tags were replaced with {{ component_vars.is_filled }}
variables. If your slot name contained special characters, see the section \"Accessing slot names with special characters\".
In certain circumstances, you may want the behavior of slot filling to depend on whether or not a particular slot is filled.
For example, suppose we have the following component template:
<div class=\"frontmatter-component\">\n <div class=\"title\">\n {% slot \"title\" %}Title{% endslot %}\n </div>\n <div class=\"subtitle\">\n {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n </div>\n</div>\n
By default the slot named 'subtitle' is empty. Yet when the component is used without explicit fills, the div containing the slot is still rendered, as shown below:
<div class=\"frontmatter-component\">\n <div class=\"title\">Title</div>\n <div class=\"subtitle\"></div>\n</div>\n
This may not be what you want. What if instead the outer 'subtitle' div should only be included when the inner slot is in fact filled?
The answer is to use the {{ component_vars.is_filled.<name> }}
variable. You can use this together with Django's {% if/elif/else/endif %}
tags to define a block whose contents will be rendered only if the component slot with the corresponding 'name' is filled.
This is what our example looks like with component_vars.is_filled
.
<div class=\"frontmatter-component\">\n <div class=\"title\">\n {% slot \"title\" %}Title{% endslot %}\n </div>\n {% if component_vars.is_filled.subtitle %}\n <div class=\"subtitle\">\n {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n </div>\n {% endif %}\n</div>\n
Here's our example with more complex branching.
<div class=\"frontmatter-component\">\n <div class=\"title\">\n {% slot \"title\" %}Title{% endslot %}\n </div>\n {% if component_vars.is_filled.subtitle %}\n <div class=\"subtitle\">\n {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n </div>\n {% elif component_vars.is_filled.title %}\n ...\n {% elif component_vars.is_filled.<name> %}\n ...\n {% endif %}\n</div>\n
Sometimes you're not interested in whether a slot is filled, but rather that it isn't. To negate the meaning of component_vars.is_filled
, simply treat it as boolean and negate it with not
:
{% if not component_vars.is_filled.subtitle %}\n<div class=\"subtitle\">\n {% slot \"subtitle\" / %}\n</div>\n{% endif %}\n
"},{"location":"#accessing-is_filled-of-slot-names-with-special-characters","title":"Accessing is_filled
of slot names with special characters","text":"To be able to access a slot name via component_vars.is_filled
, the slot name needs to be composed of only alphanumeric characters and underscores (e.g. this__isvalid_123
).
However, you can still define slots with other special characters. In such case, the slot name in component_vars.is_filled
is modified to replace all invalid characters into _
.
So a slot named \"my super-slot :)\"
will be available as component_vars.is_filled.my_super_slot___
.
"},{"location":"#scoped-slots","title":"Scoped slots","text":"Added in version 0.76:
Consider a component with slot(s). This component may do some processing on the inputs, and then use the processed variable in the slot's default template:
@register(\"my_comp\")\nclass MyComp(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" default %}\n input: {{ input }}\n {% endslot %}\n </div>\n \"\"\"\n\n def get_context_data(self, input):\n processed_input = do_something(input)\n return {\"input\": processed_input}\n
You may want to design a component so that users of your component can still access the input
variable, so they don't have to recompute it.
This behavior is called \"scoped slots\". This is inspired by Vue scoped slots and scoped slots of django-web-components.
Using scoped slots consists of two steps:
- Passing data to
slot
tag - Accessing data in
fill
tag
"},{"location":"#passing-data-to-slots","title":"Passing data to slots","text":"To pass the data to the slot
tag, simply pass them as keyword attributes (key=value
):
@register(\"my_comp\")\nclass MyComp(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" default input=input %}\n input: {{ input }}\n {% endslot %}\n </div>\n \"\"\"\n\n def get_context_data(self, input):\n processed_input = do_something(input)\n return {\n \"input\": processed_input,\n }\n
"},{"location":"#accessing-slot-data-in-fill","title":"Accessing slot data in fill","text":"Next, we head over to where we define a fill for this slot. Here, to access the slot data we set the data
attribute to the name of the variable through which we want to access the slot data. In the example below, we set it to data
:
{% component \"my_comp\" %}\n {% fill \"content\" data=\"data\" %}\n {{ data.input }}\n {% endfill %}\n{% endcomponent %}\n
To access slot data on a default slot, you have to explictly define the {% fill %}
tags.
So this works:
{% component \"my_comp\" %}\n {% fill \"content\" data=\"data\" %}\n {{ data.input }}\n {% endfill %}\n{% endcomponent %}\n
While this does not:
{% component \"my_comp\" data=\"data\" %}\n {{ data.input }}\n{% endcomponent %}\n
Note: You cannot set the data
attribute and default
attribute) to the same name. This raises an error:
{% component \"my_comp\" %}\n {% fill \"content\" data=\"slot_var\" default=\"slot_var\" %}\n {{ slot_var.input }}\n {% endfill %}\n{% endcomponent %}\n
"},{"location":"#passing-data-to-components","title":"Passing data to components","text":"As seen above, you can pass arguments to components like so:
<body>\n {% component \"calendar\" date=\"2015-06-19\" %}\n {% endcomponent %}\n</body>\n
"},{"location":"#accessing-data-passed-to-the-component","title":"Accessing data passed to the component","text":"When you call Component.render
or Component.render_to_response
, the inputs to these methods can be accessed from within the instance under self.input
.
This means that you can use self.input
inside: - get_context_data
- get_template_name
- get_template_string
self.input
is defined only for the duration of Component.render
, and returns None
when called outside of this.
self.input
has the same fields as the input to Component.render
:
class TestComponent(Component):\n def get_context_data(self, var1, var2, variable, another, **attrs):\n assert self.input.args == (123, \"str\")\n assert self.input.kwargs == {\"variable\": \"test\", \"another\": 1}\n assert self.input.slots == {\"my_slot\": \"MY_SLOT\"}\n assert isinstance(self.input.context, Context)\n\n return {\n \"variable\": variable,\n }\n\nrendered = TestComponent.render(\n kwargs={\"variable\": \"test\", \"another\": 1},\n args=(123, \"str\"),\n slots={\"my_slot\": \"MY_SLOT\"},\n)\n
"},{"location":"#rendering-html-attributes","title":"Rendering HTML attributes","text":"New in version 0.74:
You can use the html_attrs
tag to render HTML attributes, given a dictionary of values.
So if you have a template:
<div class=\"{{ classes }}\" data-id=\"{{ my_id }}\">\n</div>\n
You can simplify it with html_attrs
tag:
<div {% html_attrs attrs %}>\n</div>\n
where attrs
is:
attrs = {\n \"class\": classes,\n \"data-id\": my_id,\n}\n
This feature is inspired by merge_attrs
tag of django-web-components and \"fallthrough attributes\" feature of Vue.
"},{"location":"#removing-atttributes","title":"Removing atttributes","text":"Attributes that are set to None
or False
are NOT rendered.
So given this input:
attrs = {\n \"class\": \"text-green\",\n \"required\": False,\n \"data-id\": None,\n}\n
And template:
<div {% html_attrs attrs %}>\n</div>\n
Then this renders:
<div class=\"text-green\"></div>\n
"},{"location":"#boolean-attributes","title":"Boolean attributes","text":"In HTML, boolean attributes are usually rendered with no value. Consider the example below where the first button is disabled and the second is not:
<button disabled>Click me!</button> <button>Click me!</button>\n
HTML rendering with html_attrs
tag or attributes_to_string
works the same way, where key=True
is rendered simply as key
, and key=False
is not render at all.
So given this input:
attrs = {\n \"disabled\": True,\n \"autofocus\": False,\n}\n
And template:
<div {% html_attrs attrs %}>\n</div>\n
Then this renders:
<div disabled></div>\n
"},{"location":"#default-attributes","title":"Default attributes","text":"Sometimes you may want to specify default values for attributes. You can pass a second argument (or kwarg defaults
) to set the defaults.
<div {% html_attrs attrs defaults %}>\n ...\n</div>\n
In the example above, if attrs
contains e.g. the class
key, html_attrs
will render:
class=\"{{ attrs.class }}\"
Otherwise, html_attrs
will render:
class=\"{{ defaults.class }}\"
"},{"location":"#appending-attributes","title":"Appending attributes","text":"For the class
HTML attribute, it's common that we want to join multiple values, instead of overriding them. For example, if you're authoring a component, you may want to ensure that the component will ALWAYS have a specific class. Yet, you may want to allow users of your component to supply their own classes.
We can achieve this by adding extra kwargs. These values will be appended, instead of overwriting the previous value.
So if we have a variable attrs
:
attrs = {\n \"class\": \"my-class pa-4\",\n}\n
And on html_attrs
tag, we set the key class
:
<div {% html_attrs attrs class=\"some-class\" %}>\n</div>\n
Then these will be merged and rendered as:
<div data-value=\"my-class pa-4 some-class\"></div>\n
To simplify merging of variables, you can supply the same key multiple times, and these will be all joined together:
{# my_var = \"class-from-var text-red\" #}\n<div {% html_attrs attrs class=\"some-class another-class\" class=my_var %}>\n</div>\n
Renders:
<div\n data-value=\"my-class pa-4 some-class another-class class-from-var text-red\"\n></div>\n
"},{"location":"#rules-for-html_attrs","title":"Rules for html_attrs
","text":" - Both
attrs
and defaults
can be passed as positional args
{% html_attrs attrs defaults key=val %}
or as kwargs
{% html_attrs key=val defaults=defaults attrs=attrs %}
-
Both attrs
and defaults
are optional (can be omitted)
-
Both attrs
and defaults
are dictionaries, and we can define them the same way we define dictionaries for the component
tag. So either as attrs=attrs
or attrs:key=value
.
-
All other kwargs are appended and can be repeated.
"},{"location":"#examples-for-html_attrs","title":"Examples for html_attrs
","text":"Assuming that:
class_from_var = \"from-var\"\n\nattrs = {\n \"class\": \"from-attrs\",\n \"type\": \"submit\",\n}\n\ndefaults = {\n \"class\": \"from-defaults\",\n \"role\": \"button\",\n}\n
Then:
- Empty tag
{% html_attr %}
renders (empty string):
- Only kwargs
{% html_attr class=\"some-class\" class=class_from_var data-id=\"123\" %}
renders: class=\"some-class from-var\" data-id=\"123\"
- Only attrs
{% html_attr attrs %}
renders: class=\"from-attrs\" type=\"submit\"
- Attrs as kwarg
{% html_attr attrs=attrs %}
renders: class=\"from-attrs\" type=\"submit\"
- Only defaults (as kwarg)
{% html_attr defaults=defaults %}
renders: class=\"from-defaults\" role=\"button\"
- Attrs using the
prefix:key=value
construct {% html_attr attrs:class=\"from-attrs\" attrs:type=\"submit\" %}
renders: class=\"from-attrs\" type=\"submit\"
- Defaults using the
prefix:key=value
construct {% html_attr defaults:class=\"from-defaults\" %}
renders: class=\"from-defaults\" role=\"button\"
- All together (1) - attrs and defaults as positional args:
{% html_attrs attrs defaults class=\"added_class\" class=class_from_var data-id=123 %}
renders: class=\"from-attrs added_class from-var\" type=\"submit\" role=\"button\" data-id=123
- All together (2) - attrs and defaults as kwargs args:
{% html_attrs class=\"added_class\" class=class_from_var data-id=123 attrs=attrs defaults=defaults %}
renders: class=\"from-attrs added_class from-var\" type=\"submit\" role=\"button\" data-id=123
- All together (3) - mixed:
{% html_attrs attrs defaults:class=\"default-class\" class=\"added_class\" class=class_from_var data-id=123 %}
renders: class=\"from-attrs added_class from-var\" type=\"submit\" data-id=123
"},{"location":"#full-example-for-html_attrs","title":"Full example for html_attrs
","text":"@register(\"my_comp\")\nclass MyComp(Component):\n template: t.django_html = \"\"\"\n <div\n {% html_attrs attrs\n defaults:class=\"pa-4 text-red\"\n class=\"my-comp-date\"\n class=class_from_var\n data-id=\"123\"\n %}\n >\n Today's date is <span>{{ date }}</span>\n </div>\n \"\"\"\n\n def get_context_data(self, date: Date, attrs: dict):\n return {\n \"date\": date,\n \"attrs\": attrs,\n \"class_from_var\": \"extra-class\"\n }\n\n@register(\"parent\")\nclass Parent(Component):\n template: t.django_html = \"\"\"\n {% component \"my_comp\"\n date=date\n attrs:class=\"pa-0 border-solid border-red\"\n attrs:data-json=json_data\n attrs:@click=\"(e) => onClick(e, 'from_parent')\"\n / %}\n \"\"\"\n\n def get_context_data(self, date: Date):\n return {\n \"date\": datetime.now(),\n \"json_data\": json.dumps({\"value\": 456})\n }\n
Note: For readability, we've split the tags across multiple lines.
Inside MyComp
, we defined a default attribute
defaults:class=\"pa-4 text-red\"
So if attrs
includes key class
, the default above will be ignored.
MyComp
also defines class
key twice. It means that whether the class
attribute is taken from attrs
or defaults
, the two class
values will be appended to it.
So by default, MyComp
renders:
<div class=\"pa-4 text-red my-comp-date extra-class\" data-id=\"123\">...</div>\n
Next, let's consider what will be rendered when we call MyComp
from Parent
component.
MyComp
accepts a attrs
dictionary, that is passed to html_attrs
, so the contents of that dictionary are rendered as the HTML attributes.
In Parent
, we make use of passing dictionary key-value pairs as kwargs to define individual attributes as if they were regular kwargs.
So all kwargs that start with attrs:
will be collected into an attrs
dict.
attrs:class=\"pa-0 border-solid border-red\"\n attrs:data-json=json_data\n attrs:@click=\"(e) => onClick(e, 'from_parent')\"\n
And get_context_data
of MyComp
will receive attrs
input with following keys:
attrs = {\n \"class\": \"pa-0 border-solid\",\n \"data-json\": '{\"value\": 456}',\n \"@click\": \"(e) => onClick(e, 'from_parent')\",\n}\n
attrs[\"class\"]
overrides the default value for class
, whereas other keys will be merged.
So in the end MyComp
will render:
<div\n class=\"pa-0 border-solid my-comp-date extra-class\"\n data-id=\"123\"\n data-json='{\"value\": 456}'\n @click=\"(e) => onClick(e, 'from_parent')\"\n>\n ...\n</div>\n
"},{"location":"#rendering-html-attributes-outside-of-templates","title":"Rendering HTML attributes outside of templates","text":"If you need to use serialize HTML attributes outside of Django template and the html_attrs
tag, you can use attributes_to_string
:
from django_components.attributes import attributes_to_string\n\nattrs = {\n \"class\": \"my-class text-red pa-4\",\n \"data-id\": 123,\n \"required\": True,\n \"disabled\": False,\n \"ignored-attr\": None,\n}\n\nattributes_to_string(attrs)\n# 'class=\"my-class text-red pa-4\" data-id=\"123\" required'\n
"},{"location":"#template-tag-syntax","title":"Template tag syntax","text":"All template tags in django_component, like {% component %}
or {% slot %}
, and so on, support extra syntax that makes it possible to write components like in Vue or React.
"},{"location":"#special-characters","title":"Special characters","text":"New in version 0.71:
Keyword arguments can contain special characters # @ . - _
, so keywords like so are still valid:
<body>\n {% component \"calendar\" my-date=\"2015-06-19\" @click.native=do_something #some_id=True / %}\n</body>\n
These can then be accessed inside get_context_data
so:
@register(\"calendar\")\nclass Calendar(Component):\n # Since # . @ - are not valid identifiers, we have to\n # use `**kwargs` so the method can accept these args.\n def get_context_data(self, **kwargs):\n return {\n \"date\": kwargs[\"my-date\"],\n \"id\": kwargs[\"#some_id\"],\n \"on_click\": kwargs[\"@click.native\"]\n }\n
"},{"location":"#spread-operator","title":"Spread operator","text":"New in version 0.93:
Instead of passing keyword arguments one-by-one:
{% component \"calendar\" title=\"How to abc\" date=\"2015-06-19\" author=\"John Wick\" / %}\n
You can use a spread operator ...dict
to apply key-value pairs from a dictionary:
post_data = {\n \"title\": \"How to...\",\n \"date\": \"2015-06-19\",\n \"author\": \"John Wick\",\n}\n
{% component \"calendar\" ...post_data / %}\n
This behaves similar to JSX's spread operator or Vue's v-bind
.
Spread operators are treated as keyword arguments, which means that: 1. Spread operators must come after positional arguments. 2. You cannot use spread operators for positional-only arguments.
Other than that, you can use spread operators multiple times, and even put keyword arguments in-between or after them:
{% component \"calendar\" ...post_data id=post.id ...extra / %}\n
In a case of conflicts, the values added later (right-most) overwrite previous values.
"},{"location":"#use-template-tags-inside-component-inputs","title":"Use template tags inside component inputs","text":"New in version 0.93
When passing data around, sometimes you may need to do light transformations, like negating booleans or filtering lists.
Normally, what you would have to do is to define ALL the variables inside get_context_data()
. But this can get messy if your components contain a lot of logic.
@register(\"calendar\")\nclass Calendar(Component):\n def get_context_data(self, id: str, editable: bool):\n return {\n \"editable\": editable,\n \"readonly\": not editable,\n \"input_id\": f\"input-{id}\",\n \"icon_id\": f\"icon-{id}\",\n ...\n }\n
Instead, template tags in django_components ({% component %}
, {% slot %}
, {% provide %}
, etc) allow you to treat literal string values as templates:
{% component 'blog_post'\n \"As positional arg {# yay #}\"\n title=\"{{ person.first_name }} {{ person.last_name }}\"\n id=\"{% random_int 10 20 %}\"\n author=\"John Wick {# TODO: parametrize #}\"\n/ %}\n
In the example above: - Component test
receives a positional argument with value \"As positional arg \"
. The comment is omitted. - Kwarg title
is passed as a string, e.g. John Doe
- Kwarg id
is passed as int
, e.g. 15
- Kwarg author
is passed as a string, e.g. John Wick
(Comment omitted)
This is inspired by django-cotton.
"},{"location":"#passing-data-as-string-vs-original-values","title":"Passing data as string vs original values","text":"Sometimes you may want to use the template tags to transform or generate the data that is then passed to the component.
The data doesn't necessarily have to be strings. In the example above, the kwarg id
was passed as an integer, NOT a string.
Although the string literals for components inputs are treated as regular Django templates, there is one special case:
When the string literal contains only a single template tag, with no extra text, then the value is passed as the original type instead of a string.
Here, page
is an integer:
{% component 'blog_post' page=\"{% random_int 10 20 %}\" / %}\n
Here, page
is a string:
{% component 'blog_post' page=\" {% random_int 10 20 %} \" / %}\n
And same applies to the {{ }}
variable tags:
Here, items
is a list:
{% component 'cat_list' items=\"{{ cats|slice:':2' }}\" / %}\n
Here, items
is a string:
{% component 'cat_list' items=\"{{ cats|slice:':2' }} See more\" / %}\n
"},{"location":"#evaluating-python-expressions-in-template","title":"Evaluating Python expressions in template","text":"You can even go a step further and have a similar experience to Vue or React, where you can evaluate arbitrary code expressions:
<MyForm\n value={ isEnabled ? inputValue : null }\n/>\n
Similar is possible with django-expr
, which adds an expr
tag and filter that you can use to evaluate Python expressions from within the template:
{% component \"my_form\"\n value=\"{% expr 'input_value if is_enabled else None' %}\"\n/ %}\n
Note: Never use this feature to mix business logic and template logic. Business logic should still be in the template!
"},{"location":"#pass-dictonary-by-its-key-value-pairs","title":"Pass dictonary by its key-value pairs","text":"New in version 0.74:
Sometimes, a component may expect a dictionary as one of its inputs.
Most commonly, this happens when a component accepts a dictionary of HTML attributes (usually called attrs
) to pass to the underlying template.
In such cases, we may want to define some HTML attributes statically, and other dynamically. But for that, we need to define this dictionary on Python side:
@register(\"my_comp\")\nclass MyComp(Component):\n template = \"\"\"\n {% component \"other\" attrs=attrs / %}\n \"\"\"\n\n def get_context_data(self, some_id: str):\n attrs = {\n \"class\": \"pa-4 flex\",\n \"data-some-id\": some_id,\n \"@click.stop\": \"onClickHandler\",\n }\n return {\"attrs\": attrs}\n
But as you can see in the case above, the event handler @click.stop
and styling pa-4 flex
are disconnected from the template. If the component grew in size and we moved the HTML to a separate file, we would have hard time reasoning about the component's template.
Luckily, there's a better way.
When we want to pass a dictionary to a component, we can define individual key-value pairs as component kwargs, so we can keep all the relevant information in the template. For that, we prefix the key with the name of the dict and :
. So key class
of input attrs
becomes attrs:class
. And our example becomes:
@register(\"my_comp\")\nclass MyComp(Component):\n template = \"\"\"\n {% component \"other\"\n attrs:class=\"pa-4 flex\"\n attrs:data-some-id=some_id\n attrs:@click.stop=\"onClickHandler\"\n / %}\n \"\"\"\n\n def get_context_data(self, some_id: str):\n return {\"some_id\": some_id}\n
Sweet! Now all the relevant HTML is inside the template, and we can move it to a separate file with confidence:
{% component \"other\"\n attrs:class=\"pa-4 flex\"\n attrs:data-some-id=some_id\n attrs:@click.stop=\"onClickHandler\"\n/ %}\n
Note: It is NOT possible to define nested dictionaries, so attrs:my_key:two=2
would be interpreted as:
{\"attrs\": {\"my_key:two\": 2}}\n
"},{"location":"#prop-drilling-and-dependency-injection-provide-inject","title":"Prop drilling and dependency injection (provide / inject)","text":"New in version 0.80:
Django components supports dependency injection with the combination of:
{% provide %}
tag inject()
method of the Component
class
"},{"location":"#what-is-dependency-injection-and-prop-drilling","title":"What is \"dependency injection\" and \"prop drilling\"?","text":"Prop drilling refers to a scenario in UI development where you need to pass data through many layers of a component tree to reach the nested components that actually need the data.
Normally, you'd use props to send data from a parent component to its children. However, this straightforward method becomes cumbersome and inefficient if the data has to travel through many levels or if several components scattered at different depths all need the same piece of information.
This results in a situation where the intermediate components, which don't need the data for their own functioning, end up having to manage and pass along these props. This clutters the component tree and makes the code verbose and harder to manage.
A neat solution to avoid prop drilling is using the \"provide and inject\" technique, AKA dependency injection.
With dependency injection, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.
This feature is inspired by Vue's Provide / Inject and React's Context / useContext.
"},{"location":"#how-to-use-provide-inject","title":"How to use provide / inject","text":"As the name suggest, using provide / inject consists of 2 steps
- Providing data
- Injecting provided data
For examples of advanced uses of provide / inject, see this discussion.
"},{"location":"#using-provide-tag","title":"Using {% provide %}
tag","text":"First we use the {% provide %}
tag to define the data we want to \"provide\" (make available).
{% provide \"my_data\" key=\"hi\" another=123 %}\n {% component \"child\" / %} <--- Can access \"my_data\"\n{% endprovide %}\n\n{% component \"child\" / %} <--- Cannot access \"my_data\"\n
Notice that the provide
tag REQUIRES a name as a first argument. This is the key by which we can then access the data passed to this tag.
provide
tag key, similarly to the name argument in component
or slot
tags, has these requirements:
- The key must be a string literal
- It must be a valid identifier (AKA a valid Python variable name)
Once you've set the name, you define the data you want to \"provide\" by passing it as keyword arguments. This is similar to how you pass data to the {% with %}
tag.
NOTE: Kwargs passed to {% provide %}
are NOT added to the context. In the example below, the {{ key }}
won't render anything:
{% provide \"my_data\" key=\"hi\" another=123 %}\n {{ key }}\n{% endprovide %}\n
"},{"location":"#using-inject-method","title":"Using inject()
method","text":"To \"inject\" (access) the data defined on the provide
tag, you can use the inject()
method inside of get_context_data()
.
For a component to be able to \"inject\" some data, the component ({% component %}
tag) must be nested inside the {% provide %}
tag.
In the example from previous section, we've defined two kwargs: key=\"hi\" another=123
. That means that if we now inject \"my_data\"
, we get an object with 2 attributes - key
and another
.
class ChildComponent(Component):\n def get_context_data(self):\n my_data = self.inject(\"my_data\")\n print(my_data.key) # hi\n print(my_data.another) # 123\n return {}\n
First argument to inject
is the key of the provided data. This must match the string that you used in the provide
tag. If no provider with given key is found, inject
raises a KeyError
.
To avoid the error, you can pass a second argument to inject
to which will act as a default value, similar to dict.get(key, default)
:
class ChildComponent(Component):\n def get_context_data(self):\n my_data = self.inject(\"invalid_key\", DEFAULT_DATA)\n assert my_data == DEFAUKT_DATA\n return {}\n
The instance returned from inject()
is a subclass of NamedTuple
, so the instance is immutable. This ensures that the data returned from inject
will always have all the keys that were passed to the provide
tag.
NOTE: inject()
works strictly only in get_context_data
. If you try to call it from elsewhere, it will raise an error.
"},{"location":"#full-example","title":"Full example","text":"@register(\"child\")\nclass ChildComponent(Component):\n template = \"\"\"\n <div> {{ my_data.key }} </div>\n <div> {{ my_data.another }} </div>\n \"\"\"\n\n def get_context_data(self):\n my_data = self.inject(\"my_data\", \"default\")\n return {\"my_data\": my_data}\n\ntemplate_str = \"\"\"\n {% load component_tags %}\n {% provide \"my_data\" key=\"hi\" another=123 %}\n {% component \"child\" / %}\n {% endprovide %}\n\"\"\"\n
renders:
<div>hi</div>\n<div>123</div>\n
"},{"location":"#component-context-and-scope","title":"Component context and scope","text":"By default, context variables are passed down the template as in regular Django - deeper scopes can access the variables from the outer scopes. So if you have several nested forloops, then inside the deep-most loop you can access variables defined by all previous loops.
With this in mind, the {% component %}
tag behaves similarly to {% include %}
tag - inside the component tag, you can access all variables that were defined outside of it.
And just like with {% include %}
, if you don't want a specific component template to have access to the parent context, add only
to the {% component %}
tag:
{% component \"calendar\" date=\"2015-06-19\" only %}{% endcomponent %}\n
NOTE: {% csrf_token %}
tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the only
modifier.
If you find yourself using the only
modifier often, you can set the context_behavior option to \"isolated\"
, which automatically applies the only
modifier. This is useful if you want to make sure that components don't accidentally access the outer context.
Components can also access the outer context in their context methods like get_context_data
by accessing the property self.outer_context
.
"},{"location":"#customizing-component-tags-with-tagformatter","title":"Customizing component tags with TagFormatter","text":"New in version 0.89
By default, components are rendered using the pair of {% component %}
/ {% endcomponent %}
template tags:
{% component \"button\" href=\"...\" disabled %}\nClick me!\n{% endcomponent %}\n\n{# or #}\n\n{% component \"button\" href=\"...\" disabled / %}\n
You can change this behaviour in the settings under the COMPONENTS.tag_formatter
.
For example, if you set the tag formatter to django_components.shorthand_component_formatter
, the components will use their name as the template tags:
{% button href=\"...\" disabled %}\n Click me!\n{% endbutton %}\n\n{# or #}\n\n{% button href=\"...\" disabled / %}\n
"},{"location":"#available-tagformatters","title":"Available TagFormatters","text":"django_components provides following predefined TagFormatters:
-
ComponentFormatter
(django_components.component_formatter
)
Default
Uses the component
and endcomponent
tags, and the component name is gives as the first positional argument.
Example as block:
{% component \"button\" href=\"...\" %}\n {% fill \"content\" %}\n ...\n {% endfill %}\n{% endcomponent %}\n
Example as inlined tag:
{% component \"button\" href=\"...\" / %}\n
-
ShorthandComponentFormatter
(django_components.shorthand_component_formatter
)
Uses the component name as start tag, and end<component_name>
as an end tag.
Example as block:
{% button href=\"...\" %}\n Click me!\n{% endbutton %}\n
Example as inlined tag:
{% button href=\"...\" / %}\n
"},{"location":"#writing-your-own-tagformatter","title":"Writing your own TagFormatter","text":""},{"location":"#background","title":"Background","text":"First, let's discuss how TagFormatters work, and how components are rendered in django_components.
When you render a component with {% component %}
(or your own tag), the following happens: 1. component
must be registered as a Django's template tag 2. Django triggers django_components's tag handler for tag component
. 3. The tag handler passes the tag contents for pre-processing to TagFormatter.parse()
.
So if you render this:\n```django\n{% component \"button\" href=\"...\" disabled %}\n{% endcomponent %}\n```\n\nThen `TagFormatter.parse()` will receive a following input:\n```py\n[\"component\", '\"button\"', 'href=\"...\"', 'disabled']\n```\n
-
TagFormatter
extracts the component name and the remaining input.
So, given the above, TagFormatter.parse()
returns the following:
TagResult(\n component_name=\"button\",\n tokens=['href=\"...\"', 'disabled']\n)\n
5. The tag handler resumes, using the tokens returned from TagFormatter
. So, continuing the example, at this point the tag handler practically behaves as if you rendered:
{% component href=\"...\" disabled %}\n
6. Tag handler looks up the component button
, and passes the args, kwargs, and slots to it.
"},{"location":"#tagformatter","title":"TagFormatter","text":"TagFormatter
handles following parts of the process above: - Generates start/end tags, given a component. This is what you then call from within your template as {% component %}
.
- When you
{% component %}
, tag formatter pre-processes the tag contents, so it can link back the custom template tag to the right component.
To do so, subclass from TagFormatterABC
and implement following method: - start_tag
- end_tag
- parse
For example, this is the implementation of ShorthandComponentFormatter
class ShorthandComponentFormatter(TagFormatterABC):\n # Given a component name, generate the start template tag\n def start_tag(self, name: str) -> str:\n return name # e.g. 'button'\n\n # Given a component name, generate the start template tag\n def end_tag(self, name: str) -> str:\n return f\"end{name}\" # e.g. 'endbutton'\n\n # Given a tag, e.g.\n # `{% button href=\"...\" disabled %}`\n #\n # The parser receives:\n # `['button', 'href=\"...\"', 'disabled']`\n def parse(self, tokens: List[str]) -> TagResult:\n tokens = [*tokens]\n name = tokens.pop(0)\n return TagResult(\n name, # e.g. 'button'\n tokens # e.g. ['href=\"...\"', 'disabled']\n )\n
That's it! And once your TagFormatter
is ready, don't forget to update the settings!
"},{"location":"#defining-htmljscss-files","title":"Defining HTML/JS/CSS files","text":"django_component's management of files builds on top of Django's Media
class.
To be familiar with how Django handles static files, we recommend reading also:
- How to manage static files (e.g. images, JavaScript, CSS)
"},{"location":"#defining-file-paths-relative-to-component-or-static-dirs","title":"Defining file paths relative to component or static dirs","text":"As seen in the getting started example, to associate HTML/JS/CSS files with a component, you set them as template_name
, Media.js
and Media.css
respectively:
# In a file [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"template.html\"\n\n class Media:\n css = \"style.css\"\n js = \"script.js\"\n
In the example above, the files are defined relative to the directory where component.py
is.
Alternatively, you can specify the file paths relative to the directories set in STATICFILES_DIRS
.
Assuming that STATICFILES_DIRS
contains path [project root]/components
, we can rewrite the example as:
# In a file [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"calendar/template.html\"\n\n class Media:\n css = \"calendar/style.css\"\n js = \"calendar/script.js\"\n
NOTE: In case of conflict, the preference goes to resolving the files relative to the component's directory.
"},{"location":"#defining-multiple-paths","title":"Defining multiple paths","text":"Each component can have only a single template. However, you can define as many JS or CSS files as you want using a list.
class MyComponent(Component):\n class Media:\n js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n
"},{"location":"#configuring-css-media-types","title":"Configuring CSS Media Types","text":"You can define which stylesheets will be associated with which CSS Media types. You do so by defining CSS files as a dictionary.
See the corresponding Django Documentation.
Again, you can set either a single file or a list of files per media type:
class MyComponent(Component):\n class Media:\n css = {\n \"all\": \"path/to/style1.css\",\n \"print\": \"path/to/style2.css\",\n }\n
class MyComponent(Component):\n class Media:\n css = {\n \"all\": [\"path/to/style1.css\", \"path/to/style2.css\"],\n \"print\": [\"path/to/style3.css\", \"path/to/style4.css\"],\n }\n
NOTE: When you define CSS as a string or a list, the all
media type is implied.
"},{"location":"#supported-types-for-file-paths","title":"Supported types for file paths","text":"File paths can be any of:
str
bytes
PathLike
(__fspath__
method) SafeData
(__html__
method) Callable
that returns any of the above, evaluated at class creation (__new__
)
from pathlib import Path\n\nfrom django.utils.safestring import mark_safe\n\nclass SimpleComponent(Component):\n class Media:\n css = [\n mark_safe('<link href=\"/static/calendar/style.css\" rel=\"stylesheet\" />'),\n Path(\"calendar/style1.css\"),\n \"calendar/style2.css\",\n b\"calendar/style3.css\",\n lambda: \"calendar/style4.css\",\n ]\n js = [\n mark_safe('<script src=\"/static/calendar/script.js\"></script>'),\n Path(\"calendar/script1.js\"),\n \"calendar/script2.js\",\n b\"calendar/script3.js\",\n lambda: \"calendar/script4.js\",\n ]\n
"},{"location":"#path-as-objects","title":"Path as objects","text":"In the example above, you could see that when we used mark_safe
to mark a string as a SafeString
, we had to define the full <script>
/<link>
tag.
This is an extension of Django's Paths as objects feature, where \"safe\" strings are taken as is, and accessed only at render time.
Because of that, the paths defined as \"safe\" strings are NEVER resolved, neither relative to component's directory, nor relative to STATICFILES_DIRS
.
\"Safe\" strings can be used to lazily resolve a path, or to customize the <script>
or <link>
tag for individual paths:
class LazyJsPath:\n def __init__(self, static_path: str) -> None:\n self.static_path = static_path\n\n def __html__(self):\n full_path = static(self.static_path)\n return format_html(\n f'<script type=\"module\" src=\"{full_path}\"></script>'\n )\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"calendar/template.html\"\n\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n\n class Media:\n css = \"calendar/style.css\"\n js = [\n # <script> tag constructed by Media class\n \"calendar/script1.js\",\n # Custom <script> tag\n LazyJsPath(\"calendar/script2.js\"),\n ]\n
"},{"location":"#customize-how-paths-are-rendered-into-html-tags-with-media_class","title":"Customize how paths are rendered into HTML tags with media_class
","text":"Sometimes you may need to change how all CSS <link>
or JS <script>
tags are rendered for a given component. You can achieve this by providing your own subclass of Django's Media
class to component's media_class
attribute.
Normally, the JS and CSS paths are passed to Media
class, which decides how the paths are resolved and how the <link>
and <script>
tags are constructed.
To change how the tags are constructed, you can override the Media.render_js
and Media.render_css
methods:
from django.forms.widgets import Media\nfrom django_components import Component, register\n\nclass MyMedia(Media):\n # Same as original Media.render_js, except\n # the `<script>` tag has also `type=\"module\"`\n def render_js(self):\n tags = []\n for path in self._js:\n if hasattr(path, \"__html__\"):\n tag = path.__html__()\n else:\n tag = format_html(\n '<script type=\"module\" src=\"{}\"></script>',\n self.absolute_path(path)\n )\n return tags\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"calendar/template.html\"\n\n class Media:\n css = \"calendar/style.css\"\n js = \"calendar/script.js\"\n\n # Override the behavior of Media class\n media_class = MyMedia\n
NOTE: The instance of the Media
class (or it's subclass) is available under Component.media
after the class creation (__new__
).
"},{"location":"#rendering-jscss-dependencies","title":"Rendering JS/CSS dependencies","text":"The JS and CSS files included in components are not automatically rendered. Instead, use the following tags to specify where to render the dependencies:
component_dependencies
- Renders both JS and CSS component_js_dependencies
- Renders only JS component_css_dependencies
- Reneders only CSS
JS files are rendered as <script>
tags. CSS files are rendered as <style>
tags.
"},{"location":"#setting-up-componentdependencymiddleware","title":"Setting Up ComponentDependencyMiddleware
","text":"ComponentDependencyMiddleware
is a Django middleware designed to manage and inject CSS/JS dependencies for rendered components dynamically. It ensures that only the necessary stylesheets and scripts are loaded in your HTML responses, based on the components used in your Django templates.
To set it up, add the middleware to your MIDDLEWARE
in settings.py:
MIDDLEWARE = [\n # ... other middleware classes ...\n 'django_components.middleware.ComponentDependencyMiddleware'\n # ... other middleware classes ...\n]\n
Then, enable RENDER_DEPENDENCIES
in setting.py:
COMPONENTS = {\n \"RENDER_DEPENDENCIES\": True,\n # ... other component settings ...\n}\n
"},{"location":"#available-settings","title":"Available settings","text":"All library settings are handled from a global COMPONENTS
variable that is read from settings.py
. By default you don't need it set, there are resonable defaults.
"},{"location":"#configure-the-module-where-components-are-loaded-from","title":"Configure the module where components are loaded from","text":"Configure the location where components are loaded. To do this, add a COMPONENTS
variable to you settings.py
with a list of python paths to load. This allows you to build a structure of components that are independent from your apps.
COMPONENTS = {\n \"libraries\": [\n \"mysite.components.forms\",\n \"mysite.components.buttons\",\n \"mysite.components.cards\",\n ],\n}\n
Where mysite/components/forms.py
may look like this:
@register(\"form_simple\")\nclass FormSimple(Component):\n template = \"\"\"\n <form>\n ...\n </form>\n \"\"\"\n\n@register(\"form_other\")\nclass FormOther(Component):\n template = \"\"\"\n <form>\n ...\n </form>\n \"\"\"\n
In the rare cases when you need to manually trigger the import of libraries, you can use the import_libraries
function:
from django_components import import_libraries\n\nimport_libraries()\n
"},{"location":"#disable-autodiscovery","title":"Disable autodiscovery","text":"If you specify all the component locations with the setting above and have a lot of apps, you can (very) slightly speed things up by disabling autodiscovery.
COMPONENTS = {\n \"autodiscover\": False,\n}\n
"},{"location":"#tune-the-template-cache","title":"Tune the template cache","text":"Each time a template is rendered it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up. By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are using the template
method of a component to render lots of dynamic templates, you can increase this number. To remove the cache limit altogether and cache everything, set template_cache_size to None
.
COMPONENTS = {\n \"template_cache_size\": 256,\n}\n
"},{"location":"#context-behavior-setting","title":"Context behavior setting","text":"NOTE: context_behavior
and slot_context_behavior
options were merged in v0.70.
If you are migrating from BEFORE v0.67, set context_behavior
to \"django\"
. From v0.67 to v0.78 (incl) the default value was \"isolated\"
.
For v0.79 and later, the default is again \"django\"
. See the rationale for change here.
You can configure what variables are available inside the {% fill %}
tags. See Component context and scope.
This has two modes:
\"django\"
- Default - The default Django template behavior.
Inside the {% fill %}
tag, the context variables you can access are a union of:
- All the variables that were OUTSIDE the fill tag, including any loops or with tag
-
Data returned from get_context_data()
of the component that wraps the fill tag.
-
\"isolated\"
- Similar behavior to Vue or React, this is useful if you want to make sure that components don't accidentally access variables defined outside of the component.
Inside the {% fill %}
tag, you can ONLY access variables from 2 places:
get_context_data()
of the component which defined the template (AKA the \"root\" component) - Any loops (
{% for ... %}
) that the {% fill %}
tag is part of.
COMPONENTS = {\n \"context_behavior\": \"isolated\",\n}\n
"},{"location":"#example-django","title":"Example \"django\"","text":"Given this template:
class RootComp(Component):\n template = \"\"\"\n {% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n {% endwith %}\n \"\"\"\n def get_context_data(self):\n return { \"my_var\": 123 }\n
Then if get_context_data()
of the component \"my_comp\"
returns following data:
{ \"my_var\": 456 }\n
Then the template will be rendered as:
456 # my_var\nfeta # cheese\n
Because \"my_comp\"
overshadows the variable \"my_var\"
, so {{ my_var }}
equals 456
.
And variable \"cheese\"
equals feta
, because the fill CAN access all the data defined in the outer layers, like the {% with %}
tag.
"},{"location":"#example-isolated","title":"Example \"isolated\"","text":"Given this template:
class RootComp(Component):\n template = \"\"\"\n {% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n {% endwith %}\n \"\"\"\n def get_context_data(self):\n return { \"my_var\": 123 }\n
Then if get_context_data()
of the component \"my_comp\"
returns following data:
{ \"my_var\": 456 }\n
Then the template will be rendered as:
123 # my_var\n # cheese\n
Because variables \"my_var\"
and \"cheese\"
are searched only inside RootComponent.get_context_data()
. But since \"cheese\"
is not defined there, it's empty.
Notice that the variables defined with the {% with %}
tag are ignored inside the {% fill %}
tag with the \"isolated\"
mode.
"},{"location":"#tag-formatter-setting","title":"Tag formatter setting","text":"Set the TagFormatter
instance.
Can be set either as direct reference, or as an import string;
COMPONENTS = {\n \"tag_formatter\": \"django_components.component_formatter\"\n}\n
Or
from django_components import component_formatter\n\nCOMPONENTS = {\n \"tag_formatter\": component_formatter\n}\n
"},{"location":"#logging-and-debugging","title":"Logging and debugging","text":"Django components supports logging with Django. This can help with troubleshooting.
To configure logging for Django components, set the django_components
logger in LOGGING
in settings.py
(below).
Also see the settings.py
file in sampleproject for a real-life example.
import logging\nimport sys\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n \"handlers\": {\n \"console\": {\n 'class': 'logging.StreamHandler',\n 'stream': sys.stdout,\n },\n },\n \"loggers\": {\n \"django_components\": {\n \"level\": logging.DEBUG,\n \"handlers\": [\"console\"],\n },\n },\n}\n
"},{"location":"#management-command","title":"Management Command","text":"You can use the built-in management command startcomponent
to create a django component. The command accepts the following arguments and options:
-
name
: The name of the component to create. This is a required argument.
-
--path
: The path to the components directory. This is an optional argument. If not provided, the command will use the BASE_DIR
setting from your Django settings.
-
--js
: The name of the JavaScript file. This is an optional argument. The default value is script.js
.
-
--css
: The name of the CSS file. This is an optional argument. The default value is style.css
.
-
--template
: The name of the template file. This is an optional argument. The default value is template.html
.
-
--force
: This option allows you to overwrite existing files if they exist. This is an optional argument.
-
--verbose
: This option allows the command to print additional information during component creation. This is an optional argument.
-
--dry-run
: This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False
.
"},{"location":"#management-command-usage","title":"Management Command Usage","text":"To use the command, run the following command in your terminal:
python manage.py startcomponent <name> --path <path> --js <js_filename> --css <css_filename> --template <template_filename> --force --verbose --dry-run\n
Replace <name>
, <path>
, <js_filename>
, <css_filename>
, and <template_filename>
with your desired values.
"},{"location":"#management-command-examples","title":"Management Command Examples","text":"Here are some examples of how you can use the command:
"},{"location":"#creating-a-component-with-default-settings","title":"Creating a Component with Default Settings","text":"To create a component with the default settings, you only need to provide the name of the component:
python manage.py startcomponent my_component\n
This will create a new component named my_component
in the components
directory of your Django project. The JavaScript, CSS, and template files will be named script.js
, style.css
, and template.html
, respectively.
"},{"location":"#creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"You can also create a component with custom settings by providing additional arguments:
python manage.py startcomponent new_component --path my_components --js my_script.js --css my_style.css --template my_template.html\n
This will create a new component named new_component
in the my_components
directory. The JavaScript, CSS, and template files will be named my_script.js
, my_style.css
, and my_template.html
, respectively.
"},{"location":"#overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"If you want to overwrite an existing component, you can use the --force
option:
python manage.py startcomponent my_component --force\n
This will overwrite the existing my_component
if it exists.
"},{"location":"#simulating-component-creation","title":"Simulating Component Creation","text":"If you want to simulate the creation of a component without actually creating any files, you can use the --dry-run
option:
python manage.py startcomponent my_component --dry-run\n
This will simulate the creation of my_component
without creating any files.
"},{"location":"#community-examples","title":"Community examples","text":"One of our goals with django-components
is to make it easy to share components between projects. If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.
- django-htmx-components: A set of components for use with htmx. Try out the live demo.
"},{"location":"#running-django-components-project-locally","title":"Running django-components project locally","text":""},{"location":"#install-locally-and-run-the-tests","title":"Install locally and run the tests","text":"Start by forking the project by clicking the Fork button up in the right corner in the GitHub . This makes a copy of the repository in your own name. Now you can clone this repository locally and start adding features:
git clone https://github.com/<your GitHub username>/django-components.git\n
To quickly run the tests install the local dependencies by running:
pip install -r requirements-dev.txt\n
Now you can run the tests to make sure everything works as expected:
pytest\n
The library is also tested across many versions of Python and Django. To run tests that way:
pyenv install -s 3.8\npyenv install -s 3.9\npyenv install -s 3.10\npyenv install -s 3.11\npyenv install -s 3.12\npyenv local 3.8 3.9 3.10 3.11 3.12\ntox -p\n
"},{"location":"#developing-against-live-django-app","title":"Developing against live Django app","text":"How do you check that your changes to django-components project will work in an actual Django project?
Use the sampleproject demo project to validate the changes:
- Navigate to sampleproject directory:
cd sampleproject\n
- Install dependencies from the requirements.txt file:
pip install -r requirements.txt\n
- Link to your local version of django-components:
pip install -e ..\n
NOTE: The path (in this case ..
) must point to the directory that has the setup.py
file.
- Start Django server
python manage.py runserver\n
Once the server is up, it should be available at http://127.0.0.1:8000.
To display individual components, add them to the urls.py
, like in the case of http://127.0.0.1:8000/greeting
"},{"location":"#development-guides","title":"Development guides","text":""},{"location":"CHANGELOG/","title":"Release notes","text":"Version 0.93 - Spread operator ...dict
inside template tags. See Spread operator) - Use template tags inside string literals in component inputs. See Use template tags inside component inputs)
\ud83d\udea8\ud83d\udce2 Version 0.92 - BREAKING CHANGE: Component
class is no longer a subclass of View
. To configure the View
class, set the Component.View
nested class. HTTP methods like get
or post
can still be defined directly on Component
class, and Component.as_view()
internally calls Component.View.as_view()
. (See Modifying the View class)
-
The inputs (args, kwargs, slots, context, ...) that you pass to Component.render()
can be accessed from within get_context_data
, get_template_string
and get_template_name
via self.input
. (See Accessing data passed to the component)
-
Typing: Component
class supports generics that specify types for Component.render
(See Adding type hints with Generics)
Version 0.90 - All tags (component
, slot
, fill
, ...) now support \"self-closing\" or \"inline\" form, where you can omit the closing tag:
{# Before #}\n{% component \"button\" %}{% endcomponent %}\n{# After #}\n{% component \"button\" / %}\n
- All tags now support the \"dictionary key\" or \"aggregate\" syntax (kwarg:key=val
): {% component \"button\" attrs:class=\"hidden\" %}\n
- You can change how the components are written in the template with TagFormatter. The default is `django_components.component_formatter`:\n```django\n{% component \"button\" href=\"...\" disabled %}\n Click me!\n{% endcomponent %}\n```\n\nWhile `django_components.shorthand_component_formatter` allows you to write components like so:\n\n```django\n{% button href=\"...\" disabled %}\n Click me!\n{% endbutton %}\n
\ud83d\udea8\ud83d\udce2 Version 0.85 Autodiscovery module resolution changed. Following undocumented behavior was removed:
- Previously, autodiscovery also imported any
[app]/components.py
files, and used SETTINGS_MODULE
to search for component dirs. - To migrate from:
[app]/components.py
- Define each module in COMPONENTS.libraries
setting, or import each module inside the AppConfig.ready()
hook in respective apps.py
files. SETTINGS_MODULE
- Define component dirs using STATICFILES_DIRS
- Previously, autodiscovery handled relative files in
STATICFILES_DIRS
. To align with Django, STATICFILES_DIRS
now must be full paths (Django docs).
\ud83d\udea8\ud83d\udce2 Version 0.81 Aligned the render_to_response
method with the (now public) render
method of Component
class. Moreover, slots passed to these can now be rendered also as functions.
- BREAKING CHANGE: The order of arguments to
render_to_response
has changed.
Version 0.80 introduces dependency injection with the {% provide %}
tag and inject()
method.
\ud83d\udea8\ud83d\udce2 Version 0.79
- BREAKING CHANGE: Default value for the
COMPONENTS.context_behavior
setting was changes from \"isolated\"
to \"django\"
. If you did not set this value explicitly before, this may be a breaking change. See the rationale for change here.
\ud83d\udea8\ud83d\udce2 Version 0.77 CHANGED the syntax for accessing default slot content.
- Previously, the syntax was
{% fill \"my_slot\" as \"alias\" %}
and {{ alias.default }}
. - Now, the syntax is
{% fill \"my_slot\" default=\"alias\" %}
and {{ alias }}
.
Version 0.74 introduces html_attrs
tag and prefix:key=val
construct for passing dicts to components.
\ud83d\udea8\ud83d\udce2 Version 0.70
{% if_filled \"my_slot\" %}
tags were replaced with {{ component_vars.is_filled.my_slot }}
variables. - Simplified settings -
slot_context_behavior
and context_behavior
were merged. See the documentation for more details.
Version 0.67 CHANGED the default way how context variables are resolved in slots. See the documentation for more details.
\ud83d\udea8\ud83d\udce2 Version 0.5 CHANGES THE SYNTAX for components. component_block
is now component
, and component
blocks need an ending endcomponent
tag. The new python manage.py upgradecomponent
command can be used to upgrade a directory (use --path argument to point to each dir) of templates that use components to the new syntax automatically.
This change is done to simplify the API in anticipation of a 1.0 release of django_components. After 1.0 we intend to be stricter with big changes like this in point releases.
Version 0.34 adds components as views, which allows you to handle requests and render responses from within a component. See the documentation for more details.
Version 0.28 introduces 'implicit' slot filling and the default
option for slot
tags.
Version 0.27 adds a second installable app: django_components.safer_staticfiles. It provides the same behavior as django.contrib.staticfiles but with extra security guarantees (more info below in Security Notes).
Version 0.26 changes the syntax for {% slot %}
tags. From now on, we separate defining a slot ({% slot %}
) from filling a slot with content ({% fill %}
). This means you will likely need to change a lot of slot tags to fill. We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice featuPpre to have access to. Hoping that this will feel worth it!
Version 0.22 starts autoimporting all files inside components subdirectores, to simplify setup. An existing project might start to get AlreadyRegistered-errors because of this. To solve this, either remove your custom loading of components, or set \"autodiscover\": False in settings.COMPONENTS.
Version 0.17 renames Component.context
and Component.template
to get_context_data
and get_template_name
. The old methods still work, but emit a deprecation warning. This change was done to sync naming with Django's class based views, and make using django-components more familiar to Django users. Component.context
and Component.template
will be removed when version 1.0 is released.
Static files
Components can be organized however you prefer. That said, our prefered way is to keep the files of a component close together by bundling them in the same directory. This means that files containing backend logic, such as Python modules and HTML templates, live in the same directory as static files, e.g. JS and CSS.
If your are using django.contrib.staticfiles to collect static files, no distinction is 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.
As of v0.27, django-components ships with an additional installable app django_components.safer_staticfiles. It is a drop-in replacement for django.contrib.staticfiles. Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server. To use it, add it to INSTALLED_APPS and remove django.contrib.staticfiles.
INSTALLED_APPS = [\n # 'django.contrib.staticfiles', # <-- REMOVE\n 'django_components',\n 'django_components.safer_staticfiles' # <-- ADD\n]\n
If you are on an older version of django-components, your alternatives are a) passing --ignore <pattern>
options to the collecstatic CLI command, or b) defining a subclass of StaticFilesConfig. Both routes are described in the official docs of the staticfiles app.
Note that safer_staticfiles
excludes the .py
and .html
files for collectstatic command:
python manage.py collectstatic\n
but it is ignored on the development server:
python manage.py runserver\n
For a step-by-step guide on deploying production server with static files, see the demo project.
Optional
To avoid loading the app in each template using {% load component_tags %}
, you can add the tag as a 'builtin' in settings.py
TEMPLATES = [\n {\n ...,\n 'OPTIONS': {\n 'context_processors': [\n ...\n ],\n 'builtins': [\n 'django_components.templatetags.component_tags',\n ]\n },\n },\n]\n
Read on to find out how to build your first component!
Create your first component
A component in django-components is the combination of four things: CSS, Javascript, a Django template, and some Python code to put them all together.
sampleproject/\n \u251c\u2500\u2500 calendarapp/\n \u251c\u2500\u2500 components/ \ud83c\udd95\n \u2502 \u2514\u2500\u2500 calendar/ \ud83c\udd95\n \u2502 \u251c\u2500\u2500 calendar.py \ud83c\udd95\n \u2502 \u251c\u2500\u2500 script.js \ud83c\udd95\n \u2502 \u251c\u2500\u2500 style.css \ud83c\udd95\n \u2502 \u2514\u2500\u2500 template.html \ud83c\udd95\n \u251c\u2500\u2500 sampleproject/\n \u251c\u2500\u2500 manage.py\n \u2514\u2500\u2500 requirements.txt\n
Start by creating empty files in the structure above.
First, you need a CSS file. Be sure to prefix all rules with a unique class so they don't clash with other rules.
[project root]/components/calendar/style.css/* In a file called [project root]/components/calendar/style.css */\n.calendar-component {\n width: 200px;\n background: pink;\n}\n.calendar-component span {\n font-weight: bold;\n}\n
Then you need a javascript file that specifies how you interact with this component. You are free to use any javascript framework you want. A good way to make sure this component doesn't clash with other components is to define all code inside an anonymous function that calls itself. This makes all variables defined only be defined inside this component and not affect other components.
[project root]/components/calendar/script.js/* In a file called [project root]/components/calendar/script.js */\n(function () {\n if (document.querySelector(\".calendar-component\")) {\n document.querySelector(\".calendar-component\").onclick = function () {\n alert(\"Clicked calendar!\");\n };\n }\n})();\n
Now you need a Django template for your component. Feel free to define more variables like date
in this example. When creating an instance of this component we will send in the values for these variables. The template will be rendered with whatever template backend you've specified in your Django settings file.
[project root]/components/calendar/calendar.html{# In a file called [project root]/components/calendar/template.html #}\n<div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n
Finally, we use django-components to tie this together. Start by creating a file called calendar.py
in your component calendar directory. It will be auto-detected and loaded by the app.
Inside this file we create a Component by inheriting from the Component class and specifying the context method. We also register the global component registry so that we easily can render it anywhere in our templates.
[project root]/components/calendar/calendar.py## In a file called [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n # Templates inside `[your apps]/components` dir and `[project root]/components` dir\n # will be automatically found. To customize which template to use based on context\n # you can override method `get_template_name` instead of specifying `template_name`.\n #\n # `template_name` can be relative to dir where `calendar.py` is, or relative to STATICFILES_DIRS\n template_name = \"template.html\"\n\n # This component takes one parameter, a date string to show in the template\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n\n # Both `css` and `js` can be relative to dir where `calendar.py` is, or relative to STATICFILES_DIRS\n class Media:\n css = \"style.css\"\n js = \"script.js\"\n
And voil\u00e1!! We've created our first component.
Syntax highlight and code assistance
"},{"location":"CHANGELOG/#pycharm-or-other-jetbrains-ides","title":"Pycharm (or other Jetbrains IDEs)","text":"If you're a Pycharm user (or any other editor from Jetbrains), you can have coding assistance as well:
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n\n # language=HTML\n template= \"\"\"\n <div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n \"\"\"\n\n # language=CSS\n css = \"\"\"\n .calendar-component { width: 200px; background: pink; }\n .calendar-component span { font-weight: bold; }\n \"\"\"\n\n # language=JS\n js = \"\"\"\n (function(){\n if (document.querySelector(\".calendar-component\")) {\n document.querySelector(\".calendar-component\").onclick = function(){ alert(\"Clicked calendar!\"); };\n }\n })()\n \"\"\"\n
You don't need to use types.django_html
, types.css
, types.js
since Pycharm uses language injections. You only need to write the comments # language=<lang>
above the variables.
Use components outside of templates
New in version 0.81
Components can be rendered outside of Django templates, calling them as regular functions (\"React-style\").
The component class defines render
and render_to_response
class methods. These methods accept positional args, kwargs, and slots, offering the same flexibility as the {% component %}
tag:
class SimpleComponent(Component):\n template = \"\"\"\n {% load component_tags %}\n hello: {{ hello }}\n foo: {{ foo }}\n kwargs: {{ kwargs|safe }}\n slot_first: {% slot \"first\" required / %}\n \"\"\"\n\n def get_context_data(self, arg1, arg2, **kwargs):\n return {\n \"hello\": arg1,\n \"foo\": arg2,\n \"kwargs\": kwargs,\n }\n\nrendered = SimpleComponent.render(\n args=[\"world\", \"bar\"],\n kwargs={\"kw1\": \"test\", \"kw2\": \"ooo\"},\n slots={\"first\": \"FIRST_SLOT\"},\n context={\"from_context\": 98},\n)\n
Renders:
hello: world\nfoo: bar\nkwargs: {'kw1': 'test', 'kw2': 'ooo'}\nslot_first: FIRST_SLOT\n
"},{"location":"CHANGELOG/#slotfunc","title":"SlotFunc
","text":"When rendering components with slots in render
or render_to_response
, you can pass either a string or a function.
The function has following signature:
def render_func(\n context: Context,\n data: Dict[str, Any],\n slot_ref: SlotRef,\n) -> str | SafeString:\n return nodelist.render(ctx)\n
context
- Django's Context available to the Slot Node. data
- Data passed to the {% slot %}
tag. See Scoped Slots. slot_ref
- The default slot content. See Accessing original content of slots. - NOTE: The slot is lazily evaluated. To render the slot, convert it to string with
str(slot_ref)
.
Example:
def footer_slot(ctx, data, slot_ref):\n return f\"\"\"\n SLOT_DATA: {data['abc']}\n ORIGINAL: {slot_ref}\n \"\"\"\n\nMyComponent.render_to_response(\n slots={\n \"footer\": footer_slot,\n },\n)\n
"},{"location":"CHANGELOG/#response-class-of-render_to_response","title":"Response class of render_to_response
","text":"While render
method returns a plain string, render_to_response
wraps the rendered content in a \"Response\" class. By default, this is django.http.HttpResponse
.
If you want to use a different Response class in render_to_response
, set the Component.response_class
attribute:
class MyResponse(HttpResponse):\n def __init__(self, *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n # Configure response\n self.headers = ...\n self.status = ...\n\nclass SimpleComponent(Component):\n response_class = MyResponse\n template: types.django_html = \"HELLO\"\n\nresponse = SimpleComponent.render_to_response()\nassert isinstance(response, MyResponse)\n
Component as view example
Here's an example of a calendar component defined as a view:
## In a file called [project root]/components/calendar.py\nfrom django_components import Component, ComponentView, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n\n template = \"\"\"\n <div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" / %}\n </div>\n <div class=\"body\">\n Today's date is <span>{{ date }}</span>\n </div>\n </div>\n \"\"\"\n\n # Handle GET requests\n def get(self, request, *args, **kwargs):\n context = {\n \"date\": request.GET.get(\"date\", \"2020-06-06\"),\n }\n slots = {\n \"header\": \"Calendar header\",\n }\n # Return HttpResponse with the rendered content\n return self.render_to_response(\n context=context,\n slots=slots,\n )\n
Then, to use this component as a view, you should create a urls.py
file in your components directory, and add a path to the component's view:
## In a file called [project root]/components/urls.py\nfrom django.urls import path\nfrom components.calendar.calendar import Calendar\n\nurlpatterns = [\n path(\"calendar/\", Calendar.as_view()),\n]\n
Component.as_view()
is a shorthand for calling View.as_view()
and passing the component instance as one of the arguments.
Remember to add __init__.py
to your components directory, so that Django can find the urls.py
file.
Finally, include the component's urls in your project's urls.py
file:
## In a file called [project root]/urls.py\nfrom django.urls import include, path\n\nurlpatterns = [\n path(\"components/\", include(\"components.urls\")),\n]\n
Note: Slots content are automatically escaped by default to prevent XSS attacks. To disable escaping, set escape_slots_content=False
in the render_to_response
method. If you do so, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.
If you're planning on passing an HTML string, check Django's use of format_html
and mark_safe
.
"},{"location":"CHANGELOG/#registering-components","title":"Registering components","text":"In previous examples you could repeatedly see us using @register()
to \"register\" the components. In this section we dive deeper into what it actually means and how you can manage (add or remove) components.
As a reminder, we may have a component like this:
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"template.html\"\n\n # This component takes one parameter, a date string to show in the template\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n
which we then render in the template as:
{% component \"calendar\" date=\"1970-01-01\" %}\n{% endcomponent %}\n
As you can see, @register
links up the component class with the {% component %}
template tag. So when the template tag comes across a component called \"calendar\"
, it can look up it's class and instantiate it.
"},{"location":"CHANGELOG/#working-with-componentregistry","title":"Working with ComponentRegistry","text":"The default ComponentRegistry
instance can be imported as:
from django_components import registry\n
You can use the registry to manually add/remove/get components:
from django_components import registry\n\n## Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n## Get all or single\nregistry.all() # {\"button\": ButtonComponent, \"card\": CardComponent}\nregistry.get(\"card\") # CardComponent\n\n## Unregister single component\nregistry.unregister(\"card\")\n\n## Unregister all components\nregistry.clear()\n
"},{"location":"CHANGELOG/#autodiscovery","title":"Autodiscovery","text":"Every component that you want to use in the template with the {% component %}
tag needs to be registered with the ComponentRegistry. Normally, we use the @register
decorator for that:
from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n ...\n
But for the component to be registered, the code needs to be executed - the file needs to be imported as a module.
One way to do that is by importing all your components in apps.py
:
from django.apps import AppConfig\n\nclass MyAppConfig(AppConfig):\n name = \"my_app\"\n\n def ready(self) -> None:\n from components.card.card import Card\n from components.list.list import List\n from components.menu.menu import Menu\n from components.button.button import Button\n ...\n
However, there's a simpler way!
By default, the Python files in the STATICFILES_DIRS
directories are auto-imported in order to auto-register the components.
Autodiscovery occurs when Django is loaded, during the ready
hook of the apps.py
file.
If you are using autodiscovery, keep a few points in mind:
- Avoid defining any logic on the module-level inside the
components
dir, that you would not want to run anyway. - Components inside the auto-imported files still need to be registered with
@register()
- Auto-imported component files must be valid Python modules, they must use suffix
.py
, and module name should follow PEP-8.
Autodiscovery can be disabled in the settings.
"},{"location":"CHANGELOG/#using-slots-in-templates","title":"Using slots in templates","text":"New in version 0.26:
- The
slot
tag now serves only to declare new slots inside the component template. - To override the content of a declared slot, use the newly introduced
fill
tag instead. - Whereas unfilled slots used to raise a warning, filling a slot is now optional by default.
- To indicate that a slot must be filled, the new
required
option should be added at the end of the slot
tag.
Components support something called 'slots'. When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content. This mechanism makes components more reusable and composable. This behavior is similar to slots in Vue.
In the example below we introduce two block tags that work hand in hand to make this work. These are...
{% slot <name> %}
/{% endslot %}
: Declares a new slot in the component template. {% fill <name> %}
/{% endfill %}
: (Used inside a component
tag pair.) Fills a declared slot with the specified content.
Let's update our calendar component to support more customization. We'll add slot
tag pairs to its template, template.html.
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" %}Calendar header{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"body\" %}Today's date is <span>{{ date }}</span>{% endslot %}\n </div>\n</div>\n
When using the component, you specify which slots you want to fill and where you want to use the defaults from the template. It looks like this:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"body\" %}Can you believe it's already <span>{{ date }}</span>??{% endfill %}\n{% endcomponent %}\n
Since the 'header' fill is unspecified, it's taken from the base template. If you put this in a template, and pass in date=2020-06-06
, this is what gets rendered:
<div class=\"calendar-component\">\n <div class=\"header\">\n Calendar header\n </div>\n <div class=\"body\">\n Can you believe it's already <span>2020-06-06</span>??\n </div>\n</div>\n
"},{"location":"CHANGELOG/#render-fill-in-multiple-places","title":"Render fill in multiple places","text":"Added in version 0.70
You can render the same content in multiple places by defining multiple slots with identical names:
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"image\" %}Image here{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"image\" %}Image here{% endslot %}\n </div>\n</div>\n
So if used like:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"image\" %}\n <img src=\"...\" />\n {% endfill %}\n{% endcomponent %}\n
This renders:
<div class=\"calendar-component\">\n <div class=\"header\">\n <img src=\"...\" />\n </div>\n <div class=\"body\">\n <img src=\"...\" />\n </div>\n</div>\n
"},{"location":"CHANGELOG/#accessing-original-content-of-slots","title":"Accessing original content of slots","text":"Added in version 0.26
NOTE: In version 0.77, the syntax was changed from
{% fill \"my_slot\" as \"alias\" %} {{ alias.default }}\n
to
{% fill \"my_slot\" default=\"slot_default\" %} {{ slot_default }}\n
Sometimes you may want to keep the original slot, but only wrap or prepend/append content to it. To do so, you can access the default slot via the default
kwarg.
Similarly to the data
attribute, you specify the variable name through which the default slot will be made available.
For instance, let's say you're filling a slot called 'body'. To render the original slot, assign it to a variable using the 'default'
keyword. You then render this variable to insert the default content:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"body\" default=\"body_default\" %}\n {{ body_default }}. Have a great day!\n {% endfill %}\n{% endcomponent %}\n
This produces:
<div class=\"calendar-component\">\n <div class=\"header\">\n Calendar header\n </div>\n <div class=\"body\">\n Today's date is <span>2020-06-06</span>. Have a great day!\n </div>\n</div>\n
"},{"location":"CHANGELOG/#accessing-is_filled-of-slot-names-with-special-characters","title":"Accessing is_filled
of slot names with special characters","text":"To be able to access a slot name via component_vars.is_filled
, the slot name needs to be composed of only alphanumeric characters and underscores (e.g. this__isvalid_123
).
However, you can still define slots with other special characters. In such case, the slot name in component_vars.is_filled
is modified to replace all invalid characters into _
.
So a slot named \"my super-slot :)\"
will be available as component_vars.is_filled.my_super_slot___
.
"},{"location":"CHANGELOG/#passing-data-to-slots","title":"Passing data to slots","text":"To pass the data to the slot
tag, simply pass them as keyword attributes (key=value
):
@register(\"my_comp\")\nclass MyComp(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" default input=input %}\n input: {{ input }}\n {% endslot %}\n </div>\n \"\"\"\n\n def get_context_data(self, input):\n processed_input = do_something(input)\n return {\n \"input\": processed_input,\n }\n
"},{"location":"CHANGELOG/#passing-data-to-components","title":"Passing data to components","text":"As seen above, you can pass arguments to components like so:
<body>\n {% component \"calendar\" date=\"2015-06-19\" %}\n {% endcomponent %}\n</body>\n
"},{"location":"CHANGELOG/#rendering-html-attributes","title":"Rendering HTML attributes","text":"New in version 0.74:
You can use the html_attrs
tag to render HTML attributes, given a dictionary of values.
So if you have a template:
<div class=\"{{ classes }}\" data-id=\"{{ my_id }}\">\n</div>\n
You can simplify it with html_attrs
tag:
<div {% html_attrs attrs %}>\n</div>\n
where attrs
is:
attrs = {\n \"class\": classes,\n \"data-id\": my_id,\n}\n
This feature is inspired by merge_attrs
tag of django-web-components and \"fallthrough attributes\" feature of Vue.
"},{"location":"CHANGELOG/#boolean-attributes","title":"Boolean attributes","text":"In HTML, boolean attributes are usually rendered with no value. Consider the example below where the first button is disabled and the second is not:
<button disabled>Click me!</button> <button>Click me!</button>\n
HTML rendering with html_attrs
tag or attributes_to_string
works the same way, where key=True
is rendered simply as key
, and key=False
is not render at all.
So given this input:
attrs = {\n \"disabled\": True,\n \"autofocus\": False,\n}\n
And template:
<div {% html_attrs attrs %}>\n</div>\n
Then this renders:
<div disabled></div>\n
"},{"location":"CHANGELOG/#appending-attributes","title":"Appending attributes","text":"For the class
HTML attribute, it's common that we want to join multiple values, instead of overriding them. For example, if you're authoring a component, you may want to ensure that the component will ALWAYS have a specific class. Yet, you may want to allow users of your component to supply their own classes.
We can achieve this by adding extra kwargs. These values will be appended, instead of overwriting the previous value.
So if we have a variable attrs
:
attrs = {\n \"class\": \"my-class pa-4\",\n}\n
And on html_attrs
tag, we set the key class
:
<div {% html_attrs attrs class=\"some-class\" %}>\n</div>\n
Then these will be merged and rendered as:
<div data-value=\"my-class pa-4 some-class\"></div>\n
To simplify merging of variables, you can supply the same key multiple times, and these will be all joined together:
{# my_var = \"class-from-var text-red\" #}\n<div {% html_attrs attrs class=\"some-class another-class\" class=my_var %}>\n</div>\n
Renders:
<div\n data-value=\"my-class pa-4 some-class another-class class-from-var text-red\"\n></div>\n
"},{"location":"CHANGELOG/#examples-for-html_attrs","title":"Examples for html_attrs
","text":"Assuming that:
class_from_var = \"from-var\"\n\nattrs = {\n \"class\": \"from-attrs\",\n \"type\": \"submit\",\n}\n\ndefaults = {\n \"class\": \"from-defaults\",\n \"role\": \"button\",\n}\n
Then:
- Empty tag
{% html_attr %}
renders (empty string):
- Only kwargs
{% html_attr class=\"some-class\" class=class_from_var data-id=\"123\" %}
renders: class=\"some-class from-var\" data-id=\"123\"
- Only attrs
{% html_attr attrs %}
renders: class=\"from-attrs\" type=\"submit\"
- Attrs as kwarg
{% html_attr attrs=attrs %}
renders: class=\"from-attrs\" type=\"submit\"
- Only defaults (as kwarg)
{% html_attr defaults=defaults %}
renders: class=\"from-defaults\" role=\"button\"
- Attrs using the
prefix:key=value
construct {% html_attr attrs:class=\"from-attrs\" attrs:type=\"submit\" %}
renders: class=\"from-attrs\" type=\"submit\"
- Defaults using the
prefix:key=value
construct {% html_attr defaults:class=\"from-defaults\" %}
renders: class=\"from-defaults\" role=\"button\"
- All together (1) - attrs and defaults as positional args:
{% html_attrs attrs defaults class=\"added_class\" class=class_from_var data-id=123 %}
renders: class=\"from-attrs added_class from-var\" type=\"submit\" role=\"button\" data-id=123
- All together (2) - attrs and defaults as kwargs args:
{% html_attrs class=\"added_class\" class=class_from_var data-id=123 attrs=attrs defaults=defaults %}
renders: class=\"from-attrs added_class from-var\" type=\"submit\" role=\"button\" data-id=123
- All together (3) - mixed:
{% html_attrs attrs defaults:class=\"default-class\" class=\"added_class\" class=class_from_var data-id=123 %}
renders: class=\"from-attrs added_class from-var\" type=\"submit\" data-id=123
"},{"location":"CHANGELOG/#rendering-html-attributes-outside-of-templates","title":"Rendering HTML attributes outside of templates","text":"If you need to use serialize HTML attributes outside of Django template and the html_attrs
tag, you can use attributes_to_string
:
from django_components.attributes import attributes_to_string\n\nattrs = {\n \"class\": \"my-class text-red pa-4\",\n \"data-id\": 123,\n \"required\": True,\n \"disabled\": False,\n \"ignored-attr\": None,\n}\n\nattributes_to_string(attrs)\n## 'class=\"my-class text-red pa-4\" data-id=\"123\" required'\n
Special characters
New in version 0.71:
Keyword arguments can contain special characters # @ . - _
, so keywords like so are still valid:
<body>\n {% component \"calendar\" my-date=\"2015-06-19\" @click.native=do_something #some_id=True / %}\n</body>\n
These can then be accessed inside get_context_data
so:
@register(\"calendar\")\nclass Calendar(Component):\n # Since # . @ - are not valid identifiers, we have to\n # use `**kwargs` so the method can accept these args.\n def get_context_data(self, **kwargs):\n return {\n \"date\": kwargs[\"my-date\"],\n \"id\": kwargs[\"#some_id\"],\n \"on_click\": kwargs[\"@click.native\"]\n }\n
"},{"location":"CHANGELOG/#use-template-tags-inside-component-inputs","title":"Use template tags inside component inputs","text":"New in version 0.93
When passing data around, sometimes you may need to do light transformations, like negating booleans or filtering lists.
Normally, what you would have to do is to define ALL the variables inside get_context_data()
. But this can get messy if your components contain a lot of logic.
@register(\"calendar\")\nclass Calendar(Component):\n def get_context_data(self, id: str, editable: bool):\n return {\n \"editable\": editable,\n \"readonly\": not editable,\n \"input_id\": f\"input-{id}\",\n \"icon_id\": f\"icon-{id}\",\n ...\n }\n
Instead, template tags in django_components ({% component %}
, {% slot %}
, {% provide %}
, etc) allow you to treat literal string values as templates:
{% component 'blog_post'\n \"As positional arg {# yay #}\"\n title=\"{{ person.first_name }} {{ person.last_name }}\"\n id=\"{% random_int 10 20 %}\"\n author=\"John Wick {# TODO: parametrize #}\"\n/ %}\n
In the example above: - Component test
receives a positional argument with value \"As positional arg \"
. The comment is omitted. - Kwarg title
is passed as a string, e.g. John Doe
- Kwarg id
is passed as int
, e.g. 15
- Kwarg author
is passed as a string, e.g. John Wick
(Comment omitted)
This is inspired by django-cotton.
"},{"location":"CHANGELOG/#evaluating-python-expressions-in-template","title":"Evaluating Python expressions in template","text":"You can even go a step further and have a similar experience to Vue or React, where you can evaluate arbitrary code expressions:
<MyForm\n value={ isEnabled ? inputValue : null }\n/>\n
Similar is possible with django-expr
, which adds an expr
tag and filter that you can use to evaluate Python expressions from within the template:
{% component \"my_form\"\n value=\"{% expr 'input_value if is_enabled else None' %}\"\n/ %}\n
Note: Never use this feature to mix business logic and template logic. Business logic should still be in the template!
"},{"location":"CHANGELOG/#prop-drilling-and-dependency-injection-provide-inject","title":"Prop drilling and dependency injection (provide / inject)","text":"New in version 0.80:
Django components supports dependency injection with the combination of:
{% provide %}
tag inject()
method of the Component
class
"},{"location":"CHANGELOG/#how-to-use-provide-inject","title":"How to use provide / inject","text":"As the name suggest, using provide / inject consists of 2 steps
- Providing data
- Injecting provided data
For examples of advanced uses of provide / inject, see this discussion.
"},{"location":"CHANGELOG/#using-inject-method","title":"Using inject()
method","text":"To \"inject\" (access) the data defined on the provide
tag, you can use the inject()
method inside of get_context_data()
.
For a component to be able to \"inject\" some data, the component ({% component %}
tag) must be nested inside the {% provide %}
tag.
In the example from previous section, we've defined two kwargs: key=\"hi\" another=123
. That means that if we now inject \"my_data\"
, we get an object with 2 attributes - key
and another
.
class ChildComponent(Component):\n def get_context_data(self):\n my_data = self.inject(\"my_data\")\n print(my_data.key) # hi\n print(my_data.another) # 123\n return {}\n
First argument to inject
is the key of the provided data. This must match the string that you used in the provide
tag. If no provider with given key is found, inject
raises a KeyError
.
To avoid the error, you can pass a second argument to inject
to which will act as a default value, similar to dict.get(key, default)
:
class ChildComponent(Component):\n def get_context_data(self):\n my_data = self.inject(\"invalid_key\", DEFAULT_DATA)\n assert my_data == DEFAUKT_DATA\n return {}\n
The instance returned from inject()
is a subclass of NamedTuple
, so the instance is immutable. This ensures that the data returned from inject
will always have all the keys that were passed to the provide
tag.
NOTE: inject()
works strictly only in get_context_data
. If you try to call it from elsewhere, it will raise an error.
"},{"location":"CHANGELOG/#component-context-and-scope","title":"Component context and scope","text":"By default, context variables are passed down the template as in regular Django - deeper scopes can access the variables from the outer scopes. So if you have several nested forloops, then inside the deep-most loop you can access variables defined by all previous loops.
With this in mind, the {% component %}
tag behaves similarly to {% include %}
tag - inside the component tag, you can access all variables that were defined outside of it.
And just like with {% include %}
, if you don't want a specific component template to have access to the parent context, add only
to the {% component %}
tag:
{% component \"calendar\" date=\"2015-06-19\" only %}{% endcomponent %}\n
NOTE: {% csrf_token %}
tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the only
modifier.
If you find yourself using the only
modifier often, you can set the context_behavior option to \"isolated\"
, which automatically applies the only
modifier. This is useful if you want to make sure that components don't accidentally access the outer context.
Components can also access the outer context in their context methods like get_context_data
by accessing the property self.outer_context
.
Available TagFormatters
django_components provides following predefined TagFormatters:
-
ComponentFormatter
(django_components.component_formatter
)
Default
Uses the component
and endcomponent
tags, and the component name is gives as the first positional argument.
Example as block:
{% component \"button\" href=\"...\" %}\n {% fill \"content\" %}\n ...\n {% endfill %}\n{% endcomponent %}\n
Example as inlined tag:
{% component \"button\" href=\"...\" / %}\n
-
ShorthandComponentFormatter
(django_components.shorthand_component_formatter
)
Uses the component name as start tag, and end<component_name>
as an end tag.
Example as block:
{% button href=\"...\" %}\n Click me!\n{% endbutton %}\n
Example as inlined tag:
{% button href=\"...\" / %}\n
"},{"location":"CHANGELOG/#background","title":"Background","text":"First, let's discuss how TagFormatters work, and how components are rendered in django_components.
When you render a component with {% component %}
(or your own tag), the following happens: 1. component
must be registered as a Django's template tag 2. Django triggers django_components's tag handler for tag component
. 3. The tag handler passes the tag contents for pre-processing to TagFormatter.parse()
.
So if you render this:\n```django\n{% component \"button\" href=\"...\" disabled %}\n{% endcomponent %}\n```\n\nThen `TagFormatter.parse()` will receive a following input:\n```py\n[\"component\", '\"button\"', 'href=\"...\"', 'disabled']\n```\n
-
TagFormatter
extracts the component name and the remaining input.
So, given the above, TagFormatter.parse()
returns the following:
TagResult(\n component_name=\"button\",\n tokens=['href=\"...\"', 'disabled']\n)\n
5. The tag handler resumes, using the tokens returned from TagFormatter
. So, continuing the example, at this point the tag handler practically behaves as if you rendered:
{% component href=\"...\" disabled %}\n
6. Tag handler looks up the component button
, and passes the args, kwargs, and slots to it.
"},{"location":"CHANGELOG/#defining-htmljscss-files","title":"Defining HTML/JS/CSS files","text":"django_component's management of files builds on top of Django's Media
class.
To be familiar with how Django handles static files, we recommend reading also:
- How to manage static files (e.g. images, JavaScript, CSS)
"},{"location":"CHANGELOG/#defining-multiple-paths","title":"Defining multiple paths","text":"Each component can have only a single template. However, you can define as many JS or CSS files as you want using a list.
class MyComponent(Component):\n class Media:\n js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n
"},{"location":"CHANGELOG/#supported-types-for-file-paths","title":"Supported types for file paths","text":"File paths can be any of:
str
bytes
PathLike
(__fspath__
method) SafeData
(__html__
method) Callable
that returns any of the above, evaluated at class creation (__new__
)
from pathlib import Path\n\nfrom django.utils.safestring import mark_safe\n\nclass SimpleComponent(Component):\n class Media:\n css = [\n mark_safe('<link href=\"/static/calendar/style.css\" rel=\"stylesheet\" />'),\n Path(\"calendar/style1.css\"),\n \"calendar/style2.css\",\n b\"calendar/style3.css\",\n lambda: \"calendar/style4.css\",\n ]\n js = [\n mark_safe('<script src=\"/static/calendar/script.js\"></script>'),\n Path(\"calendar/script1.js\"),\n \"calendar/script2.js\",\n b\"calendar/script3.js\",\n lambda: \"calendar/script4.js\",\n ]\n
"},{"location":"CHANGELOG/#customize-how-paths-are-rendered-into-html-tags-with-media_class","title":"Customize how paths are rendered into HTML tags with media_class
","text":"Sometimes you may need to change how all CSS <link>
or JS <script>
tags are rendered for a given component. You can achieve this by providing your own subclass of Django's Media
class to component's media_class
attribute.
Normally, the JS and CSS paths are passed to Media
class, which decides how the paths are resolved and how the <link>
and <script>
tags are constructed.
To change how the tags are constructed, you can override the Media.render_js
and Media.render_css
methods:
from django.forms.widgets import Media\nfrom django_components import Component, register\n\nclass MyMedia(Media):\n # Same as original Media.render_js, except\n # the `<script>` tag has also `type=\"module\"`\n def render_js(self):\n tags = []\n for path in self._js:\n if hasattr(path, \"__html__\"):\n tag = path.__html__()\n else:\n tag = format_html(\n '<script type=\"module\" src=\"{}\"></script>',\n self.absolute_path(path)\n )\n return tags\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"calendar/template.html\"\n\n class Media:\n css = \"calendar/style.css\"\n js = \"calendar/script.js\"\n\n # Override the behavior of Media class\n media_class = MyMedia\n
NOTE: The instance of the Media
class (or it's subclass) is available under Component.media
after the class creation (__new__
).
Setting Up ComponentDependencyMiddleware
ComponentDependencyMiddleware
is a Django middleware designed to manage and inject CSS/JS dependencies for rendered components dynamically. It ensures that only the necessary stylesheets and scripts are loaded in your HTML responses, based on the components used in your Django templates.
To set it up, add the middleware to your MIDDLEWARE
in settings.py:
MIDDLEWARE = [\n # ... other middleware classes ...\n 'django_components.middleware.ComponentDependencyMiddleware'\n # ... other middleware classes ...\n]\n
Then, enable RENDER_DEPENDENCIES
in setting.py:
COMPONENTS = {\n \"RENDER_DEPENDENCIES\": True,\n # ... other component settings ...\n}\n
Configure the module where components are loaded from
Configure the location where components are loaded. To do this, add a COMPONENTS
variable to you settings.py
with a list of python paths to load. This allows you to build a structure of components that are independent from your apps.
COMPONENTS = {\n \"libraries\": [\n \"mysite.components.forms\",\n \"mysite.components.buttons\",\n \"mysite.components.cards\",\n ],\n}\n
Where mysite/components/forms.py
may look like this:
@register(\"form_simple\")\nclass FormSimple(Component):\n template = \"\"\"\n <form>\n ...\n </form>\n \"\"\"\n\n@register(\"form_other\")\nclass FormOther(Component):\n template = \"\"\"\n <form>\n ...\n </form>\n \"\"\"\n
In the rare cases when you need to manually trigger the import of libraries, you can use the import_libraries
function:
from django_components import import_libraries\n\nimport_libraries()\n
"},{"location":"CHANGELOG/#tune-the-template-cache","title":"Tune the template cache","text":"Each time a template is rendered it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up. By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are using the template
method of a component to render lots of dynamic templates, you can increase this number. To remove the cache limit altogether and cache everything, set template_cache_size to None
.
COMPONENTS = {\n \"template_cache_size\": 256,\n}\n
"},{"location":"CHANGELOG/#example-django","title":"Example \"django\"","text":"Given this template:
class RootComp(Component):\n template = \"\"\"\n {% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n {% endwith %}\n \"\"\"\n def get_context_data(self):\n return { \"my_var\": 123 }\n
Then if get_context_data()
of the component \"my_comp\"
returns following data:
{ \"my_var\": 456 }\n
Then the template will be rendered as:
456 # my_var\nfeta # cheese\n
Because \"my_comp\"
overshadows the variable \"my_var\"
, so {{ my_var }}
equals 456
.
And variable \"cheese\"
equals feta
, because the fill CAN access all the data defined in the outer layers, like the {% with %}
tag.
"},{"location":"CHANGELOG/#tag-formatter-setting","title":"Tag formatter setting","text":"Set the TagFormatter
instance.
Can be set either as direct reference, or as an import string;
COMPONENTS = {\n \"tag_formatter\": \"django_components.component_formatter\"\n}\n
Or
from django_components import component_formatter\n\nCOMPONENTS = {\n \"tag_formatter\": component_formatter\n}\n
Management Command
You can use the built-in management command startcomponent
to create a django component. The command accepts the following arguments and options:
-
name
: The name of the component to create. This is a required argument.
-
--path
: The path to the components directory. This is an optional argument. If not provided, the command will use the BASE_DIR
setting from your Django settings.
-
--js
: The name of the JavaScript file. This is an optional argument. The default value is script.js
.
-
--css
: The name of the CSS file. This is an optional argument. The default value is style.css
.
-
--template
: The name of the template file. This is an optional argument. The default value is template.html
.
-
--force
: This option allows you to overwrite existing files if they exist. This is an optional argument.
-
--verbose
: This option allows the command to print additional information during component creation. This is an optional argument.
-
--dry-run
: This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False
.
"},{"location":"CHANGELOG/#management-command-examples","title":"Management Command Examples","text":"Here are some examples of how you can use the command:
"},{"location":"CHANGELOG/#creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"You can also create a component with custom settings by providing additional arguments:
python manage.py startcomponent new_component --path my_components --js my_script.js --css my_style.css --template my_template.html\n
This will create a new component named new_component
in the my_components
directory. The JavaScript, CSS, and template files will be named my_script.js
, my_style.css
, and my_template.html
, respectively.
"},{"location":"CHANGELOG/#simulating-component-creation","title":"Simulating Component Creation","text":"If you want to simulate the creation of a component without actually creating any files, you can use the --dry-run
option:
python manage.py startcomponent my_component --dry-run\n
This will simulate the creation of my_component
without creating any files.
Running django-components project locally
"},{"location":"CHANGELOG/#developing-against-live-django-app","title":"Developing against live Django app","text":"How do you check that your changes to django-components project will work in an actual Django project?
Use the sampleproject demo project to validate the changes:
- Navigate to sampleproject directory:
cd sampleproject\n
- Install dependencies from the requirements.txt file:
pip install -r requirements.txt\n
- Link to your local version of django-components:
pip install -e ..\n
NOTE: The path (in this case ..
) must point to the directory that has the setup.py
file.
- Start Django server
python manage.py runserver\n
Once the server is up, it should be available at http://127.0.0.1:8000.
To display individual components, add them to the urls.py
, like in the case of http://127.0.0.1:8000/greeting
"},{"location":"CODE_OF_CONDUCT/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"CODE_OF_CONDUCT/#our-pledge","title":"Our Pledge","text":"In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
"},{"location":"CODE_OF_CONDUCT/#our-standards","title":"Our Standards","text":"Examples of behavior that contributes to creating a positive environment include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
"},{"location":"CODE_OF_CONDUCT/#our-responsibilities","title":"Our Responsibilities","text":"Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
"},{"location":"CODE_OF_CONDUCT/#scope","title":"Scope","text":"This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
"},{"location":"CODE_OF_CONDUCT/#enforcement","title":"Enforcement","text":"Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at emil@emilstenstrom.se. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
"},{"location":"CODE_OF_CONDUCT/#attribution","title":"Attribution","text":"This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq
"},{"location":"SUMMARY/","title":"SUMMARY","text":" - README
- Changelog
- Code of Conduct
- License
- Reference
- API Reference
"},{"location":"license/","title":"License","text":"MIT License
Copyright (c) 2019 Emil Stenstr\u00f6m
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"},{"location":"slot_rendering/","title":"Slot rendering","text":"This doc serves as a primer on how component slots and fills are resolved.
"},{"location":"slot_rendering/#flow","title":"Flow","text":" -
Imagine you have a template. Some kind of text, maybe HTML:
| ------\n| ---------\n| ----\n| -------\n
-
The template may contain some vars, tags, etc
| -- {{ my_var }} --\n| ---------\n| ----\n| -------\n
-
The template also contains some slots, etc
| -- {{ my_var }} --\n| ---------\n| -- {% slot \"myslot\" %} ---\n| -- {% endslot %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| -- {% endslot %} ---\n| -------\n
-
Slots may be nested
| -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %} ---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- JKL {{ my_var }}\n| -- {% endslot %} ---\n| -------\n
-
Some slots may be inside fills for other components
| -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %}---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ------\n| -- {% component \"mycomp\" %} ---\n| ---- {% slot \"myslot\" %} ---\n| ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n| ---- {% endslot %} ---\n| -- {% endcomponent %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- PQR {{ my_var }}\n| -- {% endslot %} ---\n| -------\n
-
I want to render the slots with {% fill %}
tag that were defined OUTSIDE of this template. How do I do that?
-
Traverse the template to collect ALL slots
- NOTE: I will also look inside
{% slot %}
and {% fill %}
tags, since they are all still defined within the same TEMPLATE.
I should end up with a list like this:
- Name: \"myslot\"\n ID 0001\n Content:\n | ----- DEF {{ my_var }}\n | ----- {% slot \"myslot_inner\" %}\n | -------- GHI {{ my_var }}\n | ----- {% endslot %}\n- Name: \"myslot_inner\"\n ID 0002\n Content:\n | -------- GHI {{ my_var }}\n- Name: \"myslot\"\n ID 0003\n Content:\n | ------- JKL {{ my_var }}\n | ------- {% slot \"myslot_inner\" %}\n | ---------- MNO {{ my_var }}\n | ------- {% endslot %}\n- Name: \"myslot_inner\"\n ID 0004\n Content:\n | ---------- MNO {{ my_var }}\n- Name: \"myslot2\"\n ID 0005\n Content:\n | ---- PQR {{ my_var }}\n
-
Note the relationships - which slot is nested in which one
I should end up with a graph-like data like:
- 0001: [0002]\n- 0002: []\n- 0003: [0004]\n- 0004: []\n- 0005: []\n
In other words, the data tells us that slot ID 0001
is PARENT of slot 0002
.
This is important, because, IF parent template provides slot fill for slot 0001, then we DON'T NEED TO render it's children, AKA slot 0002.
-
Find roots of the slot relationships
The data from previous step can be understood also as a collection of directled acyclig graphs (DAG), e.g.:
0001 --> 0002\n0003 --> 0004\n0005\n
So we find the roots (0001
, 0003
, 0005
), AKA slots that are NOT nested in other slots. We do so by going over ALL entries from previous step. Those IDs which are NOT mentioned in ANY of the lists are the roots.
Because of the nature of nested structures, there cannot be any cycles.
-
Recursively render slots, starting from roots.
-
First we take each of the roots.
-
Then we check if there is a slot fill for given slot name.
-
If YES we replace the slot node with the fill node.
-
If NO, then we will replace slot nodes with their children, e.g.:
| ---- {% slot \"myslot\" %} ---\n| ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n| ---- {% endslot %} ---\n
Becomes | ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n
-
We check if the slot includes any children {% slot %}
tags. If YES, then continue with step 4. for them, and wait until they finish.
-
At this point, ALL slots should be rendered and we should have something like this:
| -- {{ my_var }} --\n| -- ABC\n| ----- DEF {{ my_var }}\n| -------- GHI {{ my_var }}\n| ------\n| -- {% component \"mycomp\" %} ---\n| ------- JKL {{ my_var }}\n| ---- {% component \"mycomp\" %} ---\n| ---------- MNO {{ my_var }}\n| ---- {% endcomponent %} ---\n| -- {% endcomponent %} ---\n| ----\n| -- {% component \"mycomp2\" %} ---\n| ---- PQR {{ my_var }}\n| -- {% endcomponent %} ---\n| ----\n
- NOTE: Inserting fills into {% slots %} should NOT introduce new {% slots %}, as the fills should be already rendered!
"},{"location":"slot_rendering/#using-the-correct-context-in-slotfill-tags","title":"Using the correct context in {% slot/fill %} tags","text":"In previous section, we said that the {% fill %}
tags should be already rendered by the time they are inserted into the {% slot %}
tags.
This is not quite true. To help you understand, consider this complex case:
| -- {% for var in [1, 2, 3] %} ---\n| ---- {% component \"mycomp2\" %} ---\n| ------ {% fill \"first\" %}\n| ------- STU {{ my_var }}\n| ------- {{ var }}\n| ------ {% endfill %}\n| ------ {% fill \"second\" %}\n| -------- {% component var=var my_var=my_var %}\n| ---------- VWX {{ my_var }}\n| -------- {% endcomponent %}\n| ------ {% endfill %}\n| ---- {% endcomponent %} ---\n| -- {% endfor %} ---\n| -------\n
We want the forloop variables to be available inside the {% fill %}
tags. Because of that, however, we CANNOT render the fills/slots in advance.
Instead, our solution is closer to how Vue handles slots. In Vue, slots are effectively functions that accept a context variables and render some content.
While we do not wrap the logic in a function, we do PREPARE IN ADVANCE: 1. The content that should be rendered for each slot 2. The context variables from get_context_data()
Thus, once we reach the {% slot %}
node, in it's render()
method, we access the data above, and, depending on the context_behavior
setting, include the current context or not. For more info, see SlotNode.render()
.
"},{"location":"slots_and_blocks/","title":"Using slot
and block
tags","text":" -
First let's clarify how include
and extends
tags work inside components. So when component template includes include
or extends
tags, it's as if the \"included\" template was inlined. So if the \"included\" template contains slot
tags, then the component uses those slots.
So if you have a template `abc.html`:\n```django\n<div>\n hello\n {% slot \"body\" %}{% endslot %}\n</div>\n```\n\nAnd components that make use of `abc.html` via `include` or `extends`:\n```py\nfrom django_components import Component, register\n\n@register(\"my_comp_extends\")\nclass MyCompWithExtends(Component):\n template = \"\"\"{% extends \"abc.html\" %}\"\"\"\n\n@register(\"my_comp_include\")\nclass MyCompWithInclude(Component):\n template = \"\"\"{% include \"abc.html\" %}\"\"\"\n```\n\nThen you can set slot fill for the slot imported via `include/extends`:\n\n```django\n{% component \"my_comp_extends\" %}\n {% fill \"body\" %}\n 123\n {% endfill %}\n{% endcomponent %}\n```\n\nAnd it will render:\n```html\n<div>\n hello\n 123\n</div>\n```\n
-
Slot and block
So if you have a template abc.html
like so:
<div>\n hello\n {% block inner %}\n 1\n {% slot \"body\" %}\n 2\n {% endslot %}\n {% endblock %}\n</div>\n
and component my_comp
:
@register(\"my_comp\")\nclass MyComp(Component):\n template_name = \"abc.html\"\n
Then:
-
Since the block
wasn't overriden, you can use the body
slot:
{% component \"my_comp\" %}\n {% fill \"body\" %}\n XYZ\n {% endfill %}\n{% endcomponent %}\n
And we get:
<div>hello 1 XYZ</div>\n
-
blocks
CANNOT be overriden through the component
tag, so something like this:
{% component \"my_comp\" %}\n {% fill \"body\" %}\n XYZ\n {% endfill %}\n{% endcomponent %}\n{% block \"inner\" %}\n 456\n{% endblock %}\n
Will still render the component content just the same:
<div>hello 1 XYZ</div>\n
-
You CAN override the block
tags of abc.html
if my component template uses extends
. In that case, just as you would expect, the block inner
inside abc.html
will render OVERRIDEN
:
@register(\"my_comp\")\nclass MyComp(Component):\ntemplate_name = \"\"\"\n{% extends \"abc.html\" %}\n\n {% block inner %}\n OVERRIDEN\n {% endblock %}\n \"\"\"\n ```\n
-
This is where it gets interesting (but still intuitive). You can insert even new slots
inside these \"overriding\" blocks:
@register(\"my_comp\")\nclass MyComp(Component):\n template_name = \"\"\"\n {% extends \"abc.html\" %}\n\n {% load component_tags %}\n {% block \"inner\" %}\n OVERRIDEN\n {% slot \"new_slot\" %}\n hello\n {% endslot %}\n {% endblock %}\n \"\"\"\n
And you can then pass fill for this new_slot
when rendering the component:
{% component \"my_comp\" %}\n {% fill \"new_slot\" %}\n XYZ\n {% endfill %}\n{% endcomponent %}\n
NOTE: Currently you can supply fills for both new_slot
and body
slots, and you will not get an error for an invalid/unknown slot name. But since body
slot is not rendered, it just won't do anything. So this renders the same as above:
{% component \"my_comp\" %}\n {% fill \"new_slot\" %}\n XYZ\n {% endfill %}\n {% fill \"body\" %}\n www\n {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/SUMMARY/","title":"SUMMARY","text":" - django_components
- app_settings
- apps
- attributes
- autodiscover
- component
- component_media
- component_registry
- context
- expression
- library
- logger
- management
- commands
- startcomponent
- upgradecomponent
- middleware
- node
- provide
- safer_staticfiles
- slots
- tag_formatter
- template_loader
- template_parser
- templatetags
- types
- utils
"},{"location":"reference/django_components/","title":"Index","text":""},{"location":"reference/django_components/#django_components","title":"django_components","text":"Main package for Django Components.
"},{"location":"reference/django_components/#django_components.app_settings","title":"app_settings","text":""},{"location":"reference/django_components/#django_components.app_settings.ContextBehavior","title":"ContextBehavior","text":" Bases: str
, Enum
"},{"location":"reference/django_components/#django_components.app_settings.ContextBehavior.DJANGO","title":"DJANGO class-attribute
instance-attribute
","text":"DJANGO = 'django'\n
With this setting, component fills behave as usual Django tags. That is, they enrich the context, and pass it along.
- Component fills use the context of the component they are within.
- Variables from
get_context_data
are available to the component fill.
Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the get_context_data()
method
{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
456 # my_var\nfeta # cheese\n
Because \"my_comp\" overrides the variable \"my_var\", so {{ my_var }}
equals 456
.
And variable \"cheese\" will equal feta
, because the fill CAN access the current context.
"},{"location":"reference/django_components/#django_components.app_settings.ContextBehavior.ISOLATED","title":"ISOLATED class-attribute
instance-attribute
","text":"ISOLATED = 'isolated'\n
This setting makes the component fills behave similar to Vue or React, where the fills use EXCLUSIVELY the context variables defined in get_context_data
.
Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the get_context_data()
method
{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
123 # my_var\n # cheese\n
Because both variables \"my_var\" and \"cheese\" are taken from the root context. Since \"cheese\" is not defined in root context, it's empty.
"},{"location":"reference/django_components/#django_components.attributes","title":"attributes","text":""},{"location":"reference/django_components/#django_components.attributes.append_attributes","title":"append_attributes","text":"append_attributes(*args: Tuple[str, Any]) -> Dict\n
Merges the key-value pairs and returns a new dictionary.
If a key is present multiple times, its values are concatenated with a space character as separator in the final dictionary.
Source code in src/django_components/attributes.py
def append_attributes(*args: Tuple[str, Any]) -> Dict:\n \"\"\"\n Merges the key-value pairs and returns a new dictionary.\n\n If a key is present multiple times, its values are concatenated with a space\n character as separator in the final dictionary.\n \"\"\"\n result: Dict = {}\n\n for key, value in args:\n if key in result:\n result[key] += \" \" + value\n else:\n result[key] = value\n\n return result\n
"},{"location":"reference/django_components/#django_components.attributes.attributes_to_string","title":"attributes_to_string","text":"attributes_to_string(attributes: Mapping[str, Any]) -> str\n
Convert a dict of attributes to a string.
Source code in src/django_components/attributes.py
def attributes_to_string(attributes: Mapping[str, Any]) -> str:\n \"\"\"Convert a dict of attributes to a string.\"\"\"\n attr_list = []\n\n for key, value in attributes.items():\n if value is None or value is False:\n continue\n if value is True:\n attr_list.append(conditional_escape(key))\n else:\n attr_list.append(format_html('{}=\"{}\"', key, value))\n\n return mark_safe(SafeString(\" \").join(attr_list))\n
"},{"location":"reference/django_components/#django_components.autodiscover","title":"autodiscover","text":""},{"location":"reference/django_components/#django_components.autodiscover.autodiscover","title":"autodiscover","text":"autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Search for component files and import them. Returns a list of module paths of imported files.
Autodiscover searches in the locations as defined by Loader.get_dirs
.
You can map the module paths with map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Source code in src/django_components/autodiscover.py
def autodiscover(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Search for component files and import them. Returns a list of module\n paths of imported files.\n\n Autodiscover searches in the locations as defined by `Loader.get_dirs`.\n\n You can map the module paths with `map_module` function. This serves\n as an escape hatch for when you need to use this function in tests.\n \"\"\"\n dirs = get_dirs()\n component_filepaths = search_dirs(dirs, \"**/*.py\")\n logger.debug(f\"Autodiscover found {len(component_filepaths)} files in component directories.\")\n\n modules = [_filepath_to_python_module(filepath) for filepath in component_filepaths]\n return _import_modules(modules, map_module)\n
"},{"location":"reference/django_components/#django_components.autodiscover.get_dirs","title":"get_dirs","text":"get_dirs(engine: Optional[Engine] = None) -> List[Path]\n
Helper for using django_component's FilesystemLoader class to obtain a list of directories where component python files may be defined.
Source code in src/django_components/autodiscover.py
def get_dirs(engine: Optional[Engine] = None) -> List[Path]:\n \"\"\"\n Helper for using django_component's FilesystemLoader class to obtain a list\n of directories where component python files may be defined.\n \"\"\"\n current_engine = engine\n if current_engine is None:\n current_engine = Engine.get_default()\n\n loader = Loader(current_engine)\n return loader.get_dirs()\n
"},{"location":"reference/django_components/#django_components.autodiscover.import_libraries","title":"import_libraries","text":"import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Import modules set in COMPONENTS.libraries
setting.
You can map the module paths with map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Source code in src/django_components/autodiscover.py
def import_libraries(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Import modules set in `COMPONENTS.libraries` setting.\n\n You can map the module paths with `map_module` function. This serves\n as an escape hatch for when you need to use this function in tests.\n \"\"\"\n from django_components.app_settings import app_settings\n\n return _import_modules(app_settings.LIBRARIES, map_module)\n
"},{"location":"reference/django_components/#django_components.autodiscover.search_dirs","title":"search_dirs","text":"search_dirs(dirs: List[Path], search_glob: str) -> List[Path]\n
Search the directories for the given glob pattern. Glob search results are returned as a flattened list.
Source code in src/django_components/autodiscover.py
def search_dirs(dirs: List[Path], search_glob: str) -> List[Path]:\n \"\"\"\n Search the directories for the given glob pattern. Glob search results are returned\n as a flattened list.\n \"\"\"\n matched_files: List[Path] = []\n for directory in dirs:\n for path in glob.iglob(str(Path(directory) / search_glob), recursive=True):\n matched_files.append(Path(path))\n\n return matched_files\n
"},{"location":"reference/django_components/#django_components.component","title":"component","text":""},{"location":"reference/django_components/#django_components.component.Component","title":"Component","text":"Component(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n fill_content: Optional[Dict[str, FillContent]] = None,\n)\n
Bases: Generic[ArgsType, KwargsType, DataType, SlotsType]
Source code in src/django_components/component.py
def __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n fill_content: Optional[Dict[str, FillContent]] = None,\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.fill_content = fill_content or {}\n self.component_id = component_id or gen_id()\n self._render_stack: Deque[RenderInput[ArgsType, KwargsType, SlotsType]] = deque()\n
"},{"location":"reference/django_components/#django_components.component.Component.Media","title":"Media class-attribute
instance-attribute
","text":"Media = ComponentMediaInput\n
Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/#django_components.component.Component.css","title":"css class-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/#django_components.component.Component.input","title":"input property
","text":"input: Optional[RenderInput[ArgsType, KwargsType, SlotsType]]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the render
method.
"},{"location":"reference/django_components/#django_components.component.Component.js","title":"js class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/#django_components.component.Component.media","title":"media instance-attribute
","text":"media: Media\n
Normalized definition of JS and CSS media files associated with this component.
NOTE: This field is generated from Component.Media class.
"},{"location":"reference/django_components/#django_components.component.Component.response_class","title":"response_class class-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from render_to_response
"},{"location":"reference/django_components/#django_components.component.Component.template","title":"template class-attribute
instance-attribute
","text":"template: Optional[str] = None\n
Inlined Django template associated with this component.
"},{"location":"reference/django_components/#django_components.component.Component.template_name","title":"template_name class-attribute
","text":"template_name: Optional[str] = None\n
Relative filepath to the Django template associated with this component.
"},{"location":"reference/django_components/#django_components.component.Component.as_view","title":"as_view classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling Component.View.as_view
and passing component instance to it.
Source code in src/django_components/component.py
@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # Allow the View class to access this component via `self.component`\n component = cls()\n return component.View.as_view(**initkwargs, component=component)\n
"},{"location":"reference/django_components/#django_components.component.Component.inject","title":"inject","text":"inject(key: str, default: Optional[Any] = None) -> Any\n
Use this method to retrieve the data that was passed to a {% provide %}
tag with the corresponding key.
To retrieve the data, inject()
must be called inside a component that's inside the {% provide %}
tag.
You may also pass a default that will be used if the provide
tag with given key was NOT found.
This method mut be used inside the get_context_data()
method and raises an error if called elsewhere.
Example:
Given this template:
{% provide \"provider\" hello=\"world\" %}\n {% component \"my_comp\" %}\n {% endcomponent %}\n{% endprovide %}\n
And given this definition of \"my_comp\" component:
from django_components import Component, register\n\n@register(\"my_comp\")\nclass MyComp(Component):\n template = \"hi {{ data.hello }}!\"\n def get_context_data(self):\n data = self.inject(\"provider\")\n return {\"data\": data}\n
This renders into:
hi world!\n
As the {{ data.hello }}
is taken from the \"provider\".
Source code in src/django_components/component.py
def inject(self, key: str, default: Optional[Any] = None) -> Any:\n \"\"\"\n Use this method to retrieve the data that was passed to a `{% provide %}` tag\n with the corresponding key.\n\n To retrieve the data, `inject()` must be called inside a component that's\n inside the `{% provide %}` tag.\n\n You may also pass a default that will be used if the `provide` tag with given\n key was NOT found.\n\n This method mut be used inside the `get_context_data()` method and raises\n an error if called elsewhere.\n\n Example:\n\n Given this template:\n ```django\n {% provide \"provider\" hello=\"world\" %}\n {% component \"my_comp\" %}\n {% endcomponent %}\n {% endprovide %}\n ```\n\n And given this definition of \"my_comp\" component:\n ```py\n from django_components import Component, register\n\n @register(\"my_comp\")\n class MyComp(Component):\n template = \"hi {{ data.hello }}!\"\n def get_context_data(self):\n data = self.inject(\"provider\")\n return {\"data\": data}\n ```\n\n This renders into:\n ```\n hi world!\n ```\n\n As the `{{ data.hello }}` is taken from the \"provider\".\n \"\"\"\n if self.input is None:\n raise RuntimeError(\n f\"Method 'inject()' of component '{self.name}' was called outside of 'get_context_data()'\"\n )\n\n return get_injected_context_var(self.name, self.input.context, key, default)\n
"},{"location":"reference/django_components/#django_components.component.Component.render","title":"render classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n) -> str\n
Render the component into a string.
Inputs: - args
- Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %}
- kwargs
- Kwargs for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %}
- slots
- Component slot fills. This is the same as pasing {% fill %}
tags to the component. Accepts a dictionary of { slot_name: slot_content }
where slot_content
can be a string or render function. - escape_slots_content
- Whether the content from slots
should be escaped. - context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs.
Example:
MyComponent.render(\n args=[1, \"two\", {}],\n kwargs={\n \"key\": 123,\n },\n slots={\n \"header\": 'STATIC TEXT HERE',\n \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n },\n escape_slots_content=False,\n)\n
Source code in src/django_components/component.py
@classmethod\ndef render(\n cls,\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n) -> str:\n \"\"\"\n Render the component into a string.\n\n Inputs:\n - `args` - Positional args for the component. This is the same as calling the component\n as `{% component \"my_comp\" arg1 arg2 ... %}`\n - `kwargs` - Kwargs for the component. This is the same as calling the component\n as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n or render function.\n - `escape_slots_content` - Whether the content from `slots` should be escaped.\n - `context` - A context (dictionary or Django's Context) within which the component\n is rendered. The keys on the context can be accessed from within the template.\n - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n component's args and kwargs.\n\n Example:\n ```py\n MyComponent.render(\n args=[1, \"two\", {}],\n kwargs={\n \"key\": 123,\n },\n slots={\n \"header\": 'STATIC TEXT HERE',\n \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n },\n escape_slots_content=False,\n )\n ```\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n return comp._render(context, args, kwargs, slots, escape_slots_content)\n
"},{"location":"reference/django_components/#django_components.component.Component.render_css_dependencies","title":"render_css_dependencies","text":"render_css_dependencies() -> SafeString\n
Render only CSS dependencies available in the media class or provided as a string.
Source code in src/django_components/component.py
def render_css_dependencies(self) -> SafeString:\n \"\"\"Render only CSS dependencies available in the media class or provided as a string.\"\"\"\n if self.css is not None:\n return mark_safe(f\"<style>{self.css}</style>\")\n return mark_safe(\"\\n\".join(self.media.render_css()))\n
"},{"location":"reference/django_components/#django_components.component.Component.render_dependencies","title":"render_dependencies","text":"render_dependencies() -> SafeString\n
Helper function to render all dependencies for a component.
Source code in src/django_components/component.py
def render_dependencies(self) -> SafeString:\n \"\"\"Helper function to render all dependencies for a component.\"\"\"\n dependencies = []\n\n css_deps = self.render_css_dependencies()\n if css_deps:\n dependencies.append(css_deps)\n\n js_deps = self.render_js_dependencies()\n if js_deps:\n dependencies.append(js_deps)\n\n return mark_safe(\"\\n\".join(dependencies))\n
"},{"location":"reference/django_components/#django_components.component.Component.render_js_dependencies","title":"render_js_dependencies","text":"render_js_dependencies() -> SafeString\n
Render only JS dependencies available in the media class or provided as a string.
Source code in src/django_components/component.py
def render_js_dependencies(self) -> SafeString:\n \"\"\"Render only JS dependencies available in the media class or provided as a string.\"\"\"\n if self.js is not None:\n return mark_safe(f\"<script>{self.js}</script>\")\n return mark_safe(\"\\n\".join(self.media.render_js()))\n
"},{"location":"reference/django_components/#django_components.component.Component.render_to_response","title":"render_to_response classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n *response_args: Any,\n **response_kwargs: Any\n) -> HttpResponse\n
Render the component and wrap the content in the response class.
The response class is taken from Component.response_class
. Defaults to django.http.HttpResponse
.
This is the interface for the django.views.View
class which allows us to use components as Django views with component.as_view()
.
Inputs: - args
- Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %}
- kwargs
- Kwargs for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %}
- slots
- Component slot fills. This is the same as pasing {% fill %}
tags to the component. Accepts a dictionary of { slot_name: slot_content }
where slot_content
can be a string or render function. - escape_slots_content
- Whether the content from slots
should be escaped. - context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs.
Any additional args and kwargs are passed to the response_class
.
Example:
MyComponent.render_to_response(\n args=[1, \"two\", {}],\n kwargs={\n \"key\": 123,\n },\n slots={\n \"header\": 'STATIC TEXT HERE',\n \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n },\n escape_slots_content=False,\n # HttpResponse input\n status=201,\n headers={...},\n)\n# HttpResponse(content=..., status=201, headers=...)\n
Source code in src/django_components/component.py
@classmethod\ndef render_to_response(\n cls,\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n *response_args: Any,\n **response_kwargs: Any,\n) -> HttpResponse:\n \"\"\"\n Render the component and wrap the content in the response class.\n\n The response class is taken from `Component.response_class`. Defaults to `django.http.HttpResponse`.\n\n This is the interface for the `django.views.View` class which allows us to\n use components as Django views with `component.as_view()`.\n\n Inputs:\n - `args` - Positional args for the component. This is the same as calling the component\n as `{% component \"my_comp\" arg1 arg2 ... %}`\n - `kwargs` - Kwargs for the component. This is the same as calling the component\n as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n or render function.\n - `escape_slots_content` - Whether the content from `slots` should be escaped.\n - `context` - A context (dictionary or Django's Context) within which the component\n is rendered. The keys on the context can be accessed from within the template.\n - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n component's args and kwargs.\n\n Any additional args and kwargs are passed to the `response_class`.\n\n Example:\n ```py\n MyComponent.render_to_response(\n args=[1, \"two\", {}],\n kwargs={\n \"key\": 123,\n },\n slots={\n \"header\": 'STATIC TEXT HERE',\n \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n },\n escape_slots_content=False,\n # HttpResponse input\n status=201,\n headers={...},\n )\n # HttpResponse(content=..., status=201, headers=...)\n ```\n \"\"\"\n content = cls.render(\n args=args,\n kwargs=kwargs,\n context=context,\n slots=slots,\n escape_slots_content=escape_slots_content,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
"},{"location":"reference/django_components/#django_components.component.ComponentNode","title":"ComponentNode","text":"ComponentNode(\n name: str,\n args: List[Expression],\n kwargs: RuntimeKwargs,\n isolated_context: bool = False,\n fill_nodes: Optional[List[FillNode]] = None,\n node_id: Optional[str] = None,\n)\n
Bases: BaseNode
Django.template.Node subclass that renders a django-components component
Source code in src/django_components/component.py
def __init__(\n self,\n name: str,\n args: List[Expression],\n kwargs: RuntimeKwargs,\n isolated_context: bool = False,\n fill_nodes: Optional[List[FillNode]] = None,\n node_id: Optional[str] = None,\n) -> None:\n super().__init__(nodelist=NodeList(fill_nodes), args=args, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.isolated_context = isolated_context\n self.fill_nodes = fill_nodes or []\n
"},{"location":"reference/django_components/#django_components.component.ComponentView","title":"ComponentView","text":"ComponentView(component: Component, **kwargs: Any)\n
Bases: View
Subclass of django.views.View
where the Component
instance is available via self.component
.
Source code in src/django_components/component.py
def __init__(self, component: \"Component\", **kwargs: Any) -> None:\n super().__init__(**kwargs)\n self.component = component\n
"},{"location":"reference/django_components/#django_components.component_media","title":"component_media","text":""},{"location":"reference/django_components/#django_components.component_media.ComponentMediaInput","title":"ComponentMediaInput","text":"Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/#django_components.component_media.MediaMeta","title":"MediaMeta","text":" Bases: MediaDefiningClass
Metaclass for handling media files for components.
Similar to MediaDefiningClass
, this class supports the use of Media
attribute to define associated JS/CSS files, which are then available under media
attribute as a instance of Media
class.
This subclass has following changes:
"},{"location":"reference/django_components/#django_components.component_media.MediaMeta--1-support-for-multiple-interfaces-of-jscss","title":"1. Support for multiple interfaces of JS/CSS","text":" -
As plain strings
class MyComponent(Component):\n class Media:\n js = \"path/to/script.js\"\n css = \"path/to/style.css\"\n
-
As lists
class MyComponent(Component):\n class Media:\n js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n
-
[CSS ONLY] Dicts of strings
class MyComponent(Component):\n class Media:\n css = {\n \"all\": \"path/to/style1.css\",\n \"print\": \"path/to/style2.css\",\n }\n
-
[CSS ONLY] Dicts of lists
class MyComponent(Component):\n class Media:\n css = {\n \"all\": [\"path/to/style1.css\"],\n \"print\": [\"path/to/style2.css\"],\n }\n
"},{"location":"reference/django_components/#django_components.component_media.MediaMeta--2-media-are-first-resolved-relative-to-class-definition-file","title":"2. Media are first resolved relative to class definition file","text":"E.g. if in a directory my_comp
you have script.js
and my_comp.py
, and my_comp.py
looks like this:
class MyComponent(Component):\n class Media:\n js = \"script.js\"\n
Then script.js
will be resolved as my_comp/script.js
.
"},{"location":"reference/django_components/#django_components.component_media.MediaMeta--3-media-can-be-defined-as-str-bytes-pathlike-safestring-or-function-of-thereof","title":"3. Media can be defined as str, bytes, PathLike, SafeString, or function of thereof","text":"E.g.:
def lazy_eval_css():\n # do something\n return path\n\nclass MyComponent(Component):\n class Media:\n js = b\"script.js\"\n css = lazy_eval_css\n
"},{"location":"reference/django_components/#django_components.component_media.MediaMeta--4-subclass-media-class-with-media_class","title":"4. Subclass Media
class with media_class
","text":"Normal MediaDefiningClass
creates an instance of Media
class under the media
attribute. This class allows to override which class will be instantiated with media_class
attribute:
class MyMedia(Media):\n def render_js(self):\n ...\n\nclass MyComponent(Component):\n media_class = MyMedia\n def get_context_data(self):\n assert isinstance(self.media, MyMedia)\n
"},{"location":"reference/django_components/#django_components.component_registry","title":"component_registry","text":""},{"location":"reference/django_components/#django_components.component_registry.registry","title":"registry module-attribute
","text":"registry: ComponentRegistry = ComponentRegistry()\n
The default and global component registry. Use this instance to directly register or remove components:
# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Get single\nregistry.get(\"button\")\n# Get all\nregistry.all()\n# Unregister single\nregistry.unregister(\"button\")\n# Unregister all\nregistry.clear()\n
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry","title":"ComponentRegistry","text":"ComponentRegistry(library: Optional[Library] = None)\n
Manages which components can be used in the template tags.
Each ComponentRegistry instance is associated with an instance of Django's Library. So when you register or unregister a component to/from a component registry, behind the scenes the registry automatically adds/removes the component's template tag to/from the Library.
The Library instance can be set at instantiation. If omitted, then the default Library instance from django_components is used. The Library instance can be accessed under library
attribute.
Example:
# Use with default Library\nregistry = ComponentRegistry()\n\n# Or a custom one\nmy_lib = Library()\nregistry = ComponentRegistry(library=my_lib)\n\n# Usage\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\nregistry.all()\nregistry.clear()\nregistry.get()\n
Source code in src/django_components/component_registry.py
def __init__(self, library: Optional[Library] = None) -> None:\n self._registry: Dict[str, ComponentRegistryEntry] = {} # component name -> component_entry mapping\n self._tags: Dict[str, Set[str]] = {} # tag -> list[component names]\n self._library = library\n
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.library","title":"library property
","text":"library: Library\n
The template tag library with which the component registry is associated.
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.all","title":"all","text":"all() -> Dict[str, Type[Component]]\n
Retrieve all registered component classes.
Example:
# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then get all\nregistry.all()\n# > {\n# > \"button\": ButtonComponent,\n# > \"card\": CardComponent,\n# > }\n
Source code in src/django_components/component_registry.py
def all(self) -> Dict[str, Type[\"Component\"]]:\n \"\"\"\n Retrieve all registered component classes.\n\n Example:\n\n ```py\n # First register components\n registry.register(\"button\", ButtonComponent)\n registry.register(\"card\", CardComponent)\n # Then get all\n registry.all()\n # > {\n # > \"button\": ButtonComponent,\n # > \"card\": CardComponent,\n # > }\n ```\n \"\"\"\n comps = {key: entry.cls for key, entry in self._registry.items()}\n return comps\n
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.clear","title":"clear","text":"clear() -> None\n
Clears the registry, unregistering all components.
Example:
# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then clear\nregistry.clear()\n# Then get all\nregistry.all()\n# > {}\n
Source code in src/django_components/component_registry.py
def clear(self) -> None:\n \"\"\"\n Clears the registry, unregistering all components.\n\n Example:\n\n ```py\n # First register components\n registry.register(\"button\", ButtonComponent)\n registry.register(\"card\", CardComponent)\n # Then clear\n registry.clear()\n # Then get all\n registry.all()\n # > {}\n ```\n \"\"\"\n all_comp_names = list(self._registry.keys())\n for comp_name in all_comp_names:\n self.unregister(comp_name)\n\n self._registry = {}\n self._tags = {}\n
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.get","title":"get","text":"get(name: str) -> Type[Component]\n
Retrieve a component class registered under the given name.
Raises NotRegistered
if the given name is not registered.
Example:
# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then get\nregistry.get(\"button\")\n# > ButtonComponent\n
Source code in src/django_components/component_registry.py
def get(self, name: str) -> Type[\"Component\"]:\n \"\"\"\n Retrieve a component class registered under the given name.\n\n Raises `NotRegistered` if the given name is not registered.\n\n Example:\n\n ```py\n # First register component\n registry.register(\"button\", ButtonComponent)\n # Then get\n registry.get(\"button\")\n # > ButtonComponent\n ```\n \"\"\"\n if name not in self._registry:\n raise NotRegistered('The component \"%s\" is not registered' % name)\n\n return self._registry[name].cls\n
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.register","title":"register","text":"register(name: str, component: Type[Component]) -> None\n
Register a component with this registry under the given name.
A component MUST be registered before it can be used in a template such as:
{% component \"my_comp\" %}{% endcomponent %}\n
Raises AlreadyRegistered
if a different component was already registered under the same name.
Example:
registry.register(\"button\", ButtonComponent)\n
Source code in src/django_components/component_registry.py
def register(self, name: str, component: Type[\"Component\"]) -> None:\n \"\"\"\n Register a component with this registry under the given name.\n\n A component MUST be registered before it can be used in a template such as:\n ```django\n {% component \"my_comp\" %}{% endcomponent %}\n ```\n\n Raises `AlreadyRegistered` if a different component was already registered\n under the same name.\n\n Example:\n\n ```py\n registry.register(\"button\", ButtonComponent)\n ```\n \"\"\"\n existing_component = self._registry.get(name)\n if existing_component and existing_component.cls._class_hash != component._class_hash:\n raise AlreadyRegistered('The component \"%s\" has already been registered' % name)\n\n entry = self._register_to_library(name, component)\n\n # Keep track of which components use which tags, because multiple components may\n # use the same tag.\n tag = entry.tag\n if tag not in self._tags:\n self._tags[tag] = set()\n self._tags[tag].add(name)\n\n self._registry[name] = entry\n
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.unregister","title":"unregister","text":"unregister(name: str) -> None\n
Unlinks a previously-registered component from the registry under the given name.
Once a component is unregistered, it CANNOT be used in a template anymore. Following would raise an error:
{% component \"my_comp\" %}{% endcomponent %}\n
Raises NotRegistered
if the given name is not registered.
Example:
# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
Source code in src/django_components/component_registry.py
def unregister(self, name: str) -> None:\n \"\"\"\n Unlinks a previously-registered component from the registry under the given name.\n\n Once a component is unregistered, it CANNOT be used in a template anymore.\n Following would raise an error:\n ```django\n {% component \"my_comp\" %}{% endcomponent %}\n ```\n\n Raises `NotRegistered` if the given name is not registered.\n\n Example:\n\n ```py\n # First register component\n registry.register(\"button\", ButtonComponent)\n # Then unregister\n registry.unregister(\"button\")\n ```\n \"\"\"\n # Validate\n self.get(name)\n\n entry = self._registry[name]\n tag = entry.tag\n\n # Unregister the tag from library if this was the last component using this tag\n # Unlink component from tag\n self._tags[tag].remove(name)\n\n # Cleanup\n is_tag_empty = not len(self._tags[tag])\n if is_tag_empty:\n del self._tags[tag]\n\n # Only unregister a tag if it's NOT protected\n is_protected = is_tag_protected(self.library, tag)\n if not is_protected:\n # Unregister the tag from library if this was the last component using this tag\n if is_tag_empty and tag in self.library.tags:\n del self.library.tags[tag]\n\n del self._registry[name]\n
"},{"location":"reference/django_components/#django_components.component_registry.register","title":"register","text":"register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]\n
Class decorator to register a component.
Usage:
@register(\"my_component\")\nclass MyComponent(Component):\n ...\n
Optionally specify which ComponentRegistry
the component should be registered to by setting the registry
kwarg:
my_lib = django.template.Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n ...\n
Source code in src/django_components/component_registry.py
def register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]:\n \"\"\"\n Class decorator to register a component.\n\n Usage:\n\n ```py\n @register(\"my_component\")\n class MyComponent(Component):\n ...\n ```\n\n Optionally specify which `ComponentRegistry` the component should be registered to by\n setting the `registry` kwarg:\n\n ```py\n my_lib = django.template.Library()\n my_reg = ComponentRegistry(library=my_lib)\n\n @register(\"my_component\", registry=my_reg)\n class MyComponent(Component):\n ...\n ```\n \"\"\"\n if registry is None:\n registry = _the_registry\n\n def decorator(component: _TComp) -> _TComp:\n registry.register(name=name, component=component)\n return component\n\n return decorator\n
"},{"location":"reference/django_components/#django_components.context","title":"context","text":"This file centralizes various ways we use Django's Context class pass data across components, nodes, slots, and contexts.
You can think of the Context as our storage system.
"},{"location":"reference/django_components/#django_components.context.copy_forloop_context","title":"copy_forloop_context","text":"copy_forloop_context(from_context: Context, to_context: Context) -> None\n
Forward the info about the current loop
Source code in src/django_components/context.py
def copy_forloop_context(from_context: Context, to_context: Context) -> None:\n \"\"\"Forward the info about the current loop\"\"\"\n # Note that the ForNode (which implements for loop behavior) does not\n # only add the `forloop` key, but also keys corresponding to the loop elements\n # So if the loop syntax is `{% for my_val in my_lists %}`, then ForNode also\n # sets a `my_val` key.\n # For this reason, instead of copying individual keys, we copy the whole stack layer\n # set by ForNode.\n if \"forloop\" in from_context:\n forloop_dict_index = find_last_index(from_context.dicts, lambda d: \"forloop\" in d)\n to_context.update(from_context.dicts[forloop_dict_index])\n
"},{"location":"reference/django_components/#django_components.context.get_injected_context_var","title":"get_injected_context_var","text":"get_injected_context_var(component_name: str, context: Context, key: str, default: Optional[Any] = None) -> Any\n
Retrieve a 'provided' field. The field MUST have been previously 'provided' by the component's ancestors using the {% provide %}
template tag.
Source code in src/django_components/context.py
def get_injected_context_var(\n component_name: str,\n context: Context,\n key: str,\n default: Optional[Any] = None,\n) -> Any:\n \"\"\"\n Retrieve a 'provided' field. The field MUST have been previously 'provided'\n by the component's ancestors using the `{% provide %}` template tag.\n \"\"\"\n # NOTE: For simplicity, we keep the provided values directly on the context.\n # This plays nicely with Django's Context, which behaves like a stack, so \"newer\"\n # values overshadow the \"older\" ones.\n internal_key = _INJECT_CONTEXT_KEY_PREFIX + key\n\n # Return provided value if found\n if internal_key in context:\n return context[internal_key]\n\n # If a default was given, return that\n if default is not None:\n return default\n\n # Otherwise raise error\n raise KeyError(\n f\"Component '{component_name}' tried to inject a variable '{key}' before it was provided.\"\n f\" To fix this, make sure that at least one ancestor of component '{component_name}' has\"\n f\" the variable '{key}' in their 'provide' attribute.\"\n )\n
"},{"location":"reference/django_components/#django_components.context.prepare_context","title":"prepare_context","text":"prepare_context(context: Context, component_id: str) -> None\n
Initialize the internal context state.
Source code in src/django_components/context.py
def prepare_context(\n context: Context,\n component_id: str,\n) -> None:\n \"\"\"Initialize the internal context state.\"\"\"\n # Initialize mapping dicts within this rendering run.\n # This is shared across the whole render chain, thus we set it only once.\n if _FILLED_SLOTS_CONTENT_CONTEXT_KEY not in context:\n context[_FILLED_SLOTS_CONTENT_CONTEXT_KEY] = {}\n\n set_component_id(context, component_id)\n
"},{"location":"reference/django_components/#django_components.context.set_component_id","title":"set_component_id","text":"set_component_id(context: Context, component_id: str) -> None\n
We use the Context object to pass down info on inside of which component we are currently rendering.
Source code in src/django_components/context.py
def set_component_id(context: Context, component_id: str) -> None:\n \"\"\"\n We use the Context object to pass down info on inside of which component\n we are currently rendering.\n \"\"\"\n # Store the previous component so we can detect if the current component\n # is the top-most or not. If it is, then \"_parent_component_id\" is None\n context[_PARENT_COMP_CONTEXT_KEY] = context.get(_CURRENT_COMP_CONTEXT_KEY, None)\n context[_CURRENT_COMP_CONTEXT_KEY] = component_id\n
"},{"location":"reference/django_components/#django_components.context.set_provided_context_var","title":"set_provided_context_var","text":"set_provided_context_var(context: Context, key: str, provided_kwargs: Dict[str, Any]) -> None\n
'Provide' given data under given key. In other words, this data can be retrieved using self.inject(key)
inside of get_context_data()
method of components that are nested inside the {% provide %}
tag.
Source code in src/django_components/context.py
def set_provided_context_var(\n context: Context,\n key: str,\n provided_kwargs: Dict[str, Any],\n) -> None:\n \"\"\"\n 'Provide' given data under given key. In other words, this data can be retrieved\n using `self.inject(key)` inside of `get_context_data()` method of components that\n are nested inside the `{% provide %}` tag.\n \"\"\"\n # NOTE: We raise TemplateSyntaxError since this func should be called only from\n # within template.\n if not key:\n raise TemplateSyntaxError(\n \"Provide tag received an empty string. Key must be non-empty and a valid identifier.\"\n )\n if not key.isidentifier():\n raise TemplateSyntaxError(\n \"Provide tag received a non-identifier string. Key must be non-empty and a valid identifier.\"\n )\n\n # We turn the kwargs into a NamedTuple so that the object that's \"provided\"\n # is immutable. This ensures that the data returned from `inject` will always\n # have all the keys that were passed to the `provide` tag.\n tpl_cls = namedtuple(\"DepInject\", provided_kwargs.keys()) # type: ignore[misc]\n payload = tpl_cls(**provided_kwargs)\n\n internal_key = _INJECT_CONTEXT_KEY_PREFIX + key\n context[internal_key] = payload\n
"},{"location":"reference/django_components/#django_components.expression","title":"expression","text":""},{"location":"reference/django_components/#django_components.expression.Operator","title":"Operator","text":" Bases: ABC
Operator describes something that somehow changes the inputs to template tags (the {% %}
).
For example, a SpreadOperator inserts one or more kwargs at the specified location.
"},{"location":"reference/django_components/#django_components.expression.SpreadOperator","title":"SpreadOperator","text":"SpreadOperator(expr: Expression)\n
Bases: Operator
Operator that inserts one or more kwargs at the specified location.
Source code in src/django_components/expression.py
def __init__(self, expr: Expression) -> None:\n self.expr = expr\n
"},{"location":"reference/django_components/#django_components.expression.process_aggregate_kwargs","title":"process_aggregate_kwargs","text":"process_aggregate_kwargs(kwargs: Mapping[str, Any]) -> Dict[str, Any]\n
This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs start with some prefix delimited with :
(e.g. attrs:
).
Example:
process_component_kwargs({\"abc:one\": 1, \"abc:two\": 2, \"def:three\": 3, \"four\": 4})\n# {\"abc\": {\"one\": 1, \"two\": 2}, \"def\": {\"three\": 3}, \"four\": 4}\n
We want to support a use case similar to Vue's fallthrough attributes. In other words, where a component author can designate a prop (input) which is a dict and which will be rendered as HTML attributes.
This is useful for allowing component users to tweak styling or add event handling to the underlying HTML. E.g.:
class=\"pa-4 d-flex text-black\"
or @click.stop=\"alert('clicked!')\"
So if the prop is attrs
, and the component is called like so:
{% component \"my_comp\" attrs=attrs %}\n
then, if attrs
is:
{\"class\": \"text-red pa-4\", \"@click\": \"dispatch('my_event', 123)\"}\n
and the component template is:
<div {% html_attrs attrs add:class=\"extra-class\" %}></div>\n
Then this renders:
<div class=\"text-red pa-4 extra-class\" @click=\"dispatch('my_event', 123)\" ></div>\n
However, this way it is difficult for the component user to define the attrs
variable, especially if they want to combine static and dynamic values. Because they will need to pre-process the attrs
dict.
So, instead, we allow to \"aggregate\" props into a dict. So all props that start with attrs:
, like attrs:class=\"text-red\"
, will be collected into a dict at key attrs
.
This provides sufficient flexiblity to make it easy for component users to provide \"fallthrough attributes\", and sufficiently easy for component authors to process that input while still being able to provide their own keys.
Source code in src/django_components/expression.py
def process_aggregate_kwargs(kwargs: Mapping[str, Any]) -> Dict[str, Any]:\n \"\"\"\n This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs\n start with some prefix delimited with `:` (e.g. `attrs:`).\n\n Example:\n ```py\n process_component_kwargs({\"abc:one\": 1, \"abc:two\": 2, \"def:three\": 3, \"four\": 4})\n # {\"abc\": {\"one\": 1, \"two\": 2}, \"def\": {\"three\": 3}, \"four\": 4}\n ```\n\n ---\n\n We want to support a use case similar to Vue's fallthrough attributes.\n In other words, where a component author can designate a prop (input)\n which is a dict and which will be rendered as HTML attributes.\n\n This is useful for allowing component users to tweak styling or add\n event handling to the underlying HTML. E.g.:\n\n `class=\"pa-4 d-flex text-black\"` or `@click.stop=\"alert('clicked!')\"`\n\n So if the prop is `attrs`, and the component is called like so:\n ```django\n {% component \"my_comp\" attrs=attrs %}\n ```\n\n then, if `attrs` is:\n ```py\n {\"class\": \"text-red pa-4\", \"@click\": \"dispatch('my_event', 123)\"}\n ```\n\n and the component template is:\n ```django\n <div {% html_attrs attrs add:class=\"extra-class\" %}></div>\n ```\n\n Then this renders:\n ```html\n <div class=\"text-red pa-4 extra-class\" @click=\"dispatch('my_event', 123)\" ></div>\n ```\n\n However, this way it is difficult for the component user to define the `attrs`\n variable, especially if they want to combine static and dynamic values. Because\n they will need to pre-process the `attrs` dict.\n\n So, instead, we allow to \"aggregate\" props into a dict. So all props that start\n with `attrs:`, like `attrs:class=\"text-red\"`, will be collected into a dict\n at key `attrs`.\n\n This provides sufficient flexiblity to make it easy for component users to provide\n \"fallthrough attributes\", and sufficiently easy for component authors to process\n that input while still being able to provide their own keys.\n \"\"\"\n processed_kwargs = {}\n nested_kwargs: Dict[str, Dict[str, Any]] = {}\n for key, val in kwargs.items():\n if not is_aggregate_key(key):\n processed_kwargs[key] = val\n continue\n\n # NOTE: Trim off the prefix from keys\n prefix, sub_key = key.split(\":\", 1)\n if prefix not in nested_kwargs:\n nested_kwargs[prefix] = {}\n nested_kwargs[prefix][sub_key] = val\n\n # Assign aggregated values into normal input\n for key, val in nested_kwargs.items():\n if key in processed_kwargs:\n raise TemplateSyntaxError(\n f\"Received argument '{key}' both as a regular input ({key}=...)\"\n f\" and as an aggregate dict ('{key}:key=...'). Must be only one of the two\"\n )\n processed_kwargs[key] = val\n\n return processed_kwargs\n
"},{"location":"reference/django_components/#django_components.library","title":"library","text":"Module for interfacing with Django's Library (django.template.library
)
"},{"location":"reference/django_components/#django_components.library.PROTECTED_TAGS","title":"PROTECTED_TAGS module-attribute
","text":"PROTECTED_TAGS = [\n \"component_dependencies\",\n \"component_css_dependencies\",\n \"component_js_dependencies\",\n \"fill\",\n \"html_attrs\",\n \"provide\",\n \"slot\",\n]\n
These are the names that users cannot choose for their components, as they would conflict with other tags in the Library.
"},{"location":"reference/django_components/#django_components.logger","title":"logger","text":""},{"location":"reference/django_components/#django_components.logger.trace","title":"trace","text":"trace(logger: Logger, message: str, *args: Any, **kwargs: Any) -> None\n
TRACE level logger.
To display TRACE logs, set the logging level to 5.
Example:
LOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"handlers\": {\n \"console\": {\n \"class\": \"logging.StreamHandler\",\n \"stream\": sys.stdout,\n },\n },\n \"loggers\": {\n \"django_components\": {\n \"level\": 5,\n \"handlers\": [\"console\"],\n },\n },\n}\n
Source code in src/django_components/logger.py
def trace(logger: logging.Logger, message: str, *args: Any, **kwargs: Any) -> None:\n \"\"\"\n TRACE level logger.\n\n To display TRACE logs, set the logging level to 5.\n\n Example:\n ```py\n LOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"handlers\": {\n \"console\": {\n \"class\": \"logging.StreamHandler\",\n \"stream\": sys.stdout,\n },\n },\n \"loggers\": {\n \"django_components\": {\n \"level\": 5,\n \"handlers\": [\"console\"],\n },\n },\n }\n ```\n \"\"\"\n if actual_trace_level_num == -1:\n setup_logging()\n if logger.isEnabledFor(actual_trace_level_num):\n logger.log(actual_trace_level_num, message, *args, **kwargs)\n
"},{"location":"reference/django_components/#django_components.logger.trace_msg","title":"trace_msg","text":"trace_msg(\n action: Literal[\"PARSE\", \"ASSOC\", \"RENDR\", \"GET\", \"SET\"],\n node_type: Literal[\"COMP\", \"FILL\", \"SLOT\", \"PROVIDE\", \"N/A\"],\n node_name: str,\n node_id: str,\n msg: str = \"\",\n component_id: Optional[str] = None,\n) -> None\n
TRACE level logger with opinionated format for tracing interaction of components, nodes, and slots. Formats messages like so:
\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"
Source code in src/django_components/logger.py
def trace_msg(\n action: Literal[\"PARSE\", \"ASSOC\", \"RENDR\", \"GET\", \"SET\"],\n node_type: Literal[\"COMP\", \"FILL\", \"SLOT\", \"PROVIDE\", \"N/A\"],\n node_name: str,\n node_id: str,\n msg: str = \"\",\n component_id: Optional[str] = None,\n) -> None:\n \"\"\"\n TRACE level logger with opinionated format for tracing interaction of components,\n nodes, and slots. Formats messages like so:\n\n `\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"`\n \"\"\"\n msg_prefix = \"\"\n if action == \"ASSOC\":\n if not component_id:\n raise ValueError(\"component_id must be set for the ASSOC action\")\n msg_prefix = f\"TO COMP {component_id}\"\n elif action == \"RENDR\" and node_type == \"FILL\":\n if not component_id:\n raise ValueError(\"component_id must be set for the RENDER action\")\n msg_prefix = f\"FOR COMP {component_id}\"\n\n msg_parts = [f\"{action} {node_type} {node_name} ID {node_id}\", *([msg_prefix] if msg_prefix else []), msg]\n full_msg = \" \".join(msg_parts)\n\n # NOTE: When debugging tests during development, it may be easier to change\n # this to `print()`\n trace(logger, full_msg)\n
"},{"location":"reference/django_components/#django_components.management","title":"management","text":""},{"location":"reference/django_components/#django_components.management.commands","title":"commands","text":""},{"location":"reference/django_components/#django_components.management.commands.upgradecomponent","title":"upgradecomponent","text":""},{"location":"reference/django_components/#django_components.middleware","title":"middleware","text":""},{"location":"reference/django_components/#django_components.middleware.ComponentDependencyMiddleware","title":"ComponentDependencyMiddleware","text":"ComponentDependencyMiddleware(get_response: Callable[[HttpRequest], HttpResponse])\n
Middleware that inserts CSS/JS dependencies for all rendered components at points marked with template tags.
Source code in src/django_components/middleware.py
def __init__(self, get_response: \"Callable[[HttpRequest], HttpResponse]\") -> None:\n self.get_response = get_response\n\n if iscoroutinefunction(self.get_response):\n markcoroutinefunction(self)\n
"},{"location":"reference/django_components/#django_components.middleware.DependencyReplacer","title":"DependencyReplacer","text":"DependencyReplacer(css_string: bytes, js_string: bytes)\n
Replacer for use in re.sub that replaces the first placeholder CSS and JS tags it encounters and removes any subsequent ones.
Source code in src/django_components/middleware.py
def __init__(self, css_string: bytes, js_string: bytes) -> None:\n self.js_string = js_string\n self.css_string = css_string\n
"},{"location":"reference/django_components/#django_components.middleware.join_media","title":"join_media","text":"join_media(components: Iterable[Component]) -> Media\n
Return combined media object for iterable of components.
Source code in src/django_components/middleware.py
def join_media(components: Iterable[\"Component\"]) -> Media:\n \"\"\"Return combined media object for iterable of components.\"\"\"\n\n return sum([component.media for component in components], Media())\n
"},{"location":"reference/django_components/#django_components.node","title":"node","text":""},{"location":"reference/django_components/#django_components.node.BaseNode","title":"BaseNode","text":"BaseNode(\n nodelist: Optional[NodeList] = None,\n node_id: Optional[str] = None,\n args: Optional[List[Expression]] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n)\n
Bases: Node
Shared behavior for our subclasses of Django's Node
Source code in src/django_components/node.py
def __init__(\n self,\n nodelist: Optional[NodeList] = None,\n node_id: Optional[str] = None,\n args: Optional[List[Expression]] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n):\n self.nodelist = nodelist or NodeList()\n self.node_id = node_id or gen_id()\n self.args = args or []\n self.kwargs = kwargs or RuntimeKwargs({})\n
"},{"location":"reference/django_components/#django_components.node.get_node_children","title":"get_node_children","text":"get_node_children(node: Node, context: Optional[Context] = None) -> NodeList\n
Get child Nodes from Node's nodelist atribute.
This function is taken from get_nodes_by_type
method of django.template.base.Node
.
Source code in src/django_components/node.py
def get_node_children(node: Node, context: Optional[Context] = None) -> NodeList:\n \"\"\"\n Get child Nodes from Node's nodelist atribute.\n\n This function is taken from `get_nodes_by_type` method of `django.template.base.Node`.\n \"\"\"\n # Special case - {% extends %} tag - Load the template and go deeper\n if isinstance(node, ExtendsNode):\n # NOTE: When {% extends %} node is being parsed, it collects all remaining template\n # under node.nodelist.\n # Hence, when we come across ExtendsNode in the template, we:\n # 1. Go over all nodes in the template using `node.nodelist`\n # 2. Go over all nodes in the \"parent\" template, via `node.get_parent`\n nodes = NodeList()\n nodes.extend(node.nodelist)\n template = node.get_parent(context)\n nodes.extend(template.nodelist)\n return nodes\n\n # Special case - {% include %} tag - Load the template and go deeper\n elif isinstance(node, IncludeNode):\n template = get_template_for_include_node(node, context)\n return template.nodelist\n\n nodes = NodeList()\n for attr in node.child_nodelists:\n nodelist = getattr(node, attr, [])\n if nodelist:\n nodes.extend(nodelist)\n return nodes\n
"},{"location":"reference/django_components/#django_components.node.get_template_for_include_node","title":"get_template_for_include_node","text":"get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template\n
This snippet is taken directly from IncludeNode.render()
. Unfortunately the render logic doesn't separate out template loading logic from rendering, so we have to copy the method.
Source code in src/django_components/node.py
def get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template:\n \"\"\"\n This snippet is taken directly from `IncludeNode.render()`. Unfortunately the\n render logic doesn't separate out template loading logic from rendering, so we\n have to copy the method.\n \"\"\"\n template = include_node.template.resolve(context)\n # Does this quack like a Template?\n if not callable(getattr(template, \"render\", None)):\n # If not, try the cache and select_template().\n template_name = template or ()\n if isinstance(template_name, str):\n template_name = (\n construct_relative_path(\n include_node.origin.template_name,\n template_name,\n ),\n )\n else:\n template_name = tuple(template_name)\n cache = context.render_context.dicts[0].setdefault(include_node, {})\n template = cache.get(template_name)\n if template is None:\n template = context.template.engine.select_template(template_name)\n cache[template_name] = template\n # Use the base.Template of a backends.django.Template.\n elif hasattr(template, \"template\"):\n template = template.template\n return template\n
"},{"location":"reference/django_components/#django_components.node.walk_nodelist","title":"walk_nodelist","text":"walk_nodelist(nodes: NodeList, callback: Callable[[Node], Optional[str]], context: Optional[Context] = None) -> None\n
Recursively walk a NodeList, calling callback
for each Node.
Source code in src/django_components/node.py
def walk_nodelist(\n nodes: NodeList,\n callback: Callable[[Node], Optional[str]],\n context: Optional[Context] = None,\n) -> None:\n \"\"\"Recursively walk a NodeList, calling `callback` for each Node.\"\"\"\n node_queue: List[NodeTraverse] = [NodeTraverse(node=node, parent=None) for node in nodes]\n while len(node_queue):\n traverse = node_queue.pop()\n callback(traverse)\n child_nodes = get_node_children(traverse.node, context)\n child_traverses = [NodeTraverse(node=child_node, parent=traverse) for child_node in child_nodes]\n node_queue.extend(child_traverses)\n
"},{"location":"reference/django_components/#django_components.provide","title":"provide","text":""},{"location":"reference/django_components/#django_components.provide.ProvideNode","title":"ProvideNode","text":"ProvideNode(name: str, nodelist: NodeList, node_id: Optional[str] = None, kwargs: Optional[RuntimeKwargs] = None)\n
Bases: BaseNode
Implementation of the {% provide %}
tag. For more info see Component.inject
.
Source code in src/django_components/provide.py
def __init__(\n self,\n name: str,\n nodelist: NodeList,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.nodelist = nodelist\n self.node_id = node_id or gen_id()\n self.kwargs = kwargs or RuntimeKwargs({})\n
"},{"location":"reference/django_components/#django_components.safer_staticfiles","title":"safer_staticfiles","text":""},{"location":"reference/django_components/#django_components.safer_staticfiles.apps","title":"apps","text":""},{"location":"reference/django_components/#django_components.safer_staticfiles.apps.SaferStaticFilesConfig","title":"SaferStaticFilesConfig","text":" Bases: StaticFilesConfig
Extend the ignore_patterns
class attr of StaticFilesConfig to include Python modules and HTML files.
When this class is registered as an installed app, $ ./manage.py collectstatic
will ignore .py and .html files, preventing potentially sensitive backend logic from being leaked by the static file server.
See https://docs.djangoproject.com/en/5.0/ref/contrib/staticfiles/#customizing-the-ignored-pattern-list
"},{"location":"reference/django_components/#django_components.slots","title":"slots","text":""},{"location":"reference/django_components/#django_components.slots.FillContent","title":"FillContent dataclass
","text":"FillContent(content_func: SlotFunc[TSlotData], slot_default_var: Optional[SlotDefaultName], slot_data_var: Optional[SlotDataName])\n
Bases: Generic[TSlotData]
This represents content set with the {% fill %}
tag, e.g.:
{% component \"my_comp\" %}\n {% fill \"first_slot\" %} <--- This\n hi\n {{ my_var }}\n hello\n {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/django_components/#django_components.slots.FillNode","title":"FillNode","text":"FillNode(name: FilterExpression, nodelist: NodeList, kwargs: RuntimeKwargs, node_id: Optional[str] = None, is_implicit: bool = False)\n
Bases: BaseNode
Set when a component
tag pair is passed template content that excludes fill
tags. Nodes of this type contribute their nodelists to slots marked as 'default'.
Source code in src/django_components/slots.py
def __init__(\n self,\n name: FilterExpression,\n nodelist: NodeList,\n kwargs: RuntimeKwargs,\n node_id: Optional[str] = None,\n is_implicit: bool = False,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.is_implicit = is_implicit\n self.component_id: Optional[str] = None\n
"},{"location":"reference/django_components/#django_components.slots.Slot","title":"Slot","text":" Bases: NamedTuple
This represents content set with the {% slot %}
tag, e.g.:
{% slot \"my_comp\" default %} <--- This\n hi\n {{ my_var }}\n hello\n{% endslot %}\n
"},{"location":"reference/django_components/#django_components.slots.SlotFill","title":"SlotFill dataclass
","text":"SlotFill(\n name: str,\n escaped_name: str,\n is_filled: bool,\n content_func: SlotFunc[TSlotData],\n context_data: Mapping,\n slot_default_var: Optional[SlotDefaultName],\n slot_data_var: Optional[SlotDataName],\n)\n
Bases: Generic[TSlotData]
SlotFill describes what WILL be rendered.
It is a Slot that has been resolved against FillContents passed to a Component.
"},{"location":"reference/django_components/#django_components.slots.SlotNode","title":"SlotNode","text":"SlotNode(\n name: str,\n nodelist: NodeList,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n is_required: bool = False,\n is_default: bool = False,\n)\n
Bases: BaseNode
Source code in src/django_components/slots.py
def __init__(\n self,\n name: str,\n nodelist: NodeList,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n is_required: bool = False,\n is_default: bool = False,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.is_required = is_required\n self.is_default = is_default\n
"},{"location":"reference/django_components/#django_components.slots.SlotRef","title":"SlotRef","text":"SlotRef(slot: SlotNode, context: Context)\n
SlotRef allows to treat a slot as a variable. The slot is rendered only once the instance is coerced to string.
This is used to access slots as variables inside the templates. When a SlotRef is rendered in the template with {{ my_lazy_slot }}
, it will output the contents of the slot.
Source code in src/django_components/slots.py
def __init__(self, slot: \"SlotNode\", context: Context):\n self._slot = slot\n self._context = context\n
"},{"location":"reference/django_components/#django_components.slots.parse_slot_fill_nodes_from_component_nodelist","title":"parse_slot_fill_nodes_from_component_nodelist","text":"parse_slot_fill_nodes_from_component_nodelist(component_nodelist: NodeList, ComponentNodeCls: Type[Node]) -> List[FillNode]\n
Given a component body (django.template.NodeList
), find all slot fills, whether defined explicitly with {% fill %}
or implicitly.
So if we have a component body:
{% component \"mycomponent\" %}\n {% fill \"first_fill\" %}\n Hello!\n {% endfill %}\n {% fill \"second_fill\" %}\n Hello too!\n {% endfill %}\n{% endcomponent %}\n
Then this function returns the nodes (django.template.Node
) for fill \"first_fill\"
and fill \"second_fill\"
. Source code in src/django_components/slots.py
def parse_slot_fill_nodes_from_component_nodelist(\n component_nodelist: NodeList,\n ComponentNodeCls: Type[Node],\n) -> List[FillNode]:\n \"\"\"\n Given a component body (`django.template.NodeList`), find all slot fills,\n whether defined explicitly with `{% fill %}` or implicitly.\n\n So if we have a component body:\n ```django\n {% component \"mycomponent\" %}\n {% fill \"first_fill\" %}\n Hello!\n {% endfill %}\n {% fill \"second_fill\" %}\n Hello too!\n {% endfill %}\n {% endcomponent %}\n ```\n Then this function returns the nodes (`django.template.Node`) for `fill \"first_fill\"`\n and `fill \"second_fill\"`.\n \"\"\"\n fill_nodes: List[FillNode] = []\n if nodelist_has_content(component_nodelist):\n for parse_fn in (\n _try_parse_as_default_fill,\n _try_parse_as_named_fill_tag_set,\n ):\n curr_fill_nodes = parse_fn(component_nodelist, ComponentNodeCls)\n if curr_fill_nodes:\n fill_nodes = curr_fill_nodes\n break\n else:\n raise TemplateSyntaxError(\n \"Illegal content passed to 'component' tag pair. \"\n \"Possible causes: 1) Explicit 'fill' tags cannot occur alongside other \"\n \"tags except comment tags; 2) Default (default slot-targeting) content \"\n \"is mixed with explict 'fill' tags.\"\n )\n return fill_nodes\n
"},{"location":"reference/django_components/#django_components.slots.resolve_slots","title":"resolve_slots","text":"resolve_slots(\n context: Context,\n template: Template,\n component_name: Optional[str],\n context_data: Mapping[str, Any],\n fill_content: Dict[SlotName, FillContent],\n) -> Tuple[Dict[SlotId, Slot], Dict[SlotId, SlotFill]]\n
Search the template for all SlotNodes, and associate the slots with the given fills.
Returns tuple of: - Slots defined in the component's Template with {% slot %}
tag - SlotFills (AKA slots matched with fills) describing what will be rendered for each slot.
Source code in src/django_components/slots.py
def resolve_slots(\n context: Context,\n template: Template,\n component_name: Optional[str],\n context_data: Mapping[str, Any],\n fill_content: Dict[SlotName, FillContent],\n) -> Tuple[Dict[SlotId, Slot], Dict[SlotId, SlotFill]]:\n \"\"\"\n Search the template for all SlotNodes, and associate the slots\n with the given fills.\n\n Returns tuple of:\n - Slots defined in the component's Template with `{% slot %}` tag\n - SlotFills (AKA slots matched with fills) describing what will be rendered for each slot.\n \"\"\"\n slot_fills = {\n name: SlotFill(\n name=name,\n escaped_name=_escape_slot_name(name),\n is_filled=True,\n content_func=fill.content_func,\n context_data=context_data,\n slot_default_var=fill.slot_default_var,\n slot_data_var=fill.slot_data_var,\n )\n for name, fill in fill_content.items()\n }\n\n slots: Dict[SlotId, Slot] = {}\n # This holds info on which slot (key) has which slots nested in it (value list)\n slot_children: Dict[SlotId, List[SlotId]] = {}\n\n def on_node(entry: NodeTraverse) -> None:\n node = entry.node\n if not isinstance(node, SlotNode):\n return\n\n # 1. Collect slots\n # Basically we take all the important info form the SlotNode, so the logic is\n # less coupled to Django's Template/Node. Plain tuples should also help with\n # troubleshooting.\n slot = Slot(\n id=node.node_id,\n name=node.name,\n nodelist=node.nodelist,\n is_default=node.is_default,\n is_required=node.is_required,\n )\n slots[node.node_id] = slot\n\n # 2. Figure out which Slots are nested in other Slots, so we can render\n # them from outside-inwards, so we can skip inner Slots if fills are provided.\n # We should end up with a graph-like data like:\n # - 0001: [0002]\n # - 0002: []\n # - 0003: [0004]\n # In other words, the data tells us that slot ID 0001 is PARENT of slot 0002.\n curr_entry = entry.parent\n while curr_entry and curr_entry.parent is not None:\n if not isinstance(curr_entry.node, SlotNode):\n curr_entry = curr_entry.parent\n continue\n\n parent_slot_id = curr_entry.node.node_id\n if parent_slot_id not in slot_children:\n slot_children[parent_slot_id] = []\n slot_children[parent_slot_id].append(node.node_id)\n break\n\n walk_nodelist(template.nodelist, on_node, context)\n\n # 3. Figure out which slot the default/implicit fill belongs to\n slot_fills = _resolve_default_slot(\n template_name=template.name,\n component_name=component_name,\n slots=slots,\n slot_fills=slot_fills,\n )\n\n # 4. Detect any errors with slots/fills\n _report_slot_errors(slots, slot_fills, component_name)\n\n # 5. Find roots of the slot relationships\n top_level_slot_ids: List[SlotId] = []\n for node_id, slot in slots.items():\n if node_id not in slot_children or not slot_children[node_id]:\n top_level_slot_ids.append(node_id)\n\n # 6. Walk from out-most slots inwards, and decide whether and how\n # we will render each slot.\n resolved_slots: Dict[SlotId, SlotFill] = {}\n slot_ids_queue = deque([*top_level_slot_ids])\n while len(slot_ids_queue):\n slot_id = slot_ids_queue.pop()\n slot = slots[slot_id]\n\n # Check if there is a slot fill for given slot name\n if slot.name in slot_fills:\n # If yes, we remember which slot we want to replace with already-rendered fills\n resolved_slots[slot_id] = slot_fills[slot.name]\n # Since the fill cannot include other slots, we can leave this path\n continue\n else:\n # If no, then the slot is NOT filled, and we will render the slot's default (what's\n # between the slot tags)\n resolved_slots[slot_id] = SlotFill(\n name=slot.name,\n escaped_name=_escape_slot_name(slot.name),\n is_filled=False,\n content_func=_nodelist_to_slot_render_func(slot.nodelist),\n context_data=context_data,\n slot_default_var=None,\n slot_data_var=None,\n )\n # Since the slot's default CAN include other slots (because it's defined in\n # the same template), we need to enqueue the slot's children\n if slot_id in slot_children and slot_children[slot_id]:\n slot_ids_queue.extend(slot_children[slot_id])\n\n # By the time we get here, we should know, for each slot, how it will be rendered\n # -> Whether it will be replaced with a fill, or whether we render slot's defaults.\n return slots, resolved_slots\n
"},{"location":"reference/django_components/#django_components.tag_formatter","title":"tag_formatter","text":""},{"location":"reference/django_components/#django_components.tag_formatter.ComponentFormatter","title":"ComponentFormatter","text":"ComponentFormatter(tag: str)\n
Bases: TagFormatterABC
The original django_component's component tag formatter, it uses the component
and endcomponent
tags, and the component name is gives as the first positional arg.
Example as block:
{% component \"mycomp\" abc=123 %}\n {% fill \"myfill\" %}\n ...\n {% endfill %}\n{% endcomponent %}\n
Example as inlined tag:
{% component \"mycomp\" abc=123 / %}\n
Source code in src/django_components/tag_formatter.py
def __init__(self, tag: str):\n self.tag = tag\n
"},{"location":"reference/django_components/#django_components.tag_formatter.InternalTagFormatter","title":"InternalTagFormatter","text":"InternalTagFormatter(tag_formatter: TagFormatterABC)\n
Internal wrapper around user-provided TagFormatters, so that we validate the outputs.
Source code in src/django_components/tag_formatter.py
def __init__(self, tag_formatter: TagFormatterABC):\n self.tag_formatter = tag_formatter\n
"},{"location":"reference/django_components/#django_components.tag_formatter.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":" Bases: TagFormatterABC
The component tag formatter that uses <name>
/ end<name>
tags.
This is similar to django-web-components and django-slippers syntax.
Example as block:
{% mycomp abc=123 %}\n {% fill \"myfill\" %}\n ...\n {% endfill %}\n{% endmycomp %}\n
Example as inlined tag:
{% mycomp abc=123 / %}\n
"},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC","title":"TagFormatterABC","text":" Bases: ABC
"},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC.end_tag","title":"end_tag abstractmethod
","text":"end_tag(name: str) -> str\n
Formats the end tag of a block component.
Source code in src/django_components/tag_formatter.py
@abc.abstractmethod\ndef end_tag(self, name: str) -> str:\n \"\"\"Formats the end tag of a block component.\"\"\"\n ...\n
"},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC.parse","title":"parse abstractmethod
","text":"parse(tokens: List[str]) -> TagResult\n
Given the tokens (words) of a component start tag, this function extracts the component name from the tokens list, and returns TagResult
, which is a tuple of (component_name, remaining_tokens)
.
Example:
Given a component declarations:
{% component \"my_comp\" key=val key2=val2 %}
This function receives a list of tokens
['component', '\"my_comp\"', 'key=val', 'key2=val2']
component
is the tag name, which we drop. \"my_comp\"
is the component name, but we must remove the extra quotes. And we pass remaining tokens unmodified, as that's the input to the component.
So in the end, we return a tuple:
('my_comp', ['key=val', 'key2=val2'])
Source code in src/django_components/tag_formatter.py
@abc.abstractmethod\ndef parse(self, tokens: List[str]) -> TagResult:\n \"\"\"\n Given the tokens (words) of a component start tag, this function extracts\n the component name from the tokens list, and returns `TagResult`, which\n is a tuple of `(component_name, remaining_tokens)`.\n\n Example:\n\n Given a component declarations:\n\n `{% component \"my_comp\" key=val key2=val2 %}`\n\n This function receives a list of tokens\n\n `['component', '\"my_comp\"', 'key=val', 'key2=val2']`\n\n `component` is the tag name, which we drop. `\"my_comp\"` is the component name,\n but we must remove the extra quotes. And we pass remaining tokens unmodified,\n as that's the input to the component.\n\n So in the end, we return a tuple:\n\n `('my_comp', ['key=val', 'key2=val2'])`\n \"\"\"\n ...\n
"},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC.start_tag","title":"start_tag abstractmethod
","text":"start_tag(name: str) -> str\n
Formats the start tag of a component.
Source code in src/django_components/tag_formatter.py
@abc.abstractmethod\ndef start_tag(self, name: str) -> str:\n \"\"\"Formats the start tag of a component.\"\"\"\n ...\n
"},{"location":"reference/django_components/#django_components.tag_formatter.TagResult","title":"TagResult","text":" Bases: NamedTuple
The return value from TagFormatter.parse()
"},{"location":"reference/django_components/#django_components.tag_formatter.TagResult.component_name","title":"component_name instance-attribute
","text":"component_name: str\n
Component name extracted from the template tag
"},{"location":"reference/django_components/#django_components.tag_formatter.TagResult.tokens","title":"tokens instance-attribute
","text":"tokens: List[str]\n
Remaining tokens (words) that were passed to the tag, with component name removed
"},{"location":"reference/django_components/#django_components.tag_formatter.get_tag_formatter","title":"get_tag_formatter","text":"get_tag_formatter() -> InternalTagFormatter\n
Returns an instance of the currently configured component tag formatter.
Source code in src/django_components/tag_formatter.py
def get_tag_formatter() -> InternalTagFormatter:\n \"\"\"Returns an instance of the currently configured component tag formatter.\"\"\"\n # Allow users to configure the component TagFormatter\n formatter_cls_or_str = app_settings.TAG_FORMATTER\n\n if isinstance(formatter_cls_or_str, str):\n tag_formatter: TagFormatterABC = import_string(formatter_cls_or_str)\n else:\n tag_formatter = formatter_cls_or_str\n\n return InternalTagFormatter(tag_formatter)\n
"},{"location":"reference/django_components/#django_components.template_loader","title":"template_loader","text":"Template loader that loads templates from each Django app's \"components\" directory.
"},{"location":"reference/django_components/#django_components.template_loader.Loader","title":"Loader","text":" Bases: Loader
"},{"location":"reference/django_components/#django_components.template_loader.Loader.get_dirs","title":"get_dirs","text":"get_dirs() -> List[Path]\n
Prepare directories that may contain component files:
Searches for dirs set in STATICFILES_DIRS
settings. If none set, defaults to searching for a \"components\" app. The dirs in STATICFILES_DIRS
must be absolute paths.
Paths are accepted only if they resolve to a directory. E.g. /path/to/django_project/my_app/components/
.
If STATICFILES_DIRS
is not set or empty, then BASE_DIR
is required.
Source code in src/django_components/template_loader.py
def get_dirs(self) -> List[Path]:\n \"\"\"\n Prepare directories that may contain component files:\n\n Searches for dirs set in `STATICFILES_DIRS` settings. If none set, defaults to searching\n for a \"components\" app. The dirs in `STATICFILES_DIRS` must be absolute paths.\n\n Paths are accepted only if they resolve to a directory.\n E.g. `/path/to/django_project/my_app/components/`.\n\n If `STATICFILES_DIRS` is not set or empty, then `BASE_DIR` is required.\n \"\"\"\n # Allow to configure from settings which dirs should be checked for components\n if hasattr(settings, \"STATICFILES_DIRS\") and settings.STATICFILES_DIRS:\n component_dirs = settings.STATICFILES_DIRS\n else:\n component_dirs = [settings.BASE_DIR / \"components\"]\n\n logger.debug(\n \"Template loader will search for valid template dirs from following options:\\n\"\n + \"\\n\".join([f\" - {str(d)}\" for d in component_dirs])\n )\n\n directories: Set[Path] = set()\n for component_dir in component_dirs:\n # Consider tuples for STATICFILES_DIRS (See #489)\n # See https://docs.djangoproject.com/en/5.0/ref/settings/#prefixes-optional\n if isinstance(component_dir, (tuple, list)) and len(component_dir) == 2:\n component_dir = component_dir[1]\n try:\n Path(component_dir)\n except TypeError:\n logger.warning(\n f\"STATICFILES_DIRS expected str, bytes or os.PathLike object, or tuple/list of length 2. \"\n f\"See Django documentation. Got {type(component_dir)} : {component_dir}\"\n )\n continue\n\n if not Path(component_dir).is_absolute():\n raise ValueError(f\"STATICFILES_DIRS must contain absolute paths, got '{component_dir}'\")\n else:\n directories.add(Path(component_dir).resolve())\n\n logger.debug(\n \"Template loader matched following template dirs:\\n\" + \"\\n\".join([f\" - {str(d)}\" for d in directories])\n )\n return list(directories)\n
"},{"location":"reference/django_components/#django_components.template_parser","title":"template_parser","text":"Overrides for the Django Template system to allow finer control over template parsing.
Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py
"},{"location":"reference/django_components/#django_components.template_parser.parse_bits","title":"parse_bits","text":"parse_bits(\n parser: Parser, bits: List[str], params: List[str], name: str\n) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]\n
Parse bits for template tag helpers simple_tag and inclusion_tag, in particular by detecting syntax errors and by extracting positional and keyword arguments.
This is a simplified version of django.template.library.parse_bits
where we use custom regex to handle special characters in keyword names.
Furthermore, our version allows duplicate keys, and instead of return kwargs as a dict, we return it as a list of key-value pairs. So it is up to the user of this function to decide whether they support duplicate keys or not.
Source code in src/django_components/template_parser.py
def parse_bits(\n parser: Parser,\n bits: List[str],\n params: List[str],\n name: str,\n) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]:\n \"\"\"\n Parse bits for template tag helpers simple_tag and inclusion_tag, in\n particular by detecting syntax errors and by extracting positional and\n keyword arguments.\n\n This is a simplified version of `django.template.library.parse_bits`\n where we use custom regex to handle special characters in keyword names.\n\n Furthermore, our version allows duplicate keys, and instead of return kwargs\n as a dict, we return it as a list of key-value pairs. So it is up to the\n user of this function to decide whether they support duplicate keys or not.\n \"\"\"\n args: List[FilterExpression] = []\n kwargs: List[Tuple[str, FilterExpression]] = []\n unhandled_params = list(params)\n for bit in bits:\n # First we try to extract a potential kwarg from the bit\n kwarg = token_kwargs([bit], parser)\n if kwarg:\n # The kwarg was successfully extracted\n param, value = kwarg.popitem()\n # All good, record the keyword argument\n kwargs.append((str(param), value))\n if param in unhandled_params:\n # If using the keyword syntax for a positional arg, then\n # consume it.\n unhandled_params.remove(param)\n else:\n if kwargs:\n raise TemplateSyntaxError(\n \"'%s' received some positional argument(s) after some \" \"keyword argument(s)\" % name\n )\n else:\n # Record the positional argument\n args.append(parser.compile_filter(bit))\n try:\n # Consume from the list of expected positional arguments\n unhandled_params.pop(0)\n except IndexError:\n pass\n if unhandled_params:\n # Some positional arguments were not supplied\n raise TemplateSyntaxError(\n \"'%s' did not receive value(s) for the argument(s): %s\"\n % (name, \", \".join(\"'%s'\" % p for p in unhandled_params))\n )\n return args, kwargs\n
"},{"location":"reference/django_components/#django_components.template_parser.token_kwargs","title":"token_kwargs","text":"token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]\n
Parse token keyword arguments and return a dictionary of the arguments retrieved from the bits
token list.
bits
is a list containing the remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments are removed from this list.
There is no requirement for all remaining token bits
to be keyword arguments, so return the dictionary as soon as an invalid argument format is reached.
Source code in src/django_components/template_parser.py
def token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]:\n \"\"\"\n Parse token keyword arguments and return a dictionary of the arguments\n retrieved from the ``bits`` token list.\n\n `bits` is a list containing the remainder of the token (split by spaces)\n that is to be checked for arguments. Valid arguments are removed from this\n list.\n\n There is no requirement for all remaining token ``bits`` to be keyword\n arguments, so return the dictionary as soon as an invalid argument format\n is reached.\n \"\"\"\n if not bits:\n return {}\n match = kwarg_re.match(bits[0])\n kwarg_format = match and match[1]\n if not kwarg_format:\n return {}\n\n kwargs: Dict[str, FilterExpression] = {}\n while bits:\n if kwarg_format:\n match = kwarg_re.match(bits[0])\n if not match or not match[1]:\n return kwargs\n key, value = match.groups()\n del bits[:1]\n else:\n if len(bits) < 3 or bits[1] != \"as\":\n return kwargs\n key, value = bits[2], bits[0]\n del bits[:3]\n\n # This is the only difference from the original token_kwargs. We use\n # the ComponentsFilterExpression instead of the original FilterExpression.\n kwargs[key] = ComponentsFilterExpression(value, parser)\n if bits and not kwarg_format:\n if bits[0] != \"and\":\n return kwargs\n del bits[:1]\n return kwargs\n
"},{"location":"reference/django_components/#django_components.templatetags","title":"templatetags","text":""},{"location":"reference/django_components/#django_components.templatetags.component_tags","title":"component_tags","text":""},{"location":"reference/django_components/#django_components.templatetags.component_tags.component","title":"component","text":"component(parser: Parser, token: Token, tag_name: str) -> ComponentNode\n
To give the component access to the template context {% component \"name\" positional_arg keyword_arg=value ... %}
To render the component in an isolated context {% component \"name\" positional_arg keyword_arg=value ... only %}
Positional and keyword arguments can be literals or template variables. The component name must be a single- or double-quotes string and must be either the first positional argument or, if there are no positional arguments, passed as 'name'.
Source code in src/django_components/templatetags/component_tags.py
def component(parser: Parser, token: Token, tag_name: str) -> ComponentNode:\n \"\"\"\n To give the component access to the template context:\n ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... %}```\n\n To render the component in an isolated context:\n ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... only %}```\n\n Positional and keyword arguments can be literals or template variables.\n The component name must be a single- or double-quotes string and must\n be either the first positional argument or, if there are no positional\n arguments, passed as 'name'.\n \"\"\"\n _fix_nested_tags(parser, token)\n bits = token.split_contents()\n\n # Let the TagFormatter pre-process the tokens\n formatter = get_tag_formatter()\n result = formatter.parse([*bits])\n end_tag = formatter.end_tag(result.component_name)\n\n # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n bits = [bits[0], *result.tokens]\n token.contents = \" \".join(bits)\n\n tag = _parse_tag(\n tag_name,\n parser,\n token,\n params=True, # Allow many args\n flags=[\"only\"],\n keywordonly_kwargs=True,\n repeatable_kwargs=False,\n end_tag=end_tag,\n )\n\n # Check for isolated context keyword\n isolated_context = tag.flags[\"only\"] or app_settings.CONTEXT_BEHAVIOR == ContextBehavior.ISOLATED\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n body = tag.parse_body()\n fill_nodes = parse_slot_fill_nodes_from_component_nodelist(body, ComponentNode)\n\n # Tag all fill nodes as children of this particular component instance\n for node in fill_nodes:\n trace_msg(\"ASSOC\", \"FILL\", node.name, node.node_id, component_id=tag.id)\n node.component_id = tag.id\n\n component_node = ComponentNode(\n name=result.component_name,\n args=tag.args,\n kwargs=tag.kwargs,\n isolated_context=isolated_context,\n fill_nodes=fill_nodes,\n node_id=tag.id,\n )\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n return component_node\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"component_css_dependencies(preload: str = '') -> SafeString\n
Marks location where CSS link tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_css_dependencies\")\ndef component_css_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where CSS link tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_css_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.component_dependencies","title":"component_dependencies","text":"component_dependencies(preload: str = '') -> SafeString\n
Marks location where CSS link and JS script tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_dependencies\")\ndef component_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where CSS link and JS script tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER + JS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"component_js_dependencies(preload: str = '') -> SafeString\n
Marks location where JS script tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_js_dependencies\")\ndef component_js_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where JS script tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + JS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_js_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.fill","title":"fill","text":"fill(parser: Parser, token: Token) -> FillNode\n
Block tag whose contents 'fill' (are inserted into) an identically named 'slot'-block in the component template referred to by a parent component. It exists to make component nesting easier.
This tag is available only within a {% component %}..{% endcomponent %} block. Runtime checks should prohibit other usages.
Source code in src/django_components/templatetags/component_tags.py
@register.tag(\"fill\")\ndef fill(parser: Parser, token: Token) -> FillNode:\n \"\"\"\n Block tag whose contents 'fill' (are inserted into) an identically named\n 'slot'-block in the component template referred to by a parent component.\n It exists to make component nesting easier.\n\n This tag is available only within a {% component %}..{% endcomponent %} block.\n Runtime checks should prohibit other usages.\n \"\"\"\n tag = _parse_tag(\n \"fill\",\n parser,\n token,\n params=[\"name\"],\n keywordonly_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n repeatable_kwargs=False,\n end_tag=\"endfill\",\n )\n slot_name = tag.named_args[\"name\"]\n\n trace_msg(\"PARSE\", \"FILL\", str(slot_name), tag.id)\n\n body = tag.parse_body()\n fill_node = FillNode(\n nodelist=body,\n name=slot_name,\n node_id=tag.id,\n kwargs=tag.kwargs,\n )\n\n trace_msg(\"PARSE\", \"FILL\", str(slot_name), tag.id, \"...Done!\")\n return fill_node\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode\n
This tag takes: - Optional dictionary of attributes (attrs
) - Optional dictionary of defaults (defaults
) - Additional kwargs that are appended to the former two
The inputs are merged and resulting dict is rendered as HTML attributes (key=\"value\"
).
Rules: 1. Both attrs
and defaults
can be passed as positional args or as kwargs 2. Both attrs
and defaults
are optional (can be omitted) 3. Both attrs
and defaults
are dictionaries, and we can define them the same way we define dictionaries for the component
tag. So either as attrs=attrs
or attrs:key=value
. 4. All other kwargs (key=value
) are appended and can be repeated.
Normal kwargs (key=value
) are concatenated to existing keys. So if e.g. key \"class\" is supplied with value \"my-class\", then adding class=\"extra-class\"
will result in `class=\"my-class extra-class\".
Example:
{% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n
Source code in src/django_components/templatetags/component_tags.py
@register.tag(\"html_attrs\")\ndef html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode:\n \"\"\"\n This tag takes:\n - Optional dictionary of attributes (`attrs`)\n - Optional dictionary of defaults (`defaults`)\n - Additional kwargs that are appended to the former two\n\n The inputs are merged and resulting dict is rendered as HTML attributes\n (`key=\"value\"`).\n\n Rules:\n 1. Both `attrs` and `defaults` can be passed as positional args or as kwargs\n 2. Both `attrs` and `defaults` are optional (can be omitted)\n 3. Both `attrs` and `defaults` are dictionaries, and we can define them the same way\n we define dictionaries for the `component` tag. So either as `attrs=attrs` or\n `attrs:key=value`.\n 4. All other kwargs (`key=value`) are appended and can be repeated.\n\n Normal kwargs (`key=value`) are concatenated to existing keys. So if e.g. key\n \"class\" is supplied with value \"my-class\", then adding `class=\"extra-class\"`\n will result in `class=\"my-class extra-class\".\n\n Example:\n ```htmldjango\n {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n ```\n \"\"\"\n tag = _parse_tag(\n \"html_attrs\",\n parser,\n token,\n params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n optional_params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n flags=[],\n keywordonly_kwargs=True,\n repeatable_kwargs=True,\n )\n\n return HtmlAttrsNode(\n kwargs=tag.kwargs,\n kwarg_pairs=tag.kwarg_pairs,\n )\n
"},{"location":"reference/django_components/#django_components.types","title":"types","text":"Helper types for IDEs.
"},{"location":"reference/django_components/#django_components.utils","title":"utils","text":""},{"location":"reference/django_components/#django_components.utils.gen_id","title":"gen_id","text":"gen_id(length: int = 5) -> str\n
Generate a unique ID that can be associated with a Node
Source code in src/django_components/utils.py
def gen_id(length: int = 5) -> str:\n \"\"\"Generate a unique ID that can be associated with a Node\"\"\"\n # Global counter to avoid conflicts\n global _id\n _id += 1\n\n # Pad the ID with `0`s up to 4 digits, e.g. `0007`\n return f\"{_id:04}\"\n
"},{"location":"reference/django_components/app_settings/","title":"
app_settings","text":""},{"location":"reference/django_components/app_settings/#django_components.app_settings","title":"app_settings","text":""},{"location":"reference/django_components/app_settings/#django_components.app_settings.ContextBehavior","title":"ContextBehavior","text":" Bases: str
, Enum
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ContextBehavior.DJANGO","title":"DJANGO class-attribute
instance-attribute
","text":"DJANGO = 'django'\n
With this setting, component fills behave as usual Django tags. That is, they enrich the context, and pass it along.
- Component fills use the context of the component they are within.
- Variables from
get_context_data
are available to the component fill.
Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the get_context_data()
method
{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
456 # my_var\nfeta # cheese\n
Because \"my_comp\" overrides the variable \"my_var\", so {{ my_var }}
equals 456
.
And variable \"cheese\" will equal feta
, because the fill CAN access the current context.
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ContextBehavior.ISOLATED","title":"ISOLATED class-attribute
instance-attribute
","text":"ISOLATED = 'isolated'\n
This setting makes the component fills behave similar to Vue or React, where the fills use EXCLUSIVELY the context variables defined in get_context_data
.
Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the get_context_data()
method
{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
123 # my_var\n # cheese\n
Because both variables \"my_var\" and \"cheese\" are taken from the root context. Since \"cheese\" is not defined in root context, it's empty.
"},{"location":"reference/django_components/apps/","title":"
apps","text":""},{"location":"reference/django_components/apps/#django_components.apps","title":"apps","text":""},{"location":"reference/django_components/attributes/","title":"
attributes","text":""},{"location":"reference/django_components/attributes/#django_components.attributes","title":"attributes","text":""},{"location":"reference/django_components/attributes/#django_components.attributes.append_attributes","title":"append_attributes","text":"append_attributes(*args: Tuple[str, Any]) -> Dict\n
Merges the key-value pairs and returns a new dictionary.
If a key is present multiple times, its values are concatenated with a space character as separator in the final dictionary.
Source code in src/django_components/attributes.py
def append_attributes(*args: Tuple[str, Any]) -> Dict:\n \"\"\"\n Merges the key-value pairs and returns a new dictionary.\n\n If a key is present multiple times, its values are concatenated with a space\n character as separator in the final dictionary.\n \"\"\"\n result: Dict = {}\n\n for key, value in args:\n if key in result:\n result[key] += \" \" + value\n else:\n result[key] = value\n\n return result\n
"},{"location":"reference/django_components/attributes/#django_components.attributes.attributes_to_string","title":"attributes_to_string","text":"attributes_to_string(attributes: Mapping[str, Any]) -> str\n
Convert a dict of attributes to a string.
Source code in src/django_components/attributes.py
def attributes_to_string(attributes: Mapping[str, Any]) -> str:\n \"\"\"Convert a dict of attributes to a string.\"\"\"\n attr_list = []\n\n for key, value in attributes.items():\n if value is None or value is False:\n continue\n if value is True:\n attr_list.append(conditional_escape(key))\n else:\n attr_list.append(format_html('{}=\"{}\"', key, value))\n\n return mark_safe(SafeString(\" \").join(attr_list))\n
"},{"location":"reference/django_components/autodiscover/","title":"
autodiscover","text":""},{"location":"reference/django_components/autodiscover/#django_components.autodiscover","title":"autodiscover","text":""},{"location":"reference/django_components/autodiscover/#django_components.autodiscover.autodiscover","title":"autodiscover","text":"autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Search for component files and import them. Returns a list of module paths of imported files.
Autodiscover searches in the locations as defined by Loader.get_dirs
.
You can map the module paths with map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Source code in src/django_components/autodiscover.py
def autodiscover(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Search for component files and import them. Returns a list of module\n paths of imported files.\n\n Autodiscover searches in the locations as defined by `Loader.get_dirs`.\n\n You can map the module paths with `map_module` function. This serves\n as an escape hatch for when you need to use this function in tests.\n \"\"\"\n dirs = get_dirs()\n component_filepaths = search_dirs(dirs, \"**/*.py\")\n logger.debug(f\"Autodiscover found {len(component_filepaths)} files in component directories.\")\n\n modules = [_filepath_to_python_module(filepath) for filepath in component_filepaths]\n return _import_modules(modules, map_module)\n
"},{"location":"reference/django_components/autodiscover/#django_components.autodiscover.get_dirs","title":"get_dirs","text":"get_dirs(engine: Optional[Engine] = None) -> List[Path]\n
Helper for using django_component's FilesystemLoader class to obtain a list of directories where component python files may be defined.
Source code in src/django_components/autodiscover.py
def get_dirs(engine: Optional[Engine] = None) -> List[Path]:\n \"\"\"\n Helper for using django_component's FilesystemLoader class to obtain a list\n of directories where component python files may be defined.\n \"\"\"\n current_engine = engine\n if current_engine is None:\n current_engine = Engine.get_default()\n\n loader = Loader(current_engine)\n return loader.get_dirs()\n
"},{"location":"reference/django_components/autodiscover/#django_components.autodiscover.import_libraries","title":"import_libraries","text":"import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Import modules set in COMPONENTS.libraries
setting.
You can map the module paths with map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Source code in src/django_components/autodiscover.py
def import_libraries(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Import modules set in `COMPONENTS.libraries` setting.\n\n You can map the module paths with `map_module` function. This serves\n as an escape hatch for when you need to use this function in tests.\n \"\"\"\n from django_components.app_settings import app_settings\n\n return _import_modules(app_settings.LIBRARIES, map_module)\n
"},{"location":"reference/django_components/autodiscover/#django_components.autodiscover.search_dirs","title":"search_dirs","text":"search_dirs(dirs: List[Path], search_glob: str) -> List[Path]\n
Search the directories for the given glob pattern. Glob search results are returned as a flattened list.
Source code in src/django_components/autodiscover.py
def search_dirs(dirs: List[Path], search_glob: str) -> List[Path]:\n \"\"\"\n Search the directories for the given glob pattern. Glob search results are returned\n as a flattened list.\n \"\"\"\n matched_files: List[Path] = []\n for directory in dirs:\n for path in glob.iglob(str(Path(directory) / search_glob), recursive=True):\n matched_files.append(Path(path))\n\n return matched_files\n
"},{"location":"reference/django_components/component/","title":"
component","text":""},{"location":"reference/django_components/component/#django_components.component","title":"component","text":""},{"location":"reference/django_components/component/#django_components.component.Component","title":"Component","text":"Component(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n fill_content: Optional[Dict[str, FillContent]] = None,\n)\n
Bases: Generic[ArgsType, KwargsType, DataType, SlotsType]
Source code in src/django_components/component.py
def __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n fill_content: Optional[Dict[str, FillContent]] = None,\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.fill_content = fill_content or {}\n self.component_id = component_id or gen_id()\n self._render_stack: Deque[RenderInput[ArgsType, KwargsType, SlotsType]] = deque()\n
"},{"location":"reference/django_components/component/#django_components.component.Component.Media","title":"Media class-attribute
instance-attribute
","text":"Media = ComponentMediaInput\n
Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/component/#django_components.component.Component.css","title":"css class-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/component/#django_components.component.Component.input","title":"input property
","text":"input: Optional[RenderInput[ArgsType, KwargsType, SlotsType]]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the render
method.
"},{"location":"reference/django_components/component/#django_components.component.Component.js","title":"js class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/component/#django_components.component.Component.media","title":"media instance-attribute
","text":"media: Media\n
Normalized definition of JS and CSS media files associated with this component.
NOTE: This field is generated from Component.Media class.
"},{"location":"reference/django_components/component/#django_components.component.Component.response_class","title":"response_class class-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from render_to_response
"},{"location":"reference/django_components/component/#django_components.component.Component.template","title":"template class-attribute
instance-attribute
","text":"template: Optional[str] = None\n
Inlined Django template associated with this component.
"},{"location":"reference/django_components/component/#django_components.component.Component.template_name","title":"template_name class-attribute
","text":"template_name: Optional[str] = None\n
Relative filepath to the Django template associated with this component.
"},{"location":"reference/django_components/component/#django_components.component.Component.as_view","title":"as_view classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling Component.View.as_view
and passing component instance to it.
Source code in src/django_components/component.py
@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # Allow the View class to access this component via `self.component`\n component = cls()\n return component.View.as_view(**initkwargs, component=component)\n
"},{"location":"reference/django_components/component/#django_components.component.Component.inject","title":"inject","text":"inject(key: str, default: Optional[Any] = None) -> Any\n
Use this method to retrieve the data that was passed to a {% provide %}
tag with the corresponding key.
To retrieve the data, inject()
must be called inside a component that's inside the {% provide %}
tag.
You may also pass a default that will be used if the provide
tag with given key was NOT found.
This method mut be used inside the get_context_data()
method and raises an error if called elsewhere.
Example:
Given this template:
{% provide \"provider\" hello=\"world\" %}\n {% component \"my_comp\" %}\n {% endcomponent %}\n{% endprovide %}\n
And given this definition of \"my_comp\" component:
from django_components import Component, register\n\n@register(\"my_comp\")\nclass MyComp(Component):\n template = \"hi {{ data.hello }}!\"\n def get_context_data(self):\n data = self.inject(\"provider\")\n return {\"data\": data}\n
This renders into:
hi world!\n
As the {{ data.hello }}
is taken from the \"provider\".
Source code in src/django_components/component.py
def inject(self, key: str, default: Optional[Any] = None) -> Any:\n \"\"\"\n Use this method to retrieve the data that was passed to a `{% provide %}` tag\n with the corresponding key.\n\n To retrieve the data, `inject()` must be called inside a component that's\n inside the `{% provide %}` tag.\n\n You may also pass a default that will be used if the `provide` tag with given\n key was NOT found.\n\n This method mut be used inside the `get_context_data()` method and raises\n an error if called elsewhere.\n\n Example:\n\n Given this template:\n ```django\n {% provide \"provider\" hello=\"world\" %}\n {% component \"my_comp\" %}\n {% endcomponent %}\n {% endprovide %}\n ```\n\n And given this definition of \"my_comp\" component:\n ```py\n from django_components import Component, register\n\n @register(\"my_comp\")\n class MyComp(Component):\n template = \"hi {{ data.hello }}!\"\n def get_context_data(self):\n data = self.inject(\"provider\")\n return {\"data\": data}\n ```\n\n This renders into:\n ```\n hi world!\n ```\n\n As the `{{ data.hello }}` is taken from the \"provider\".\n \"\"\"\n if self.input is None:\n raise RuntimeError(\n f\"Method 'inject()' of component '{self.name}' was called outside of 'get_context_data()'\"\n )\n\n return get_injected_context_var(self.name, self.input.context, key, default)\n
"},{"location":"reference/django_components/component/#django_components.component.Component.render","title":"render classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n) -> str\n
Render the component into a string.
Inputs: - args
- Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %}
- kwargs
- Kwargs for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %}
- slots
- Component slot fills. This is the same as pasing {% fill %}
tags to the component. Accepts a dictionary of { slot_name: slot_content }
where slot_content
can be a string or render function. - escape_slots_content
- Whether the content from slots
should be escaped. - context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs.
Example:
MyComponent.render(\n args=[1, \"two\", {}],\n kwargs={\n \"key\": 123,\n },\n slots={\n \"header\": 'STATIC TEXT HERE',\n \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n },\n escape_slots_content=False,\n)\n
Source code in src/django_components/component.py
@classmethod\ndef render(\n cls,\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n) -> str:\n \"\"\"\n Render the component into a string.\n\n Inputs:\n - `args` - Positional args for the component. This is the same as calling the component\n as `{% component \"my_comp\" arg1 arg2 ... %}`\n - `kwargs` - Kwargs for the component. This is the same as calling the component\n as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n or render function.\n - `escape_slots_content` - Whether the content from `slots` should be escaped.\n - `context` - A context (dictionary or Django's Context) within which the component\n is rendered. The keys on the context can be accessed from within the template.\n - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n component's args and kwargs.\n\n Example:\n ```py\n MyComponent.render(\n args=[1, \"two\", {}],\n kwargs={\n \"key\": 123,\n },\n slots={\n \"header\": 'STATIC TEXT HERE',\n \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n },\n escape_slots_content=False,\n )\n ```\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n return comp._render(context, args, kwargs, slots, escape_slots_content)\n
"},{"location":"reference/django_components/component/#django_components.component.Component.render_css_dependencies","title":"render_css_dependencies","text":"render_css_dependencies() -> SafeString\n
Render only CSS dependencies available in the media class or provided as a string.
Source code in src/django_components/component.py
def render_css_dependencies(self) -> SafeString:\n \"\"\"Render only CSS dependencies available in the media class or provided as a string.\"\"\"\n if self.css is not None:\n return mark_safe(f\"<style>{self.css}</style>\")\n return mark_safe(\"\\n\".join(self.media.render_css()))\n
"},{"location":"reference/django_components/component/#django_components.component.Component.render_dependencies","title":"render_dependencies","text":"render_dependencies() -> SafeString\n
Helper function to render all dependencies for a component.
Source code in src/django_components/component.py
def render_dependencies(self) -> SafeString:\n \"\"\"Helper function to render all dependencies for a component.\"\"\"\n dependencies = []\n\n css_deps = self.render_css_dependencies()\n if css_deps:\n dependencies.append(css_deps)\n\n js_deps = self.render_js_dependencies()\n if js_deps:\n dependencies.append(js_deps)\n\n return mark_safe(\"\\n\".join(dependencies))\n
"},{"location":"reference/django_components/component/#django_components.component.Component.render_js_dependencies","title":"render_js_dependencies","text":"render_js_dependencies() -> SafeString\n
Render only JS dependencies available in the media class or provided as a string.
Source code in src/django_components/component.py
def render_js_dependencies(self) -> SafeString:\n \"\"\"Render only JS dependencies available in the media class or provided as a string.\"\"\"\n if self.js is not None:\n return mark_safe(f\"<script>{self.js}</script>\")\n return mark_safe(\"\\n\".join(self.media.render_js()))\n
"},{"location":"reference/django_components/component/#django_components.component.Component.render_to_response","title":"render_to_response classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n *response_args: Any,\n **response_kwargs: Any\n) -> HttpResponse\n
Render the component and wrap the content in the response class.
The response class is taken from Component.response_class
. Defaults to django.http.HttpResponse
.
This is the interface for the django.views.View
class which allows us to use components as Django views with component.as_view()
.
Inputs: - args
- Positional args for the component. This is the same as calling the component as {% component \"my_comp\" arg1 arg2 ... %}
- kwargs
- Kwargs for the component. This is the same as calling the component as {% component \"my_comp\" key1=val1 key2=val2 ... %}
- slots
- Component slot fills. This is the same as pasing {% fill %}
tags to the component. Accepts a dictionary of { slot_name: slot_content }
where slot_content
can be a string or render function. - escape_slots_content
- Whether the content from slots
should be escaped. - context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs.
Any additional args and kwargs are passed to the response_class
.
Example:
MyComponent.render_to_response(\n args=[1, \"two\", {}],\n kwargs={\n \"key\": 123,\n },\n slots={\n \"header\": 'STATIC TEXT HERE',\n \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n },\n escape_slots_content=False,\n # HttpResponse input\n status=201,\n headers={...},\n)\n# HttpResponse(content=..., status=201, headers=...)\n
Source code in src/django_components/component.py
@classmethod\ndef render_to_response(\n cls,\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n *response_args: Any,\n **response_kwargs: Any,\n) -> HttpResponse:\n \"\"\"\n Render the component and wrap the content in the response class.\n\n The response class is taken from `Component.response_class`. Defaults to `django.http.HttpResponse`.\n\n This is the interface for the `django.views.View` class which allows us to\n use components as Django views with `component.as_view()`.\n\n Inputs:\n - `args` - Positional args for the component. This is the same as calling the component\n as `{% component \"my_comp\" arg1 arg2 ... %}`\n - `kwargs` - Kwargs for the component. This is the same as calling the component\n as `{% component \"my_comp\" key1=val1 key2=val2 ... %}`\n - `slots` - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.\n Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string\n or render function.\n - `escape_slots_content` - Whether the content from `slots` should be escaped.\n - `context` - A context (dictionary or Django's Context) within which the component\n is rendered. The keys on the context can be accessed from within the template.\n - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via\n component's args and kwargs.\n\n Any additional args and kwargs are passed to the `response_class`.\n\n Example:\n ```py\n MyComponent.render_to_response(\n args=[1, \"two\", {}],\n kwargs={\n \"key\": 123,\n },\n slots={\n \"header\": 'STATIC TEXT HERE',\n \"footer\": lambda ctx, slot_kwargs, slot_ref: f'CTX: {ctx['hello']} SLOT_DATA: {slot_kwargs['abc']}',\n },\n escape_slots_content=False,\n # HttpResponse input\n status=201,\n headers={...},\n )\n # HttpResponse(content=..., status=201, headers=...)\n ```\n \"\"\"\n content = cls.render(\n args=args,\n kwargs=kwargs,\n context=context,\n slots=slots,\n escape_slots_content=escape_slots_content,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
"},{"location":"reference/django_components/component/#django_components.component.ComponentNode","title":"ComponentNode","text":"ComponentNode(\n name: str,\n args: List[Expression],\n kwargs: RuntimeKwargs,\n isolated_context: bool = False,\n fill_nodes: Optional[List[FillNode]] = None,\n node_id: Optional[str] = None,\n)\n
Bases: BaseNode
Django.template.Node subclass that renders a django-components component
Source code in src/django_components/component.py
def __init__(\n self,\n name: str,\n args: List[Expression],\n kwargs: RuntimeKwargs,\n isolated_context: bool = False,\n fill_nodes: Optional[List[FillNode]] = None,\n node_id: Optional[str] = None,\n) -> None:\n super().__init__(nodelist=NodeList(fill_nodes), args=args, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.isolated_context = isolated_context\n self.fill_nodes = fill_nodes or []\n
"},{"location":"reference/django_components/component/#django_components.component.ComponentView","title":"ComponentView","text":"ComponentView(component: Component, **kwargs: Any)\n
Bases: View
Subclass of django.views.View
where the Component
instance is available via self.component
.
Source code in src/django_components/component.py
def __init__(self, component: \"Component\", **kwargs: Any) -> None:\n super().__init__(**kwargs)\n self.component = component\n
"},{"location":"reference/django_components/component_media/","title":"
component_media","text":""},{"location":"reference/django_components/component_media/#django_components.component_media","title":"component_media","text":""},{"location":"reference/django_components/component_media/#django_components.component_media.ComponentMediaInput","title":"ComponentMediaInput","text":"Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta","title":"MediaMeta","text":" Bases: MediaDefiningClass
Metaclass for handling media files for components.
Similar to MediaDefiningClass
, this class supports the use of Media
attribute to define associated JS/CSS files, which are then available under media
attribute as a instance of Media
class.
This subclass has following changes:
"},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--1-support-for-multiple-interfaces-of-jscss","title":"1. Support for multiple interfaces of JS/CSS","text":" -
As plain strings
class MyComponent(Component):\n class Media:\n js = \"path/to/script.js\"\n css = \"path/to/style.css\"\n
-
As lists
class MyComponent(Component):\n class Media:\n js = [\"path/to/script1.js\", \"path/to/script2.js\"]\n css = [\"path/to/style1.css\", \"path/to/style2.css\"]\n
-
[CSS ONLY] Dicts of strings
class MyComponent(Component):\n class Media:\n css = {\n \"all\": \"path/to/style1.css\",\n \"print\": \"path/to/style2.css\",\n }\n
-
[CSS ONLY] Dicts of lists
class MyComponent(Component):\n class Media:\n css = {\n \"all\": [\"path/to/style1.css\"],\n \"print\": [\"path/to/style2.css\"],\n }\n
"},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--2-media-are-first-resolved-relative-to-class-definition-file","title":"2. Media are first resolved relative to class definition file","text":"E.g. if in a directory my_comp
you have script.js
and my_comp.py
, and my_comp.py
looks like this:
class MyComponent(Component):\n class Media:\n js = \"script.js\"\n
Then script.js
will be resolved as my_comp/script.js
.
"},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--3-media-can-be-defined-as-str-bytes-pathlike-safestring-or-function-of-thereof","title":"3. Media can be defined as str, bytes, PathLike, SafeString, or function of thereof","text":"E.g.:
def lazy_eval_css():\n # do something\n return path\n\nclass MyComponent(Component):\n class Media:\n js = b\"script.js\"\n css = lazy_eval_css\n
"},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--4-subclass-media-class-with-media_class","title":"4. Subclass Media
class with media_class
","text":"Normal MediaDefiningClass
creates an instance of Media
class under the media
attribute. This class allows to override which class will be instantiated with media_class
attribute:
class MyMedia(Media):\n def render_js(self):\n ...\n\nclass MyComponent(Component):\n media_class = MyMedia\n def get_context_data(self):\n assert isinstance(self.media, MyMedia)\n
"},{"location":"reference/django_components/component_registry/","title":"
component_registry","text":""},{"location":"reference/django_components/component_registry/#django_components.component_registry","title":"component_registry","text":""},{"location":"reference/django_components/component_registry/#django_components.component_registry.registry","title":"registry module-attribute
","text":"registry: ComponentRegistry = ComponentRegistry()\n
The default and global component registry. Use this instance to directly register or remove components:
# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Get single\nregistry.get(\"button\")\n# Get all\nregistry.all()\n# Unregister single\nregistry.unregister(\"button\")\n# Unregister all\nregistry.clear()\n
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry","title":"ComponentRegistry","text":"ComponentRegistry(library: Optional[Library] = None)\n
Manages which components can be used in the template tags.
Each ComponentRegistry instance is associated with an instance of Django's Library. So when you register or unregister a component to/from a component registry, behind the scenes the registry automatically adds/removes the component's template tag to/from the Library.
The Library instance can be set at instantiation. If omitted, then the default Library instance from django_components is used. The Library instance can be accessed under library
attribute.
Example:
# Use with default Library\nregistry = ComponentRegistry()\n\n# Or a custom one\nmy_lib = Library()\nregistry = ComponentRegistry(library=my_lib)\n\n# Usage\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\nregistry.all()\nregistry.clear()\nregistry.get()\n
Source code in src/django_components/component_registry.py
def __init__(self, library: Optional[Library] = None) -> None:\n self._registry: Dict[str, ComponentRegistryEntry] = {} # component name -> component_entry mapping\n self._tags: Dict[str, Set[str]] = {} # tag -> list[component names]\n self._library = library\n
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.library","title":"library property
","text":"library: Library\n
The template tag library with which the component registry is associated.
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.all","title":"all","text":"all() -> Dict[str, Type[Component]]\n
Retrieve all registered component classes.
Example:
# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then get all\nregistry.all()\n# > {\n# > \"button\": ButtonComponent,\n# > \"card\": CardComponent,\n# > }\n
Source code in src/django_components/component_registry.py
def all(self) -> Dict[str, Type[\"Component\"]]:\n \"\"\"\n Retrieve all registered component classes.\n\n Example:\n\n ```py\n # First register components\n registry.register(\"button\", ButtonComponent)\n registry.register(\"card\", CardComponent)\n # Then get all\n registry.all()\n # > {\n # > \"button\": ButtonComponent,\n # > \"card\": CardComponent,\n # > }\n ```\n \"\"\"\n comps = {key: entry.cls for key, entry in self._registry.items()}\n return comps\n
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.clear","title":"clear","text":"clear() -> None\n
Clears the registry, unregistering all components.
Example:
# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then clear\nregistry.clear()\n# Then get all\nregistry.all()\n# > {}\n
Source code in src/django_components/component_registry.py
def clear(self) -> None:\n \"\"\"\n Clears the registry, unregistering all components.\n\n Example:\n\n ```py\n # First register components\n registry.register(\"button\", ButtonComponent)\n registry.register(\"card\", CardComponent)\n # Then clear\n registry.clear()\n # Then get all\n registry.all()\n # > {}\n ```\n \"\"\"\n all_comp_names = list(self._registry.keys())\n for comp_name in all_comp_names:\n self.unregister(comp_name)\n\n self._registry = {}\n self._tags = {}\n
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.get","title":"get","text":"get(name: str) -> Type[Component]\n
Retrieve a component class registered under the given name.
Raises NotRegistered
if the given name is not registered.
Example:
# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then get\nregistry.get(\"button\")\n# > ButtonComponent\n
Source code in src/django_components/component_registry.py
def get(self, name: str) -> Type[\"Component\"]:\n \"\"\"\n Retrieve a component class registered under the given name.\n\n Raises `NotRegistered` if the given name is not registered.\n\n Example:\n\n ```py\n # First register component\n registry.register(\"button\", ButtonComponent)\n # Then get\n registry.get(\"button\")\n # > ButtonComponent\n ```\n \"\"\"\n if name not in self._registry:\n raise NotRegistered('The component \"%s\" is not registered' % name)\n\n return self._registry[name].cls\n
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.register","title":"register","text":"register(name: str, component: Type[Component]) -> None\n
Register a component with this registry under the given name.
A component MUST be registered before it can be used in a template such as:
{% component \"my_comp\" %}{% endcomponent %}\n
Raises AlreadyRegistered
if a different component was already registered under the same name.
Example:
registry.register(\"button\", ButtonComponent)\n
Source code in src/django_components/component_registry.py
def register(self, name: str, component: Type[\"Component\"]) -> None:\n \"\"\"\n Register a component with this registry under the given name.\n\n A component MUST be registered before it can be used in a template such as:\n ```django\n {% component \"my_comp\" %}{% endcomponent %}\n ```\n\n Raises `AlreadyRegistered` if a different component was already registered\n under the same name.\n\n Example:\n\n ```py\n registry.register(\"button\", ButtonComponent)\n ```\n \"\"\"\n existing_component = self._registry.get(name)\n if existing_component and existing_component.cls._class_hash != component._class_hash:\n raise AlreadyRegistered('The component \"%s\" has already been registered' % name)\n\n entry = self._register_to_library(name, component)\n\n # Keep track of which components use which tags, because multiple components may\n # use the same tag.\n tag = entry.tag\n if tag not in self._tags:\n self._tags[tag] = set()\n self._tags[tag].add(name)\n\n self._registry[name] = entry\n
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.unregister","title":"unregister","text":"unregister(name: str) -> None\n
Unlinks a previously-registered component from the registry under the given name.
Once a component is unregistered, it CANNOT be used in a template anymore. Following would raise an error:
{% component \"my_comp\" %}{% endcomponent %}\n
Raises NotRegistered
if the given name is not registered.
Example:
# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
Source code in src/django_components/component_registry.py
def unregister(self, name: str) -> None:\n \"\"\"\n Unlinks a previously-registered component from the registry under the given name.\n\n Once a component is unregistered, it CANNOT be used in a template anymore.\n Following would raise an error:\n ```django\n {% component \"my_comp\" %}{% endcomponent %}\n ```\n\n Raises `NotRegistered` if the given name is not registered.\n\n Example:\n\n ```py\n # First register component\n registry.register(\"button\", ButtonComponent)\n # Then unregister\n registry.unregister(\"button\")\n ```\n \"\"\"\n # Validate\n self.get(name)\n\n entry = self._registry[name]\n tag = entry.tag\n\n # Unregister the tag from library if this was the last component using this tag\n # Unlink component from tag\n self._tags[tag].remove(name)\n\n # Cleanup\n is_tag_empty = not len(self._tags[tag])\n if is_tag_empty:\n del self._tags[tag]\n\n # Only unregister a tag if it's NOT protected\n is_protected = is_tag_protected(self.library, tag)\n if not is_protected:\n # Unregister the tag from library if this was the last component using this tag\n if is_tag_empty and tag in self.library.tags:\n del self.library.tags[tag]\n\n del self._registry[name]\n
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.register","title":"register","text":"register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]\n
Class decorator to register a component.
Usage:
@register(\"my_component\")\nclass MyComponent(Component):\n ...\n
Optionally specify which ComponentRegistry
the component should be registered to by setting the registry
kwarg:
my_lib = django.template.Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n ...\n
Source code in src/django_components/component_registry.py
def register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]:\n \"\"\"\n Class decorator to register a component.\n\n Usage:\n\n ```py\n @register(\"my_component\")\n class MyComponent(Component):\n ...\n ```\n\n Optionally specify which `ComponentRegistry` the component should be registered to by\n setting the `registry` kwarg:\n\n ```py\n my_lib = django.template.Library()\n my_reg = ComponentRegistry(library=my_lib)\n\n @register(\"my_component\", registry=my_reg)\n class MyComponent(Component):\n ...\n ```\n \"\"\"\n if registry is None:\n registry = _the_registry\n\n def decorator(component: _TComp) -> _TComp:\n registry.register(name=name, component=component)\n return component\n\n return decorator\n
"},{"location":"reference/django_components/context/","title":"
context","text":""},{"location":"reference/django_components/context/#django_components.context","title":"context","text":"This file centralizes various ways we use Django's Context class pass data across components, nodes, slots, and contexts.
You can think of the Context as our storage system.
"},{"location":"reference/django_components/context/#django_components.context.copy_forloop_context","title":"copy_forloop_context","text":"copy_forloop_context(from_context: Context, to_context: Context) -> None\n
Forward the info about the current loop
Source code in src/django_components/context.py
def copy_forloop_context(from_context: Context, to_context: Context) -> None:\n \"\"\"Forward the info about the current loop\"\"\"\n # Note that the ForNode (which implements for loop behavior) does not\n # only add the `forloop` key, but also keys corresponding to the loop elements\n # So if the loop syntax is `{% for my_val in my_lists %}`, then ForNode also\n # sets a `my_val` key.\n # For this reason, instead of copying individual keys, we copy the whole stack layer\n # set by ForNode.\n if \"forloop\" in from_context:\n forloop_dict_index = find_last_index(from_context.dicts, lambda d: \"forloop\" in d)\n to_context.update(from_context.dicts[forloop_dict_index])\n
"},{"location":"reference/django_components/context/#django_components.context.get_injected_context_var","title":"get_injected_context_var","text":"get_injected_context_var(component_name: str, context: Context, key: str, default: Optional[Any] = None) -> Any\n
Retrieve a 'provided' field. The field MUST have been previously 'provided' by the component's ancestors using the {% provide %}
template tag.
Source code in src/django_components/context.py
def get_injected_context_var(\n component_name: str,\n context: Context,\n key: str,\n default: Optional[Any] = None,\n) -> Any:\n \"\"\"\n Retrieve a 'provided' field. The field MUST have been previously 'provided'\n by the component's ancestors using the `{% provide %}` template tag.\n \"\"\"\n # NOTE: For simplicity, we keep the provided values directly on the context.\n # This plays nicely with Django's Context, which behaves like a stack, so \"newer\"\n # values overshadow the \"older\" ones.\n internal_key = _INJECT_CONTEXT_KEY_PREFIX + key\n\n # Return provided value if found\n if internal_key in context:\n return context[internal_key]\n\n # If a default was given, return that\n if default is not None:\n return default\n\n # Otherwise raise error\n raise KeyError(\n f\"Component '{component_name}' tried to inject a variable '{key}' before it was provided.\"\n f\" To fix this, make sure that at least one ancestor of component '{component_name}' has\"\n f\" the variable '{key}' in their 'provide' attribute.\"\n )\n
"},{"location":"reference/django_components/context/#django_components.context.prepare_context","title":"prepare_context","text":"prepare_context(context: Context, component_id: str) -> None\n
Initialize the internal context state.
Source code in src/django_components/context.py
def prepare_context(\n context: Context,\n component_id: str,\n) -> None:\n \"\"\"Initialize the internal context state.\"\"\"\n # Initialize mapping dicts within this rendering run.\n # This is shared across the whole render chain, thus we set it only once.\n if _FILLED_SLOTS_CONTENT_CONTEXT_KEY not in context:\n context[_FILLED_SLOTS_CONTENT_CONTEXT_KEY] = {}\n\n set_component_id(context, component_id)\n
"},{"location":"reference/django_components/context/#django_components.context.set_component_id","title":"set_component_id","text":"set_component_id(context: Context, component_id: str) -> None\n
We use the Context object to pass down info on inside of which component we are currently rendering.
Source code in src/django_components/context.py
def set_component_id(context: Context, component_id: str) -> None:\n \"\"\"\n We use the Context object to pass down info on inside of which component\n we are currently rendering.\n \"\"\"\n # Store the previous component so we can detect if the current component\n # is the top-most or not. If it is, then \"_parent_component_id\" is None\n context[_PARENT_COMP_CONTEXT_KEY] = context.get(_CURRENT_COMP_CONTEXT_KEY, None)\n context[_CURRENT_COMP_CONTEXT_KEY] = component_id\n
"},{"location":"reference/django_components/context/#django_components.context.set_provided_context_var","title":"set_provided_context_var","text":"set_provided_context_var(context: Context, key: str, provided_kwargs: Dict[str, Any]) -> None\n
'Provide' given data under given key. In other words, this data can be retrieved using self.inject(key)
inside of get_context_data()
method of components that are nested inside the {% provide %}
tag.
Source code in src/django_components/context.py
def set_provided_context_var(\n context: Context,\n key: str,\n provided_kwargs: Dict[str, Any],\n) -> None:\n \"\"\"\n 'Provide' given data under given key. In other words, this data can be retrieved\n using `self.inject(key)` inside of `get_context_data()` method of components that\n are nested inside the `{% provide %}` tag.\n \"\"\"\n # NOTE: We raise TemplateSyntaxError since this func should be called only from\n # within template.\n if not key:\n raise TemplateSyntaxError(\n \"Provide tag received an empty string. Key must be non-empty and a valid identifier.\"\n )\n if not key.isidentifier():\n raise TemplateSyntaxError(\n \"Provide tag received a non-identifier string. Key must be non-empty and a valid identifier.\"\n )\n\n # We turn the kwargs into a NamedTuple so that the object that's \"provided\"\n # is immutable. This ensures that the data returned from `inject` will always\n # have all the keys that were passed to the `provide` tag.\n tpl_cls = namedtuple(\"DepInject\", provided_kwargs.keys()) # type: ignore[misc]\n payload = tpl_cls(**provided_kwargs)\n\n internal_key = _INJECT_CONTEXT_KEY_PREFIX + key\n context[internal_key] = payload\n
"},{"location":"reference/django_components/expression/","title":"
expression","text":""},{"location":"reference/django_components/expression/#django_components.expression","title":"expression","text":""},{"location":"reference/django_components/expression/#django_components.expression.Operator","title":"Operator","text":" Bases: ABC
Operator describes something that somehow changes the inputs to template tags (the {% %}
).
For example, a SpreadOperator inserts one or more kwargs at the specified location.
"},{"location":"reference/django_components/expression/#django_components.expression.SpreadOperator","title":"SpreadOperator","text":"SpreadOperator(expr: Expression)\n
Bases: Operator
Operator that inserts one or more kwargs at the specified location.
Source code in src/django_components/expression.py
def __init__(self, expr: Expression) -> None:\n self.expr = expr\n
"},{"location":"reference/django_components/expression/#django_components.expression.process_aggregate_kwargs","title":"process_aggregate_kwargs","text":"process_aggregate_kwargs(kwargs: Mapping[str, Any]) -> Dict[str, Any]\n
This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs start with some prefix delimited with :
(e.g. attrs:
).
Example:
process_component_kwargs({\"abc:one\": 1, \"abc:two\": 2, \"def:three\": 3, \"four\": 4})\n# {\"abc\": {\"one\": 1, \"two\": 2}, \"def\": {\"three\": 3}, \"four\": 4}\n
We want to support a use case similar to Vue's fallthrough attributes. In other words, where a component author can designate a prop (input) which is a dict and which will be rendered as HTML attributes.
This is useful for allowing component users to tweak styling or add event handling to the underlying HTML. E.g.:
class=\"pa-4 d-flex text-black\"
or @click.stop=\"alert('clicked!')\"
So if the prop is attrs
, and the component is called like so:
{% component \"my_comp\" attrs=attrs %}\n
then, if attrs
is:
{\"class\": \"text-red pa-4\", \"@click\": \"dispatch('my_event', 123)\"}\n
and the component template is:
<div {% html_attrs attrs add:class=\"extra-class\" %}></div>\n
Then this renders:
<div class=\"text-red pa-4 extra-class\" @click=\"dispatch('my_event', 123)\" ></div>\n
However, this way it is difficult for the component user to define the attrs
variable, especially if they want to combine static and dynamic values. Because they will need to pre-process the attrs
dict.
So, instead, we allow to \"aggregate\" props into a dict. So all props that start with attrs:
, like attrs:class=\"text-red\"
, will be collected into a dict at key attrs
.
This provides sufficient flexiblity to make it easy for component users to provide \"fallthrough attributes\", and sufficiently easy for component authors to process that input while still being able to provide their own keys.
Source code in src/django_components/expression.py
def process_aggregate_kwargs(kwargs: Mapping[str, Any]) -> Dict[str, Any]:\n \"\"\"\n This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs\n start with some prefix delimited with `:` (e.g. `attrs:`).\n\n Example:\n ```py\n process_component_kwargs({\"abc:one\": 1, \"abc:two\": 2, \"def:three\": 3, \"four\": 4})\n # {\"abc\": {\"one\": 1, \"two\": 2}, \"def\": {\"three\": 3}, \"four\": 4}\n ```\n\n ---\n\n We want to support a use case similar to Vue's fallthrough attributes.\n In other words, where a component author can designate a prop (input)\n which is a dict and which will be rendered as HTML attributes.\n\n This is useful for allowing component users to tweak styling or add\n event handling to the underlying HTML. E.g.:\n\n `class=\"pa-4 d-flex text-black\"` or `@click.stop=\"alert('clicked!')\"`\n\n So if the prop is `attrs`, and the component is called like so:\n ```django\n {% component \"my_comp\" attrs=attrs %}\n ```\n\n then, if `attrs` is:\n ```py\n {\"class\": \"text-red pa-4\", \"@click\": \"dispatch('my_event', 123)\"}\n ```\n\n and the component template is:\n ```django\n <div {% html_attrs attrs add:class=\"extra-class\" %}></div>\n ```\n\n Then this renders:\n ```html\n <div class=\"text-red pa-4 extra-class\" @click=\"dispatch('my_event', 123)\" ></div>\n ```\n\n However, this way it is difficult for the component user to define the `attrs`\n variable, especially if they want to combine static and dynamic values. Because\n they will need to pre-process the `attrs` dict.\n\n So, instead, we allow to \"aggregate\" props into a dict. So all props that start\n with `attrs:`, like `attrs:class=\"text-red\"`, will be collected into a dict\n at key `attrs`.\n\n This provides sufficient flexiblity to make it easy for component users to provide\n \"fallthrough attributes\", and sufficiently easy for component authors to process\n that input while still being able to provide their own keys.\n \"\"\"\n processed_kwargs = {}\n nested_kwargs: Dict[str, Dict[str, Any]] = {}\n for key, val in kwargs.items():\n if not is_aggregate_key(key):\n processed_kwargs[key] = val\n continue\n\n # NOTE: Trim off the prefix from keys\n prefix, sub_key = key.split(\":\", 1)\n if prefix not in nested_kwargs:\n nested_kwargs[prefix] = {}\n nested_kwargs[prefix][sub_key] = val\n\n # Assign aggregated values into normal input\n for key, val in nested_kwargs.items():\n if key in processed_kwargs:\n raise TemplateSyntaxError(\n f\"Received argument '{key}' both as a regular input ({key}=...)\"\n f\" and as an aggregate dict ('{key}:key=...'). Must be only one of the two\"\n )\n processed_kwargs[key] = val\n\n return processed_kwargs\n
"},{"location":"reference/django_components/library/","title":"
library","text":""},{"location":"reference/django_components/library/#django_components.library","title":"library","text":"Module for interfacing with Django's Library (django.template.library
)
"},{"location":"reference/django_components/library/#django_components.library.PROTECTED_TAGS","title":"PROTECTED_TAGS module-attribute
","text":"PROTECTED_TAGS = [\n \"component_dependencies\",\n \"component_css_dependencies\",\n \"component_js_dependencies\",\n \"fill\",\n \"html_attrs\",\n \"provide\",\n \"slot\",\n]\n
These are the names that users cannot choose for their components, as they would conflict with other tags in the Library.
"},{"location":"reference/django_components/logger/","title":"
logger","text":""},{"location":"reference/django_components/logger/#django_components.logger","title":"logger","text":""},{"location":"reference/django_components/logger/#django_components.logger.trace","title":"trace","text":"trace(logger: Logger, message: str, *args: Any, **kwargs: Any) -> None\n
TRACE level logger.
To display TRACE logs, set the logging level to 5.
Example:
LOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"handlers\": {\n \"console\": {\n \"class\": \"logging.StreamHandler\",\n \"stream\": sys.stdout,\n },\n },\n \"loggers\": {\n \"django_components\": {\n \"level\": 5,\n \"handlers\": [\"console\"],\n },\n },\n}\n
Source code in src/django_components/logger.py
def trace(logger: logging.Logger, message: str, *args: Any, **kwargs: Any) -> None:\n \"\"\"\n TRACE level logger.\n\n To display TRACE logs, set the logging level to 5.\n\n Example:\n ```py\n LOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"handlers\": {\n \"console\": {\n \"class\": \"logging.StreamHandler\",\n \"stream\": sys.stdout,\n },\n },\n \"loggers\": {\n \"django_components\": {\n \"level\": 5,\n \"handlers\": [\"console\"],\n },\n },\n }\n ```\n \"\"\"\n if actual_trace_level_num == -1:\n setup_logging()\n if logger.isEnabledFor(actual_trace_level_num):\n logger.log(actual_trace_level_num, message, *args, **kwargs)\n
"},{"location":"reference/django_components/logger/#django_components.logger.trace_msg","title":"trace_msg","text":"trace_msg(\n action: Literal[\"PARSE\", \"ASSOC\", \"RENDR\", \"GET\", \"SET\"],\n node_type: Literal[\"COMP\", \"FILL\", \"SLOT\", \"PROVIDE\", \"N/A\"],\n node_name: str,\n node_id: str,\n msg: str = \"\",\n component_id: Optional[str] = None,\n) -> None\n
TRACE level logger with opinionated format for tracing interaction of components, nodes, and slots. Formats messages like so:
\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"
Source code in src/django_components/logger.py
def trace_msg(\n action: Literal[\"PARSE\", \"ASSOC\", \"RENDR\", \"GET\", \"SET\"],\n node_type: Literal[\"COMP\", \"FILL\", \"SLOT\", \"PROVIDE\", \"N/A\"],\n node_name: str,\n node_id: str,\n msg: str = \"\",\n component_id: Optional[str] = None,\n) -> None:\n \"\"\"\n TRACE level logger with opinionated format for tracing interaction of components,\n nodes, and slots. Formats messages like so:\n\n `\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"`\n \"\"\"\n msg_prefix = \"\"\n if action == \"ASSOC\":\n if not component_id:\n raise ValueError(\"component_id must be set for the ASSOC action\")\n msg_prefix = f\"TO COMP {component_id}\"\n elif action == \"RENDR\" and node_type == \"FILL\":\n if not component_id:\n raise ValueError(\"component_id must be set for the RENDER action\")\n msg_prefix = f\"FOR COMP {component_id}\"\n\n msg_parts = [f\"{action} {node_type} {node_name} ID {node_id}\", *([msg_prefix] if msg_prefix else []), msg]\n full_msg = \" \".join(msg_parts)\n\n # NOTE: When debugging tests during development, it may be easier to change\n # this to `print()`\n trace(logger, full_msg)\n
"},{"location":"reference/django_components/management/","title":"Index","text":""},{"location":"reference/django_components/management/#django_components.management","title":"management","text":""},{"location":"reference/django_components/management/#django_components.management.commands","title":"commands","text":""},{"location":"reference/django_components/management/#django_components.management.commands.upgradecomponent","title":"upgradecomponent","text":""},{"location":"reference/django_components/management/commands/","title":"Index","text":""},{"location":"reference/django_components/management/commands/#django_components.management.commands","title":"commands","text":""},{"location":"reference/django_components/management/commands/#django_components.management.commands.upgradecomponent","title":"upgradecomponent","text":""},{"location":"reference/django_components/management/commands/startcomponent/","title":"
startcomponent","text":""},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent","title":"startcomponent","text":""},{"location":"reference/django_components/management/commands/upgradecomponent/","title":"
upgradecomponent","text":""},{"location":"reference/django_components/management/commands/upgradecomponent/#django_components.management.commands.upgradecomponent","title":"upgradecomponent","text":""},{"location":"reference/django_components/middleware/","title":"
middleware","text":""},{"location":"reference/django_components/middleware/#django_components.middleware","title":"middleware","text":""},{"location":"reference/django_components/middleware/#django_components.middleware.ComponentDependencyMiddleware","title":"ComponentDependencyMiddleware","text":"ComponentDependencyMiddleware(get_response: Callable[[HttpRequest], HttpResponse])\n
Middleware that inserts CSS/JS dependencies for all rendered components at points marked with template tags.
Source code in src/django_components/middleware.py
def __init__(self, get_response: \"Callable[[HttpRequest], HttpResponse]\") -> None:\n self.get_response = get_response\n\n if iscoroutinefunction(self.get_response):\n markcoroutinefunction(self)\n
"},{"location":"reference/django_components/middleware/#django_components.middleware.DependencyReplacer","title":"DependencyReplacer","text":"DependencyReplacer(css_string: bytes, js_string: bytes)\n
Replacer for use in re.sub that replaces the first placeholder CSS and JS tags it encounters and removes any subsequent ones.
Source code in src/django_components/middleware.py
def __init__(self, css_string: bytes, js_string: bytes) -> None:\n self.js_string = js_string\n self.css_string = css_string\n
"},{"location":"reference/django_components/middleware/#django_components.middleware.join_media","title":"join_media","text":"join_media(components: Iterable[Component]) -> Media\n
Return combined media object for iterable of components.
Source code in src/django_components/middleware.py
def join_media(components: Iterable[\"Component\"]) -> Media:\n \"\"\"Return combined media object for iterable of components.\"\"\"\n\n return sum([component.media for component in components], Media())\n
"},{"location":"reference/django_components/node/","title":"
node","text":""},{"location":"reference/django_components/node/#django_components.node","title":"node","text":""},{"location":"reference/django_components/node/#django_components.node.BaseNode","title":"BaseNode","text":"BaseNode(\n nodelist: Optional[NodeList] = None,\n node_id: Optional[str] = None,\n args: Optional[List[Expression]] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n)\n
Bases: Node
Shared behavior for our subclasses of Django's Node
Source code in src/django_components/node.py
def __init__(\n self,\n nodelist: Optional[NodeList] = None,\n node_id: Optional[str] = None,\n args: Optional[List[Expression]] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n):\n self.nodelist = nodelist or NodeList()\n self.node_id = node_id or gen_id()\n self.args = args or []\n self.kwargs = kwargs or RuntimeKwargs({})\n
"},{"location":"reference/django_components/node/#django_components.node.get_node_children","title":"get_node_children","text":"get_node_children(node: Node, context: Optional[Context] = None) -> NodeList\n
Get child Nodes from Node's nodelist atribute.
This function is taken from get_nodes_by_type
method of django.template.base.Node
.
Source code in src/django_components/node.py
def get_node_children(node: Node, context: Optional[Context] = None) -> NodeList:\n \"\"\"\n Get child Nodes from Node's nodelist atribute.\n\n This function is taken from `get_nodes_by_type` method of `django.template.base.Node`.\n \"\"\"\n # Special case - {% extends %} tag - Load the template and go deeper\n if isinstance(node, ExtendsNode):\n # NOTE: When {% extends %} node is being parsed, it collects all remaining template\n # under node.nodelist.\n # Hence, when we come across ExtendsNode in the template, we:\n # 1. Go over all nodes in the template using `node.nodelist`\n # 2. Go over all nodes in the \"parent\" template, via `node.get_parent`\n nodes = NodeList()\n nodes.extend(node.nodelist)\n template = node.get_parent(context)\n nodes.extend(template.nodelist)\n return nodes\n\n # Special case - {% include %} tag - Load the template and go deeper\n elif isinstance(node, IncludeNode):\n template = get_template_for_include_node(node, context)\n return template.nodelist\n\n nodes = NodeList()\n for attr in node.child_nodelists:\n nodelist = getattr(node, attr, [])\n if nodelist:\n nodes.extend(nodelist)\n return nodes\n
"},{"location":"reference/django_components/node/#django_components.node.get_template_for_include_node","title":"get_template_for_include_node","text":"get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template\n
This snippet is taken directly from IncludeNode.render()
. Unfortunately the render logic doesn't separate out template loading logic from rendering, so we have to copy the method.
Source code in src/django_components/node.py
def get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template:\n \"\"\"\n This snippet is taken directly from `IncludeNode.render()`. Unfortunately the\n render logic doesn't separate out template loading logic from rendering, so we\n have to copy the method.\n \"\"\"\n template = include_node.template.resolve(context)\n # Does this quack like a Template?\n if not callable(getattr(template, \"render\", None)):\n # If not, try the cache and select_template().\n template_name = template or ()\n if isinstance(template_name, str):\n template_name = (\n construct_relative_path(\n include_node.origin.template_name,\n template_name,\n ),\n )\n else:\n template_name = tuple(template_name)\n cache = context.render_context.dicts[0].setdefault(include_node, {})\n template = cache.get(template_name)\n if template is None:\n template = context.template.engine.select_template(template_name)\n cache[template_name] = template\n # Use the base.Template of a backends.django.Template.\n elif hasattr(template, \"template\"):\n template = template.template\n return template\n
"},{"location":"reference/django_components/node/#django_components.node.walk_nodelist","title":"walk_nodelist","text":"walk_nodelist(nodes: NodeList, callback: Callable[[Node], Optional[str]], context: Optional[Context] = None) -> None\n
Recursively walk a NodeList, calling callback
for each Node.
Source code in src/django_components/node.py
def walk_nodelist(\n nodes: NodeList,\n callback: Callable[[Node], Optional[str]],\n context: Optional[Context] = None,\n) -> None:\n \"\"\"Recursively walk a NodeList, calling `callback` for each Node.\"\"\"\n node_queue: List[NodeTraverse] = [NodeTraverse(node=node, parent=None) for node in nodes]\n while len(node_queue):\n traverse = node_queue.pop()\n callback(traverse)\n child_nodes = get_node_children(traverse.node, context)\n child_traverses = [NodeTraverse(node=child_node, parent=traverse) for child_node in child_nodes]\n node_queue.extend(child_traverses)\n
"},{"location":"reference/django_components/provide/","title":"
provide","text":""},{"location":"reference/django_components/provide/#django_components.provide","title":"provide","text":""},{"location":"reference/django_components/provide/#django_components.provide.ProvideNode","title":"ProvideNode","text":"ProvideNode(name: str, nodelist: NodeList, node_id: Optional[str] = None, kwargs: Optional[RuntimeKwargs] = None)\n
Bases: BaseNode
Implementation of the {% provide %}
tag. For more info see Component.inject
.
Source code in src/django_components/provide.py
def __init__(\n self,\n name: str,\n nodelist: NodeList,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.nodelist = nodelist\n self.node_id = node_id or gen_id()\n self.kwargs = kwargs or RuntimeKwargs({})\n
"},{"location":"reference/django_components/safer_staticfiles/","title":"Index","text":""},{"location":"reference/django_components/safer_staticfiles/#django_components.safer_staticfiles","title":"safer_staticfiles","text":""},{"location":"reference/django_components/safer_staticfiles/#django_components.safer_staticfiles.apps","title":"apps","text":""},{"location":"reference/django_components/safer_staticfiles/#django_components.safer_staticfiles.apps.SaferStaticFilesConfig","title":"SaferStaticFilesConfig","text":" Bases: StaticFilesConfig
Extend the ignore_patterns
class attr of StaticFilesConfig to include Python modules and HTML files.
When this class is registered as an installed app, $ ./manage.py collectstatic
will ignore .py and .html files, preventing potentially sensitive backend logic from being leaked by the static file server.
See https://docs.djangoproject.com/en/5.0/ref/contrib/staticfiles/#customizing-the-ignored-pattern-list
"},{"location":"reference/django_components/safer_staticfiles/apps/","title":"
apps","text":""},{"location":"reference/django_components/safer_staticfiles/apps/#django_components.safer_staticfiles.apps","title":"apps","text":""},{"location":"reference/django_components/safer_staticfiles/apps/#django_components.safer_staticfiles.apps.SaferStaticFilesConfig","title":"SaferStaticFilesConfig","text":" Bases: StaticFilesConfig
Extend the ignore_patterns
class attr of StaticFilesConfig to include Python modules and HTML files.
When this class is registered as an installed app, $ ./manage.py collectstatic
will ignore .py and .html files, preventing potentially sensitive backend logic from being leaked by the static file server.
See https://docs.djangoproject.com/en/5.0/ref/contrib/staticfiles/#customizing-the-ignored-pattern-list
"},{"location":"reference/django_components/slots/","title":"
slots","text":""},{"location":"reference/django_components/slots/#django_components.slots","title":"slots","text":""},{"location":"reference/django_components/slots/#django_components.slots.FillContent","title":"FillContent dataclass
","text":"FillContent(content_func: SlotFunc[TSlotData], slot_default_var: Optional[SlotDefaultName], slot_data_var: Optional[SlotDataName])\n
Bases: Generic[TSlotData]
This represents content set with the {% fill %}
tag, e.g.:
{% component \"my_comp\" %}\n {% fill \"first_slot\" %} <--- This\n hi\n {{ my_var }}\n hello\n {% endfill %}\n{% endcomponent %}\n
"},{"location":"reference/django_components/slots/#django_components.slots.FillNode","title":"FillNode","text":"FillNode(name: FilterExpression, nodelist: NodeList, kwargs: RuntimeKwargs, node_id: Optional[str] = None, is_implicit: bool = False)\n
Bases: BaseNode
Set when a component
tag pair is passed template content that excludes fill
tags. Nodes of this type contribute their nodelists to slots marked as 'default'.
Source code in src/django_components/slots.py
def __init__(\n self,\n name: FilterExpression,\n nodelist: NodeList,\n kwargs: RuntimeKwargs,\n node_id: Optional[str] = None,\n is_implicit: bool = False,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.is_implicit = is_implicit\n self.component_id: Optional[str] = None\n
"},{"location":"reference/django_components/slots/#django_components.slots.Slot","title":"Slot","text":" Bases: NamedTuple
This represents content set with the {% slot %}
tag, e.g.:
{% slot \"my_comp\" default %} <--- This\n hi\n {{ my_var }}\n hello\n{% endslot %}\n
"},{"location":"reference/django_components/slots/#django_components.slots.SlotFill","title":"SlotFill dataclass
","text":"SlotFill(\n name: str,\n escaped_name: str,\n is_filled: bool,\n content_func: SlotFunc[TSlotData],\n context_data: Mapping,\n slot_default_var: Optional[SlotDefaultName],\n slot_data_var: Optional[SlotDataName],\n)\n
Bases: Generic[TSlotData]
SlotFill describes what WILL be rendered.
It is a Slot that has been resolved against FillContents passed to a Component.
"},{"location":"reference/django_components/slots/#django_components.slots.SlotNode","title":"SlotNode","text":"SlotNode(\n name: str,\n nodelist: NodeList,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n is_required: bool = False,\n is_default: bool = False,\n)\n
Bases: BaseNode
Source code in src/django_components/slots.py
def __init__(\n self,\n name: str,\n nodelist: NodeList,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n is_required: bool = False,\n is_default: bool = False,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.is_required = is_required\n self.is_default = is_default\n
"},{"location":"reference/django_components/slots/#django_components.slots.SlotRef","title":"SlotRef","text":"SlotRef(slot: SlotNode, context: Context)\n
SlotRef allows to treat a slot as a variable. The slot is rendered only once the instance is coerced to string.
This is used to access slots as variables inside the templates. When a SlotRef is rendered in the template with {{ my_lazy_slot }}
, it will output the contents of the slot.
Source code in src/django_components/slots.py
def __init__(self, slot: \"SlotNode\", context: Context):\n self._slot = slot\n self._context = context\n
"},{"location":"reference/django_components/slots/#django_components.slots.parse_slot_fill_nodes_from_component_nodelist","title":"parse_slot_fill_nodes_from_component_nodelist","text":"parse_slot_fill_nodes_from_component_nodelist(component_nodelist: NodeList, ComponentNodeCls: Type[Node]) -> List[FillNode]\n
Given a component body (django.template.NodeList
), find all slot fills, whether defined explicitly with {% fill %}
or implicitly.
So if we have a component body:
{% component \"mycomponent\" %}\n {% fill \"first_fill\" %}\n Hello!\n {% endfill %}\n {% fill \"second_fill\" %}\n Hello too!\n {% endfill %}\n{% endcomponent %}\n
Then this function returns the nodes (django.template.Node
) for fill \"first_fill\"
and fill \"second_fill\"
. Source code in src/django_components/slots.py
def parse_slot_fill_nodes_from_component_nodelist(\n component_nodelist: NodeList,\n ComponentNodeCls: Type[Node],\n) -> List[FillNode]:\n \"\"\"\n Given a component body (`django.template.NodeList`), find all slot fills,\n whether defined explicitly with `{% fill %}` or implicitly.\n\n So if we have a component body:\n ```django\n {% component \"mycomponent\" %}\n {% fill \"first_fill\" %}\n Hello!\n {% endfill %}\n {% fill \"second_fill\" %}\n Hello too!\n {% endfill %}\n {% endcomponent %}\n ```\n Then this function returns the nodes (`django.template.Node`) for `fill \"first_fill\"`\n and `fill \"second_fill\"`.\n \"\"\"\n fill_nodes: List[FillNode] = []\n if nodelist_has_content(component_nodelist):\n for parse_fn in (\n _try_parse_as_default_fill,\n _try_parse_as_named_fill_tag_set,\n ):\n curr_fill_nodes = parse_fn(component_nodelist, ComponentNodeCls)\n if curr_fill_nodes:\n fill_nodes = curr_fill_nodes\n break\n else:\n raise TemplateSyntaxError(\n \"Illegal content passed to 'component' tag pair. \"\n \"Possible causes: 1) Explicit 'fill' tags cannot occur alongside other \"\n \"tags except comment tags; 2) Default (default slot-targeting) content \"\n \"is mixed with explict 'fill' tags.\"\n )\n return fill_nodes\n
"},{"location":"reference/django_components/slots/#django_components.slots.resolve_slots","title":"resolve_slots","text":"resolve_slots(\n context: Context,\n template: Template,\n component_name: Optional[str],\n context_data: Mapping[str, Any],\n fill_content: Dict[SlotName, FillContent],\n) -> Tuple[Dict[SlotId, Slot], Dict[SlotId, SlotFill]]\n
Search the template for all SlotNodes, and associate the slots with the given fills.
Returns tuple of: - Slots defined in the component's Template with {% slot %}
tag - SlotFills (AKA slots matched with fills) describing what will be rendered for each slot.
Source code in src/django_components/slots.py
def resolve_slots(\n context: Context,\n template: Template,\n component_name: Optional[str],\n context_data: Mapping[str, Any],\n fill_content: Dict[SlotName, FillContent],\n) -> Tuple[Dict[SlotId, Slot], Dict[SlotId, SlotFill]]:\n \"\"\"\n Search the template for all SlotNodes, and associate the slots\n with the given fills.\n\n Returns tuple of:\n - Slots defined in the component's Template with `{% slot %}` tag\n - SlotFills (AKA slots matched with fills) describing what will be rendered for each slot.\n \"\"\"\n slot_fills = {\n name: SlotFill(\n name=name,\n escaped_name=_escape_slot_name(name),\n is_filled=True,\n content_func=fill.content_func,\n context_data=context_data,\n slot_default_var=fill.slot_default_var,\n slot_data_var=fill.slot_data_var,\n )\n for name, fill in fill_content.items()\n }\n\n slots: Dict[SlotId, Slot] = {}\n # This holds info on which slot (key) has which slots nested in it (value list)\n slot_children: Dict[SlotId, List[SlotId]] = {}\n\n def on_node(entry: NodeTraverse) -> None:\n node = entry.node\n if not isinstance(node, SlotNode):\n return\n\n # 1. Collect slots\n # Basically we take all the important info form the SlotNode, so the logic is\n # less coupled to Django's Template/Node. Plain tuples should also help with\n # troubleshooting.\n slot = Slot(\n id=node.node_id,\n name=node.name,\n nodelist=node.nodelist,\n is_default=node.is_default,\n is_required=node.is_required,\n )\n slots[node.node_id] = slot\n\n # 2. Figure out which Slots are nested in other Slots, so we can render\n # them from outside-inwards, so we can skip inner Slots if fills are provided.\n # We should end up with a graph-like data like:\n # - 0001: [0002]\n # - 0002: []\n # - 0003: [0004]\n # In other words, the data tells us that slot ID 0001 is PARENT of slot 0002.\n curr_entry = entry.parent\n while curr_entry and curr_entry.parent is not None:\n if not isinstance(curr_entry.node, SlotNode):\n curr_entry = curr_entry.parent\n continue\n\n parent_slot_id = curr_entry.node.node_id\n if parent_slot_id not in slot_children:\n slot_children[parent_slot_id] = []\n slot_children[parent_slot_id].append(node.node_id)\n break\n\n walk_nodelist(template.nodelist, on_node, context)\n\n # 3. Figure out which slot the default/implicit fill belongs to\n slot_fills = _resolve_default_slot(\n template_name=template.name,\n component_name=component_name,\n slots=slots,\n slot_fills=slot_fills,\n )\n\n # 4. Detect any errors with slots/fills\n _report_slot_errors(slots, slot_fills, component_name)\n\n # 5. Find roots of the slot relationships\n top_level_slot_ids: List[SlotId] = []\n for node_id, slot in slots.items():\n if node_id not in slot_children or not slot_children[node_id]:\n top_level_slot_ids.append(node_id)\n\n # 6. Walk from out-most slots inwards, and decide whether and how\n # we will render each slot.\n resolved_slots: Dict[SlotId, SlotFill] = {}\n slot_ids_queue = deque([*top_level_slot_ids])\n while len(slot_ids_queue):\n slot_id = slot_ids_queue.pop()\n slot = slots[slot_id]\n\n # Check if there is a slot fill for given slot name\n if slot.name in slot_fills:\n # If yes, we remember which slot we want to replace with already-rendered fills\n resolved_slots[slot_id] = slot_fills[slot.name]\n # Since the fill cannot include other slots, we can leave this path\n continue\n else:\n # If no, then the slot is NOT filled, and we will render the slot's default (what's\n # between the slot tags)\n resolved_slots[slot_id] = SlotFill(\n name=slot.name,\n escaped_name=_escape_slot_name(slot.name),\n is_filled=False,\n content_func=_nodelist_to_slot_render_func(slot.nodelist),\n context_data=context_data,\n slot_default_var=None,\n slot_data_var=None,\n )\n # Since the slot's default CAN include other slots (because it's defined in\n # the same template), we need to enqueue the slot's children\n if slot_id in slot_children and slot_children[slot_id]:\n slot_ids_queue.extend(slot_children[slot_id])\n\n # By the time we get here, we should know, for each slot, how it will be rendered\n # -> Whether it will be replaced with a fill, or whether we render slot's defaults.\n return slots, resolved_slots\n
"},{"location":"reference/django_components/tag_formatter/","title":"
tag_formatter","text":""},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter","title":"tag_formatter","text":""},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.ComponentFormatter","title":"ComponentFormatter","text":"ComponentFormatter(tag: str)\n
Bases: TagFormatterABC
The original django_component's component tag formatter, it uses the component
and endcomponent
tags, and the component name is gives as the first positional arg.
Example as block:
{% component \"mycomp\" abc=123 %}\n {% fill \"myfill\" %}\n ...\n {% endfill %}\n{% endcomponent %}\n
Example as inlined tag:
{% component \"mycomp\" abc=123 / %}\n
Source code in src/django_components/tag_formatter.py
def __init__(self, tag: str):\n self.tag = tag\n
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.InternalTagFormatter","title":"InternalTagFormatter","text":"InternalTagFormatter(tag_formatter: TagFormatterABC)\n
Internal wrapper around user-provided TagFormatters, so that we validate the outputs.
Source code in src/django_components/tag_formatter.py
def __init__(self, tag_formatter: TagFormatterABC):\n self.tag_formatter = tag_formatter\n
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":" Bases: TagFormatterABC
The component tag formatter that uses <name>
/ end<name>
tags.
This is similar to django-web-components and django-slippers syntax.
Example as block:
{% mycomp abc=123 %}\n {% fill \"myfill\" %}\n ...\n {% endfill %}\n{% endmycomp %}\n
Example as inlined tag:
{% mycomp abc=123 / %}\n
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC","title":"TagFormatterABC","text":" Bases: ABC
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC.end_tag","title":"end_tag abstractmethod
","text":"end_tag(name: str) -> str\n
Formats the end tag of a block component.
Source code in src/django_components/tag_formatter.py
@abc.abstractmethod\ndef end_tag(self, name: str) -> str:\n \"\"\"Formats the end tag of a block component.\"\"\"\n ...\n
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC.parse","title":"parse abstractmethod
","text":"parse(tokens: List[str]) -> TagResult\n
Given the tokens (words) of a component start tag, this function extracts the component name from the tokens list, and returns TagResult
, which is a tuple of (component_name, remaining_tokens)
.
Example:
Given a component declarations:
{% component \"my_comp\" key=val key2=val2 %}
This function receives a list of tokens
['component', '\"my_comp\"', 'key=val', 'key2=val2']
component
is the tag name, which we drop. \"my_comp\"
is the component name, but we must remove the extra quotes. And we pass remaining tokens unmodified, as that's the input to the component.
So in the end, we return a tuple:
('my_comp', ['key=val', 'key2=val2'])
Source code in src/django_components/tag_formatter.py
@abc.abstractmethod\ndef parse(self, tokens: List[str]) -> TagResult:\n \"\"\"\n Given the tokens (words) of a component start tag, this function extracts\n the component name from the tokens list, and returns `TagResult`, which\n is a tuple of `(component_name, remaining_tokens)`.\n\n Example:\n\n Given a component declarations:\n\n `{% component \"my_comp\" key=val key2=val2 %}`\n\n This function receives a list of tokens\n\n `['component', '\"my_comp\"', 'key=val', 'key2=val2']`\n\n `component` is the tag name, which we drop. `\"my_comp\"` is the component name,\n but we must remove the extra quotes. And we pass remaining tokens unmodified,\n as that's the input to the component.\n\n So in the end, we return a tuple:\n\n `('my_comp', ['key=val', 'key2=val2'])`\n \"\"\"\n ...\n
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC.start_tag","title":"start_tag abstractmethod
","text":"start_tag(name: str) -> str\n
Formats the start tag of a component.
Source code in src/django_components/tag_formatter.py
@abc.abstractmethod\ndef start_tag(self, name: str) -> str:\n \"\"\"Formats the start tag of a component.\"\"\"\n ...\n
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagResult","title":"TagResult","text":" Bases: NamedTuple
The return value from TagFormatter.parse()
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagResult.component_name","title":"component_name instance-attribute
","text":"component_name: str\n
Component name extracted from the template tag
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagResult.tokens","title":"tokens instance-attribute
","text":"tokens: List[str]\n
Remaining tokens (words) that were passed to the tag, with component name removed
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.get_tag_formatter","title":"get_tag_formatter","text":"get_tag_formatter() -> InternalTagFormatter\n
Returns an instance of the currently configured component tag formatter.
Source code in src/django_components/tag_formatter.py
def get_tag_formatter() -> InternalTagFormatter:\n \"\"\"Returns an instance of the currently configured component tag formatter.\"\"\"\n # Allow users to configure the component TagFormatter\n formatter_cls_or_str = app_settings.TAG_FORMATTER\n\n if isinstance(formatter_cls_or_str, str):\n tag_formatter: TagFormatterABC = import_string(formatter_cls_or_str)\n else:\n tag_formatter = formatter_cls_or_str\n\n return InternalTagFormatter(tag_formatter)\n
"},{"location":"reference/django_components/template_loader/","title":"
template_loader","text":""},{"location":"reference/django_components/template_loader/#django_components.template_loader","title":"template_loader","text":"Template loader that loads templates from each Django app's \"components\" directory.
"},{"location":"reference/django_components/template_loader/#django_components.template_loader.Loader","title":"Loader","text":" Bases: Loader
"},{"location":"reference/django_components/template_loader/#django_components.template_loader.Loader.get_dirs","title":"get_dirs","text":"get_dirs() -> List[Path]\n
Prepare directories that may contain component files:
Searches for dirs set in STATICFILES_DIRS
settings. If none set, defaults to searching for a \"components\" app. The dirs in STATICFILES_DIRS
must be absolute paths.
Paths are accepted only if they resolve to a directory. E.g. /path/to/django_project/my_app/components/
.
If STATICFILES_DIRS
is not set or empty, then BASE_DIR
is required.
Source code in src/django_components/template_loader.py
def get_dirs(self) -> List[Path]:\n \"\"\"\n Prepare directories that may contain component files:\n\n Searches for dirs set in `STATICFILES_DIRS` settings. If none set, defaults to searching\n for a \"components\" app. The dirs in `STATICFILES_DIRS` must be absolute paths.\n\n Paths are accepted only if they resolve to a directory.\n E.g. `/path/to/django_project/my_app/components/`.\n\n If `STATICFILES_DIRS` is not set or empty, then `BASE_DIR` is required.\n \"\"\"\n # Allow to configure from settings which dirs should be checked for components\n if hasattr(settings, \"STATICFILES_DIRS\") and settings.STATICFILES_DIRS:\n component_dirs = settings.STATICFILES_DIRS\n else:\n component_dirs = [settings.BASE_DIR / \"components\"]\n\n logger.debug(\n \"Template loader will search for valid template dirs from following options:\\n\"\n + \"\\n\".join([f\" - {str(d)}\" for d in component_dirs])\n )\n\n directories: Set[Path] = set()\n for component_dir in component_dirs:\n # Consider tuples for STATICFILES_DIRS (See #489)\n # See https://docs.djangoproject.com/en/5.0/ref/settings/#prefixes-optional\n if isinstance(component_dir, (tuple, list)) and len(component_dir) == 2:\n component_dir = component_dir[1]\n try:\n Path(component_dir)\n except TypeError:\n logger.warning(\n f\"STATICFILES_DIRS expected str, bytes or os.PathLike object, or tuple/list of length 2. \"\n f\"See Django documentation. Got {type(component_dir)} : {component_dir}\"\n )\n continue\n\n if not Path(component_dir).is_absolute():\n raise ValueError(f\"STATICFILES_DIRS must contain absolute paths, got '{component_dir}'\")\n else:\n directories.add(Path(component_dir).resolve())\n\n logger.debug(\n \"Template loader matched following template dirs:\\n\" + \"\\n\".join([f\" - {str(d)}\" for d in directories])\n )\n return list(directories)\n
"},{"location":"reference/django_components/template_parser/","title":"
template_parser","text":""},{"location":"reference/django_components/template_parser/#django_components.template_parser","title":"template_parser","text":"Overrides for the Django Template system to allow finer control over template parsing.
Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py
"},{"location":"reference/django_components/template_parser/#django_components.template_parser.parse_bits","title":"parse_bits","text":"parse_bits(\n parser: Parser, bits: List[str], params: List[str], name: str\n) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]\n
Parse bits for template tag helpers simple_tag and inclusion_tag, in particular by detecting syntax errors and by extracting positional and keyword arguments.
This is a simplified version of django.template.library.parse_bits
where we use custom regex to handle special characters in keyword names.
Furthermore, our version allows duplicate keys, and instead of return kwargs as a dict, we return it as a list of key-value pairs. So it is up to the user of this function to decide whether they support duplicate keys or not.
Source code in src/django_components/template_parser.py
def parse_bits(\n parser: Parser,\n bits: List[str],\n params: List[str],\n name: str,\n) -> Tuple[List[FilterExpression], List[Tuple[str, FilterExpression]]]:\n \"\"\"\n Parse bits for template tag helpers simple_tag and inclusion_tag, in\n particular by detecting syntax errors and by extracting positional and\n keyword arguments.\n\n This is a simplified version of `django.template.library.parse_bits`\n where we use custom regex to handle special characters in keyword names.\n\n Furthermore, our version allows duplicate keys, and instead of return kwargs\n as a dict, we return it as a list of key-value pairs. So it is up to the\n user of this function to decide whether they support duplicate keys or not.\n \"\"\"\n args: List[FilterExpression] = []\n kwargs: List[Tuple[str, FilterExpression]] = []\n unhandled_params = list(params)\n for bit in bits:\n # First we try to extract a potential kwarg from the bit\n kwarg = token_kwargs([bit], parser)\n if kwarg:\n # The kwarg was successfully extracted\n param, value = kwarg.popitem()\n # All good, record the keyword argument\n kwargs.append((str(param), value))\n if param in unhandled_params:\n # If using the keyword syntax for a positional arg, then\n # consume it.\n unhandled_params.remove(param)\n else:\n if kwargs:\n raise TemplateSyntaxError(\n \"'%s' received some positional argument(s) after some \" \"keyword argument(s)\" % name\n )\n else:\n # Record the positional argument\n args.append(parser.compile_filter(bit))\n try:\n # Consume from the list of expected positional arguments\n unhandled_params.pop(0)\n except IndexError:\n pass\n if unhandled_params:\n # Some positional arguments were not supplied\n raise TemplateSyntaxError(\n \"'%s' did not receive value(s) for the argument(s): %s\"\n % (name, \", \".join(\"'%s'\" % p for p in unhandled_params))\n )\n return args, kwargs\n
"},{"location":"reference/django_components/template_parser/#django_components.template_parser.token_kwargs","title":"token_kwargs","text":"token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]\n
Parse token keyword arguments and return a dictionary of the arguments retrieved from the bits
token list.
bits
is a list containing the remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments are removed from this list.
There is no requirement for all remaining token bits
to be keyword arguments, so return the dictionary as soon as an invalid argument format is reached.
Source code in src/django_components/template_parser.py
def token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]:\n \"\"\"\n Parse token keyword arguments and return a dictionary of the arguments\n retrieved from the ``bits`` token list.\n\n `bits` is a list containing the remainder of the token (split by spaces)\n that is to be checked for arguments. Valid arguments are removed from this\n list.\n\n There is no requirement for all remaining token ``bits`` to be keyword\n arguments, so return the dictionary as soon as an invalid argument format\n is reached.\n \"\"\"\n if not bits:\n return {}\n match = kwarg_re.match(bits[0])\n kwarg_format = match and match[1]\n if not kwarg_format:\n return {}\n\n kwargs: Dict[str, FilterExpression] = {}\n while bits:\n if kwarg_format:\n match = kwarg_re.match(bits[0])\n if not match or not match[1]:\n return kwargs\n key, value = match.groups()\n del bits[:1]\n else:\n if len(bits) < 3 or bits[1] != \"as\":\n return kwargs\n key, value = bits[2], bits[0]\n del bits[:3]\n\n # This is the only difference from the original token_kwargs. We use\n # the ComponentsFilterExpression instead of the original FilterExpression.\n kwargs[key] = ComponentsFilterExpression(value, parser)\n if bits and not kwarg_format:\n if bits[0] != \"and\":\n return kwargs\n del bits[:1]\n return kwargs\n
"},{"location":"reference/django_components/templatetags/","title":"Index","text":""},{"location":"reference/django_components/templatetags/#django_components.templatetags","title":"templatetags","text":""},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags","title":"component_tags","text":""},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component","title":"component","text":"component(parser: Parser, token: Token, tag_name: str) -> ComponentNode\n
To give the component access to the template context {% component \"name\" positional_arg keyword_arg=value ... %}
To render the component in an isolated context {% component \"name\" positional_arg keyword_arg=value ... only %}
Positional and keyword arguments can be literals or template variables. The component name must be a single- or double-quotes string and must be either the first positional argument or, if there are no positional arguments, passed as 'name'.
Source code in src/django_components/templatetags/component_tags.py
def component(parser: Parser, token: Token, tag_name: str) -> ComponentNode:\n \"\"\"\n To give the component access to the template context:\n ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... %}```\n\n To render the component in an isolated context:\n ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... only %}```\n\n Positional and keyword arguments can be literals or template variables.\n The component name must be a single- or double-quotes string and must\n be either the first positional argument or, if there are no positional\n arguments, passed as 'name'.\n \"\"\"\n _fix_nested_tags(parser, token)\n bits = token.split_contents()\n\n # Let the TagFormatter pre-process the tokens\n formatter = get_tag_formatter()\n result = formatter.parse([*bits])\n end_tag = formatter.end_tag(result.component_name)\n\n # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n bits = [bits[0], *result.tokens]\n token.contents = \" \".join(bits)\n\n tag = _parse_tag(\n tag_name,\n parser,\n token,\n params=True, # Allow many args\n flags=[\"only\"],\n keywordonly_kwargs=True,\n repeatable_kwargs=False,\n end_tag=end_tag,\n )\n\n # Check for isolated context keyword\n isolated_context = tag.flags[\"only\"] or app_settings.CONTEXT_BEHAVIOR == ContextBehavior.ISOLATED\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n body = tag.parse_body()\n fill_nodes = parse_slot_fill_nodes_from_component_nodelist(body, ComponentNode)\n\n # Tag all fill nodes as children of this particular component instance\n for node in fill_nodes:\n trace_msg(\"ASSOC\", \"FILL\", node.name, node.node_id, component_id=tag.id)\n node.component_id = tag.id\n\n component_node = ComponentNode(\n name=result.component_name,\n args=tag.args,\n kwargs=tag.kwargs,\n isolated_context=isolated_context,\n fill_nodes=fill_nodes,\n node_id=tag.id,\n )\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n return component_node\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"component_css_dependencies(preload: str = '') -> SafeString\n
Marks location where CSS link tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_css_dependencies\")\ndef component_css_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where CSS link tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_css_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component_dependencies","title":"component_dependencies","text":"component_dependencies(preload: str = '') -> SafeString\n
Marks location where CSS link and JS script tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_dependencies\")\ndef component_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where CSS link and JS script tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER + JS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"component_js_dependencies(preload: str = '') -> SafeString\n
Marks location where JS script tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_js_dependencies\")\ndef component_js_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where JS script tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + JS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_js_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.fill","title":"fill","text":"fill(parser: Parser, token: Token) -> FillNode\n
Block tag whose contents 'fill' (are inserted into) an identically named 'slot'-block in the component template referred to by a parent component. It exists to make component nesting easier.
This tag is available only within a {% component %}..{% endcomponent %} block. Runtime checks should prohibit other usages.
Source code in src/django_components/templatetags/component_tags.py
@register.tag(\"fill\")\ndef fill(parser: Parser, token: Token) -> FillNode:\n \"\"\"\n Block tag whose contents 'fill' (are inserted into) an identically named\n 'slot'-block in the component template referred to by a parent component.\n It exists to make component nesting easier.\n\n This tag is available only within a {% component %}..{% endcomponent %} block.\n Runtime checks should prohibit other usages.\n \"\"\"\n tag = _parse_tag(\n \"fill\",\n parser,\n token,\n params=[\"name\"],\n keywordonly_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n repeatable_kwargs=False,\n end_tag=\"endfill\",\n )\n slot_name = tag.named_args[\"name\"]\n\n trace_msg(\"PARSE\", \"FILL\", str(slot_name), tag.id)\n\n body = tag.parse_body()\n fill_node = FillNode(\n nodelist=body,\n name=slot_name,\n node_id=tag.id,\n kwargs=tag.kwargs,\n )\n\n trace_msg(\"PARSE\", \"FILL\", str(slot_name), tag.id, \"...Done!\")\n return fill_node\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode\n
This tag takes: - Optional dictionary of attributes (attrs
) - Optional dictionary of defaults (defaults
) - Additional kwargs that are appended to the former two
The inputs are merged and resulting dict is rendered as HTML attributes (key=\"value\"
).
Rules: 1. Both attrs
and defaults
can be passed as positional args or as kwargs 2. Both attrs
and defaults
are optional (can be omitted) 3. Both attrs
and defaults
are dictionaries, and we can define them the same way we define dictionaries for the component
tag. So either as attrs=attrs
or attrs:key=value
. 4. All other kwargs (key=value
) are appended and can be repeated.
Normal kwargs (key=value
) are concatenated to existing keys. So if e.g. key \"class\" is supplied with value \"my-class\", then adding class=\"extra-class\"
will result in `class=\"my-class extra-class\".
Example:
{% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n
Source code in src/django_components/templatetags/component_tags.py
@register.tag(\"html_attrs\")\ndef html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode:\n \"\"\"\n This tag takes:\n - Optional dictionary of attributes (`attrs`)\n - Optional dictionary of defaults (`defaults`)\n - Additional kwargs that are appended to the former two\n\n The inputs are merged and resulting dict is rendered as HTML attributes\n (`key=\"value\"`).\n\n Rules:\n 1. Both `attrs` and `defaults` can be passed as positional args or as kwargs\n 2. Both `attrs` and `defaults` are optional (can be omitted)\n 3. Both `attrs` and `defaults` are dictionaries, and we can define them the same way\n we define dictionaries for the `component` tag. So either as `attrs=attrs` or\n `attrs:key=value`.\n 4. All other kwargs (`key=value`) are appended and can be repeated.\n\n Normal kwargs (`key=value`) are concatenated to existing keys. So if e.g. key\n \"class\" is supplied with value \"my-class\", then adding `class=\"extra-class\"`\n will result in `class=\"my-class extra-class\".\n\n Example:\n ```htmldjango\n {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n ```\n \"\"\"\n tag = _parse_tag(\n \"html_attrs\",\n parser,\n token,\n params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n optional_params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n flags=[],\n keywordonly_kwargs=True,\n repeatable_kwargs=True,\n )\n\n return HtmlAttrsNode(\n kwargs=tag.kwargs,\n kwarg_pairs=tag.kwarg_pairs,\n )\n
"},{"location":"reference/django_components/templatetags/component_tags/","title":"
component_tags","text":""},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags","title":"component_tags","text":""},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component","title":"component","text":"component(parser: Parser, token: Token, tag_name: str) -> ComponentNode\n
To give the component access to the template context {% component \"name\" positional_arg keyword_arg=value ... %}
To render the component in an isolated context {% component \"name\" positional_arg keyword_arg=value ... only %}
Positional and keyword arguments can be literals or template variables. The component name must be a single- or double-quotes string and must be either the first positional argument or, if there are no positional arguments, passed as 'name'.
Source code in src/django_components/templatetags/component_tags.py
def component(parser: Parser, token: Token, tag_name: str) -> ComponentNode:\n \"\"\"\n To give the component access to the template context:\n ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... %}```\n\n To render the component in an isolated context:\n ```#!htmldjango {% component \"name\" positional_arg keyword_arg=value ... only %}```\n\n Positional and keyword arguments can be literals or template variables.\n The component name must be a single- or double-quotes string and must\n be either the first positional argument or, if there are no positional\n arguments, passed as 'name'.\n \"\"\"\n _fix_nested_tags(parser, token)\n bits = token.split_contents()\n\n # Let the TagFormatter pre-process the tokens\n formatter = get_tag_formatter()\n result = formatter.parse([*bits])\n end_tag = formatter.end_tag(result.component_name)\n\n # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n bits = [bits[0], *result.tokens]\n token.contents = \" \".join(bits)\n\n tag = _parse_tag(\n tag_name,\n parser,\n token,\n params=True, # Allow many args\n flags=[\"only\"],\n keywordonly_kwargs=True,\n repeatable_kwargs=False,\n end_tag=end_tag,\n )\n\n # Check for isolated context keyword\n isolated_context = tag.flags[\"only\"] or app_settings.CONTEXT_BEHAVIOR == ContextBehavior.ISOLATED\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n body = tag.parse_body()\n fill_nodes = parse_slot_fill_nodes_from_component_nodelist(body, ComponentNode)\n\n # Tag all fill nodes as children of this particular component instance\n for node in fill_nodes:\n trace_msg(\"ASSOC\", \"FILL\", node.name, node.node_id, component_id=tag.id)\n node.component_id = tag.id\n\n component_node = ComponentNode(\n name=result.component_name,\n args=tag.args,\n kwargs=tag.kwargs,\n isolated_context=isolated_context,\n fill_nodes=fill_nodes,\n node_id=tag.id,\n )\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n return component_node\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"component_css_dependencies(preload: str = '') -> SafeString\n
Marks location where CSS link tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_css_dependencies\")\ndef component_css_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where CSS link tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_css_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component_dependencies","title":"component_dependencies","text":"component_dependencies(preload: str = '') -> SafeString\n
Marks location where CSS link and JS script tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_dependencies\")\ndef component_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where CSS link and JS script tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + CSS_DEPENDENCY_PLACEHOLDER + JS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"component_js_dependencies(preload: str = '') -> SafeString\n
Marks location where JS script tags should be rendered.
Source code in src/django_components/templatetags/component_tags.py
@register.simple_tag(name=\"component_js_dependencies\")\ndef component_js_dependencies(preload: str = \"\") -> SafeString:\n \"\"\"Marks location where JS script tags should be rendered.\"\"\"\n\n if is_dependency_middleware_active():\n preloaded_dependencies = []\n for component in _get_components_from_preload_str(preload):\n preloaded_dependencies.append(RENDERED_COMMENT_TEMPLATE.format(name=component.registered_name))\n return mark_safe(\"\\n\".join(preloaded_dependencies) + JS_DEPENDENCY_PLACEHOLDER)\n else:\n rendered_dependencies = []\n for component in _get_components_from_registry(component_registry):\n rendered_dependencies.append(component.render_js_dependencies())\n\n return mark_safe(\"\\n\".join(rendered_dependencies))\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.fill","title":"fill","text":"fill(parser: Parser, token: Token) -> FillNode\n
Block tag whose contents 'fill' (are inserted into) an identically named 'slot'-block in the component template referred to by a parent component. It exists to make component nesting easier.
This tag is available only within a {% component %}..{% endcomponent %} block. Runtime checks should prohibit other usages.
Source code in src/django_components/templatetags/component_tags.py
@register.tag(\"fill\")\ndef fill(parser: Parser, token: Token) -> FillNode:\n \"\"\"\n Block tag whose contents 'fill' (are inserted into) an identically named\n 'slot'-block in the component template referred to by a parent component.\n It exists to make component nesting easier.\n\n This tag is available only within a {% component %}..{% endcomponent %} block.\n Runtime checks should prohibit other usages.\n \"\"\"\n tag = _parse_tag(\n \"fill\",\n parser,\n token,\n params=[\"name\"],\n keywordonly_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n repeatable_kwargs=False,\n end_tag=\"endfill\",\n )\n slot_name = tag.named_args[\"name\"]\n\n trace_msg(\"PARSE\", \"FILL\", str(slot_name), tag.id)\n\n body = tag.parse_body()\n fill_node = FillNode(\n nodelist=body,\n name=slot_name,\n node_id=tag.id,\n kwargs=tag.kwargs,\n )\n\n trace_msg(\"PARSE\", \"FILL\", str(slot_name), tag.id, \"...Done!\")\n return fill_node\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode\n
This tag takes: - Optional dictionary of attributes (attrs
) - Optional dictionary of defaults (defaults
) - Additional kwargs that are appended to the former two
The inputs are merged and resulting dict is rendered as HTML attributes (key=\"value\"
).
Rules: 1. Both attrs
and defaults
can be passed as positional args or as kwargs 2. Both attrs
and defaults
are optional (can be omitted) 3. Both attrs
and defaults
are dictionaries, and we can define them the same way we define dictionaries for the component
tag. So either as attrs=attrs
or attrs:key=value
. 4. All other kwargs (key=value
) are appended and can be repeated.
Normal kwargs (key=value
) are concatenated to existing keys. So if e.g. key \"class\" is supplied with value \"my-class\", then adding class=\"extra-class\"
will result in `class=\"my-class extra-class\".
Example:
{% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n
Source code in src/django_components/templatetags/component_tags.py
@register.tag(\"html_attrs\")\ndef html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode:\n \"\"\"\n This tag takes:\n - Optional dictionary of attributes (`attrs`)\n - Optional dictionary of defaults (`defaults`)\n - Additional kwargs that are appended to the former two\n\n The inputs are merged and resulting dict is rendered as HTML attributes\n (`key=\"value\"`).\n\n Rules:\n 1. Both `attrs` and `defaults` can be passed as positional args or as kwargs\n 2. Both `attrs` and `defaults` are optional (can be omitted)\n 3. Both `attrs` and `defaults` are dictionaries, and we can define them the same way\n we define dictionaries for the `component` tag. So either as `attrs=attrs` or\n `attrs:key=value`.\n 4. All other kwargs (`key=value`) are appended and can be repeated.\n\n Normal kwargs (`key=value`) are concatenated to existing keys. So if e.g. key\n \"class\" is supplied with value \"my-class\", then adding `class=\"extra-class\"`\n will result in `class=\"my-class extra-class\".\n\n Example:\n ```htmldjango\n {% html_attrs attrs defaults:class=\"default-class\" class=\"extra-class\" data-id=\"123\" %}\n ```\n \"\"\"\n tag = _parse_tag(\n \"html_attrs\",\n parser,\n token,\n params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n optional_params=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n flags=[],\n keywordonly_kwargs=True,\n repeatable_kwargs=True,\n )\n\n return HtmlAttrsNode(\n kwargs=tag.kwargs,\n kwarg_pairs=tag.kwarg_pairs,\n )\n
"},{"location":"reference/django_components/types/","title":"
types","text":""},{"location":"reference/django_components/types/#django_components.types","title":"types","text":"Helper types for IDEs.
"},{"location":"reference/django_components/utils/","title":"
utils","text":""},{"location":"reference/django_components/utils/#django_components.utils","title":"utils","text":""},{"location":"reference/django_components/utils/#django_components.utils.gen_id","title":"gen_id","text":"gen_id(length: int = 5) -> str\n
Generate a unique ID that can be associated with a Node
Source code in src/django_components/utils.py
def gen_id(length: int = 5) -> str:\n \"\"\"Generate a unique ID that can be associated with a Node\"\"\"\n # Global counter to avoid conflicts\n global _id\n _id += 1\n\n # Pad the ID with `0`s up to 4 digits, e.g. `0007`\n return f\"{_id:04}\"\n
"}]}
\ No newline at end of file
diff --git a/dev/sitemap.xml.gz b/dev/sitemap.xml.gz
index 512942ad..a0f46d8a 100644
Binary files a/dev/sitemap.xml.gz and b/dev/sitemap.xml.gz differ
diff --git a/versions.json b/versions.json
index 8c414bc7..15eebdd1 100644
--- a/versions.json
+++ b/versions.json
@@ -6,7 +6,7 @@
},
{
"version": "dev",
- "title": "dev (fc5ea78)",
+ "title": "dev (39cff5a)",
"aliases": []
},
{