Release notesΒ€
π¨π’ v0.110Β€
GeneralΒ€
π¨π’ BREAKING CHANGESΒ€
-
Installation changes:
- If your components include JS or CSS, you now must use the middleware and add django-components' URLs to your
urlpatterns
(See "Adding support for JS and CSS")
- If your components include JS or CSS, you now must use the middleware and add django-components' URLs to your
-
Component typing signature changed from
Component[Args, Kwargs, Data, Slots] +
Changelog - Django-Components Django-ComponentsChangelogRelease notesΒ€
v0.114Β€
FixΒ€
- Prevent rendering Slot tags during fill discovery stage to fix a case when a component inside a slot fill tried to access provided data too early.
v0.113Β€
FixΒ€
- Ensure consistent order of scripts in
Component.Media.js
v0.112Β€
FixΒ€
- Allow components to accept default fill even if no default slot was encountered during rendering
v0.111Β€
FixΒ€
- Prevent rendering Component tags during fill discovery stage to fix a case when a component inside the default slot tried to access provided data too early.
π¨π’ v0.110Β€
GeneralΒ€
π¨π’ BREAKING CHANGESΒ€
-
Installation changes:
- If your components include JS or CSS, you now must use the middleware and add django-components' URLs to your
urlpatterns
(See "Adding support for JS and CSS")
- If your components include JS or CSS, you now must use the middleware and add django-components' URLs to your
-
Component typing signature changed from
to
-
If you rendered a component A with
Component.render()
and then inserted that into another component B, now you must passrender_dependencies=False
to component A:- Use
get_component_dirs()
andget_component_files()
to get the same list of dirs / files that would be imported byautodiscover()
, but without actually importing them.
RefactorΒ€
-
For advanced use cases, use can omit the middleware and instead manage component JS and CSS dependencies yourself with
render_dependencies
-
The
ComponentRegistry
settingsRegistrySettings
were lowercased to align with the global settings: RegistrySettings.CONTEXT_BEHAVIOR
->RegistrySettings.context_behavior
RegistrySettings.TAG_FORMATTER
->RegistrySettings.tag_formatter
The old uppercase settings
CONTEXT_BEHAVIOR
andTAG_FORMATTER
are deprecated and will be removed in v1.-
The setting
reload_on_template_change
was renamed toreload_on_file_change
. And now it properly triggers server reload when any file in the component dirs change. The old namereload_on_template_change
is deprecated and will be removed in v1. -
The setting
forbidden_static_files
was renamed tostatic_files_forbidden
to align withstatic_files_allowed
The old nameforbidden_static_files
is deprecated and will be removed in v1.
TagsΒ€
π¨π’ BREAKING CHANGESΒ€
-
{% component_dependencies %}
tag was removed. Instead, use{% component_js_dependencies %}
and{% component_css_dependencies %}
-
The combined tag was removed to encourage the best practice of putting JS scripts at the end of
<body>
, and CSS styles inside<head>
.On the other hand, co-locating JS script and CSS styles can lead to a flash of unstyled content, as either JS scripts will block the rendering, or CSS will load too late.
-
-
The undocumented keyword arg
preload
of{% component_js_dependencies %}
and{% component_css_dependencies %}
tags was removed. This will be replaced with HTML fragment support.
FixΒ€
- Allow using forward slash (
/
) when defining custom TagFormatter, e.g.{% MyComp %}..{% /MyComp %}
.
RefactorΒ€
{% component_dependencies %}
tags are now OPTIONAL - If your components use JS and CSS, but you don't use{% component_dependencies %}
tags, the JS and CSS will now be, by default, inserted at the end of<body>
and at the end of<head>
respectively.
SlotsΒ€
FeatΒ€
- Fills can now be defined within loops (
{% for %}
) or other tags (like{% with %}
), or even other templates using{% include %}
.
Following is now possible
- Use
get_component_dirs()
andget_component_files()
to get the same list of dirs / files that would be imported byautodiscover()
, but without actually importing them.
RefactorΒ€
-
For advanced use cases, use can omit the middleware and instead manage component JS and CSS dependencies yourself with
render_dependencies
-
The
ComponentRegistry
settingsRegistrySettings
were lowercased to align with the global settings: RegistrySettings.CONTEXT_BEHAVIOR
->RegistrySettings.context_behavior
RegistrySettings.TAG_FORMATTER
->RegistrySettings.tag_formatter
The old uppercase settings
CONTEXT_BEHAVIOR
andTAG_FORMATTER
are deprecated and will be removed in v1.-
The setting
reload_on_template_change
was renamed toreload_on_file_change
. And now it properly triggers server reload when any file in the component dirs change. The old namereload_on_template_change
is deprecated and will be removed in v1. -
The setting
forbidden_static_files
was renamed tostatic_files_forbidden
to align withstatic_files_allowed
The old nameforbidden_static_files
is deprecated and will be removed in v1.
TagsΒ€
π¨π’ BREAKING CHANGESΒ€
-
{% component_dependencies %}
tag was removed. Instead, use{% component_js_dependencies %}
and{% component_css_dependencies %}
-
The combined tag was removed to encourage the best practice of putting JS scripts at the end of
<body>
, and CSS styles inside<head>
.On the other hand, co-locating JS script and CSS styles can lead to a flash of unstyled content, as either JS scripts will block the rendering, or CSS will load too late.
-
-
The undocumented keyword arg
preload
of{% component_js_dependencies %}
and{% component_css_dependencies %}
tags was removed. This will be replaced with HTML fragment support.
FixΒ€
- Allow using forward slash (
/
) when defining custom TagFormatter, e.g.{% MyComp %}..{% /MyComp %}
.
RefactorΒ€
{% component_dependencies %}
tags are now OPTIONAL - If your components use JS and CSS, but you don't use{% component_dependencies %}
tags, the JS and CSS will now be, by default, inserted at the end of<body>
and at the end of<head>
respectively.
SlotsΒ€
FeatΒ€
- Fills can now be defined within loops (
{% for %}
) or other tags (like{% with %}
), or even other templates using{% include %}
.
Following is now possible
{% component "table" %} {% for slot_name in slots %} {% fill name=slot_name %} {% endfill %} @@ -58,7 +58,7 @@ {% endcomponent %} </div> """ -
FixΒ€
-
Slots defined with
{% fill %}
tags are now properly accessible viaself.input.slots
inget_context_data()
-
Do not raise error if multiple slots with same name are flagged as default
-
Slots can now be defined within loops (
{% for %}
) or other tags (like{% with %}
), or even other templates using{% include %}
.
Previously, following would cause the kwarg
name
to be an empty string:FixΒ€
-
Slots defined with
{% fill %}
tags are now properly accessible viaself.input.slots
inget_context_data()
-
Do not raise error if multiple slots with same name are flagged as default
-
Slots can now be defined within loops (
{% for %}
) or other tags (like{% with %}
), or even other templates using{% include %}
.
Previously, following would cause the kwarg
name
to be an empty string:RefactorΒ€
- When you define multiple slots with the same name inside a template, you now have to set the
default
andrequired
flags individually.
<div class="calendar-component"> @@ -115,7 +115,7 @@ Hello from content slot {% endfill %} {% endcomponent %} -
π¨π’ v0.100Β€
BREAKING CHANGESΒ€
-
django_components.safer_staticfiles
app was removed. It is no longer needed. -
Installation changes:
- Instead of defining component directories in
STATICFILES_DIRS
, set them toCOMPONENTS.dirs
. -
You now must define
STATICFILES_FINDERS
- Instead of defining component directories in
FeatΒ€
- Beside the top-level
/components
directory, you can now define also app-level components dirs, e.g.[app]/components
(SeeCOMPONENTS.app_dirs
).
RefactorΒ€
- When you call
as_view()
on a component instance, that instance will be passed toView.as_view()
v0.97Β€
FixΒ€
- Fixed template caching. You can now also manually create cached templates with
cached_template()
RefactorΒ€
-
The previously undocumented
get_template
was made private. -
In it's place, there's a new
get_template
, which supersedesget_template_string
(will be removed in v1). The newget_template
is the same asget_template_string
, except it allows to return either a string or a Template instance. -
You now must use only one of
template
,get_template
,template_name
, orget_template_name
.
v0.96Β€
FeatΒ€
-
Run-time type validation for Python 3.11+ - If the
Component
class is typed, e.g.Component[Args, Kwargs, ...]
, the args, kwargs, slots, and data are validated against the given types. (See Runtime input validation with types) -
Render hooks - Set
on_render_before
andon_render_after
methods onComponent
to intercept or modify the template or context before rendering, or the rendered result afterwards. (See Component hooks) -
component_vars.is_filled
context variable can be accessed from withinon_render_before
andon_render_after
hooks asself.is_filled.my_slot
0.95Β€
FeatΒ€
- Added support for dynamic components, where the component name is passed as a variable. (See Dynamic components)
RefactorΒ€
- Changed
Component.input
to raiseRuntimeError
if accessed outside of render context. Previously it returnedNone
if unset.
v0.94Β€
FeatΒ€
-
django_components now automatically configures Django to support multi-line tags. (See Multi-line tags)
-
New setting
reload_on_template_change
. Set this toTrue
to reload the dev server on changes to component template files. (See Reload dev server on component file changes)
v0.93Β€
FeatΒ€
-
Spread operator
...dict
inside template tags. (See Spread operator) -
Use template tags inside string literals in component inputs. (See Use template tags inside component inputs)
-
Dynamic slots, fills and provides - The
name
argument for these can now be a variable, a template expression, or via spread operator -
Component library authors can now configure
CONTEXT_BEHAVIOR
andTAG_FORMATTER
settings independently from user settings.
π¨π’ v0.92Β€
BREAKING CHANGESΒ€
Component
class is no longer a subclass ofView
. To configure theView
class, set theComponent.View
nested class. HTTP methods likeget
orpost
can still be defined directly onComponent
class, andComponent.as_view()
internally callsComponent.View.as_view()
. (See Modifying the View class)
FeatΒ€
-
The inputs (args, kwargs, slots, context, ...) that you pass to
Component.render()
can be accessed from withinget_context_data
,get_template
andget_template_name
viaself.input
. (See Accessing data passed to the component) -
Typing:
Component
class supports generics that specify types forComponent.render
(See Adding type hints with Generics)
v0.90Β€
FeatΒ€
-
All tags (
component
,slot
,fill
, ...) now support "self-closing" or "inline" form, where you can omit the closing tag:π¨π’ v0.100Β€
BREAKING CHANGESΒ€
-
django_components.safer_staticfiles
app was removed. It is no longer needed. -
Installation changes:
- Instead of defining component directories in
STATICFILES_DIRS
, set them toCOMPONENTS.dirs
. -
You now must define
STATICFILES_FINDERS
- Instead of defining component directories in
FeatΒ€
- Beside the top-level
/components
directory, you can now define also app-level components dirs, e.g.[app]/components
(SeeCOMPONENTS.app_dirs
).
RefactorΒ€
- When you call
as_view()
on a component instance, that instance will be passed toView.as_view()
v0.97Β€
FixΒ€
- Fixed template caching. You can now also manually create cached templates with
cached_template()
RefactorΒ€
-
The previously undocumented
get_template
was made private. -
In it's place, there's a new
get_template
, which supersedesget_template_string
(will be removed in v1). The newget_template
is the same asget_template_string
, except it allows to return either a string or a Template instance. -
You now must use only one of
template
,get_template
,template_name
, orget_template_name
.
v0.96Β€
FeatΒ€
-
Run-time type validation for Python 3.11+ - If the
Component
class is typed, e.g.Component[Args, Kwargs, ...]
, the args, kwargs, slots, and data are validated against the given types. (See Runtime input validation with types) -
Render hooks - Set
on_render_before
andon_render_after
methods onComponent
to intercept or modify the template or context before rendering, or the rendered result afterwards. (See Component hooks) -
component_vars.is_filled
context variable can be accessed from withinon_render_before
andon_render_after
hooks asself.is_filled.my_slot
0.95Β€
FeatΒ€
- Added support for dynamic components, where the component name is passed as a variable. (See Dynamic components)
RefactorΒ€
- Changed
Component.input
to raiseRuntimeError
if accessed outside of render context. Previously it returnedNone
if unset.
v0.94Β€
FeatΒ€
-
django_components now automatically configures Django to support multi-line tags. (See Multi-line tags)
-
New setting
reload_on_template_change
. Set this toTrue
to reload the dev server on changes to component template files. (See Reload dev server on component file changes)
v0.93Β€
FeatΒ€
-
Spread operator
...dict
inside template tags. (See Spread operator) -
Use template tags inside string literals in component inputs. (See Use template tags inside component inputs)
-
Dynamic slots, fills and provides - The
name
argument for these can now be a variable, a template expression, or via spread operator -
Component library authors can now configure
CONTEXT_BEHAVIOR
andTAG_FORMATTER
settings independently from user settings.
π¨π’ v0.92Β€
BREAKING CHANGESΒ€
Component
class is no longer a subclass ofView
. To configure theView
class, set theComponent.View
nested class. HTTP methods likeget
orpost
can still be defined directly onComponent
class, andComponent.as_view()
internally callsComponent.View.as_view()
. (See Modifying the View class)
FeatΒ€
-
The inputs (args, kwargs, slots, context, ...) that you pass to
Component.render()
can be accessed from withinget_context_data
,get_template
andget_template_name
viaself.input
. (See Accessing data passed to the component) -
Typing:
Component
class supports generics that specify types forComponent.render
(See Adding type hints with Generics)
v0.90Β€
FeatΒ€
-
All tags (
component
,slot
,fill
, ...) now support "self-closing" or "inline" form, where you can omit the closing tag:{# Before #} {% component "button" %}{% endcomponent %} {# After #} {% component "button" / %} diff --git a/dev/reference/django_components/component/index.html b/dev/reference/django_components/component/index.html index 31890eae..38b86eea 100644 --- a/dev/reference/django_components/component/index.html +++ b/dev/reference/django_components/component/index.html @@ -583,35 +583,35 @@ nodelist: Optional[NodeList] = None, node_id: Optional[str] = None, ) -
Bases:
BaseNode
Django.template.Node subclass that renders a django-components component
Source code in
src/django_components/component.py
def __init__( - self, - name: str, - args: List[Expression], - kwargs: RuntimeKwargs, - registry: ComponentRegistry, # noqa F811 - isolated_context: bool = False, - nodelist: Optional[NodeList] = None, - node_id: Optional[str] = None, -) -> None: - super().__init__(nodelist=nodelist or NodeList(), args=args, kwargs=kwargs, node_id=node_id) - - self.name = name - self.isolated_context = isolated_context - self.registry = registry +
Bases:
BaseNode
Django.template.Node subclass that renders a django-components component
Source code in
src/django_components/component.py
ComponentVars Β€
Bases:
NamedTuple
Type for the variables available inside the component templates.
All variables here are scoped under
component_vars.
, so e.g. attributeis_filled
on this class is accessible inside the template as:Attributes:
-
is_filled
(Dict[str, bool]
) βDictonary describing which component slots are filled (
True
) or are not (False
).
is_filled
instance-attribute
Β€Dictonary describing which component slots are filled (
True
) or are not (False
).New in version 0.70
Use as
{{ component_vars.is_filled }}
Example:
{# Render wrapping HTML only if the slot is defined #} diff --git a/dev/reference/django_components/index.html b/dev/reference/django_components/index.html index c53f9671..715967b0 100644 --- a/dev/reference/django_components/index.html +++ b/dev/reference/django_components/index.html @@ -3889,35 +3889,35 @@ nodelist: Optional[NodeList] = None, node_id: Optional[str] = None, ) -
Bases:
BaseNode
Django.template.Node subclass that renders a django-components component
Source code in
src/django_components/component.py
def __init__( - self, - name: str, - args: List[Expression], - kwargs: RuntimeKwargs, - registry: ComponentRegistry, # noqa F811 - isolated_context: bool = False, - nodelist: Optional[NodeList] = None, - node_id: Optional[str] = None, -) -> None: - super().__init__(nodelist=nodelist or NodeList(), args=args, kwargs=kwargs, node_id=node_id) - - self.name = name - self.isolated_context = isolated_context - self.registry = registry +
Bases:
BaseNode
Django.template.Node subclass that renders a django-components component
Source code in
src/django_components/component.py
ComponentVars Β€
Bases:
NamedTuple
Type for the variables available inside the component templates.
All variables here are scoped under
component_vars.
, so e.g. attributeis_filled
on this class is accessible inside the template as:Attributes:
-
is_filled
(Dict[str, bool]
) βDictonary describing which component slots are filled (
True
) or are not (False
).
is_filled
instance-attribute
Β€slots Β€
Classes:
-
FillNode
βNode corresponding to
{% fill %}
-
Slot
βThis class holds the slot content function along with related metadata.
-
SlotFill
βSlotFill describes what WILL be rendered.
-
SlotIsFilled
βDictionary that returns
True
if the slot is filled (key is found),False
otherwise. -
SlotNode
βNode corresponding to
{% slot %}
-
SlotRef
βSlotRef allows to treat a slot as a variable. The slot is rendered only once
Functions:
-
resolve_fills
βGiven a component body (
django.template.NodeList
), find all slot fills,
FillNode Β€
Bases:
BaseNode
Node corresponding to
{% fill %}
Source code in
src/django_components/slots.py
Slot
dataclass
Β€SlotFill
dataclass
Β€Bases:
Generic[TSlotData]
SlotFill describes what WILL be rendered.
The fill may be provided by the user from the outside (
is_filled=True
), or it may be the default content of the slot (is_filled=False
).Attributes:
name
instance-attribute
Β€name: str @@ -6566,13 +6566,7 @@ {% endfill %} {% endfor %} {% endcomponent %} -
Source code in
src/django_components/slots.py
Source code in
src/django_components/slots.py
def resolve_fills( - context: Context, - nodelist: NodeList, - component_name: str, -) -> Dict[SlotName, Slot]: - """ - 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: - ```django - {% component "mycomponent" %} - {% fill "first_fill" %} - Hello! - {% endfill %} - {% fill "second_fill" %} - Hello too! - {% endfill %} - {% endcomponent %} - ``` - - Then this function finds 2 fill nodes: "first_fill" and "second_fill", - and formats them as slot functions, returning: - - ```python - { - "first_fill": SlotFunc(...), - "second_fill": SlotFunc(...), - } - ``` - - If no fill nodes are found, then the content is treated as default slot content. - - ```python - { - DEFAULT_SLOT_KEY: SlotFunc(...), - } - ``` +625 +626 +627 +628 +629 +630 +631
def resolve_fills( + context: Context, + nodelist: NodeList, + component_name: str, +) -> Dict[SlotName, Slot]: + """ + 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: + ```django + {% component "mycomponent" %} + {% fill "first_fill" %} + Hello! + {% endfill %} + {% fill "second_fill" %} + Hello too! + {% endfill %} + {% endcomponent %} + ``` + + Then this function finds 2 fill nodes: "first_fill" and "second_fill", + and formats them as slot functions, returning: + + ```python + { + "first_fill": SlotFunc(...), + "second_fill": SlotFunc(...), + } + ``` + + If no fill nodes are found, then the content is treated as default slot content. - This function also handles for-loops, if/else statements, or include tags to generate fill tags: - - ```django - {% component "mycomponent" %} - {% for slot_name in slots %} - {% fill name=slot_name %} - {% slot name=slot_name / %} - {% endfill %} - {% endfor %} - {% endcomponent %} - ``` - """ - slots: Dict[SlotName, Slot] = {} - - if not nodelist: - return slots - - maybe_fills = _extract_fill_content(nodelist, context, component_name) - - # The content has no fills, so treat it as default slot, e.g.: - # {% component "mycomponent" %} - # Hello! - # {% if True %} 123 {% endif %} - # {% endcomponent %} - if maybe_fills is False: - # Ignore empty content between `{% component %} ... {% endcomponent %}` tags - nodelist_is_empty = not len(nodelist) or all( - isinstance(node, TextNode) and not node.s.strip() for node in nodelist - ) - - if not nodelist_is_empty: - slots[DEFAULT_SLOT_KEY] = _nodelist_to_slot_render_func( - DEFAULT_SLOT_KEY, - nodelist, - data_var=None, - default_var=None, - ) - - # The content has fills - else: - # NOTE: If slot fills are explicitly defined, we use them even if they are empty (or only whitespace). - # This is different from the default slot, where we ignore empty content. - for fill in maybe_fills: - slots[fill.name] = _nodelist_to_slot_render_func( - slot_name=fill.name, - nodelist=fill.fill.nodelist, - data_var=fill.data_var, - default_var=fill.default_var, - extra_context=fill.extra_context, - ) - - return slots + ```python + { + DEFAULT_SLOT_KEY: SlotFunc(...), + } + ``` + + This function also handles for-loops, if/else statements, or include tags to generate fill tags: + + ```django + {% component "mycomponent" %} + {% for slot_name in slots %} + {% fill name=slot_name %} + {% slot name=slot_name / %} + {% endfill %} + {% endfor %} + {% endcomponent %} + ``` + """ + slots: Dict[SlotName, Slot] = {} + + if not nodelist: + return slots + + maybe_fills = _extract_fill_content(nodelist, context, component_name) + + # The content has no fills, so treat it as default slot, e.g.: + # {% component "mycomponent" %} + # Hello! + # {% if True %} 123 {% endif %} + # {% endcomponent %} + if maybe_fills is False: + # Ignore empty content between `{% component %} ... {% endcomponent %}` tags + nodelist_is_empty = not len(nodelist) or all( + isinstance(node, TextNode) and not node.s.strip() for node in nodelist + ) + + if not nodelist_is_empty: + slots[DEFAULT_SLOT_KEY] = _nodelist_to_slot_render_func( + DEFAULT_SLOT_KEY, + nodelist, + data_var=None, + default_var=None, + ) + + # The content has fills + else: + # NOTE: If slot fills are explicitly defined, we use them even if they are empty (or only whitespace). + # This is different from the default slot, where we ignore empty content. + for fill in maybe_fills: + slots[fill.name] = _nodelist_to_slot_render_func( + slot_name=fill.name, + nodelist=fill.fill.nodelist, + data_var=fill.data_var, + default_var=fill.default_var, + extra_context=fill.extra_context, + ) + + return slots
tag_formatter Β€
Classes:
-
ComponentFormatter
βThe original django_component's component tag formatter, it uses the
{% component %}
-
InternalTagFormatter
βInternal wrapper around user-provided TagFormatters, so that we validate the outputs.
-
ShorthandComponentFormatter
βThe component tag formatter that uses
{% <name> %}
/{% end<name> %}
tags. -
TagFormatterABC
βAbstract base class for defining custom tag formatters.
-
TagResult
βThe return value from
TagFormatter.parse()
.
Functions:
-
get_tag_formatter
βReturns an instance of the currently configured component tag formatter.
ComponentFormatter Β€
ComponentFormatter(tag: str)
Bases:
TagFormatterABC
The original django_component's component tag formatter, it uses the
{% component %}
and{% endcomponent %}
tags, and the component name is given as the first positional arg.Example as block:
{% component "mycomp" abc=123 %} {% fill "myfill" %} diff --git a/dev/reference/django_components/slots/index.html b/dev/reference/django_components/slots/index.html index 51b258a1..423b8af8 100644 --- a/dev/reference/django_components/slots/index.html +++ b/dev/reference/django_components/slots/index.html @@ -1,23 +1,23 @@
slots - Django-Components" > slots - Django-Components" >slots - Django-Components Django-Componentsslots
slots Β€
Classes:
-
FillNode
βNode corresponding to
{% fill %}
-
Slot
βThis class holds the slot content function along with related metadata.
-
SlotFill
βSlotFill describes what WILL be rendered.
-
SlotIsFilled
βDictionary that returns
True
if the slot is filled (key is found),False
otherwise. -
SlotNode
βNode corresponding to
{% slot %}
-
SlotRef
βSlotRef allows to treat a slot as a variable. The slot is rendered only once
Functions:
-
resolve_fills
βGiven a component body (
django.template.NodeList
), find all slot fills,
FillNode Β€
Bases:
BaseNode
Node corresponding to
{% fill %}
Source code in
src/django_components/slots.py
Slot
dataclass
Β€SlotFill
dataclass
Β€Bases:
Generic[TSlotData]
SlotFill describes what WILL be rendered.
The fill may be provided by the user from the outside (
is_filled=True
), or it may be the default content of the slot (is_filled=False
).Attributes:
name
instance-attribute
Β€name: str @@ -91,13 +91,7 @@ {% endfill %} {% endfor %} {% endcomponent %} -
Source code in
src/django_components/slots.py
Source code in
src/django_components/slots.py
def resolve_fills( - context: Context, - nodelist: NodeList, - component_name: str, -) -> Dict[SlotName, Slot]: - """ - 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: - ```django - {% component "mycomponent" %} - {% fill "first_fill" %} - Hello! - {% endfill %} - {% fill "second_fill" %} - Hello too! - {% endfill %} - {% endcomponent %} - ``` - - Then this function finds 2 fill nodes: "first_fill" and "second_fill", - and formats them as slot functions, returning: - - ```python - { - "first_fill": SlotFunc(...), - "second_fill": SlotFunc(...), - } - ``` - - If no fill nodes are found, then the content is treated as default slot content. - - ```python - { - DEFAULT_SLOT_KEY: SlotFunc(...), - } - ``` +625 +626 +627 +628 +629 +630 +631
def resolve_fills( + context: Context, + nodelist: NodeList, + component_name: str, +) -> Dict[SlotName, Slot]: + """ + 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: + ```django + {% component "mycomponent" %} + {% fill "first_fill" %} + Hello! + {% endfill %} + {% fill "second_fill" %} + Hello too! + {% endfill %} + {% endcomponent %} + ``` + + Then this function finds 2 fill nodes: "first_fill" and "second_fill", + and formats them as slot functions, returning: + + ```python + { + "first_fill": SlotFunc(...), + "second_fill": SlotFunc(...), + } + ``` + + If no fill nodes are found, then the content is treated as default slot content. - This function also handles for-loops, if/else statements, or include tags to generate fill tags: - - ```django - {% component "mycomponent" %} - {% for slot_name in slots %} - {% fill name=slot_name %} - {% slot name=slot_name / %} - {% endfill %} - {% endfor %} - {% endcomponent %} - ``` - """ - slots: Dict[SlotName, Slot] = {} - - if not nodelist: - return slots - - maybe_fills = _extract_fill_content(nodelist, context, component_name) - - # The content has no fills, so treat it as default slot, e.g.: - # {% component "mycomponent" %} - # Hello! - # {% if True %} 123 {% endif %} - # {% endcomponent %} - if maybe_fills is False: - # Ignore empty content between `{% component %} ... {% endcomponent %}` tags - nodelist_is_empty = not len(nodelist) or all( - isinstance(node, TextNode) and not node.s.strip() for node in nodelist - ) - - if not nodelist_is_empty: - slots[DEFAULT_SLOT_KEY] = _nodelist_to_slot_render_func( - DEFAULT_SLOT_KEY, - nodelist, - data_var=None, - default_var=None, - ) - - # The content has fills - else: - # NOTE: If slot fills are explicitly defined, we use them even if they are empty (or only whitespace). - # This is different from the default slot, where we ignore empty content. - for fill in maybe_fills: - slots[fill.name] = _nodelist_to_slot_render_func( - slot_name=fill.name, - nodelist=fill.fill.nodelist, - data_var=fill.data_var, - default_var=fill.default_var, - extra_context=fill.extra_context, - ) - - return slots + ```python + { + DEFAULT_SLOT_KEY: SlotFunc(...), + } + ``` + + This function also handles for-loops, if/else statements, or include tags to generate fill tags: + + ```django + {% component "mycomponent" %} + {% for slot_name in slots %} + {% fill name=slot_name %} + {% slot name=slot_name / %} + {% endfill %} + {% endfor %} + {% endcomponent %} + ``` + """ + slots: Dict[SlotName, Slot] = {} + + if not nodelist: + return slots + + maybe_fills = _extract_fill_content(nodelist, context, component_name) + + # The content has no fills, so treat it as default slot, e.g.: + # {% component "mycomponent" %} + # Hello! + # {% if True %} 123 {% endif %} + # {% endcomponent %} + if maybe_fills is False: + # Ignore empty content between `{% component %} ... {% endcomponent %}` tags + nodelist_is_empty = not len(nodelist) or all( + isinstance(node, TextNode) and not node.s.strip() for node in nodelist + ) + + if not nodelist_is_empty: + slots[DEFAULT_SLOT_KEY] = _nodelist_to_slot_render_func( + DEFAULT_SLOT_KEY, + nodelist, + data_var=None, + default_var=None, + ) + + # The content has fills + else: + # NOTE: If slot fills are explicitly defined, we use them even if they are empty (or only whitespace). + # This is different from the default slot, where we ignore empty content. + for fill in maybe_fills: + slots[fill.name] = _nodelist_to_slot_render_func( + slot_name=fill.name, + nodelist=fill.fill.nodelist, + data_var=fill.data_var, + default_var=fill.default_var, + extra_context=fill.extra_context, + ) + + return slots
Docs (Work in progress)
Django-components is a package that introduces component-based architecture to Django's server-side rendering. It aims to combine Django's templating system with the modularity seen in modern frontend frameworks.
"},{"location":"#features","title":"Features","text":"- \ud83e\udde9 Reusability: Allows creation of self-contained, reusable UI elements.
- \ud83d\udce6 Encapsulation: Each component can include its own HTML, CSS, and JavaScript.
- \ud83d\ude80 Server-side rendering: Components render on the server, improving initial load times and SEO.
- \ud83d\udc0d Django integration: Works within the Django ecosystem, using familiar concepts like template tags.
- \u26a1 Asynchronous loading: Components can render independently opening up for integration with JS frameworks like HTMX or AlpineJS.
Potential benefits:
- \ud83d\udd04 Reduced code duplication
- \ud83d\udee0\ufe0f Improved maintainability through modular design
- \ud83e\udde0 Easier management of complex UIs
- \ud83e\udd1d Enhanced collaboration between frontend and backend developers
Django-components can be particularly useful for larger Django projects that require a more structured approach to UI development, without necessitating a shift to a separate frontend framework.
"},{"location":"#quickstart","title":"Quickstart","text":"django-components lets you create reusable blocks of code needed to generate the front end code you need for a modern app.
Define a component in
components/calendar/calendar.py
like this:@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"template.html\"\n\n def get_context_data(self, date):\n return {\"date\": date}\n
With this
template.html
file:<div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n
Use the component like this:
{% component \"calendar\" date=\"2024-11-06\" %}{% endcomponent %}\n
And this is what gets rendered:
<div class=\"calendar-component\">Today's date is <span>2024-11-06</span></div>\n
Read on to learn about all the exciting details and configuration possibilities!
(If you instead prefer to jump right into the code, check out the example project)
"},{"location":"#table-of-contents","title":"Table of Contents","text":"- Release notes
- Security notes \ud83d\udea8
- Installation
- Compatibility
- Create your first component
- Using single-file components
- Use components in templates
- Use components outside of templates
- Use components as views
- Typing and validating components
- Pre-defined components
- Registering components
- Autodiscovery
- Using slots in templates
- Accessing data passed to the component
- Rendering HTML attributes
- Template tag syntax
- Prop drilling and dependency injection (provide / inject)
- Component hooks
- Component context and scope
- Pre-defined template variables
- Customizing component tags with TagFormatter
- Defining HTML/JS/CSS files
- Rendering JS/CSS dependencies
- Available settings
- Running with development server
- Logging and debugging
- Management Command
- Writing and sharing component libraries
- Community examples
- Running django-components project locally
- Development guides
Read the Release Notes to see the latest features and fixes.
"},{"location":"#security-notes","title":"Security notes \ud83d\udea8","text":"It is strongly recommended to read this section before using django-components in production.
"},{"location":"#static-files","title":"Static files","text":"Components can be organized however you prefer. That said, our prefered way is to keep the files of a component close together by bundling them in the same directory.
This means that files containing backend logic, such as Python modules and HTML templates, live in the same directory as static files, e.g. JS and CSS.
From v0.100 onwards, we keep component files (as defined by
COMPONENTS.dirs
andCOMPONENTS.app_dirs
) separate from the rest of the static files (defined bySTATICFILES_DIRS
). That way, the Python and HTML files are NOT exposed by the server. Only the static JS, CSS, and other common formats.NOTE: If you need to expose different file formats, you can configure these with
"},{"location":"#static-files-prior-to-v0100","title":"Static files prior to v0.100","text":"COMPONENTS.static_files_allowed
andCOMPONENTS.static_files_forbidden
.Prior to v0.100, if your were using django.contrib.staticfiles to collect static files, no distinction was made between the different kinds of files.
As a result, your Python code and templates may inadvertently become available on your static file server. You probably don't want this, as parts of your backend logic will be exposed, posing a potential security vulnerability.
From v0.27 until v0.100, django-components shipped with an additional installable app django_components.safer_staticfiles. It was a drop-in replacement for django.contrib.staticfiles. Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server. To use it, add it to INSTALLED_APPS and remove django.contrib.staticfiles.
INSTALLED_APPS = [\n # 'django.contrib.staticfiles', # <-- REMOVE\n 'django_components',\n 'django_components.safer_staticfiles' # <-- ADD\n]\n
If you are on an older version of django-components, your alternatives are a) passing
--ignore <pattern>
options to the collecstatic CLI command, or b) defining a subclass of StaticFilesConfig. Both routes are described in the official docs of the staticfiles app.Note that
safer_staticfiles
excludes the.py
and.html
files for collectstatic command:python manage.py collectstatic\n
but it is ignored on the development server:
python manage.py runserver\n
For a step-by-step guide on deploying production server with static files, see the demo project.
"},{"location":"#installation","title":"Installation","text":"- Install
django_components
into your environment:
pip install django_components
- Load
django_components
into Django by adding it intoINSTALLED_APPS
in settings.py:
INSTALLED_APPS = [\n ...,\n 'django_components',\n]\n
BASE_DIR
setting is required. Ensure that it is defined in settings.py:
BASE_DIR = Path(__file__).resolve().parent.parent\n
- Add / modify
COMPONENTS.dirs
and / orCOMPONENTS.app_dirs
so django_components knows where to find component HTML, JS and CSS files:
COMPONENTS = {\n \"dirs\": [\n ...,\n os.path.join(BASE_DIR, \"components\"),\n ],\n}\n
If
COMPONENTS.dirs
is omitted, django-components will by default look for a top-level/components
directory,{BASE_DIR}/components
.In addition to
COMPONENTS.dirs
, django_components will also load components from app-level directories, such asmy-app/components/
. The directories within apps are configured withCOMPONENTS.app_dirs
, and the default is[app]/components
.NOTE: The input to
COMPONENTS.dirs
is the same as forSTATICFILES_DIRS
, and the paths must be full paths. See Django docs.-
Next, to make Django load component HTML files as Django templates, modify
TEMPLATES
section of settings.py as follows: -
Remove
'APP_DIRS': True,
- NOTE: Instead of APP_DIRS, for the same effect, we will use
django.template.loaders.app_directories.Loader
- NOTE: Instead of APP_DIRS, for the same effect, we will use
- Add
loaders
toOPTIONS
list and set it to following value:
TEMPLATES = [\n {\n ...,\n 'OPTIONS': {\n 'context_processors': [\n ...\n ],\n 'loaders':[(\n 'django.template.loaders.cached.Loader', [\n # Default Django loader\n 'django.template.loaders.filesystem.Loader',\n # Inluding this is the same as APP_DIRS=True\n 'django.template.loaders.app_directories.Loader',\n # Components loader\n 'django_components.template_loader.Loader',\n ]\n )],\n },\n },\n]\n
- Lastly, be able to serve the component JS and CSS files as static files, modify
STATICFILES_FINDERS
section of settings.py as follows:
"},{"location":"#adding-support-for-js-and-css","title":"Adding support for JS and CSS","text":"STATICFILES_FINDERS = [\n # Default finders\n \"django.contrib.staticfiles.finders.FileSystemFinder\",\n \"django.contrib.staticfiles.finders.AppDirectoriesFinder\",\n # Django components\n \"django_components.finders.ComponentsFileSystemFinder\",\n]\n
If you want to use JS or CSS with components, you will need to:
- Add
ComponentDependencyMiddleware
toMIDDLEWARE
setting.
The middleware searches the outgoing HTML for all components that were rendered to generate the HTML, and adds the JS and CSS associated with those components.
MIDDLEWARE = [\n ...\n \"django_components.middleware.ComponentDependencyMiddleware\",\n]\n
Read more in Rendering JS/CSS dependencies.
- Add django-component's URL paths to your
urlpatterns
:
"},{"location":"#optional","title":"Optional","text":"from django.urls import include, path\n\nurlpatterns = [\n ...\n path(\"\", include(\"django_components.urls\")),\n]\n
To avoid loading the app in each template using
{% load component_tags %}
, you can add the tag as a 'builtin' in settings.pyTEMPLATES = [\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
[project root]/components/calendar/calendar.htmldate
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.{# In a file called [project root]/components/calendar/template.html #}\n<div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n
Finally, we use django-components to tie this together. Start by creating a file called
calendar.py
in your component calendar directory. It will be auto-detected and loaded by the app.Inside this file we create a Component by inheriting from the Component class and specifying the context method. We also register the global component registry so that we easily can render it anywhere in our templates.
[project root]/components/calendar/calendar.py# In a file called [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n # Templates inside `[your apps]/components` dir and `[project root]/components` dir\n # will be automatically found.\n #\n # `template_name` can be relative to dir where `calendar.py` is, or relative to COMPONENTS.dirs\n template_name = \"template.html\"\n # Or\n def get_template_name(context):\n return f\"template-{context['name']}.html\"\n\n # This component takes one parameter, a date string to show in the template\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n\n # Both `css` and `js` can be relative to dir where `calendar.py` is, or relative to COMPONENTS.dirs\n class Media:\n css = \"style.css\"\n js = \"script.js\"\n
And voil\u00e1!! We've created our first component.
"},{"location":"#using-single-file-components","title":"Using single-file components","text":"Components can also be defined in a single file, which is useful for small components. To do this, you can use the
[project root]/components/calendar.pytemplate
,js
, andcss
class attributes instead of thetemplate_name
andMedia
. For example, here's the calendar component from above, defined in a single file:# 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
"},{"location":"#pycharm-or-other-jetbrains-ides","title":"Pycharm (or other Jetbrains IDEs)","text":"t.django_html
,t.css
, andt.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.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
"},{"location":"#use-components-in-templates","title":"Use components in templates","text":"types.django_html
,types.css
,types.js
since Pycharm uses language injections. You only need to write the comments# language=<lang>
above the variables.First load the
component_tags
tag library, then use thecomponent_[js/css]_dependencies
andcomponent
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
andrender_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:
"},{"location":"#inputs-of-render-and-render_to_response","title":"Inputs ofhello: world\nfoo: bar\nkwargs: {'kw1': 'test', 'kw2': 'ooo'}\nslot_first: FIRST_SLOT\n
render
andrender_to_response
","text":"Both
render
andrender_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 }
whereslot_content
can be a string orSlotFunc
. -
escape_slots_content
- Whether the content fromslots
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.
SlotFunc
","text":"When rendering components with slots in
render
orrender_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:
"},{"location":"#response-class-of-render_to_response","title":"Response class ofdef 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
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 isdjango.http.HttpResponse
.If you want to use a different Response class in
render_to_response
, set theComponent.response_class
attribute:
"},{"location":"#use-components-as-views","title":"Use components as views","text":"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
New in version 0.34
Note: Since 0.92, Component no longer subclasses View. To configure the View class, set the nested
Component.View
classComponents can now be used as views: - Components define the
Component.as_view()
class method that can be used the same asView.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
andpost
to handle GET and POST requests, respectively. -
In addition,
Component
now has arender_to_response
method that renders the component template based on the provided context and slots' data and returns anHttpResponse
object.
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 callingView.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 theurls.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 therender_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
"},{"location":"#modifying-the-view-class","title":"Modifying the View class","text":"format_html
andmark_safe
.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()
orComponent.View.post()
methods. However, by default,Component.View.get()
points toComponent.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 asComponent.View
2. Subclass fromComponentView
, so the View instance has access to the component instance.In the example below, we added extra logic into
View.setup()
.Note that the POST handler is still defined at the top. This is because
View
subclassesComponentView
, which defines thepost()
method that callsComponent.post()
.If you were to overwrite the
View.post()
method, thenComponent.post()
would be ignored.
"},{"location":"#typing-and-validating-components","title":"Typing and validating components","text":""},{"location":"#adding-type-hints-with-generics","title":"Adding type hints with Generics","text":"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
New in version 0.92
The
Component
class optionally accepts type parameters that allow you to specify the types of args, kwargs, slots, and data:class Button(Component[Args, Kwargs, Slots, Data, JsData, CssData]):\n ...\n
Args
- Must be aTuple
orAny
Kwargs
- Must be aTypedDict
orAny
Data
- Must be aTypedDict
orAny
Slots
- Must be aTypedDict
orAny
Here's a full example:
from typing import NotRequired, Tuple, TypedDict, SlotContent, SlotFunc\n\n# Positional inputs\nArgs = Tuple[int, str]\n\n# Kwargs inputs\nclass Kwargs(TypedDict):\n variable: str\n another: int\n maybe_var: NotRequired[int] # May be ommited\n\n# Data returned from `get_context_data`\nclass Data(TypedDict):\n variable: str\n\n# The data available to the `my_slot` scoped slot\nclass MySlotData(TypedDict):\n value: int\n\n# Slots\nclass Slots(TypedDict):\n # Use SlotFunc for slot functions.\n # The generic specifies the `data` dictionary\n my_slot: NotRequired[SlotFunc[MySlotData]]\n # SlotContent == Union[str, SafeString]\n another_slot: SlotContent\n\nclass Button(Component[Args, Kwargs, Slots, Data, JsData, CssData]):\n def get_context_data(self, variable, another):\n return {\n \"variable\": variable,\n }\n
When you then call
Component.render
orComponent.render_to_response
, you will get type hints:
"},{"location":"#usage-for-python-311","title":"Usage for Python <3.11","text":"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
On Python 3.8-3.10, use
typing_extensions
from typing_extensions import TypedDict, NotRequired\n
Additionally on Python 3.8-3.9, also import
annotations
:from __future__ import annotations\n
Moreover, on 3.10 and less, you may not be able to use
NotRequired
, and instead you will need to mark either all keys are required, or all keys as optional, using TypeDict'stotal
kwarg.See PEP-655 for more info.
"},{"location":"#passing-additional-args-or-kwargs","title":"Passing additional args or kwargs","text":"You may have a function that supports any number of args or kwargs:
def get_context_data(self, *args, **kwargs):\n ...\n
This is not supported with the typed components.
As a workaround: - For
*args
, set a positional argument that accepts a list of values:```py\n# Tuple of one member of list of strings\nArgs = Tuple[List[str]]\n```\n
-
For
*kwargs
, set a keyword argument that accepts a dictionary of values:class Kwargs(TypedDict):\n variable: str\n another: int\n # Pass any extra keys under `extra`\n extra: Dict[str, any]\n
To declare that a component accepts no Args, Kwargs, etc, you can use
EmptyTuple
andEmptyDict
types:
"},{"location":"#runtime-input-validation-with-types","title":"Runtime input validation with types","text":"from django_components import Component, EmptyDict, EmptyTuple\n\nArgs = EmptyTuple\nKwargs = Data = Slots = EmptyDict\n\nclass Button(Component[Args, Kwargs, Slots, Data, JsData, CssData]):\n ...\n
New in version 0.96
NOTE: Kwargs, slots, and data validation is supported only for Python >=3.11
In Python 3.11 and later, when you specify the component types, you will get also runtime validation of the inputs you pass to
Component.render
orComponent.render_to_response
.So, using the example from before, if you ignored the type errors and still ran the following code:
Button.render(\n # Error: First arg must be `int`, got `float`\n args=(1.25, \"abc\"),\n # Error: Key \"another\" is missing\n kwargs={\n \"variable\": \"text\",\n },\n)\n
This would raise a
TypeError
:Component 'Button' expected positional argument at index 0 to be <class 'int'>, got 1.25 of type <class 'float'>\n
In case you need to skip these errors, you can either set the faulty member to
Any
, e.g.:# Changed `int` to `Any`\nArgs = Tuple[Any, str]\n
Or you can replace
Args
withAny
altogether, to skip the validation of args:# Replaced `Args` with `Any`\nclass Button(Component[Any, Kwargs, Slots, Data, JsData, CssData]):\n ...\n
Same applies to kwargs, data, and slots.
"},{"location":"#pre-defined-components","title":"Pre-defined components","text":""},{"location":"#dynamic-components","title":"Dynamic components","text":"If you are writing something like a form component, you may design it such that users give you the component names, and your component renders it.
While you can handle this with a series of if / else statements, this is not an extensible solution.
Instead, you can use dynamic components. Dynamic components are used in place of normal components.
{% load component_tags %}\n{% component \"dynamic\" is=component_name title=\"Cat Museum\" %}\n {% fill \"content\" %}\n HELLO_FROM_SLOT_1\n {% endfill %}\n {% fill \"sidebar\" %}\n HELLO_FROM_SLOT_2\n {% endfill %}\n{% endcomponent %}\n
or in case you use the
django_components.component_shorthand_formatter
tag formatter:{% dynamic is=component_name title=\"Cat Museu\" %}\n {% fill \"content\" %}\n HELLO_FROM_SLOT_1\n {% endfill %}\n {% fill \"sidebar\" %}\n HELLO_FROM_SLOT_2\n {% endfill %}\n{% enddynamic %}\n
These behave same way as regular components. You pass it the same args, kwargs, and slots as you would to the component that you want to render.
The only exception is that also you supply 1-2 additional inputs: -
is
- Required - The component name or a component class to render -registry
- Optional - TheComponentRegistry
that will be searched ifis
is a component name. If omitted, ALL registries are searched.By default, the dynamic component is registered under the name
\"dynamic\"
. In case of a conflict, you can change the name used for the dynamic components by defining theCOMPONENTS.dynamic_component_name
setting.If you need to use the dynamic components in Python, you can also import it from
django_components
:
"},{"location":"#registering-components","title":"Registering components","text":"from django_components import DynamicComponent\n\ncomp = SimpleTableComp if is_readonly else TableComp\n\noutput = DynamicComponent.render(\n kwargs={\n \"is\": comp,\n # Other kwargs...\n },\n # args: [...],\n # slots: {...},\n)\n
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,
"},{"location":"#what-is-componentregistry","title":"What is ComponentRegistry","text":"@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.The
@register
decorator is a shortcut for working with theComponentRegistry
.ComponentRegistry
manages which components can be used in the template tags.Each
ComponentRegistry
instance is associated with an instance of Django'sLibrary
. And Libraries are inserted into Django template using the{% load %}
tags.The
@register
decorator accepts an optional kwargregistry
, which specifies, theComponentRegistry
to register components into. If omitted, the defaultComponentRegistry
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 theLibrary
that you load when you call{% load component_tags %}
inside your template, or when you adddjango_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
"},{"location":"#working-with-componentregistry","title":"Working with ComponentRegistry","text":"{% component \"my_comp\" %}
.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:
"},{"location":"#registering-components-to-custom-componentregistry","title":"Registering components to custom ComponentRegistry","text":"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
If you are writing a component library to be shared with others, you may want to manage your own instance of
ComponentRegistry
and register components onto a differentLibrary
instance than the default one.The
Library
instance can be set at instantiation ofComponentRegistry
. 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 withmy_registry.register()
, or pass the registry to the@component.register()
decorator via theregistry
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
"},{"location":"#componentregistry-settings","title":"ComponentRegistry settings","text":"library
attribute ofComponentRegistry
.When you are creating an instance of
ComponentRegistry
, you can define the components' behavior within the template.The registry accepts these settings: -
context_behavior
-tag_formatter
from django.template import Library\nfrom django_components import ComponentRegistry, RegistrySettings\n\nregister = library = django.template.Library()\ncomp_registry = ComponentRegistry(\n library=library,\n settings=RegistrySettings(\n context_behavior=\"isolated\",\n tag_formatter=\"django_components.component_formatter\",\n ),\n)\n
These settings are the same as the ones you can set for django_components.
In fact, when you set
COMPONENT.tag_formatter
orCOMPONENT.context_behavior
, these are forwarded to the defaultComponentRegistry
.This makes it possible to have multiple registries with different settings in one projects, and makes sharing of component libraries possible.
"},{"location":"#autodiscovery","title":"Autodiscovery","text":"Every component that you want to use in the template with the
{% component %}
tag needs to be registered with the ComponentRegistry. Normally, we use the@register
decorator for that:from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n ...\n
But for the component to be registered, the code needs to be executed - the file needs to be imported as a module.
One way to do that is by importing all your components in
apps.py
:from django.apps import AppConfig\n\nclass MyAppConfig(AppConfig):\n name = \"my_app\"\n\n def ready(self) -> None:\n from components.card.card import Card\n from components.list.list import List\n from components.menu.menu import Menu\n from components.button.button import Button\n ...\n
However, there's a simpler way!
By default, the Python files in the
COMPONENTS.dirs
directories (or app-level[app]/components/
) are auto-imported in order to auto-register the components.Autodiscovery occurs when Django is loaded, during the
ready
hook of theapps.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:
"},{"location":"#using-slots-in-templates","title":"Using slots in templates","text":"from django_components import autodiscover\n\nautodiscover()\n
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 theslot
tag.
Components support something called 'slots'. When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content. This mechanism makes components more reusable and composable. This behavior is similar to slots in Vue.
In the example below we introduce two block tags that work hand in hand to make this work. These are...
{% slot <name> %}
/{% endslot %}
: Declares a new slot in the component template.{% fill <name> %}
/{% endfill %}
: (Used inside a{% component %}
tag pair.) Fills a declared slot with the specified content.
Let's update our calendar component to support more customization. We'll add
slot
tag pairs to its template, template.html.<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" %}Calendar header{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"body\" %}Today's date is <span>{{ date }}</span>{% endslot %}\n </div>\n</div>\n
When using the component, you specify which slots you want to fill and where you want to use the defaults from the template. It looks like this:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"body\" %}\n Can you believe it's already <span>{{ date }}</span>??\n {% endfill %}\n{% endcomponent %}\n
Since the 'header' fill is unspecified, it's taken from the base template. If you put this in a template, and pass in
date=2020-06-06
, this is what gets rendered:
"},{"location":"#named-slots","title":"Named slots","text":"<div class=\"calendar-component\">\n <div class=\"header\">\n Calendar header\n </div>\n <div class=\"body\">\n Can you believe it's already <span>2020-06-06</span>??\n </div>\n</div>\n
As seen in the previouse section, you can use
{% fill slot_name %}
to insert content into a specific slot.You can define fills for multiple slot simply by defining them all within the
{% component %} {% endcomponent %}
tags:{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}\n Hi this is header!\n {% endfill %}\n {% fill \"body\" %}\n Can you believe it's already <span>{{ date }}</span>??\n {% endfill %}\n{% endcomponent %}\n
You can also use
{% for %}
,{% with %}
, or other non-component tags (even{% include %}
) to construct the{% fill %}
tags, as long as these other tags do not leave any text behind!
"},{"location":"#default-slot","title":"Default slot","text":"{% component \"table\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name %}\n {{ slot_name }}\n {% endfill %}\n {% endfor %}\n\n {% with slot_name=\"abc\" %}\n {% fill name=slot_name %}\n {{ slot_name }}\n {% endfill %}\n {% endwith %}\n{% endcomponent %}\n
Added in version 0.28
As you can see, component slots lets you write reusable containers that you fill in when you use a component. This makes for highly reusable components that can be used in different circumstances.
It can become tedious to use
fill
tags everywhere, especially when you're using a component that declares only one slot. To make things easier,slot
tags can be marked with an optional keyword:default
.When added to the tag (as shown below), this option lets you pass filling content directly in the body of a
component
tag pair \u2013 without using afill
tag. Choose carefully, though: a component template may contain at most one slot that is marked asdefault
. Thedefault
option can be combined with other slot options, e.g.required
.Here's the same example as before, except with default slots and implicit filling.
The template:
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" %}Calendar header{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"body\" default %}Today's date is <span>{{ date }}</span>{% endslot %}\n </div>\n</div>\n
Including the component (notice how the
fill
tag is omitted):{% component \"calendar\" date=\"2020-06-06\" %}\n Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n
The rendered result (exactly the same as before):
<div class=\"calendar-component\">\n <div class=\"header\">Calendar header</div>\n <div class=\"body\">Can you believe it's already <span>2020-06-06</span>??</div>\n</div>\n
You may be tempted to combine implicit fills with explicit
fill
tags. This will not work. The following component template will raise an error when rendered.{# DON'T DO THIS #}\n{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}Totally new header!{% endfill %}\n Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n
Instead, you can use a named fill with name
default
to target the default fill:{# THIS WORKS #}\n{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}Totally new header!{% endfill %}\n {% fill \"default\" %}\n Can you believe it's already <span>{{ date }}</span>??\n {% endfill %}\n{% endcomponent %}\n
NOTE: If you doubly-fill a slot, that is, that both
"},{"location":"#accessing-default-slot-in-python","title":"Accessing default slot in Python","text":"{% fill \"default\" %}
and{% fill \"header\" %}
would point to the same slot, this will raise an error when rendered.Since the default slot is stored under the slot name
default
, you can access the default slot like so:
"},{"location":"#render-fill-in-multiple-places","title":"Render fill in multiple places","text":"class MyTable(Component):\n def get_context_data(self, *args, **kwargs):\n default_slot = self.input.slots[\"default\"]\n return {\n \"default_slot\": default_slot,\n }\n
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:
"},{"location":"#default-and-required-slots","title":"Default and required slots","text":"<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
If you use a slot multiple times, you can still mark the slot as
default
orrequired
. For that, you must mark each slot individually, e.g.:<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"image\" default required %}Image here{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"image\" default required %}Image here{% endslot %}\n </div>\n</div>\n
Which you can then use as regular default slot:
{% component \"calendar\" date=\"2020-06-06\" %}\n <img src=\"...\" />\n{% endcomponent %}\n
Since each slot is tagged individually, you can have multiple slots with the same name but different conditions.
E.g. in this example, we have a component that renders a user avatar - a small circular image with a profile picture of name initials.
If the component is given
image_src
orname_initials
variables, theimage
slot is optional. But if neither of those are provided, you MUST fill theimage
slot.
"},{"location":"#accessing-original-content-of-slots","title":"Accessing original content of slots","text":"<div class=\"avatar\">\n {% if image_src %}\n {% slot \"image\" default %}\n <img src=\"{{ image_src }}\" />\n {% endslot %}\n {% elif name_initials %}\n {% slot \"image\" default %}\n <div style=\"\n border-radius: 25px;\n width: 50px;\n height: 50px;\n background: blue;\n \">\n {{ name_initials }}\n </div>\n {% endslot %}\n {% else %}\n {% slot \"image\" default required / %}\n {% endif %}\n</div>\n
Added in version 0.26
NOTE: In version 0.77, the syntax was changed from
{% fill \"my_slot\" as \"alias\" %} {{ alias.default }}\n
to
{% fill \"my_slot\" default=\"slot_default\" %} {{ slot_default }}\n
Sometimes you may want to keep the original slot, but only wrap or prepend/append content to it. To do so, you can access the default slot via the
default
kwarg.Similarly to the
data
attribute, you specify the variable name through which the default slot will be made available.For instance, let's say you're filling a slot called 'body'. To render the original slot, assign it to a variable using the
'default'
keyword. You then render this variable to insert the default content:{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"body\" default=\"body_default\" %}\n {{ body_default }}. Have a great day!\n {% endfill %}\n{% endcomponent %}\n
This produces:
<div class=\"calendar-component\">\n <div class=\"header\">\n Calendar header\n </div>\n <div class=\"body\">\n Today's date is <span>2020-06-06</span>. Have a great day!\n </div>\n</div>\n
To access the original content of a default slot, set the name to
default
:
"},{"location":"#conditional-slots","title":"Conditional slots","text":"{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"default\" default=\"slot_default\" %}\n {{ slot_default }}. Have a great day!\n {% endfill %}\n{% endcomponent %}\n
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 Accessingis_filled
of slot names with special characters.In certain circumstances, you may want the behavior of slot filling to depend on whether or not a particular slot is filled.
For example, suppose we have the following component template:
<div class=\"frontmatter-component\">\n <div class=\"title\">\n {% slot \"title\" %}Title{% endslot %}\n </div>\n <div class=\"subtitle\">\n {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n </div>\n</div>\n
By default the slot named 'subtitle' is empty. Yet when the component is used without explicit fills, the div containing the slot is still rendered, as shown below:
<div class=\"frontmatter-component\">\n <div class=\"title\">Title</div>\n <div class=\"subtitle\"></div>\n</div>\n
This may not be what you want. What if instead the outer 'subtitle' div should only be included when the inner slot is in fact filled?
The answer is to use the
{{ component_vars.is_filled.<name> }}
variable. You can use this together with Django's{% if/elif/else/endif %}
tags to define a block whose contents will be rendered only if the component slot with the corresponding 'name' is filled.This is what our example looks like with
component_vars.is_filled
.<div class=\"frontmatter-component\">\n <div class=\"title\">\n {% slot \"title\" %}Title{% endslot %}\n </div>\n {% if component_vars.is_filled.subtitle %}\n <div class=\"subtitle\">\n {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n </div>\n {% endif %}\n</div>\n
Here's our example with more complex branching.
<div class=\"frontmatter-component\">\n <div class=\"title\">\n {% slot \"title\" %}Title{% endslot %}\n </div>\n {% if component_vars.is_filled.subtitle %}\n <div class=\"subtitle\">\n {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n </div>\n {% elif component_vars.is_filled.title %}\n ...\n {% elif component_vars.is_filled.<name> %}\n ...\n {% endif %}\n</div>\n
Sometimes you're not interested in whether a slot is filled, but rather that it isn't. To negate the meaning of
component_vars.is_filled
, simply treat it as boolean and negate it withnot
:
"},{"location":"#accessing-is_filled-of-slot-names-with-special-characters","title":"Accessing{% if not component_vars.is_filled.subtitle %}\n<div class=\"subtitle\">\n {% slot \"subtitle\" / %}\n</div>\n{% endif %}\n
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 ascomponent_vars.is_filled.my_super_slot___
.Same applies when you are accessing
is_filled
from within the Python, e.g.:
"},{"location":"#scoped-slots","title":"Scoped slots","text":"class MyTable(Component):\n def on_render_before(self, context, template) -> None:\n # \u2705 Works\n if self.is_filled[\"my_super_slot___\"]:\n # Do something\n\n # \u274c Does not work\n if self.is_filled[\"my super-slot :)\"]:\n # Do something\n
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
To pass the data to the
slot
tag, simply pass them as keyword attributes (key=value
):
"},{"location":"#accessing-slot-data-in-fill","title":"Accessing slot data in fill","text":"@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
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 todata
:{% component \"my_comp\" %}\n {% fill \"content\" data=\"slot_data\" %}\n {{ slot_data.input }}\n {% endfill %}\n{% endcomponent %}\n
To access slot data on a default slot, you have to explictly define the
{% fill %}
tags.So this works:
{% component \"my_comp\" %}\n {% fill \"default\" data=\"slot_data\" %}\n {{ slot_data.input }}\n {% endfill %}\n{% endcomponent %}\n
While this does not:
{% component \"my_comp\" data=\"data\" %}\n {{ data.input }}\n{% endcomponent %}\n
Note: You cannot set the
data
attribute anddefault
attribute) to the same name. This raises an error:
"},{"location":"#dynamic-slots-and-fills","title":"Dynamic slots and fills","text":"{% component \"my_comp\" %}\n {% fill \"content\" data=\"slot_var\" default=\"slot_var\" %}\n {{ slot_var.input }}\n {% endfill %}\n{% endcomponent %}\n
Until now, we were declaring slot and fill names statically, as a string literal, e.g.
{% slot \"content\" / %}\n
However, sometimes you may want to generate slots based on the given input. One example of this is a table component like that of Vuetify, which creates a header and an item slots for each user-defined column.
In django_components you can achieve the same, simply by using a variable (or a template expression) instead of a string literal:
<table>\n <tr>\n {% for header in headers %}\n <th>\n {% slot \"header-{{ header.key }}\" value=header.title %}\n {{ header.title }}\n {% endslot %}\n </th>\n {% endfor %}\n </tr>\n</table>\n
When using the component, you can either set the fill explicitly:
{% component \"table\" headers=headers items=items %}\n {% fill \"header-name\" data=\"data\" %}\n <b>{{ data.value }}</b>\n {% endfill %}\n{% endcomponent %}\n
Or also use a variable:
{% component \"table\" headers=headers items=items %}\n {# Make only the active column bold #}\n {% fill \"header-{{ active_header_name }}\" data=\"data\" %}\n <b>{{ data.value }}</b>\n {% endfill %}\n{% endcomponent %}\n
NOTE: It's better to use static slot names whenever possible for clarity. The dynamic slot names should be reserved for advanced use only.
Lastly, in rare cases, you can also pass the slot name via the spread operator. This is possible, because the slot name argument is actually a shortcut for a
name
keyword argument.So this:
{% slot \"content\" / %}\n
is the same as:
{% slot name=\"content\" / %}\n
So it's possible to define a
name
key on a dictionary, and then spread that onto the slot tag:
"},{"location":"#pass-through-all-the-slots","title":"Pass through all the slots","text":"{# slot_props = {\"name\": \"content\"} #}\n{% slot ...slot_props / %}\n
You can dynamically pass all slots to a child component. This is similar to passing all slots in Vue:
"},{"location":"#accessing-data-passed-to-the-component","title":"Accessing data passed to the component","text":"class MyTable(Component):\n def get_context_data(self, *args, **kwargs):\n return {\n \"slots\": self.input.slots,\n }\n\n template: \"\"\"\n <div>\n {% component \"child\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name data=\"data\" %}\n {% slot name=slot_name ...data / %}\n {% endfill %}\n {% endfor %}\n {% endcomponent %}\n </div>\n \"\"\"\n
When you call
Component.render
orComponent.render_to_response
, the inputs to these methods can be accessed from within the instance underself.input
.This means that you can use
self.input
inside: -get_context_data
-get_template_name
-get_template
-on_render_before
-on_render_after
self.input
is only defined during the execution ofComponent.render
, and raises aRuntimeError
when called outside of this context.self.input
has the same fields as the input toComponent.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\": ...}\n assert isinstance(self.input.context, Context)\n\n return {\n \"variable\": variable,\n }\n\nrendered = TestComponent.render(\n kwargs={\"variable\": \"test\", \"another\": 1},\n args=(123, \"str\"),\n slots={\"my_slot\": \"MY_SLOT\"},\n)\n
NOTE: The slots in
"},{"location":"#rendering-html-attributes","title":"Rendering HTML attributes","text":"self.input.slots
are normalized to slot functions.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
"},{"location":"#removing-atttributes","title":"Removing atttributes","text":"merge_attrs
tag of django-web-components and \"fallthrough attributes\" feature of Vue.Attributes that are set to
None
orFalse
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:
"},{"location":"#boolean-attributes","title":"Boolean attributes","text":"<div class=\"text-green\"></div>\n
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 orattributes_to_string
works the same way, wherekey=True
is rendered simply askey
, andkey=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:
"},{"location":"#default-attributes","title":"Default attributes","text":"<div disabled></div>\n
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. theclass
key,html_attrs
will render:class=\"{{ attrs.class }}\"
Otherwise,
html_attrs
will render:
"},{"location":"#appending-attributes","title":"Appending attributes","text":"class=\"{{ defaults.class }}\"
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 keyclass
:<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:
"},{"location":"#rules-for-html_attrs","title":"Rules for<div\n data-value=\"my-class pa-4 some-class another-class class-from-var text-red\"\n></div>\n
html_attrs
","text":"- Both
attrs
anddefaults
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
anddefaults
are optional (can be omitted) -
Both
attrs
anddefaults
are dictionaries, and we can define them the same way we define dictionaries for thecomponent
tag. So either asattrs=attrs
orattrs:key=value
. -
All other kwargs are appended and can be repeated.
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:
"},{"location":"#full-example-for-html_attrs","title":"Full example forclass=\"from-attrs added_class from-var\" type=\"submit\" data-id=123
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 attributedefaults:class=\"pa-4 text-red\"
So if
attrs
includes keyclass
, the default above will be ignored.MyComp
also definesclass
key twice. It means that whether theclass
attribute is taken fromattrs
ordefaults
, the twoclass
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
fromParent
component.MyComp
accepts aattrs
dictionary, that is passed tohtml_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 anattrs
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
ofMyComp
will receiveattrs
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 forclass
, whereas other keys will be merged.So in the end
MyComp
will render:
"},{"location":"#rendering-html-attributes-outside-of-templates","title":"Rendering HTML attributes outside of templates","text":"<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
If you need to use serialize HTML attributes outside of Django template and the
html_attrs
tag, you can useattributes_to_string
:
"},{"location":"#template-tag-syntax","title":"Template tag syntax","text":"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
All template tags in django_component, like
"},{"location":"#self-closing-tags","title":"Self-closing tags","text":"{% component %}
or{% slot %}
, and so on, support extra syntax that makes it possible to write components like in Vue or React (JSX).When you have a tag like
{% component %}
or{% slot %}
, but it has no content, you can simply append a forward slash/
at the end, instead of writing out the closing tags like{% endcomponent %}
or{% endslot %}
:So this:
{% component \"button\" %}{% endcomponent %}\n
becomes
"},{"location":"#special-characters","title":"Special characters","text":"{% component \"button\" / %}\n
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:
"},{"location":"#spread-operator","title":"Spread operator","text":"@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
New in version 0.93:
Instead of passing keyword arguments one-by-one:
{% component \"calendar\" title=\"How to abc\" date=\"2015-06-19\" author=\"John Wick\" / %}\n
You can use a spread operator
...dict
to apply key-value pairs from a dictionary:post_data = {\n \"title\": \"How to...\",\n \"date\": \"2015-06-19\",\n \"author\": \"John Wick\",\n}\n
{% component \"calendar\" ...post_data / %}\n
This behaves similar to JSX's spread operator or Vue's
v-bind
.Spread operators are treated as keyword arguments, which means that: 1. Spread operators must come after positional arguments. 2. You cannot use spread operators for positional-only arguments.
Other than that, you can use spread operators multiple times, and even put keyword arguments in-between or after them:
{% component \"calendar\" ...post_data id=post.id ...extra / %}\n
In a case of conflicts, the values added later (right-most) overwrite previous values.
"},{"location":"#use-template-tags-inside-component-inputs","title":"Use template tags inside component inputs","text":"New in version 0.93
When passing data around, sometimes you may need to do light transformations, like negating booleans or filtering lists.
Normally, what you would have to do is to define ALL the variables inside
get_context_data()
. But this can get messy if your components contain a lot of logic.@register(\"calendar\")\nclass Calendar(Component):\n def get_context_data(self, id: str, editable: bool):\n return {\n \"editable\": editable,\n \"readonly\": not editable,\n \"input_id\": f\"input-{id}\",\n \"icon_id\": f\"icon-{id}\",\n ...\n }\n
Instead, template tags in django_components (
{% component %}
,{% slot %}
,{% provide %}
, etc) allow you to treat literal string values as templates:{% component 'blog_post'\n \"As positional arg {# yay #}\"\n title=\"{{ person.first_name }} {{ person.last_name }}\"\n id=\"{% random_int 10 20 %}\"\n readonly=\"{{ editable|not }}\"\n author=\"John Wick {# TODO: parametrize #}\"\n/ %}\n
In the example above: - Component
test
receives a positional argument with value\"As positional arg \"
. The comment is omitted. - Kwargtitle
is passed as a string, e.g.John Doe
- Kwargid
is passed asint
, e.g.15
- Kwargreadonly
is passed asbool
, e.g.False
- Kwargauthor
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:
"},{"location":"#evaluating-python-expressions-in-template","title":"Evaluating Python expressions in template","text":"{% component 'cat_list' items=\"{{ cats|slice:':2' }} See more\" / %}\n
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 anexpr
tag and filter that you can use to evaluate Python expressions from within the template:{% component \"my_form\"\n value=\"{% expr 'input_value if is_enabled else None' %}\"\n/ %}\n
Note: Never use this feature to mix business logic and template logic. Business logic should still be in the view!
"},{"location":"#pass-dictonary-by-its-key-value-pairs","title":"Pass dictonary by its key-value pairs","text":"New in version 0.74:
Sometimes, a component may expect a dictionary as one of its inputs.
Most commonly, this happens when a component accepts a dictionary of HTML attributes (usually called
attrs
) to pass to the underlying template.In such cases, we may want to define some HTML attributes statically, and other dynamically. But for that, we need to define this dictionary on Python side:
@register(\"my_comp\")\nclass MyComp(Component):\n template = \"\"\"\n {% component \"other\" attrs=attrs / %}\n \"\"\"\n\n def get_context_data(self, some_id: str):\n attrs = {\n \"class\": \"pa-4 flex\",\n \"data-some-id\": some_id,\n \"@click.stop\": \"onClickHandler\",\n }\n return {\"attrs\": attrs}\n
But as you can see in the case above, the event handler
@click.stop
and stylingpa-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 keyclass
of inputattrs
becomesattrs: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:
"},{"location":"#multi-line-tags","title":"Multi-line tags","text":"{\"attrs\": {\"my_key:two\": 2}}\n
By default, Django expects a template tag to be defined on a single line.
However, this can become unwieldy if you have a component with a lot of inputs:
{% component \"card\" title=\"Joanne Arc\" subtitle=\"Head of Kitty Relations\" date_last_active=\"2024-09-03\" ... %}\n
Instead, when you install django_components, it automatically configures Django to suport multi-line tags.
So we can rewrite the above as:
{% component \"card\"\n title=\"Joanne Arc\"\n subtitle=\"Head of Kitty Relations\"\n date_last_active=\"2024-09-03\"\n ...\n%}\n
Much better!
To disable this behavior, set
"},{"location":"#prop-drilling-and-dependency-injection-provide-inject","title":"Prop drilling and dependency injection (provide / inject)","text":"COMPONENTS.multiline_tag
toFalse
New in version 0.80:
Django components supports dependency injection with the combination of:
{% provide %}
taginject()
method of theComponent
class
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 name must resolve to a valid identifier (AKA a valid Python variable name).Once you've set the name, you define the data you want to \"provide\" by passing it as keyword arguments. This is similar to how you pass data to the
{% with %}
tag.NOTE: Kwargs passed to
{% provide %}
are NOT added to the context. In the example below, the{{ key }}
won't render anything:{% provide \"my_data\" key=\"hi\" another=123 %}\n {{ key }}\n{% endprovide %}\n
Similarly to slots and fills, also provide's name argument can be set dynamically via a variable, a template expression, or a spread operator:
"},{"location":"#using-inject-method","title":"Using{% provide name=name ... %}\n ...\n{% provide %}\n</table>\n
inject()
method","text":"To \"inject\" (access) the data defined on the
provide
tag, you can use theinject()
method inside ofget_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
andanother
.class ChildComponent(Component):\n def get_context_data(self):\n my_data = self.inject(\"my_data\")\n print(my_data.key) # hi\n print(my_data.another) # 123\n return {}\n
First argument to
inject
is the key (or name) of the provided data. This must match the string that you used in theprovide
tag. If no provider with given key is found,inject
raises aKeyError
.To avoid the error, you can pass a second argument to
inject
to which will act as a default value, similar todict.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 ofNamedTuple
, so the instance is immutable. This ensures that the data returned frominject
will always have all the keys that were passed to theprovide
tag.NOTE:
"},{"location":"#full-example","title":"Full example","text":"inject()
works strictly only inget_context_data
. If you try to call it from elsewhere, it will raise an error.@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:
"},{"location":"#component-hooks","title":"Component hooks","text":"<div>hi</div>\n<div>123</div>\n
New in version 0.96
Component hooks are functions that allow you to intercept the rendering process at specific positions.
"},{"location":"#available-hooks","title":"Available hooks","text":"on_render_before
def on_render_before(\n self: Component,\n context: Context,\n template: Template\n) -> None:\n
Hook that runs just before the component's template is rendered.\n\nYou can use this hook to access or modify the context or the template:\n\n```py\ndef on_render_before(self, context, template) -> None:\n # Insert value into the Context\n context[\"from_on_before\"] = \":)\"\n\n # Append text into the Template\n template.nodelist.append(TextNode(\"FROM_ON_BEFORE\"))\n```\n
on_render_after
def on_render_after(\n self: Component,\n context: Context,\n template: Template,\n content: str\n) -> None | str | SafeString:\n
"},{"location":"#component-hooks-example","title":"Component hooks example","text":"Hook that runs just after the component's template was rendered.\nIt receives the rendered output as the last argument.\n\nYou can use this hook to access the context or the template, but modifying\nthem won't have any effect.\n\nTo override the content that gets rendered, you can return a string or SafeString from this hook:\n\n```py\ndef on_render_after(self, context, template, content):\n # Prepend text to the rendered content\n return \"Chocolate cookie recipe: \" + content\n```\n
You can use hooks together with provide / inject to create components that accept a list of items via a slot.
In the example below, each
tab_item
component will be rendered on a separate tab page, but they are all defined in the default slot of thetabs
component.See here for how it was done
"},{"location":"#component-context-and-scope","title":"Component context and scope","text":"{% component \"tabs\" %}\n {% component \"tab_item\" header=\"Tab 1\" %}\n <p>\n hello from tab 1\n </p>\n {% component \"button\" %}\n Click me!\n {% endcomponent %}\n {% endcomponent %}\n\n {% component \"tab_item\" header=\"Tab 2\" %}\n Hello this is tab 2\n {% endcomponent %}\n{% endcomponent %}\n
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, addonly
to the{% component %}
tag:{% component \"calendar\" date=\"2015-06-19\" only / %}\n
NOTE:
{% csrf_token %}
tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with theonly
modifier.If you find yourself using the
only
modifier often, you can set the context_behavior option to\"isolated\"
, which automatically applies theonly
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
"},{"location":"#example-of-accessing-outer-context","title":"Example of Accessing Outer Context","text":"get_context_data
by accessing the propertyself.outer_context
.<div>\n {% component \"calender\" / %}\n</div>\n
Assuming that the rendering context has variables such as
date
, you can useself.outer_context
to access them from withinget_context_data
. Here's how you might implement it:class Calender(Component):\n\n ...\n\n def get_context_data(self):\n outer_field = self.outer_context[\"date\"]\n return {\n \"date\": outer_fields,\n }\n
However, as a best practice, it\u2019s recommended not to rely on accessing the outer context directly through
"},{"location":"#pre-defined-template-variables","title":"Pre-defined template variables","text":"self.outer_context
. Instead, explicitly pass the variables to the component. For instance, continue passing the variables in the component tag as shown in the previous examples.Here is a list of all variables that are automatically available from within the component's template and
on_render_before
/on_render_after
hooks.-
component_vars.is_filled
New in version 0.70
Dictonary describing which slots are filled (
True
) or are not (False
).Example:
{% if component_vars.is_filled.my_slot %}\n {% slot \"my_slot\" / %}\n{% endif %}\n
This is equivalent to checking if a given key is among the slot fills:
class MyTable(Component):\n def get_context_data(self, *args, **kwargs):\n return {\n \"my_slot_filled\": \"my_slot\" in self.input.slots\n }\n
New in version 0.89
By default, components are rendered using the pair of
{% component %}
/{% endcomponent %}
template tags:{% component \"button\" href=\"...\" disabled %}\nClick me!\n{% endcomponent %}\n\n{# or #}\n\n{% component \"button\" href=\"...\" disabled / %}\n
You can change this behaviour in the settings under the
COMPONENTS.tag_formatter
.For example, if you set the tag formatter to
django_components.component_shorthand_formatter
, the components will use their name as the template tags:
"},{"location":"#available-tagformatters","title":"Available TagFormatters","text":"{% button href=\"...\" disabled %}\n Click me!\n{% endbutton %}\n\n{# or #}\n\n{% button href=\"...\" disabled / %}\n
django_components provides following predefined TagFormatters:
-
ComponentFormatter
(django_components.component_formatter
)Default
Uses the
component
andendcomponent
tags, and the component name is gives as the first positional argument.Example as block:
{% component \"button\" href=\"...\" %}\n {% fill \"content\" %}\n ...\n {% endfill %}\n{% endcomponent %}\n
Example as inlined tag:
{% component \"button\" href=\"...\" / %}\n
-
ShorthandComponentFormatter
(django_components.component_shorthand_formatter
)Uses the component name as start tag, and
end<component_name>
as an end tag.Example as block:
{% button href=\"...\" %}\n Click me!\n{% endbutton %}\n
Example as inlined tag:
{% button href=\"...\" / %}\n
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 tagcomponent
. 3. The tag handler passes the tag contents for pre-processing toTagFormatter.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:
5. The tag handler resumes, using the tokens returned fromTagResult(\n component_name=\"button\",\n tokens=['href=\"...\"', 'disabled']\n)\n
TagFormatter
.So, continuing the example, at this point the tag handler practically behaves as if you rendered:
6. Tag handler looks up the component{% component href=\"...\" disabled %}\n
button
, and passes the args, kwargs, and slots to it.
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
"},{"location":"#defining-htmljscss-files","title":"Defining HTML/JS/CSS files","text":"TagFormatter
is ready, don't forget to update the settings!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)
As seen in the getting started example, to associate HTML/JS/CSS files with a component, you set them as
template_name
,Media.js
andMedia.css
respectively:# In a file [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"template.html\"\n\n class Media:\n css = \"style.css\"\n js = \"script.js\"\n
In the example above, the files are defined relative to the directory where
component.py
is.Alternatively, you can specify the file paths relative to the directories set in
COMPONENTS.dirs
orCOMPONENTS.app_dirs
.Assuming that
COMPONENTS.dirs
contains path[project root]/components
, we can rewrite the example as:# In a file [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"calendar/template.html\"\n\n class Media:\n css = \"calendar/style.css\"\n js = \"calendar/script.js\"\n
NOTE: In case of conflict, the preference goes to resolving the files relative to the component's directory.
"},{"location":"#defining-multiple-paths","title":"Defining multiple paths","text":"Each component can have only a single template. However, you can define as many JS or CSS files as you want using a list.
"},{"location":"#configuring-css-media-types","title":"Configuring CSS Media Types","text":"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
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
"},{"location":"#supported-types-for-file-paths","title":"Supported types for file paths","text":"all
media type is implied.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__
)
"},{"location":"#path-as-objects","title":"Path as objects","text":"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
In the example above, you could see that when we used
mark_safe
to mark a string as aSafeString
, we had to define the full<script>
/<link>
tag.This is an extension of Django's Paths as objects feature, where \"safe\" strings are taken as is, and accessed only at render time.
Because of that, the paths defined as \"safe\" strings are NEVER resolved, neither relative to component's directory, nor relative to
COMPONENTS.dirs
.\"Safe\" strings can be used to lazily resolve a path, or to customize the
<script>
or<link>
tag for individual paths:
"},{"location":"#customize-how-paths-are-rendered-into-html-tags-with-media_class","title":"Customize how paths are rendered into HTML tags withclass 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
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'sMedia
class to component'smedia_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
andMedia.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
"},{"location":"#rendering-jscss-dependencies","title":"Rendering JS/CSS dependencies","text":"Media
class (or it's subclass) is available underComponent.media
after the class creation (__new__
).If: 1. Your components use JS and CSS, whether inlined via
Component.js/css
or viaComponent.Media.js/css
, 2. And you use theComponentDependencyMiddleware
middlewareThen, by default, the components' JS and CSS will be automatically inserted into the HTML: - CSS styles will be inserted at the end of the
<head>
- JS scripts will be inserted at the end of the<body>
If you want to place the dependencies elsewhere, you can override that with following Django template tags:
{% component_js_dependencies %}
- Renders only JS{% component_css_dependencies %}
- Renders only CSS
So if you have a component with JS and CSS:
from django_components import Component, types\n\nclass MyButton(Component):\n template: types.django_html = \"\"\"\n <button class=\"my-button\">\n Click me!\n </button>\n \"\"\"\n js: types.js = \"\"\"\n for (const btnEl of document.querySelectorAll(\".my-button\")) {\n btnEl.addEventListener(\"click\", () => {\n console.log(\"BUTTON CLICKED!\");\n });\n }\n \"\"\"\n css: types.css \"\"\"\n .my-button {\n background: green;\n }\n \"\"\"\n\n class Media:\n js = [\"/extra/script.js\"]\n css = [\"/extra/style.css\"]\n
Then the inlined JS and the scripts in
Media.js
will be rendered at the default place, or in{% component_js_dependencies %}
.And the inlined CSS and the styles in
Media.css
will be rendered at the default place, or in{% component_css_dependencies %}
.And if you don't specify
{% component_dependencies %}
tags, it is the equivalent of:
"},{"location":"#setting-up-componentdependencymiddleware","title":"Setting Up<!doctype html>\n<html>\n <head>\n <title>MyPage</title>\n ...\n {% component_css_dependencies %}\n </head>\n <body>\n <main>\n ...\n </main>\n {% component_js_dependencies %}\n </body>\n</html>\n
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:
"},{"location":"#render_dependencies-and-deep-dive-into-rendering-js-css-without-the-middleware","title":"MIDDLEWARE = [\n # ... other middleware classes ...\n 'django_components.middleware.ComponentDependencyMiddleware'\n # ... other middleware classes ...\n]\n
render_dependencies
and deep-dive into rendering JS / CSS without the middleware","text":"For most scenarios, using the
ComponentDependencyMiddleware
middleware will be just fine.However, this section is for you if you want to: - Render HTML that will NOT be sent as a server response - Insert pre-rendered HTML into another component - Render HTML fragments (partials)
Every time there is an HTML string that has parts which were rendered using components, and any of those components has JS / CSS, then this HTML string MUST be processed with
render_dependencies
.It is actually
"},{"location":"#render-js-css-without-the-middleware","title":"Render JS / CSS without the middleware","text":"render_dependencies
that finds all used components in the HTML string, and inserts the component's JS and CSS into{% component_dependencies %}
tags, or at the default locations.The
ComponentDependencyMiddleware
middleware just callsrender_dependencies
, passing in the HTML content. So if you rendered a template that contained{% components %}
tags, instead of the middleware, you MUST pass the result throughrender_dependencies
:from django.template.base import Template\nfrom django.template.context import Context\nfrom django_component import render_dependencies\n\ntemplate = Template(\"\"\"\n {% load component_tags %}\n <!doctype html>\n <html>\n <head>\n <title>MyPage</title>\n </head>\n <body>\n <main>\n {% component \"my_button\" %}\n Click me!\n {% endcomponent %}\n </main>\n </body>\n </html>\n\"\"\")\n\nrendered = template.render(Context({}))\nrendered = render_dependencies(rendered)\n
Same applies if you render a template using Django's
django.shortcuts.render
:from django.shortcuts import render\n\ndef my_view(request):\n rendered = render(request, \"pages/home.html\")\n rendered = render_dependencies(rendered)\n return rendered\n
Alternatively, when you render HTML with
Component.render()
orComponent.render_to_response()
, these automatically callrender_dependencies()
for you, so you don't have to:
"},{"location":"#inserting-pre-rendered-html-into-another-component","title":"Inserting pre-rendered HTML into another component","text":"from django_components import Component\n\nclass MyButton(Component):\n ...\n\n# No need to call `render_dependencies()`\nrendered = MyButton.render()\n
In previous section we've shown that
render_dependencies()
does NOT need to be called when you render a component viaComponent.render()
.API of django-components makes it possible to compose components in a \"React-like\" way, where we pre-render a piece of HTML and then insert it into a larger structure.
To do this, you must add
render_dependencies=False
to the nested components:card_actions = CardActions.render(\n kwargs={\"editable\": editable},\n render_dependencies=False,\n)\n\ncard = Card.render(\n slots={\"actions\": card_actions},\n render_dependencies=False,\n)\n\npage = MyPage.render(\n slots={\"card\": card},\n)\n
Why is
render_dependencies=False
required?As mentioned earlier, each time we call
Component.render()
, we also callrender_dependencies()
.However, there is a problem here - When we call
render_dependencies()
insideCardActions.render()
, we extract the info on components' JS and CSS from the HTML. But the template ofCardActions
contains no{% component_depedencies %}
tags, and nor<head>
nor<body>
HTML tags. So the component's JS and CSS will NOT be inserted, and will be lost.To work around this, you must set
"},{"location":"#available-settings","title":"Available settings","text":"render_dependencies=False
when rendering pieces of HTML withComponent.render()
and inserting them into larger structures.All library settings are handled from a global
COMPONENTS
variable that is read fromsettings.py
. By default you don't need it set, there are resonable defaults.Here's overview of all available settings and their defaults:
"},{"location":"#libraries-load-component-modules","title":"COMPONENTS = {\n \"autodiscover\": True,\n \"context_behavior\": \"django\", # \"django\" | \"isolated\"\n \"dirs\": [BASE_DIR / \"components\"], # Root-level \"components\" dirs, e.g. `/path/to/proj/components/`\n \"app_dirs\": [\"components\"], # App-level \"components\" dirs, e.g. `[app]/components/`\n \"dynamic_component_name\": \"dynamic\",\n \"libraries\": [], # [\"mysite.components.forms\", ...]\n \"multiline_tags\": True,\n \"reload_on_template_change\": False,\n \"static_files_allowed\": [\n \".css\",\n \".js\",\n # Images\n \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n \".jpeg\", \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n # Fonts\n \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n ],\n \"static_files_forbidden\": [\n \".html\", \".django\", \".dj\", \".tpl\",\n # Python files\n \".py\", \".pyc\",\n ],\n \"tag_formatter\": \"django_components.component_formatter\",\n \"template_cache_size\": 128,\n}\n
libraries
- Load component modules","text":"Configure the locations where components are loaded. To do this, add a
COMPONENTS
variable to yousettings.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:
"},{"location":"#autodiscover-toggle-autodiscovery","title":"from django_components import import_libraries\n\nimport_libraries()\n
autodiscover
- Toggle autodiscovery","text":"If you specify all the component locations with the setting above and have a lot of apps, you can (very) slightly speed things up by disabling autodiscovery.
"},{"location":"#dirs","title":"COMPONENTS = {\n \"autodiscover\": False,\n}\n
dirs
","text":"Specify the directories that contain your components.
Directories must be full paths, same as with STATICFILES_DIRS.
These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as a separate file.
"},{"location":"#app_dirs","title":"COMPONENTS = {\n \"dirs\": [BASE_DIR / \"components\"],\n}\n
app_dirs
","text":"Specify the app-level directories that contain your components.
Directories must be relative to app, e.g.:
COMPONENTS = {\n \"app_dirs\": [\"my_comps\"], # To search for [app]/my_comps\n}\n
These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as a separate file.
Each app will be searched for these directories.
Set to empty list to disable app-level components:
"},{"location":"#dynamic_component_name","title":"COMPONENTS = {\n \"app_dirs\": [],\n}\n
dynamic_component_name
","text":"By default, the dynamic component is registered under the name
\"dynamic\"
. In case of a conflict, use this setting to change the name used for the dynamic components.
"},{"location":"#multiline_tags-enabledisable-multiline-support","title":"COMPONENTS = {\n \"dynamic_component_name\": \"new_dynamic\",\n}\n
multiline_tags
- Enable/Disable multiline support","text":"If
True
, template tags can span multiple lines. Default:True
"},{"location":"#static_files_allowed","title":"COMPONENTS = {\n \"multiline_tags\": True,\n}\n
static_files_allowed
","text":"A list of regex patterns (as strings) that define which files within
COMPONENTS.dirs
andCOMPONENTS.app_dirs
are treated as static files.If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running
collectstatic
, and can be accessed under the static file endpoint.You can also pass in compiled regexes (
re.Pattern
) for more advanced patterns.By default, JS, CSS, and common image and font file formats are considered static files:
"},{"location":"#static_files_forbidden","title":"COMPONENTS = {\n \"static_files_allowed\": [\n \"css\",\n \"js\",\n # Images\n \".apng\", \".png\",\n \".avif\",\n \".gif\",\n \".jpg\", \".jpeg\", \".jfif\", \".pjpeg\", \".pjp\", # JPEG\n \".svg\",\n \".webp\", \".bmp\",\n \".ico\", \".cur\", # ICO\n \".tif\", \".tiff\",\n # Fonts\n \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n ],\n}\n
static_files_forbidden
","text":"A list of suffixes that define which files within
COMPONENTS.dirs
andCOMPONENTS.app_dirs
will NEVER be treated as static files.If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in
COMPONENTS.static_files_allowed
.Use this setting together with
COMPONENTS.static_files_allowed
for a fine control over what files will be exposed.You can also pass in compiled regexes (
re.Pattern
) for more advanced patterns.By default, any HTML and Python are considered NOT static files:
"},{"location":"#template_cache_size-tune-the-template-cache","title":"COMPONENTS = {\n \"static_files_forbidden\": [\n \".html\", \".django\", \".dj\", \".tpl\", \".py\", \".pyc\",\n ],\n}\n
template_cache_size
- Tune the template cache","text":"Each time a template is rendered it is cached to a global in-memory cache (using Python's
lru_cache
decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are using the
template
method of a component to render lots of dynamic templates, you can increase this number. To remove the cache limit altogether and cache everything, set template_cache_size toNone
.COMPONENTS = {\n \"template_cache_size\": 256,\n}\n
If you want add templates to the cache yourself, you can use
cached_template()
:
"},{"location":"#context_behavior-make-components-isolated-or-not","title":"from django_components import cached_template\n\ncached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n pass\n\ncached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n)\n
context_behavior
- Make components isolated (or not)","text":"NOTE:
context_behavior
andslot_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.
"},{"location":"#example-django","title":"Example \"django\"","text":"COMPONENTS = {\n \"context_behavior\": \"isolated\",\n}\n
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 }}
equals456
.And variable
"},{"location":"#example-isolated","title":"Example \"isolated\"","text":"\"cheese\"
equalsfeta
, because the fill CAN access all the data defined in the outer layers, like the{% with %}
tag.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 insideRootComponent.get_context_data()
. But since\"cheese\"
is not defined there, it's empty.Notice that the variables defined with the
"},{"location":"#reload_on_template_change-reload-dev-server-on-component-file-changes","title":"{% with %}
tag are ignored inside the{% fill %}
tag with the\"isolated\"
mode.reload_on_template_change
- Reload dev server on component file changes","text":"If
True
, configures Django to reload on component files. See Reload dev server on component file changes.NOTE: This setting should be enabled only for the dev environment!
"},{"location":"#tag_formatter-change-how-components-are-used-in-templates","title":"tag_formatter
- Change how components are used in templates","text":"Sets the
TagFormatter
instance. See the section Customizing component tags with TagFormatter.Can be set either as direct reference, or as an import string;
COMPONENTS = {\n \"tag_formatter\": \"django_components.component_formatter\"\n}\n
Or
"},{"location":"#running-with-development-server","title":"Running with development server","text":""},{"location":"#reload-dev-server-on-component-file-changes","title":"Reload dev server on component file changes","text":"from django_components import component_formatter\n\nCOMPONENTS = {\n \"tag_formatter\": component_formatter\n}\n
This is relevant if you are using the project structure as shown in our examples, where HTML, JS, CSS and Python are separate and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change comoponent files.
From relevant StackOverflow thread:
TL;DR is that the server won't reload if it thinks the changed file is in a templates directory, or in a nested sub directory of a templates directory. This is by design.
To make the dev server reload on all component files, set
reload_on_template_change
toTrue
. This configures Django to watch for component files too.NOTE: This setting should be enabled only for the dev environment!
"},{"location":"#logging-and-debugging","title":"Logging and debugging","text":"Django components supports logging with Django. This can help with troubleshooting.
To configure logging for Django components, set the
django_components
logger inLOGGING
insettings.py
(below).Also see the
settings.py
file in sampleproject for a real-life example.
"},{"location":"#management-command","title":"Management Command","text":"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
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 theBASE_DIR
setting from your Django settings. -
--js
: The name of the JavaScript file. This is an optional argument. The default value isscript.js
. -
--css
: The name of the CSS file. This is an optional argument. The default value isstyle.css
. -
--template
: The name of the template file. This is an optional argument. The default value istemplate.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 isFalse
.
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
"},{"location":"#management-command-examples","title":"Management Command Examples","text":"<name>
,<path>
,<js_filename>
,<css_filename>
, and<template_filename>
with your desired values.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
"},{"location":"#creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"my_component
in thecomponents
directory of your Django project. The JavaScript, CSS, and template files will be namedscript.js
,style.css
, andtemplate.html
, respectively.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
"},{"location":"#overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"new_component
in themy_components
directory. The JavaScript, CSS, and template files will be namedmy_script.js
,my_style.css
, andmy_template.html
, respectively.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
"},{"location":"#simulating-component-creation","title":"Simulating Component Creation","text":"my_component
if it exists.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
"},{"location":"#writing-and-sharing-component-libraries","title":"Writing and sharing component libraries","text":"my_component
without creating any files.You can publish and share your components for others to use. Here are the steps to do so:
"},{"location":"#writing-component-libraries","title":"Writing component libraries","text":"-
Create a Django project with the following structure:
project/\n |-- myapp/\n |-- __init__.py\n |-- apps.py\n |-- templates/\n |-- table/\n |-- table.py\n |-- table.js\n |-- table.css\n |-- table.html\n |-- menu.py <--- single-file component\n |-- templatetags/\n |-- __init__.py\n |-- mytags.py\n
-
Create custom
Library
andComponentRegistry
instances inmytags.py
This will be the entrypoint for using the components inside Django templates.
Remember that Django requires the
Library
instance to be accessible under theregister
variable (See Django docs):from django.template import Library\nfrom django_components import ComponentRegistry, RegistrySettings\n\nregister = library = django.template.Library()\ncomp_registry = ComponentRegistry(\n library=library,\n settings=RegistrySettings(\n context_behavior=\"isolated\",\n tag_formatter=\"django_components.component_formatter\",\n ),\n)\n
As you can see above, this is also the place where we configure how our components should behave, using the
settings
argument. If omitted, default settings are used.For library authors, we recommend setting
context_behavior
to\"isolated\"
, so that the state cannot leak into the components, and so the components' behavior is configured solely through the inputs. This means that the components will be more predictable and easier to debug.Next, you can decide how will others use your components by settingt the
tag_formatter
options.If omitted or set to
\"django_components.component_formatter\"
, your components will be used like this:{% component \"table\" items=items headers=headers %}\n{% endcomponent %}\n
Or you can use
\"django_components.component_shorthand_formatter\"
to use components like so:{% table items=items headers=headers %}\n{% endtable %}\n
Or you can define a custom TagFormatter.
Either way, these settings will be scoped only to your components. So, in the user code, there may be components side-by-side that use different formatters:
{% load mytags %}\n\n{# Component from your library \"mytags\", using the \"shorthand\" formatter #}\n{% table items=items headers=header %}\n{% endtable %}\n\n{# User-created components using the default settings #}\n{% component \"my_comp\" title=\"Abc...\" %}\n{% endcomponent %}\n
-
Write your components and register them with your instance of
ComponentRegistry
There's one difference when you are writing components that are to be shared, and that's that the components must be explicitly registered with your instance of
ComponentRegistry
from the previous step.For better user experience, you can also define the types for the args, kwargs, slots and data.
It's also a good idea to have a common prefix for your components, so they can be easily distinguished from users' components. In the example below, we use the prefix
my_
/My
.from typing import Dict, NotRequired, Optional, Tuple, TypedDict\n\nfrom django_components import Component, SlotFunc, register, types\n\nfrom myapp.templatetags.mytags import comp_registry\n\n# Define the types\nclass EmptyDict(TypedDict):\n pass\n\ntype MyMenuArgs = Tuple[int, str]\n\nclass MyMenuSlots(TypedDict):\n default: NotRequired[Optional[SlotFunc[EmptyDict]]]\n\nclass MyMenuProps(TypedDict):\n vertical: NotRequired[bool]\n klass: NotRequired[str]\n style: NotRequired[str]\n\n# Define the component\n# NOTE: Don't forget to set the `registry`!\n@register(\"my_menu\", registry=comp_registry)\nclass MyMenu(Component[MyMenuArgs, MyMenuProps, MyMenuSlots, Any, Any, Any]):\n def get_context_data(\n self,\n *args,\n attrs: Optional[Dict] = None,\n ):\n return {\n \"attrs\": attrs,\n }\n\n template: types.django_html = \"\"\"\n {# Load django_components template tags #}\n {% load component_tags %}\n\n <div {% html_attrs attrs class=\"my-menu\" %}>\n <div class=\"my-menu__content\">\n {% slot \"default\" default / %}\n </div>\n </div>\n \"\"\"\n
-
Import the components in
apps.py
Normally, users rely on autodiscovery and
COMPONENTS.dirs
to load the component files.Since you, as the library author, are not in control of the file system, it is recommended to load the components manually.
We recommend doing this in the
AppConfig.ready()
hook of yourapps.py
:from django.apps import AppConfig\n\nclass MyAppConfig(AppConfig):\n default_auto_field = \"django.db.models.BigAutoField\"\n name = \"myapp\"\n\n # This is the code that gets run when user adds myapp\n # to Django's INSTALLED_APPS\n def ready(self) -> None:\n # Import the components that you want to make available\n # inside the templates.\n from myapp.templates import (\n menu,\n table,\n )\n
Note that you can also include any other startup logic within
AppConfig.ready()
.
And that's it! The next step is to publish it.
"},{"location":"#publishing-component-libraries","title":"Publishing component libraries","text":"Once you are ready to share your library, you need to build a distribution and then publish it to PyPI.
django_components uses the
build
utility to build a distribution:python -m build --sdist --wheel --outdir dist/ .\n
And to publish to PyPI, you can use
twine
(See Python user guide)twine upload --repository pypi dist/* -u __token__ -p <PyPI_TOKEN>\n
Notes on publishing: - The user of the package NEEDS to have installed and configured
"},{"location":"#installing-and-using-component-libraries","title":"Installing and using component libraries","text":"django_components
. - If you use components where the HTML / CSS / JS files are separate, you may need to defineMANIFEST.in
to include those files with the distribution (see user guide).After the package has been published, all that remains is to install it in other django projects:
-
Install the package:
pip install myapp\n
-
Add the package to
INSTALLED_APPS
INSTALLED_APPS = [\n ...\n \"myapp\",\n]\n
-
Optionally add the template tags to the
builtins
, so you don't have to call{% load mytags %}
in every template:TEMPLATES = [\n {\n ...,\n 'OPTIONS': {\n 'context_processors': [\n ...\n ],\n 'builtins': [\n 'myapp.templatetags.mytags',\n ]\n },\n },\n]\n
-
And, at last, you can use the components in your own project!
{% my_menu title=\"Abc...\" %}\n Hello World!\n{% endmy_menu %}\n
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.
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:
"},{"location":"#running-playwright-tests","title":"Running Playwright tests","text":"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
We use Playwright for end-to-end tests. You will therefore need to install Playwright to be able to run these tests.
Luckily, Playwright makes it very easy:
pip install -r requirements-dev.txt\nplaywright install chromium --with-deps\n
After Playwright is ready, simply run the tests with
tox
:
"},{"location":"#developing-against-live-django-app","title":"Developing against live Django app","text":"tox\n
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 thesetup.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
"},{"location":"#building-js-code","title":"Building JS code","text":"urls.py
, like in the case of http://127.0.0.1:8000/greetingdjango_components uses a bit of JS code to: - Manage the loading of JS and CSS files used by the components - Allow to pass data from Python to JS
When you make changes to this JS code, you also need to compile it:
- Make sure you are inside
src/django_components_js
:
cd src/django_components_js\n
- Install the JS dependencies
npm install\n
- Compile the JS/TS code:
python build.py\n
The script will combine all JS/TS code into a single
"},{"location":"#packaging-and-publishing","title":"Packaging and publishing","text":".js
file, minify it, and copy it todjango_components/static/django_components/django_components.min.js
.To package the library into a distribution that can be published to PyPI, run:
# Install pypa/build\npython -m pip install build --user\n# Build a binary wheel and a source tarball\npython -m build --sdist --wheel --outdir dist/ .\n
To publish the package to PyPI, use
twine
(See Python user guide):twine upload --repository pypi dist/* -u __token__ -p <PyPI_TOKEN>\n
See the full workflow here.
"},{"location":"#development-guides","title":"Development guides","text":"Deep dive into how django_components' features are implemented.
- Slot rendering
- Slots and blocks
- JS and CSS dependency management
-
Installation changes:
- If your components include JS or CSS, you now must use the middleware and add django-components' URLs to your
urlpatterns
(See \"Adding support for JS and CSS\")
- If your components include JS or CSS, you now must use the middleware and add django-components' URLs to your
-
Component typing signature changed from
Component[Args, Kwargs, Data, Slots]\n
to
Component[Args, Kwargs, Slots, Data, JsData, CssData]\n
-
If you rendered a component A with
Component.render()
and then inserted that into another component B, now you must passrender_dependencies=False
to component A:prerendered_a = CompA.render(\n args=[...],\n kwargs={...},\n render_dependencies=False,\n)\n\nhtml = CompB.render(\n kwargs={\n content=prerendered_a,\n },\n)\n
- Intellisense and mypy validation for settings:
Instead of defining the
COMPONENTS
settings as a plain dict, you can useComponentsSettings
:# settings.py\nfrom django_components import ComponentsSettings\n\nCOMPONENTS = ComponentsSettings(\n autodiscover=True,\n ...\n)\n
- Use
get_component_dirs()
andget_component_files()
to get the same list of dirs / files that would be imported byautodiscover()
, but without actually importing them.
-
For advanced use cases, use can omit the middleware and instead manage component JS and CSS dependencies yourself with
render_dependencies
-
The
ComponentRegistry
settingsRegistrySettings
were lowercased to align with the global settings: RegistrySettings.CONTEXT_BEHAVIOR
->RegistrySettings.context_behavior
RegistrySettings.TAG_FORMATTER
->RegistrySettings.tag_formatter
The old uppercase settings
CONTEXT_BEHAVIOR
andTAG_FORMATTER
are deprecated and will be removed in v1.-
The setting
reload_on_template_change
was renamed toreload_on_file_change
. And now it properly triggers server reload when any file in the component dirs change. The old namereload_on_template_change
is deprecated and will be removed in v1. -
The setting
forbidden_static_files
was renamed tostatic_files_forbidden
to align withstatic_files_allowed
The old nameforbidden_static_files
is deprecated and will be removed in v1.
-
{% component_dependencies %}
tag was removed. Instead, use{% component_js_dependencies %}
and{% component_css_dependencies %}
-
The combined tag was removed to encourage the best practice of putting JS scripts at the end of
<body>
, and CSS styles inside<head>
.On the other hand, co-locating JS script and CSS styles can lead to a flash of unstyled content, as either JS scripts will block the rendering, or CSS will load too late.
-
-
The undocumented keyword arg
preload
of{% component_js_dependencies %}
and{% component_css_dependencies %}
tags was removed. This will be replaced with HTML fragment support.
- Allow using forward slash (
/
) when defining custom TagFormatter, e.g.{% MyComp %}..{% /MyComp %}
.
{% component_dependencies %}
tags are now OPTIONAL - If your components use JS and CSS, but you don't use{% component_dependencies %}
tags, the JS and CSS will now be, by default, inserted at the end of<body>
and at the end of<head>
respectively.
- Fills can now be defined within loops (
{% for %}
) or other tags (like{% with %}
), or even other templates using{% include %}
.
Following is now possible
{% component \"table\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name %}\n {% endfill %}\n {% endfor %}\n{% endcomponent %}\n
- If you need to access the data or the default content of a default fill, you can set the
name
kwarg to\"default\"
.
Previously, a default fill would be defined simply by omitting the
{% fill %}
tags:{% component \"child\" %}\n Hello world\n{% endcomponent %}\n
But in that case you could not access the slot data or the default content, like it's possible for named fills:
{% component \"child\" %}\n {% fill name=\"header\" data=\"data\" %}\n Hello {{ data.user.name }}\n {% endfill %}\n{% endcomponent %}\n
Now, you can specify default tag by using
name=\"default\"
:{% component \"child\" %}\n {% fill name=\"default\" data=\"data\" %}\n Hello {{ data.user.name }}\n {% endfill %}\n{% endcomponent %}\n
- When inside
get_context_data()
or other component methods, the default fill can now be accessed asComponent.input.slots[\"default\"]
, e.g.:
class MyTable(Component):\n def get_context_data(self, *args, **kwargs):\n default_slot = self.input.slots[\"default\"]\n ...\n
- You can now dynamically pass all slots to a child component. This is similar to passing all slots in Vue:
"},{"location":"CHANGELOG/#fix_1","title":"Fix","text":"class MyTable(Component):\n def get_context_data(self, *args, **kwargs):\n return {\n \"slots\": self.input.slots,\n }\n\n template: \"\"\"\n <div>\n {% component \"child\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name data=\"data\" %}\n {% slot name=slot_name ...data / %}\n {% endfill %}\n {% endfor %}\n {% endcomponent %}\n </div>\n \"\"\"\n
-
Slots defined with
{% fill %}
tags are now properly accessible viaself.input.slots
inget_context_data()
-
Do not raise error if multiple slots with same name are flagged as default
-
Slots can now be defined within loops (
{% for %}
) or other tags (like{% with %}
), or even other templates using{% include %}
.
Previously, following would cause the kwarg
name
to be an empty string:
"},{"location":"CHANGELOG/#refactor_2","title":"Refactor","text":"{% for slot_name in slots %}\n {% slot name=slot_name %}\n{% endfor %}\n
- When you define multiple slots with the same name inside a template, you now have to set the
default
andrequired
flags individually.
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"image\" default required %}Image here{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"image\" default required %}Image here{% endslot %}\n </div>\n</div>\n
This means you can also have multiple slots with the same name but different conditions.
E.g. in this example, we have a component that renders a user avatar - a small circular image with a profile picture of name initials.
If the component is given
image_src
orname_initials
variables, theimage
slot is optional. But if neither of those are provided, you MUST fill theimage
slot.<div class=\"avatar\">\n {% if image_src %}\n {% slot \"image\" default %}\n <img src=\"{{ image_src }}\" />\n {% endslot %}\n {% elif name_initials %}\n {% slot \"image\" default required %}\n <div style=\"\n border-radius: 25px;\n width: 50px;\n height: 50px;\n background: blue;\n \">\n {{ name_initials }}\n </div>\n {% endslot %}\n {% else %}\n {% slot \"image\" default required / %}\n {% endif %}\n</div>\n
- The slot fills that were passed to a component and which can be accessed as
Component.input.slots
can now be passed through the Django template, e.g. as inputs to other tags.
Internally, django-components handles slot fills as functions.
Previously, if you tried to pass a slot fill within a template, Django would try to call it as a function.
Now, something like this is possible:
class MyTable(Component):\n def get_context_data(self, *args, **kwargs):\n return {\n \"child_slot\": self.input.slots[\"child_slot\"],\n }\n\n template: \"\"\"\n <div>\n {% component \"child\" content=child_slot / %}\n </div>\n \"\"\"\n
NOTE: Using
{% slot %}
and{% fill %}
tags is still the preferred method, but the approach above may be necessary in some complex or edge cases.- The
is_filled
variable (and the{{ component_vars.is_filled }}
context variable) now returnsFalse
when you try to access a slot name which has not been defined:
Before:
{{ component_vars.is_filled.header }} -> True\n{{ component_vars.is_filled.footer }} -> False\n{{ component_vars.is_filled.nonexist }} -> \"\" (empty string)\n
After:
{{ component_vars.is_filled.header }} -> True\n{{ component_vars.is_filled.footer }} -> False\n{{ component_vars.is_filled.nonexist }} -> False\n
-
Components no longer raise an error if there are extra slot fills
-
Components will raise error when a slot is doubly-filled.
E.g. if we have a component with a default slot:
{% slot name=\"content\" default / %}\n
Now there is two ways how we can target this slot: Either using
name=\"default\"
orname=\"content\"
.In case you specify BOTH, the component will raise an error:
"},{"location":"CHANGELOG/#v0100","title":"\ud83d\udea8\ud83d\udce2 v0.100","text":""},{"location":"CHANGELOG/#breaking-changes_2","title":"BREAKING CHANGES","text":"{% component \"child\" %}\n {% fill slot=\"default\" %}\n Hello from default slot\n {% endfill %}\n {% fill slot=\"content\" data=\"data\" %}\n Hello from content slot\n {% endfill %}\n{% endcomponent %}\n
-
django_components.safer_staticfiles
app was removed. It is no longer needed. -
Installation changes:
- Instead of defining component directories in
STATICFILES_DIRS
, set them toCOMPONENTS.dirs
. -
You now must define
STATICFILES_FINDERS
-
See here how to migrate your settings.py
- Instead of defining component directories in
- Beside the top-level
/components
directory, you can now define also app-level components dirs, e.g.[app]/components
(SeeCOMPONENTS.app_dirs
).
- When you call
as_view()
on a component instance, that instance will be passed toView.as_view()
- Fixed template caching. You can now also manually create cached templates with
cached_template()
-
The previously undocumented
get_template
was made private. -
In it's place, there's a new
get_template
, which supersedesget_template_string
(will be removed in v1). The newget_template
is the same asget_template_string
, except it allows to return either a string or a Template instance. -
You now must use only one of
template
,get_template
,template_name
, orget_template_name
.
-
Run-time type validation for Python 3.11+ - If the
Component
class is typed, e.g.Component[Args, Kwargs, ...]
, the args, kwargs, slots, and data are validated against the given types. (See Runtime input validation with types) -
Render hooks - Set
on_render_before
andon_render_after
methods onComponent
to intercept or modify the template or context before rendering, or the rendered result afterwards. (See Component hooks) -
component_vars.is_filled
context variable can be accessed from withinon_render_before
andon_render_after
hooks asself.is_filled.my_slot
- Added support for dynamic components, where the component name is passed as a variable. (See Dynamic components)
- Changed
Component.input
to raiseRuntimeError
if accessed outside of render context. Previously it returnedNone
if unset.
-
django_components now automatically configures Django to support multi-line tags. (See Multi-line tags)
-
New setting
reload_on_template_change
. Set this toTrue
to reload the dev server on changes to component template files. (See Reload dev server on component file changes)
-
Spread operator
...dict
inside template tags. (See Spread operator) -
Use template tags inside string literals in component inputs. (See Use template tags inside component inputs)
-
Dynamic slots, fills and provides - The
name
argument for these can now be a variable, a template expression, or via spread operator -
Component library authors can now configure
CONTEXT_BEHAVIOR
andTAG_FORMATTER
settings independently from user settings.
Component
class is no longer a subclass ofView
. To configure theView
class, set theComponent.View
nested class. HTTP methods likeget
orpost
can still be defined directly onComponent
class, andComponent.as_view()
internally callsComponent.View.as_view()
. (See Modifying the View class)
-
The inputs (args, kwargs, slots, context, ...) that you pass to
Component.render()
can be accessed from withinget_context_data
,get_template
andget_template_name
viaself.input
. (See Accessing data passed to the component) -
Typing:
Component
class supports generics that specify types forComponent.render
(See Adding type hints with Generics)
-
All tags (
component
,slot
,fill
, ...) now support \"self-closing\" or \"inline\" form, where you can omit the closing tag:{# Before #}\n{% component \"button\" %}{% endcomponent %}\n{# After #}\n{% component \"button\" / %}\n
-
All tags now support the \"dictionary key\" or \"aggregate\" syntax (
kwarg:key=val
):{% component \"button\" attrs:class=\"hidden\" %}\n
-
You can change how the components are written in the template with TagFormatter.
The default is
django_components.component_formatter
:{% component \"button\" href=\"...\" disabled %}\n Click me!\n{% endcomponent %}\n
While
django_components.shorthand_component_formatter
allows you to write components like so:{% button href=\"...\" disabled %}\n Click me!\n{% endbutton %}\n
-
Autodiscovery module resolution changed. Following undocumented behavior was removed:
-
Previously, autodiscovery also imported any
[app]/components.py
files, and usedSETTINGS_MODULE
to search for component dirs.To migrate from:
-
[app]/components.py
- Define each module inCOMPONENTS.libraries
setting, or import each module inside theAppConfig.ready()
hook in respectiveapps.py
files. -
SETTINGS_MODULE
- Define component dirs usingSTATICFILES_DIRS
-
-
Previously, autodiscovery handled relative files in
STATICFILES_DIRS
. To align with Django,STATICFILES_DIRS
now must be full paths (Django docs).
-
- The order of arguments to
render_to_response
has changed, to align with the (now public)render
method ofComponent
class.
-
Component.render()
is public and documented -
Slots passed
render_to_response
andrender
can now be rendered also as functions.
- Vue-like provide/inject with the
{% provide %}
tag andinject()
method.
- 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.
-
The syntax for accessing default slot content has changed from
{% fill \"my_slot\" as \"alias\" %}\n {{ alias.default }}\n{% endfill %}\n
to
{% fill \"my_slot\" default=\"alias\" %}\n {{ alias }}\n{% endfill %}\n
-
{% html_attrs %}
tag for formatting data as HTML attributes -
prefix:key=val
construct for passing dicts to components
-
{% if_filled \"my_slot\" %}
tags were replaced with{{ component_vars.is_filled.my_slot }}
variables. -
Simplified settings -
slot_context_behavior
andcontext_behavior
were merged. See the documentation for more details.
- Changed the default way how context variables are resolved in slots. See the documentation for more details.
-
{% 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.
- Components as views, which allows you to handle requests and render responses from within a component. See the documentation for more details.
- 'implicit' slot filling and the
default
option forslot
tags.
- A second installable app
django_components.safer_staticfiles
. It provides the same behavior asdjango.contrib.staticfiles
but with extra security guarantees (more info below in Security Notes).
-
Changed the syntax for
{% slot %}
tags. From now on, we separate defining a slot ({% slot %}
) from filling a slot with content ({% fill %}
). This means you will likely need to change a lot of slot tags to fill.We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice feature to have access to. Hoping that this will feel worth it!
-
All files inside components subdirectores are autoimported to simplify setup.
An existing project might start to get
AlreadyRegistered
errors because of this. To solve this, either remove your custom loading of components, or set\"autodiscover\": False
insettings.COMPONENTS
.
-
Renamed
Component.context
andComponent.template
toget_context_data
andget_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
andComponent.template
will be removed when version 1.0 is released.
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
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
MIT License
Copyright (c) 2019 Emil Stenstr\u00f6m
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"},{"location":"migrating_from_safer_staticfiles/","title":"Migrating from safer_staticfiles","text":"This guide is for you if you're upgrating django_components to v0.100 or later from older versions.
In version 0.100, we changed how components' static JS and CSS files are handled. See more in the \"Static files\" section.
Migration steps:
- Remove
django_components.safer_staticfiles
fromINSTALLED_APPS
in yoursettings.py
, and replace it withdjango.contrib.staticfiles
.
Before:
INSTALLED_APPS = [\n \"django.contrib.admin\",\n ...\n # \"django.contrib.staticfiles\", # <-- ADD\n \"django_components\",\n \"django_components.safer_staticfiles\", # <-- REMOVE\n]\n
After:
INSTALLED_APPS = [\n \"django.contrib.admin\",\n ...\n \"django.contrib.staticfiles\",\n \"django_components\",\n]\n
- Add
STATICFILES_FINDERS
tosettings.py
, and adddjango_components.finders.ComponentsFileSystemFinder
:
STATICFILES_FINDERS = [\n # Default finders\n \"django.contrib.staticfiles.finders.FileSystemFinder\",\n \"django.contrib.staticfiles.finders.AppDirectoriesFinder\",\n # Django components\n \"django_components.finders.ComponentsFileSystemFinder\", # <-- ADDED\n]\n
- Add
COMPONENTS.dirs
tosettings.py
.
If you previously defined
STATICFILES_DIRS
, move only those directories fromSTATICFILES_DIRS
that point to components directories, and keep the rest.E.g. if you have
STATICFILES_DIRS
like this:STATICFILES_DIRS = [\n BASE_DIR / \"components\", # <-- MOVE\n BASE_DIR / \"myapp\" / \"components\", # <-- MOVE\n BASE_DIR / \"assets\",\n]\n
Then first two entries point to components dirs, whereas
/assets
points to non-component static files. In this case move only the first two paths:COMPONENTS = {\n \"dirs\": [\n BASE_DIR / \"components\", # <-- MOVED\n BASE_DIR / \"myapp\" / \"components\", # <-- MOVED\n ],\n}\n\nSTATICFILES_DIRS = [\n BASE_DIR / \"assets\",\n]\n
Moreover, if you defined app-level component directories in
STATICFILES_DIRS
before, you can now define as a RELATIVE path inapp_dirs
:
"},{"location":"devguides/dependency_mgmt/","title":"JS and CSS rendering","text":"COMPONENTS = {\n \"dirs\": [\n # Search top-level \"/components/\" dir\n BASE_DIR / \"components\",\n ],\n \"app_dirs\": [\n # Search \"/[app]/components/\" dirs\n \"components\",\n ],\n}\n\nSTATICFILES_DIRS = [\n BASE_DIR / \"assets\",\n]\n
Aim of this doc is to share the intuition on how we manage the JS and CSS (\"dependencies\") associated with components, and how we render them.
"},{"location":"devguides/dependency_mgmt/#starting-conditions","title":"Starting conditions","text":"- First of all, when we consider a component, it has two kind of dependencies - the \"inlined\" JS and CSS, and additional linked JS and CSS via
Media.js/css
:
from django_components import Component, types\n\nclass MyTable(Component):\n # Inlined JS\n js: types.js = \"\"\"\n console.log(123);\n \"\"\"\n\n # Inlined CSS\n css: types.css = \"\"\"\n .my-table {\n color: red;\n }\n \"\"\"\n\n # Linked JS / CSS\n class Media:\n js = [\n \"script-one.js\", # STATIC file relative to component file\n \"/script-two.js\", # URL path\n \"https://example.com/script-three.js\", # URL\n ]\n\n css = [\n \"style-one.css\", # STATIC file relative to component file\n \"/style-two.css\", # URL path\n \"https://example.com/style-three.css\", # URL\n ]\n
- Second thing to keep in mind is that all component's are eventually rendered into a string. And so, if we want to associate extra info with a rendered component, it has to be serialized to a string.
This is because a component may be embedded in a Django Template with the
{% component %}
tag, which, when rendered, is turned into a string:template = Template(\"\"\"\n {% load component_tags %}\n <div>\n {% component \"my_table\" / %}\n </div>\n\"\"\")\n\nhtml_str = template.render(Context({}))\n
And for this reason, we take the same approach also when we render a component with
Component.render()
- It returns a string.- Thirdly, we also want to add support for JS / CSS variables. That is, that a variable defined on the component would be somehow accessible from within the JS script / CSS style.
A simple approach to this would be to modify the inlined JS / CSS directly, and insert them for each component. But if you had extremely large JS / CSS, and e.g. only a single JS / CSS variable that you want to insert, it would be extremely wasteful to copy-paste the JS / CSS for each component instance.
So instead, a preferred approach here is to defined and insert the inlined JS / CSS only once, and have some kind of mechanism on how we make correct the JS / CSS variables available only to the correct components.
- Last important thing is that we want the JS / CSS dependencies to work also with HTML fragments.
So normally, e.g. when a user hits URL of a web page, the server renders full HTML document, with
<!doctype>
,<html>
,<head>
, and<body>
. In such case, we know about ALL JS and CSS dependencies at render time, so we can e.g. insert them into<head>
and<body>
ourselves.However this renders only the initial state. HTML fragments is a common pattern where interactivity is added to the web page by fetching and replacing bits of HTML on the main HTML document after some user action.
In the case of HTML fragments, the HTML is NOT a proper document, but only the HTML that will be inserted somewhere into the DOM.
The challenge here is that Django template for the HTML fragment MAY contain components, and these components MAY have inlined or linked JS and CSS.
def fragment_view(request):\n template = Template(\"\"\"\n {% load component_tags %}\n <div>\n {% component \"my_table\" / %}\n </div>\n \"\"\")\n\n fragment_str = template.render(Context({}))\n return HttpResponse(fragment_str, status=200)\n
User may use different libraries to fetch and insert the HTML fragments (e.g. HTMX, AlpineJS, ...). From our perspective, the only thing that we can reliably say is that we expect that the HTML fragment WILL be eventually inserted into the DOM.
So to include the corresponding JS and CSS, a simple approach could be to append them to the HTML as
<style>
and<script>
, e.g.:<!-- Original content -->\n<div>...</div>\n<!-- Associated CSS files -->\n<link href=\"http://...\" />\n<style>\n .my-class {\n color: red;\n }\n</style>\n<!-- Associated JS files -->\n<script src=\"http://...\"></script>\n<script>\n console.log(123);\n</script>\n
But this has a number of issues:
- The JS scripts would run for each instance of the component.
- Bloating of the HTML file, as each inlined JS or CSS would be included fully for each component.
- While this sound OK, this could really bloat the HTML files if we used a UI component library for the basic building blocks like buttons, lists, cards, etc.
So the solution should address all the points above. To achieve that, we manage the JS / CSS dependencies ourselves in the browser. So when a full HTML document is loaded, we keep track of which JS and CSS have been loaded. And when an HTML fragment is inserted, we check which JS / CSS dependencies it has, and load only those that have NOT been loaded yet.
This is how we achieve that:
- When a component is rendered, it inserts an HTML comment containing metadata about the rendered component.
So a template like this
{% load component_tags %}\n<div>\n {% component \"my_table\" / %}\n</div>\n{% component \"button\" %}\n Click me!\n{% endcomponent %}\n
May actually render:
<div>\n <!-- _RENDERED \"my_table_10bc2c,c020ad\" -->\n <table>\n ...\n </table>\n</div>\n<!-- _RENDERED \"button_309dcf,31c0da\" -->\n<button>Click me!</button>\n
Each
<!-- _RENDERED -->
comment includes comma-separated data - a unique hash for the component class, e.g.my_table_10bc2c
, and the component ID, e.g.c020ad
.This way, we or the user can freely pass the rendered around or transform it, treating it as a string to add / remove / replace bits. As long as the
<!-- _RENDERED -->
comments remain in the rendered string, we will be able to deduce which JS and CSS dependencies the component needs.- Post-process the rendered HTML, extracting the
<!-- _RENDERED -->
comments, and instead inserting the corresponding JS and CSS dependencies.
If we dealt only with JS, then we could get away with processing the
<!-- _RENDERED -->
comments on the client (browser). However, the CSS needs to be processed still on the server, so the browser receives CSS styles already inserted as<style>
or<link>
HTML tags. Because if we do not do that, we get a flash of unstyled content, as there will be a delay between when the HTML page loaded and when the CSS was fetched and loaded.So, assuming that a user has already rendered their template, which still contains
<!-- _RENDERED -->
comments, we need to extract and process these comments.There's multiple ways to achieve this:
-
The approach recommended to the users is to use the
ComponentDependencyMiddleware
middleware, which scans all outgoing HTML, and post-processes the<!-- _RENDERED -->
comments. -
If users are using
Component.render()
orComponent.render_to_response()
, these post-process the<!-- _RENDERED -->
comments by default.- NOTE: Users are able to opt out of the post-processing by setting
render_dependencies=False
.
- NOTE: Users are able to opt out of the post-processing by setting
-
For advanced use cases, users may use
render_dependencies()
directly. This is the function that bothComponentDependencyMiddleware
andComponent.render()
call internally.
render_dependencies()
, whether called directly, via middleware or other way, does the following:-
Find all
<!-- _RENDERED -->
comments, and for each comment: -
Look up the corresponding component class.
-
Get the component's inlined JS / CSS from
Component.js/css
, and linked JS / CSS fromComponent.Media.js/css
. -
Generate JS script that loads the JS / CSS dependencies.
-
Insert the JS scripts either at the end of
<body>
, or in place of{% component_dependencies %}
/{% component_js_dependencies %}
tags. -
To avoid the flash of unstyled content, we need place the styles into the HTML instead of dynamically loading them from within a JS script. The CSS is placed either at the end of
<head>
, or in place of{% component_dependencies %}
/{% component_css_dependencies %}
-
We cache the component's inlined JS and CSS, so they can be fetched via an URL, so the inlined JS / CSS an be treated the same way as the JS / CSS dependencies set in
Component.Media.js/css
.- NOTE: While this is currently not entirely necessary, it opens up the doors for allowing plugins to post-process the inlined JS and CSS. Because after it has been post-processed, we need to store it somewhere.
-
Server returns the post-processed HTML.
-
In the browser, the generated JS script from step 2.4 is executed. It goes through all JS and CSS dependencies it was given. If some JS / CSS was already loaded, it is NOT fetched again. Otherwise it generates the corresponding
<script>
or<link>
HTML tags to load the JS / CSS dependencies.
In the browser, the \"dependency manager JS\" may look like this:
// Load JS or CSS script if not loaded already\nComponents.loadScript(\"js\", '<script src=\"/abc/xyz/script.js\">');\nComponents.loadScript(\"css\", '<link href=\"/abc/xyz/style.css\">');\n\n// Or mark one as already-loaded, so it is ignored when\n// we call `loadScript`\nComponents.markScriptLoaded(\"js\", \"/abc/def\");\n
Note that
loadScript()
receives a whole<script>
and<link>
tags, not just the URL. This is because when Django'sMedia
class renders JS and CSS, it formats it as<script>
and<link>
tags. And we allow users to modify how the JS and CSS should be rendered into the<script>
and<link>
tags.So, if users decided to add an extra attribute to their
<script>
tags, e.g.<script defer src=\"http://...\"></script>
, then this way we make sure that thedefer
attribute will be present on the<script>
tag when it is inserted into the DOM at the time of loading the JS script.- To be able to fetch component's inlined JS and CSS, django-components adds a URL path under:
/components/cache/<str:comp_cls_hash>.<str:script_type>/
E.g.
/components/cache/my_table_10bc2c.js/
This endpoint takes the component's unique hash, e.g.
my_table_10bc2c
, and looks up the component's inlined JS or CSS.Thus, with this approach, we ensure that:
- All JS / CSS dependencies are loaded / executed only once.
- The approach is compatible with HTML fragments
- The approach is compatible with JS / CSS variables.
- Inlined JS / CSS may be post-processed by plugins
This doc serves as a primer on how component slots and fills are resolved.
"},{"location":"devguides/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
-
The names of the slots and fills may be defined using variables
| -- {% slot slot_name %} ---\n| ---- STU {{ my_var }}\n| -- {% endslot %} ---\n| -------\n
-
The slot and fill names may be defined using for loops or other variables defined within the template (e.g.
{% with %}
tag or{% ... as var %}
syntax)| -- {% for slot_name in slots %} ---\n| ---- {% slot slot_name %} ---\n| ------ STU {{ slot_name }}\n| ---- {% endslot %} ---\n| -- {% endfor %} ---\n| -------\n
-
Variables for names and for loops allow us implement \"passthrough slots\" - that is, taking all slots that our component received, and passing them to a child component, dynamically.
| -- {% component \"mycomp\" %} ---\n| ---- {% for slot_name in slots %} ---\n| ------ {% fill slot_name %} ---\n| -------- {% slot slot_name %} ---\n| ---------- XYZ {{ slot_name }}\n| --------- {% endslot %}\n| ------- {% endfill %}\n| ---- {% endfor %} ---\n| -- {% endcomponent %} ---\n| ----\n
-
Putting that all together, a document may look like this:
| -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %}---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ------\n| -- {% component \"mycomp\" %} ---\n| ---- {% slot \"myslot\" %} ---\n| ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n| ---- {% endslot %} ---\n| -- {% endcomponent %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- PQR {{ my_var }}\n| -- {% endslot %} ---\n| -------\n| -- {% for slot_name in slots %} ---\n| ---- {% component \"mycomp\" %} ---\n| ------- {% slot slot_name %}\n| ---------- STU {{ slot_name }}\n| ------- {% endslot %}\n| ---- {% endcomponent %} ---\n| -- {% endfor %} ---\n| ----\n| -- {% component \"mycomp\" %} ---\n| ---- {% for slot_name in slots %} ---\n| ------ {% fill slot_name %} ---\n| -------- {% slot slot_name %} ---\n| ---------- XYZ {{ slot_name }}\n| --------- {% endslot %}\n| ------- {% endfill %}\n| ---- {% endfor %} ---\n| -- {% endcomponent %} ---\n| -------\n
-
Given the above, we want to render the slots with
{% fill %}
tag that were defined OUTSIDE of this template. How do I do that?NOTE: Before v0.110, slots were resolved statically, by walking down the Django Template and Nodes. However, this did not allow for using for loops or other variables defined in the template.
Currently, this consists of 2 steps:
-
If a component is rendered within a template using
{% component %}
tag, determine the given{% fill %}
tags in the component's body (the content in between{% component %}
and{% endcomponent %}
).After this step, we know about all the fills that were passed to the component.
-
Then we simply render the template as usual. And then we reach the
{% slot %}
tag, we search the context for the available fills.- If there IS a fill with the same name as the slot, we render the fill.
- If the slot is marked
default
, and there is a fill nameddefault
, then we render that. - Otherwise, we render the slot's default content.
-
-
Obtaining the fills from
{% fill %}
.When a component is rendered with
{% component %}
tag, and it has some content in between{% component %}
and{% endcomponent %}
, we want to figure out if that content is a default slot (no{% fill %}
used), or if there is a collection of named{% fill %}
tags:Default slot:
| -- {% component \"mycomp\" %} ---\n| ---- STU {{ slot_name }}\n| -- {% endcomponent %} ---\n
Named slots:
| -- {% component \"mycomp\" %} ---\n| ---- {% fill \"slot_a\" %}\n| ------ STU\n| ---- {% endslot %}\n| ---- {% fill \"slot_b\" %}\n| ------ XYZ\n| ---- {% endslot %}\n| -- {% endcomponent %} ---\n
To respect any forloops or other variables defined within the template to which the fills may have access, we:
- Render the content between
{% component %}
and{% endcomponent %}
using the context outside of the component. - When we reach a
{% fill %}
tag, we capture any variables that were created between the{% component %}
and{% fill %}
tags. - When we reach
{% fill %}
tag, we do not continue rendering deeper. Instead we make a record that we found the fill tag with given name, kwargs, etc. - After the rendering is done, we check if we've encountered any fills. If yes, we expect only named fills. If no, we assume that the the component's body is a default slot.
- Lastly we process the found fills, and make them available to the context, so any slots inside the component may access these fills.
- Render the content between
-
Rendering slots
Slot rendering works similarly to collecting fills, in a sense that we do not search for the slots ahead of the time, but instead let Django handle the rendering of the template, and we step in only when Django come across as
{% slot %}
tag.When we reach a slot tag, we search the context for the available fills.
- If there IS a fill with the same name as the slot, we render the fill.
- If the slot is marked
default
, and there is a fill nameddefault
, then we render that. - Otherwise, we render the slot's default content.
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
"},{"location":"devguides/slots_and_blocks/","title":"Using{% slot %}
node, in it'srender()
method, we access the data above, and, depending on thecontext_behavior
setting, include the current context or not. For more info, seeSlotNode.render()
.slot
andblock
tags","text":"-
First let's clarify how
include
andextends
tags work inside components. So when component template includesinclude
orextends
tags, it's as if the \"included\" template was inlined. So if the \"included\" template containsslot
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 thebody
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 thecomponent
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 ofabc.html
if my component template usesextends
. In that case, just as you would expect, theblock inner
insideabc.html
will renderOVERRIDEN
:@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
andbody
slots, and you will not get an error for an invalid/unknown slot name. But sincebody
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
-
- django_components
- app_settings
- apps
- attributes
- autodiscovery
- component
- component_media
- component_registry
- components
- dynamic
- context
- dependencies
- expression
- finders
- library
- management
- commands
- startcomponent
- upgradecomponent
- middleware
- node
- provide
- slots
- tag_formatter
- template
- template_loader
- template_parser
- templatetags
- component_tags
- types
- urls
- util
- cache
- html
- loader
- logger
- misc
- nanoid
- tag_parser
- types
- validation
- django_components_js
- build
- docs
- scripts
- reference
Main package for Django Components.
Modules:
-
app_settings
\u2013 -
attributes
\u2013 -
autodiscovery
\u2013 -
component
\u2013 -
component_media
\u2013 -
component_registry
\u2013 -
components
\u2013 -
context
\u2013This file centralizes various ways we use Django's Context class
-
dependencies
\u2013All code related to management of component dependencies (JS and CSS scripts)
-
expression
\u2013 -
finders
\u2013 -
library
\u2013Module for interfacing with Django's Library (
django.template.library
) -
management
\u2013 -
middleware
\u2013 -
node
\u2013 -
provide
\u2013 -
slots
\u2013 -
tag_formatter
\u2013 -
template
\u2013 -
template_loader
\u2013Template loader that loads templates from each Django app's \"components\" directory.
-
template_parser
\u2013Overrides for the Django Template system to allow finer control over template parsing.
-
templatetags
\u2013 -
types
\u2013Helper types for IDEs.
-
util
\u2013
Classes:
-
AlreadyRegistered
\u2013Raised when you try to register a Component,
-
Component
\u2013 -
ComponentFileEntry
\u2013Result returned by
get_component_files()
. -
ComponentFormatter
\u2013The original django_component's component tag formatter, it uses the
{% component %}
-
ComponentRegistry
\u2013Manages components and makes them available
-
ComponentVars
\u2013Type for the variables available inside the component templates.
-
ComponentView
\u2013Subclass of
django.views.View
where theComponent
instance is available -
ComponentsSettings
\u2013Settings available for django_components.
-
ContextBehavior
\u2013Configure how (and whether) the context is passed to the component fills
-
DynamicComponent
\u2013This component is given a registered name or a reference to another component,
-
EmptyDict
\u2013TypedDict with no members.
-
NotRegistered
\u2013Raised when you try to access a Component,
-
RegistrySettings
\u2013Configuration for a
ComponentRegistry
. -
ShorthandComponentFormatter
\u2013The component tag formatter that uses
{% <name> %}
/{% end<name> %}
tags. -
Slot
\u2013This class holds the slot content function along with related metadata.
-
SlotRef
\u2013SlotRef allows to treat a slot as a variable. The slot is rendered only once
-
TagFormatterABC
\u2013Abstract base class for defining custom tag formatters.
-
TagProtectedError
\u2013The way the
TagFormatter
works is that, -
TagResult
\u2013The return value from
TagFormatter.parse()
.
Functions:
-
autodiscover
\u2013Search for all python files in
-
cached_template
\u2013Create a Template instance that will be cached as per the
-
get_component_dirs
\u2013Get directories that may contain component files.
-
get_component_files
\u2013Search for files within the component directories (as defined in
-
import_libraries
\u2013Import modules set in
-
register
\u2013Class decorator for registering a component
-
render_dependencies
\u2013Given a string that contains parts that were rendered by components,
Attributes:
-
EmptyTuple
\u2013Tuple with no members.
-
registry
(ComponentRegistry
) \u2013The default and global component registry.
module-attribute
","text":"EmptyTuple = Tuple[]\n
Tuple with no members.
You can use this to define a Component that accepts NO positional arguments:
from django_components import Component, EmptyTuple\n\nclass Table(Component(EmptyTuple, Any, Any, Any, Any, Any))\n ...\n
After that, when you call
Component.render()
orComponent.render_to_response()
, theargs
parameter will raise type error ifargs
is anything else than an empty tuple.Table.render(\n args: (),\n)\n
Omitting
args
is also fine:Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
"},{"location":"reference/django_components/#django_components.registry","title":"registryTable.render(\n args: (\"one\", 2, \"three\"),\n)\n
module-attribute
","text":"registry: ComponentRegistry = ComponentRegistry()\n
The default and global component registry. Use this instance to directly register or remove components:
See Registering components.
"},{"location":"reference/django_components/#django_components.AlreadyRegistered","title":"AlreadyRegistered","text":"# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get single\nregistry.get(\"button\")\n\n# Get all\nregistry.all()\n\n# Unregister single\nregistry.unregister(\"button\")\n\n# Unregister all\nregistry.clear()\n
Bases:
Exception
Raised when you try to register a Component, but it's already registered with given ComponentRegistry.
"},{"location":"reference/django_components/#django_components.Component","title":"Component","text":"Component(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Generic[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template
(Optional[Union[str, Template]]
) \u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.Component.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
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.css","title":"cssclass-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/#django_components.Component.input","title":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/#django_components.Component.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/#django_components.Component.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/#django_components.Component.media","title":"mediainstance-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.response_class","title":"response_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/#django_components.Component.template","title":"templaterender_to_response
class-attribute
instance-attribute
","text":"template: Optional[Union[str, Template]] = None\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
"},{"location":"reference/django_components/#django_components.Component.template_name","title":"template_nametemplate_name
,get_template_name
,template
orget_template
must be defined.class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/#django_components.Component.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.Component.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.Component.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.Component.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/#django_components.Component.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.Component.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.Component.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.Component.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.ComponentFileEntry","title":"ComponentFileEntry","text":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
Bases:
NamedTuple
Result returned by
get_component_files()
.Attributes:
-
dot_path
(str
) \u2013The python import path for the module. E.g.
app.components.mycomp
-
filepath
(Path
) \u2013The filesystem path to the module. E.g.
/path/to/project/app/components/mycomp.py
instance-attribute
","text":"dot_path: str\n
The python import path for the module. E.g.
"},{"location":"reference/django_components/#django_components.ComponentFileEntry.filepath","title":"filepathapp.components.mycomp
instance-attribute
","text":"filepath: Path\n
The filesystem path to the module. E.g.
"},{"location":"reference/django_components/#django_components.ComponentFormatter","title":"ComponentFormatter","text":"/path/to/project/app/components/mycomp.py
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 given as the first positional arg.Example as block:
{% component \"mycomp\" abc=123 %}\n {% fill \"myfill\" %}\n ...\n {% endfill %}\n{% endcomponent %}\n
Example as inlined tag:
Source code in{% component \"mycomp\" abc=123 / %}\n
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.ComponentRegistry","title":"ComponentRegistry","text":"def __init__(self, tag: str):\n self.tag = tag\n
ComponentRegistry(\n library: Optional[Library] = None, settings: Optional[Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]] = None\n)\n
Manages components and makes them available in the template, by default as
{% component %}
tags.{% component \"my_comp\" key=value %}\n{% endcomponent %}\n
To enable a component to be used in a template, the component must be registered with a component registry.
When you register a component to a registry, behind the scenes the registry automatically adds the component's template tag (e.g.
{% component %}
to theLibrary
. And the opposite happens when you unregister a component - the tag is removed.See Registering components.
Parameters:
-
library
(Library
, default:None
) \u2013Django
Library
associated with this registry. If omitted, the default Library instance from django_components is used. -
settings
(Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]
, default:None
) \u2013Configure how the components registered with this registry will behave when rendered. See
RegistrySettings
. Can be either a static value or a callable that returns the settings. If omitted, the settings fromCOMPONENTS
are used.
Notes:
- The default registry is available as
django_components.registry
. - The default registry is used when registering components with
@register
decorator.
Example:
"},{"location":"reference/django_components/#django_components.ComponentRegistry--using-registry-to-share-components","title":"Using registry to share components","text":"# 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
You can use component registry for isolating or \"packaging\" components:
-
Create new instance of
ComponentRegistry
and Library:my_comps = Library()\nmy_comps_reg = ComponentRegistry(library=my_comps)\n
-
Register components to the registry:
my_comps_reg.register(\"my_button\", ButtonComponent)\nmy_comps_reg.register(\"my_card\", CardComponent)\n
-
In your target project, load the Library associated with the registry:
{% load my_comps %}\n
-
Use the registered components in your templates:
{% component \"button\" %}\n{% endcomponent %}\n
Methods:
-
all
\u2013Retrieve all registered
Component
classes. -
clear
\u2013Clears the registry, unregistering all components.
-
get
\u2013Retrieve a
Component
-
register
\u2013Register a
Component
class -
unregister
\u2013Unregister the
Component
class
Attributes:
-
library
(Library
) \u2013The template tag
Library
-
settings
(InternalRegistrySettings
) \u2013Registry settings configured for this registry.
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.ComponentRegistry.library","title":"librarydef __init__(\n self,\n library: Optional[Library] = None,\n settings: Optional[Union[RegistrySettings, Callable[[\"ComponentRegistry\"], RegistrySettings]]] = None,\n) -> None:\n self._registry: Dict[str, ComponentRegistryEntry] = {} # component name -> component_entry mapping\n self._tags: Dict[str, Set[str]] = {} # tag -> list[component names]\n self._library = library\n self._settings_input = settings\n self._settings: Optional[Callable[[], InternalRegistrySettings]] = None\n\n all_registries.append(self)\n
property
","text":"library: Library\n
The template tag
"},{"location":"reference/django_components/#django_components.ComponentRegistry.settings","title":"settingsLibrary
that is associated with the registry.property
","text":"settings: InternalRegistrySettings\n
Registry settings configured for this registry.
"},{"location":"reference/django_components/#django_components.ComponentRegistry.all","title":"all","text":"all() -> Dict[str, Type[Component]]\n
Retrieve all registered
Component
classes.Returns:
-
Dict[str, Type[Component]]
\u2013Dict[str, Type[Component]]: A dictionary of component names to component classes
Example:
Source code in# 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
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.ComponentRegistry.clear","title":"clear","text":"def all(self) -> Dict[str, Type[\"Component\"]]:\n \"\"\"\n Retrieve all registered [`Component`](../api#django_components.Component) classes.\n\n Returns:\n Dict[str, Type[Component]]: A dictionary of component names to component classes\n\n **Example:**\n\n ```python\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
clear() -> None\n
Clears the registry, unregistering all components.
Example:
Source code in# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then clear\nregistry.clear()\n# Then get all\nregistry.all()\n# > {}\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.ComponentRegistry.get","title":"get","text":"def clear(self) -> None:\n \"\"\"\n Clears the registry, unregistering all components.\n\n Example:\n\n ```python\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
get(name: str) -> Type[Component]\n
Retrieve a
Component
class registered under the given name.Parameters:
-
name
(str
) \u2013The name under which the component was registered. Required.
Returns:
-
Type[Component]
\u2013Type[Component]: The component class registered under the given name.
Raises:
NotRegistered
if the given name is not registered.
Example:
Source code in# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then get\nregistry.get(\"button\")\n# > ButtonComponent\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.ComponentRegistry.register","title":"register","text":"def get(self, name: str) -> Type[\"Component\"]:\n \"\"\"\n Retrieve a [`Component`](../api#django_components.Component)\n class registered under the given name.\n\n Args:\n name (str): The name under which the component was registered. Required.\n\n Returns:\n Type[Component]: The component class registered under the given name.\n\n **Raises:**\n\n - [`NotRegistered`](../exceptions#django_components.NotRegistered)\n if the given name is not registered.\n\n **Example:**\n\n ```python\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
register(name: str, component: Type[Component]) -> None\n
Register a
Component
class with this registry under the given name.A component MUST be registered before it can be used in a template such as:
{% component \"my_comp\" %}\n{% endcomponent %}\n
Parameters:
-
name
(str
) \u2013The name under which the component will be registered. Required.
-
component
(Type[Component]
) \u2013The component class to register. Required.
Raises:
AlreadyRegistered
if a different component was already registered under the same name.
Example:
Source code inregistry.register(\"button\", ButtonComponent)\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.ComponentRegistry.unregister","title":"unregister","text":"def register(self, name: str, component: Type[\"Component\"]) -> None:\n \"\"\"\n Register a [`Component`](../api#django_components.Component) class\n 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\" %}\n {% endcomponent %}\n ```\n\n Args:\n name (str): The name under which the component will be registered. Required.\n component (Type[Component]): The component class to register. Required.\n\n **Raises:**\n\n - [`AlreadyRegistered`](../exceptions#django_components.AlreadyRegistered)\n if a different component was already registered under the same name.\n\n **Example:**\n\n ```python\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
unregister(name: str) -> None\n
Unregister the
Component
class that was registered under the given name.Once a component is unregistered, it is no longer available in the templates.
Parameters:
-
name
(str
) \u2013The name under which the component is registered. Required.
Raises:
NotRegistered
if the given name is not registered.
Example:
Source code in# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.ComponentVars","title":"ComponentVars","text":"def unregister(self, name: str) -> None:\n \"\"\"\n Unregister the [`Component`](../api#django_components.Component) class\n that was registered under the given name.\n\n Once a component is unregistered, it is no longer available in the templates.\n\n Args:\n name (str): The name under which the component is registered. Required.\n\n **Raises:**\n\n - [`NotRegistered`](../exceptions#django_components.NotRegistered)\n if the given name is not registered.\n\n **Example:**\n\n ```python\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
Bases:
NamedTuple
Type for the variables available inside the component templates.
All variables here are scoped under
component_vars.
, so e.g. attributeis_filled
on this class is accessible inside the template as:{{ component_vars.is_filled }}\n
Attributes:
-
is_filled
(Dict[str, bool]
) \u2013Dictonary describing which component slots are filled (
True
) or are not (False
).
instance-attribute
","text":"is_filled: Dict[str, bool]\n
Dictonary describing which component slots are filled (
True
) or are not (False
).New in version 0.70
Use as
{{ component_vars.is_filled }}
Example:
"},{"location":"reference/django_components/#django_components.ComponentView","title":"ComponentView","text":"{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n <div class=\"slot-wrapper\">\n {% slot \"my_slot\" / %}\n </div>\n{% endif %}\n
ComponentView(component: Component, **kwargs: Any)\n
Bases:
View
Subclass of
Source code indjango.views.View
where theComponent
instance is available viaself.component
.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.ComponentsSettings","title":"ComponentsSettings","text":"def __init__(self, component: \"Component\", **kwargs: Any) -> None:\n super().__init__(**kwargs)\n self.component = component\n
Bases:
NamedTuple
Settings available for django_components.
Example:
COMPONENTS = ComponentsSettings(\n autodiscover=False,\n dirs = [BASE_DIR / \"components\"],\n)\n
Attributes:
-
app_dirs
(Optional[Sequence[str]]
) \u2013Specify the app-level directories that contain your components.
-
autodiscover
(Optional[bool]
) \u2013Toggle whether to run autodiscovery at the Django server startup.
-
context_behavior
(Optional[ContextBehaviorType]
) \u2013Configure whether, inside a component template, you can use variables from the outside
-
dirs
(Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]]
) \u2013Specify the directories that contain your components.
-
dynamic_component_name
(Optional[str]
) \u2013By default, the dynamic component
-
forbidden_static_files
(Optional[List[Union[str, Pattern]]]
) \u2013Deprecated. Use
-
libraries
(Optional[List[str]]
) \u2013Configure extra python modules that should be loaded.
-
multiline_tags
(Optional[bool]
) \u2013Enable / disable
-
reload_on_file_change
(Optional[bool]
) \u2013This is relevant if you are using the project structure where
-
reload_on_template_change
(Optional[bool]
) \u2013Deprecated. Use
-
static_files_allowed
(Optional[List[Union[str, Pattern]]]
) \u2013A list of file extensions (including the leading dot) that define which files within
-
static_files_forbidden
(Optional[List[Union[str, Pattern]]]
) \u2013A list of file extensions (including the leading dot) that define which files within
-
tag_formatter
(Optional[Union[TagFormatterABC, str]]
) \u2013Configure what syntax is used inside Django templates to render components.
-
template_cache_size
(Optional[int]
) \u2013Configure the maximum amount of Django templates to be cached.
class-attribute
instance-attribute
","text":"app_dirs: Optional[Sequence[str]] = None\n
Specify the app-level directories that contain your components.
Defaults to
[\"components\"]
. That is, for each Django app, we search<app>/components/
for components.The paths must be relative to app, e.g.:
COMPONENTS = ComponentsSettings(\n app_dirs=[\"my_comps\"],\n)\n
To search for
<app>/my_comps/
.These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.
Set to empty list to disable app-level components:
"},{"location":"reference/django_components/#django_components.ComponentsSettings.autodiscover","title":"autodiscoverCOMPONENTS = ComponentsSettings(\n app_dirs=[],\n)\n
class-attribute
instance-attribute
","text":"autodiscover: Optional[bool] = None\n
Toggle whether to run autodiscovery at the Django server startup.
Defaults to
True
"},{"location":"reference/django_components/#django_components.ComponentsSettings.context_behavior","title":"context_behaviorCOMPONENTS = ComponentsSettings(\n autodiscover=False,\n)\n
class-attribute
instance-attribute
","text":"context_behavior: Optional[ContextBehaviorType] = None\n
Configure whether, inside a component template, you can use variables from the outside (
\"django\"
) or not (\"isolated\"
). This also affects what variables are available inside the{% fill %}
tags.Also see Component context and scope.
Defaults to
\"django\"
.COMPONENTS = ComponentsSettings(\n context_behavior=\"isolated\",\n)\n
NOTE:
context_behavior
andslot_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
"},{"location":"reference/django_components/#django_components.ComponentsSettings.dirs","title":"dirs\"django\"
. See the rationale for change here.class-attribute
instance-attribute
","text":"dirs: Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]] = None\n
Specify the directories that contain your components.
Defaults to
[Path(settings.BASE_DIR) / \"components\"]
. That is, the rootcomponents/
app.Directories must be full paths, same as with STATICFILES_DIRS.
These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.
COMPONENTS = ComponentsSettings(\n dirs=[BASE_DIR / \"components\"],\n)\n
Set to empty list to disable global components directories:
"},{"location":"reference/django_components/#django_components.ComponentsSettings.dynamic_component_name","title":"dynamic_component_nameCOMPONENTS = ComponentsSettings(\n dirs=[],\n)\n
class-attribute
instance-attribute
","text":"dynamic_component_name: Optional[str] = None\n
By default, the dynamic component is registered under the name
\"dynamic\"
.In case of a conflict, you can use this setting to change the component name used for the dynamic components.
# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
"},{"location":"reference/django_components/#django_components.ComponentsSettings.forbidden_static_files","title":"forbidden_static_files{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
class-attribute
instance-attribute
","text":"forbidden_static_files: Optional[List[Union[str, Pattern]]] = None\n
Deprecated. Use
"},{"location":"reference/django_components/#django_components.ComponentsSettings.libraries","title":"librariesCOMPONENTS.static_files_forbidden
instead.class-attribute
instance-attribute
","text":"libraries: Optional[List[str]] = None\n
Configure extra python modules that should be loaded.
This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.
Expects a list of python module paths. Defaults to empty list.
Example:
COMPONENTS = ComponentsSettings(\n libraries=[\n \"mysite.components.forms\",\n \"mysite.components.buttons\",\n \"mysite.components.cards\",\n ],\n)\n
This would be the equivalent of importing these modules from within Django's
AppConfig.ready()
:
"},{"location":"reference/django_components/#django_components.ComponentsSettings.libraries--manually-loading-libraries","title":"Manually loading libraries","text":"class MyAppConfig(AppConfig):\n def ready(self):\n import \"mysite.components.forms\"\n import \"mysite.components.buttons\"\n import \"mysite.components.cards\"\n
In the rare case that you need to manually trigger the import of libraries, you can use the
import_libraries()
function:
"},{"location":"reference/django_components/#django_components.ComponentsSettings.multiline_tags","title":"multiline_tagsfrom django_components import import_libraries\n\nimport_libraries()\n
class-attribute
instance-attribute
","text":"multiline_tags: Optional[bool] = None\n
Enable / disable multiline support for template tags. If
True
, template tags like{% component %}
or{{ my_var }}
can span multiple lines.Defaults to
True
.Disable this setting if you are making custom modifications to Django's regular expression for parsing templates at
django.template.base.tag_re
.
"},{"location":"reference/django_components/#django_components.ComponentsSettings.reload_on_file_change","title":"reload_on_file_changeCOMPONENTS = ComponentsSettings(\n multiline_tags=False,\n)\n
class-attribute
instance-attribute
","text":"reload_on_file_change: Optional[bool] = None\n
This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.
Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.
The setting
reload_on_file_change
fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.If
True
, django_components configures Django to reload when files insideCOMPONENTS.dirs
orCOMPONENTS.app_dirs
change.See Reload dev server on component file changes.
Defaults to
False
.Warning
This setting should be enabled only for the dev environment!
"},{"location":"reference/django_components/#django_components.ComponentsSettings.reload_on_template_change","title":"reload_on_template_changeclass-attribute
instance-attribute
","text":"reload_on_template_change: Optional[bool] = None\n
Deprecated. Use
"},{"location":"reference/django_components/#django_components.ComponentsSettings.static_files_allowed","title":"static_files_allowedCOMPONENTS.reload_on_file_change
instead.class-attribute
instance-attribute
","text":"static_files_allowed: Optional[List[Union[str, Pattern]]] = None\n
A list of file extensions (including the leading dot) that define which files within
COMPONENTS.dirs
orCOMPONENTS.app_dirs
are treated as static files.If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running
collectstatic
, and can be accessed under the static file endpoint.You can also pass in compiled regexes (
re.Pattern
) for more advanced patterns.By default, JS, CSS, and common image and font file formats are considered static files:
COMPONENTS = ComponentsSettings(\n static_files_allowed=[\n \".css\",\n \".js\", \".jsx\", \".ts\", \".tsx\",\n # Images\n \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n \".jpeg\", \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n # Fonts\n \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n ],\n)\n
Warning
Exposing your Python files can be a security vulnerability. See Security notes.
"},{"location":"reference/django_components/#django_components.ComponentsSettings.static_files_forbidden","title":"static_files_forbiddenclass-attribute
instance-attribute
","text":"static_files_forbidden: Optional[List[Union[str, Pattern]]] = None\n
A list of file extensions (including the leading dot) that define which files within
COMPONENTS.dirs
orCOMPONENTS.app_dirs
will NEVER be treated as static files.If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in
static_files_allowed
.Use this setting together with
static_files_allowed
for a fine control over what file types will be exposed.You can also pass in compiled regexes (
re.Pattern
) for more advanced patterns.By default, any HTML and Python are considered NOT static files:
COMPONENTS = ComponentsSettings(\n static_files_forbidden=[\n \".html\", \".django\", \".dj\", \".tpl\",\n # Python files\n \".py\", \".pyc\",\n ],\n)\n
Warning
Exposing your Python files can be a security vulnerability. See Security notes.
"},{"location":"reference/django_components/#django_components.ComponentsSettings.tag_formatter","title":"tag_formatterclass-attribute
instance-attribute
","text":"tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n
Configure what syntax is used inside Django templates to render components. See the available tag formatters.
Defaults to
\"django_components.component_formatter\"
.Learn more about Customizing component tags with TagFormatter.
Can be set either as direct reference:
from django_components import component_formatter\n\nCOMPONENTS = ComponentsSettings(\n \"tag_formatter\": component_formatter\n)\n
Or as an import string;
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_formatter\"\n)\n
Examples:
-
\"django_components.component_formatter\"
Set
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_formatter\"\n)\n
To write components like this:
{% component \"button\" href=\"...\" %}\n Click me!\n{% endcomponent %}\n
-
django_components.component_shorthand_formatter
Set
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_shorthand_formatter\"\n)\n
To write components like this:
{% button href=\"...\" %}\n Click me!\n{% endbutton %}\n
class-attribute
instance-attribute
","text":"template_cache_size: Optional[int] = None\n
Configure the maximum amount of Django templates to be cached.
Defaults to
128
.Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's
lru_cache
decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding
Component.get_template()
to render many dynamic templates, you can increase this number.COMPONENTS = ComponentsSettings(\n template_cache_size=256,\n)\n
To remove the cache limit altogether and cache everything, set
template_cache_size
toNone
.COMPONENTS = ComponentsSettings(\n template_cache_size=None,\n)\n
If you want to add templates to the cache yourself, you can use
cached_template()
:
"},{"location":"reference/django_components/#django_components.ContextBehavior","title":"ContextBehavior","text":"from django_components import cached_template\n\ncached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n pass\n\ncached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n)\n
Bases:
str
,Enum
Configure how (and whether) the context is passed to the component fills and what variables are available inside the
{% fill %}
tags.Also see Component context and scope.
Options:
django
: With this setting, component fills behave as usual Django tags.isolated
: This setting makes the component fills behave similar to Vue or React.
Attributes:
-
DJANGO
\u2013With this setting, component fills behave as usual Django tags.
-
ISOLATED
\u2013This setting makes the component fills behave similar to Vue or React, where
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
Component.get_context_data()
are available to the component fill.
Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the
Component.get_context_data()
method{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
456 # my_var\nfeta # cheese\n
Because \"my_comp\" overrides the variable \"my_var\", so
{{ my_var }}
equals456
.And variable \"cheese\" will equal
"},{"location":"reference/django_components/#django_components.ContextBehavior.ISOLATED","title":"ISOLATEDfeta
, because the fill CAN access the current context.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
Component.get_context_data()
.Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the
get_context_data()
method{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
123 # my_var\n # cheese\n
Because both variables \"my_var\" and \"cheese\" are taken from the root context. Since \"cheese\" is not defined in root context, it's empty.
"},{"location":"reference/django_components/#django_components.DynamicComponent","title":"DynamicComponent","text":"DynamicComponent(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Component
This component is given a registered name or a reference to another component, and behaves as if the other component was in its place.
The args, kwargs, and slot fills are all passed down to the underlying component.
Parameters:
-
is
(str | Type[Component]
) \u2013Component that should be rendered. Either a registered name of a component, or a Component class directly. Required.
-
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to search for the registered name. If omitted, all registries are searched until the first match.
-
*args
\u2013Additional data passed to the component.
-
**kwargs
\u2013Additional data passed to the component.
Slots:
- Any slots, depending on the actual component.
Examples:
Django
{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Python
"},{"location":"reference/django_components/#django_components.DynamicComponent--use-cases","title":"Use cases","text":"from django_components import DynamicComponent\n\nDynamicComponent.render(\n kwargs={\n \"is\": table_comp,\n \"data\": table_data,\n \"headers\": table_headers,\n },\n slots={\n \"pagination\": PaginationComponent.render(\n render_dependencies=False,\n ),\n },\n)\n
Dynamic components are suitable if you are writing something like a form component. You may design it such that users give you a list of input types, and you render components depending on the input types.
While you could handle this with a series of if / else statements, that's not an extensible approach. Instead, you can use the dynamic component in place of normal components.
"},{"location":"reference/django_components/#django_components.DynamicComponent--component-name","title":"Component name","text":"By default, the dynamic component is registered under the name
\"dynamic\"
. In case of a conflict, you can set theCOMPONENTS.dynamic_component_name
setting to change the name used for the dynamic components.# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.DynamicComponent.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
class-attribute
instance-attribute
","text":"Media = ComponentMediaInput\n
Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/#django_components.DynamicComponent.css","title":"cssclass-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/#django_components.DynamicComponent.input","title":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/#django_components.DynamicComponent.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/#django_components.DynamicComponent.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/#django_components.DynamicComponent.media","title":"mediainstance-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.DynamicComponent.response_class","title":"response_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/#django_components.DynamicComponent.template_name","title":"template_namerender_to_response
class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/#django_components.DynamicComponent.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.DynamicComponent.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.DynamicComponent.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.DynamicComponent.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/#django_components.DynamicComponent.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.DynamicComponent.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.DynamicComponent.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.DynamicComponent.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.EmptyDict","title":"EmptyDict","text":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
Bases:
TypedDict
TypedDict with no members.
You can use this to define a Component that accepts NO kwargs, or NO slots, or returns NO data from
Component.get_context_data()
/Component.get_js_data()
/Component.get_css_data()
:Accepts NO kwargs:
from django_components import Component, EmptyDict\n\nclass Table(Component(Any, EmptyDict, Any, Any, Any, Any))\n ...\n
Accepts NO slots:
from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, EmptyDict, Any, Any, Any))\n ...\n
Returns NO data from
get_context_data()
:from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, Any, EmptyDict, Any, Any))\n ...\n
Going back to the example with NO kwargs, when you then call
Component.render()
orComponent.render_to_response()
, thekwargs
parameter will raise type error ifkwargs
is anything else than an empty dict.Table.render(\n kwargs: {},\n)\n
Omitting
kwargs
is also fine:Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
"},{"location":"reference/django_components/#django_components.NotRegistered","title":"NotRegistered","text":"Table.render(\n kwargs: {\n \"one\": 2,\n \"three\": 4,\n },\n)\n
Bases:
Exception
Raised when you try to access a Component, but it's NOT registered with given ComponentRegistry.
"},{"location":"reference/django_components/#django_components.RegistrySettings","title":"RegistrySettings","text":"Bases:
NamedTuple
Configuration for a
ComponentRegistry
.These settings define how the components registered with this registry will behave when rendered.
from django_components import ComponentRegistry, RegistrySettings\n\nregistry_settings = RegistrySettings(\n context_behavior=\"django\",\n tag_formatter=\"django_components.component_shorthand_formatter\",\n)\n\nregistry = ComponentRegistry(settings=registry_settings)\n
Attributes:
-
CONTEXT_BEHAVIOR
(Optional[ContextBehaviorType]
) \u2013Deprecated. Use
context_behavior
instead. Will be removed in v1. -
TAG_FORMATTER
(Optional[Union[TagFormatterABC, str]]
) \u2013Deprecated. Use
tag_formatter
instead. Will be removed in v1. -
context_behavior
(Optional[ContextBehaviorType]
) \u2013Same as the global
-
tag_formatter
(Optional[Union[TagFormatterABC, str]]
) \u2013Same as the global
class-attribute
instance-attribute
","text":"CONTEXT_BEHAVIOR: Optional[ContextBehaviorType] = None\n
Deprecated. Use
context_behavior
instead. Will be removed in v1.Same as the global
COMPONENTS.context_behavior
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/#django_components.RegistrySettings.TAG_FORMATTER","title":"TAG_FORMATTERCOMPONENTS.context_behavior
setting.class-attribute
instance-attribute
","text":"TAG_FORMATTER: Optional[Union[TagFormatterABC, str]] = None\n
Deprecated. Use
tag_formatter
instead. Will be removed in v1.Same as the global
COMPONENTS.tag_formatter
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/#django_components.RegistrySettings.context_behavior","title":"context_behaviorCOMPONENTS.tag_formatter
setting.class-attribute
instance-attribute
","text":"context_behavior: Optional[ContextBehaviorType] = None\n
Same as the global
COMPONENTS.context_behavior
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/#django_components.RegistrySettings.tag_formatter","title":"tag_formatterCOMPONENTS.context_behavior
setting.class-attribute
instance-attribute
","text":"tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n
Same as the global
COMPONENTS.tag_formatter
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/#django_components.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":"COMPONENTS.tag_formatter
setting.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:
"},{"location":"reference/django_components/#django_components.Slot","title":"Slot{% mycomp abc=123 / %}\n
dataclass
","text":"Slot(content_func: SlotFunc[TSlotData])\n
Bases:
Generic[TSlotData]
This class holds the slot content function along with related metadata.
"},{"location":"reference/django_components/#django_components.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
Source code in{{ my_lazy_slot }}
, it will output the contents of the slot.src/django_components/slots.py
"},{"location":"reference/django_components/#django_components.TagFormatterABC","title":"TagFormatterABC","text":"def __init__(self, slot: \"SlotNode\", context: Context):\n self._slot = slot\n self._context = context\n
Bases:
ABC
Abstract base class for defining custom tag formatters.
Tag formatters define how the component tags are used in the template.
Read more about Tag formatter.
For example, with the default tag formatter (
ComponentFormatter
), components are written as:{% component \"comp_name\" %}\n{% endcomponent %}\n
While with the shorthand tag formatter (
ShorthandComponentFormatter
), components are written as:{% comp_name %}\n{% endcomp_name %}\n
Example:
Implementation for
ShorthandComponentFormatter
:from djagno_components import TagFormatterABC, TagResult\n\nclass ShorthandComponentFormatter(TagFormatterABC):\n def start_tag(self, name: str) -> str:\n return name\n\n def end_tag(self, name: str) -> str:\n return f\"end{name}\"\n\n def parse(self, tokens: List[str]) -> TagResult:\n tokens = [*tokens]\n name = tokens.pop(0)\n return TagResult(name, tokens)\n
Methods:
-
end_tag
\u2013Formats the end tag of a block component.
-
parse
\u2013Given the tokens (words) passed to a component start tag, this function extracts
-
start_tag
\u2013Formats the start tag of a component.
abstractmethod
","text":"end_tag(name: str) -> str\n
Formats the end tag of a block component.
Parameters:
-
name
(str
) \u2013Component's registered name. Required.
Returns:
-
str
(str
) \u2013The formatted end tag.
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.TagFormatterABC.parse","title":"parse@abc.abstractmethod\ndef end_tag(self, name: str) -> str:\n \"\"\"\n Formats the end tag of a block component.\n\n Args:\n name (str): Component's registered name. Required.\n\n Returns:\n str: The formatted end tag.\n \"\"\"\n ...\n
abstractmethod
","text":"parse(tokens: List[str]) -> TagResult\n
Given the tokens (words) passed to a component start tag, this function extracts the component name from the tokens list, and returns
TagResult
, which is a tuple of(component_name, remaining_tokens)
.Parameters:
-
tokens
([List(str]
) \u2013List of tokens passed to the component tag.
Returns:
-
TagResult
(TagResult
) \u2013Parsed component name and remaining tokens.
Example:
Assuming we used a component in a template like this:
{% component \"my_comp\" key=val key2=val2 %}\n{% endcomponent %}\n
This function receives a list of tokens:
['component', '\"my_comp\"', 'key=val', 'key2=val2']\n
component
is the tag name, which we drop.\"my_comp\"
is the component name, but we must remove the extra quotes.- The remaining tokens we pass unmodified, as that's the input to the component.
So in the end, we return:
Source code inTagResult('my_comp', ['key=val', 'key2=val2'])\n
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.TagFormatterABC.start_tag","title":"start_tag@abc.abstractmethod\ndef parse(self, tokens: List[str]) -> TagResult:\n \"\"\"\n Given the tokens (words) passed to a component start tag, this function extracts\n the component name from the tokens list, and returns\n [`TagResult`](../api#django_components.TagResult),\n which is a tuple of `(component_name, remaining_tokens)`.\n\n Args:\n tokens [List(str]): List of tokens passed to the component tag.\n\n Returns:\n TagResult: Parsed component name and remaining tokens.\n\n **Example:**\n\n Assuming we used a component in a template like this:\n\n ```django\n {% component \"my_comp\" key=val key2=val2 %}\n {% endcomponent %}\n ```\n\n This function receives a list of tokens:\n\n ```python\n ['component', '\"my_comp\"', 'key=val', 'key2=val2']\n ```\n\n - `component` is the tag name, which we drop.\n - `\"my_comp\"` is the component name, but we must remove the extra quotes.\n - The remaining tokens we pass unmodified, as that's the input to the component.\n\n So in the end, we return:\n\n ```python\n TagResult('my_comp', ['key=val', 'key2=val2'])\n ```\n \"\"\"\n ...\n
abstractmethod
","text":"start_tag(name: str) -> str\n
Formats the start tag of a component.
Parameters:
-
name
(str
) \u2013Component's registered name. Required.
Returns:
-
str
(str
) \u2013The formatted start tag.
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.TagProtectedError","title":"TagProtectedError","text":"@abc.abstractmethod\ndef start_tag(self, name: str) -> str:\n \"\"\"\n Formats the start tag of a component.\n\n Args:\n name (str): Component's registered name. Required.\n\n Returns:\n str: The formatted start tag.\n \"\"\"\n ...\n
Bases:
Exception
The way the
TagFormatter
works is that, based on which start and end tags are used for rendering components, theComponentRegistry
behind the scenes un-/registers the template tags with the associated instance of Django'sLibrary
.In other words, if I have registered a component
\"table\"
, and I use the shorthand syntax:{% table ... %}\n{% endtable %}\n
Then
ComponentRegistry
registers the tagtable
onto the Django's Library instance.However, that means that if we registered a component
\"slot\"
, then we would overwrite the{% slot %}
tag from django_components.Thus, this exception is raised when a component is attempted to be registered under a forbidden name, such that it would overwrite one of django_component's own template tags.
"},{"location":"reference/django_components/#django_components.TagResult","title":"TagResult","text":"Bases:
NamedTuple
The return value from
TagFormatter.parse()
.Read more about Tag formatter.
Attributes:
-
component_name
(str
) \u2013Component name extracted from the template tag
-
tokens
(List[str]
) \u2013Remaining tokens (words) that were passed to the tag, with component name removed
instance-attribute
","text":"component_name: str\n
Component name extracted from the template tag
For example, if we had tag
{% component \"my_comp\" key=val key2=val2 %}\n
Then
"},{"location":"reference/django_components/#django_components.TagResult.tokens","title":"tokenscomponent_name
would bemy_comp
.instance-attribute
","text":"tokens: List[str]\n
Remaining tokens (words) that were passed to the tag, with component name removed
For example, if we had tag
{% component \"my_comp\" key=val key2=val2 %}\n
Then
"},{"location":"reference/django_components/#django_components.autodiscover","title":"autodiscover","text":"tokens
would be['key=val', 'key2=val2']
.autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Search for all python files in
COMPONENTS.dirs
andCOMPONENTS.app_dirs
and import them.See Autodiscovery.
Parameters:
-
map_module
(Callable[[str], str]
, default:None
) \u2013Map the module paths with
map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Returns:
-
List[str]
\u2013List[str]: A list of module paths of imported files.
To get the same list of modules that
autodiscover()
would return, but without importing them, useget_component_files()
:
Source code infrom django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
src/django_components/autodiscovery.py
"},{"location":"reference/django_components/#django_components.cached_template","title":"cached_template","text":"def autodiscover(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Search for all python files in\n [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n and\n [`COMPONENTS.app_dirs`](../settings#django_components.app_settings.ComponentsSettings.app_dirs)\n and import them.\n\n See [Autodiscovery](../../concepts/fundamentals/autodiscovery).\n\n Args:\n map_module (Callable[[str], str], optional): Map the module paths with `map_module` function.\\\n This serves as an escape hatch for when you need to use this function in tests.\n\n Returns:\n List[str]: A list of module paths of imported files.\n\n To get the same list of modules that `autodiscover()` would return, but without importing them, use\n [`get_component_files()`](../api#django_components.get_component_files):\n\n ```python\n from django_components import get_component_files\n\n modules = get_component_files(\".py\")\n ```\n \"\"\"\n modules = get_component_files(\".py\")\n logger.debug(f\"Autodiscover found {len(modules)} files in component directories.\")\n return _import_modules([entry.dot_path for entry in modules], map_module)\n
cached_template(\n template_string: str,\n template_cls: Optional[Type[Template]] = None,\n origin: Optional[Origin] = None,\n name: Optional[str] = None,\n engine: Optional[Any] = None,\n) -> Template\n
Create a Template instance that will be cached as per the
COMPONENTS.template_cache_size
setting.Parameters:
-
template_string
(str
) \u2013Template as a string, same as the first argument to Django's
Template
. Required. -
template_cls
(Type[Template]
, default:None
) \u2013Specify the Template class that should be instantiated. Defaults to Django's
Template
class. -
origin
(Type[Origin]
, default:None
) \u2013Sets
Template.Origin
. -
name
(Type[str]
, default:None
) \u2013Sets
Template.name
-
engine
(Type[Any]
, default:None
) \u2013Sets
Template.engine
Source code infrom django_components import cached_template\n\ntemplate = cached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n pass\n\ntemplate = cached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n)\n
src/django_components/template.py
"},{"location":"reference/django_components/#django_components.get_component_dirs","title":"get_component_dirs","text":"def cached_template(\n template_string: str,\n template_cls: Optional[Type[Template]] = None,\n origin: Optional[Origin] = None,\n name: Optional[str] = None,\n engine: Optional[Any] = None,\n) -> Template:\n \"\"\"\n Create a Template instance that will be cached as per the\n [`COMPONENTS.template_cache_size`](../settings#django_components.app_settings.ComponentsSettings.template_cache_size)\n setting.\n\n Args:\n template_string (str): Template as a string, same as the first argument to Django's\\\n [`Template`](https://docs.djangoproject.com/en/5.1/topics/templates/#template). Required.\n template_cls (Type[Template], optional): Specify the Template class that should be instantiated.\\\n Defaults to Django's [`Template`](https://docs.djangoproject.com/en/5.1/topics/templates/#template) class.\n origin (Type[Origin], optional): Sets \\\n [`Template.Origin`](https://docs.djangoproject.com/en/5.1/howto/custom-template-backend/#origin-api-and-3rd-party-integration).\n name (Type[str], optional): Sets `Template.name`\n engine (Type[Any], optional): Sets `Template.engine`\n\n ```python\n from django_components import cached_template\n\n template = cached_template(\"Variable: {{ variable }}\")\n\n # You can optionally specify Template class, and other Template inputs:\n class MyTemplate(Template):\n pass\n\n template = cached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n )\n ```\n \"\"\" # noqa: E501\n template = _create_template(template_cls or Template, template_string, engine)\n\n # Assign the origin and name separately, so the caching doesn't depend on them\n # Since we might be accessing a template from cache, we want to define these only once\n if not getattr(template, \"_dc_cached\", False):\n template.origin = origin or Origin(UNKNOWN_SOURCE)\n template.name = name\n template._dc_cached = True\n\n return template\n
get_component_dirs(include_apps: bool = True) -> List[Path]\n
Get directories that may contain component files.
This is the heart of all features that deal with filesystem and file lookup. Autodiscovery, Django template resolution, static file resolution - They all use this.
Parameters:
-
include_apps
(bool
, default:True
) \u2013Include directories from installed Django apps. Defaults to
True
.
Returns:
-
List[Path]
\u2013List[Path]: A list of directories that may contain component files.
get_component_dirs()
searches for dirs set inCOMPONENTS.dirs
settings. If none set, defaults to searching for a\"components\"
app.In addition to that, also all installed Django apps are checked whether they contain directories as set in
COMPONENTS.app_dirs
(e.g.[app]/components
).Notes:
-
Paths that do not point to directories are ignored.
-
BASE_DIR
setting is required. -
The paths in
COMPONENTS.dirs
must be absolute paths.
src/django_components/util/loader.py
"},{"location":"reference/django_components/#django_components.get_component_files","title":"get_component_files","text":"def get_component_dirs(include_apps: bool = True) -> List[Path]:\n \"\"\"\n Get directories that may contain component files.\n\n This is the heart of all features that deal with filesystem and file lookup.\n Autodiscovery, Django template resolution, static file resolution - They all use this.\n\n Args:\n include_apps (bool, optional): Include directories from installed Django apps.\\\n Defaults to `True`.\n\n Returns:\n List[Path]: A list of directories that may contain component files.\n\n `get_component_dirs()` searches for dirs set in\n [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n settings. If none set, defaults to searching for a `\"components\"` app.\n\n In addition to that, also all installed Django apps are checked whether they contain\n directories as set in\n [`COMPONENTS.app_dirs`](../settings#django_components.app_settings.ComponentsSettings.app_dirs)\n (e.g. `[app]/components`).\n\n **Notes:**\n\n - Paths that do not point to directories are ignored.\n\n - `BASE_DIR` setting is required.\n\n - The paths in [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n must be absolute paths.\n \"\"\"\n # Allow to configure from settings which dirs should be checked for components\n component_dirs = app_settings.DIRS\n\n # TODO_REMOVE_IN_V1\n raw_component_settings = getattr(settings, \"COMPONENTS\", {})\n if isinstance(raw_component_settings, dict):\n raw_dirs_value = raw_component_settings.get(\"dirs\", None)\n elif isinstance(raw_component_settings, ComponentsSettings):\n raw_dirs_value = raw_component_settings.dirs\n else:\n raw_dirs_value = None\n is_component_dirs_set = raw_dirs_value is not None\n is_legacy_paths = (\n # Use value of `STATICFILES_DIRS` ONLY if `COMPONENT.dirs` not set\n not is_component_dirs_set\n and hasattr(settings, \"STATICFILES_DIRS\")\n and settings.STATICFILES_DIRS\n )\n if is_legacy_paths:\n # NOTE: For STATICFILES_DIRS, we use the defaults even for empty list.\n # We don't do this for COMPONENTS.dirs, so user can explicitly specify \"NO dirs\".\n component_dirs = settings.STATICFILES_DIRS or [settings.BASE_DIR / \"components\"]\n # END TODO_REMOVE_IN_V1\n\n source = \"STATICFILES_DIRS\" if is_legacy_paths else \"COMPONENTS.dirs\"\n\n logger.debug(\n \"get_component_dirs will search for valid dirs from following options:\\n\"\n + \"\\n\".join([f\" - {str(d)}\" for d in component_dirs])\n )\n\n # Add `[app]/[APP_DIR]` to the directories. This is, by default `[app]/components`\n app_paths: List[Path] = []\n if include_apps:\n for conf in apps.get_app_configs():\n for app_dir in app_settings.APP_DIRS:\n comps_path = Path(conf.path).joinpath(app_dir)\n if comps_path.exists():\n app_paths.append(comps_path)\n\n directories: Set[Path] = set(app_paths)\n\n # Validate and add other values from the config\n for component_dir in component_dirs:\n # Consider tuples for STATICFILES_DIRS (See #489)\n # See https://docs.djangoproject.com/en/5.0/ref/settings/#prefixes-optional\n if isinstance(component_dir, (tuple, list)):\n component_dir = component_dir[1]\n try:\n Path(component_dir)\n except TypeError:\n logger.warning(\n f\"{source} expected str, bytes or os.PathLike object, or tuple/list of length 2. \"\n f\"See Django documentation for STATICFILES_DIRS. Got {type(component_dir)} : {component_dir}\"\n )\n continue\n\n if not Path(component_dir).is_absolute():\n raise ValueError(f\"{source} must contain absolute paths, got '{component_dir}'\")\n else:\n directories.add(Path(component_dir).resolve())\n\n logger.debug(\n \"get_component_dirs matched following template dirs:\\n\" + \"\\n\".join([f\" - {str(d)}\" for d in directories])\n )\n return list(directories)\n
get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]\n
Search for files within the component directories (as defined in
get_component_dirs()
).Requires
BASE_DIR
setting to be set.Parameters:
-
suffix
(Optional[str]
, default:None
) \u2013The suffix to search for. E.g.
.py
,.js
,.css
. Defaults toNone
, which will search for all files.
Returns:
-
List[ComponentFileEntry]
\u2013List[ComponentFileEntry] A list of entries that contain both the filesystem path and the python import path (dot path).
Example:
Source code infrom django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
src/django_components/util/loader.py
"},{"location":"reference/django_components/#django_components.import_libraries","title":"import_libraries","text":"def get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]:\n \"\"\"\n Search for files within the component directories (as defined in\n [`get_component_dirs()`](../api#django_components.get_component_dirs)).\n\n Requires `BASE_DIR` setting to be set.\n\n Args:\n suffix (Optional[str], optional): The suffix to search for. E.g. `.py`, `.js`, `.css`.\\\n Defaults to `None`, which will search for all files.\n\n Returns:\n List[ComponentFileEntry] A list of entries that contain both the filesystem path and \\\n the python import path (dot path).\n\n **Example:**\n\n ```python\n from django_components import get_component_files\n\n modules = get_component_files(\".py\")\n ```\n \"\"\"\n search_glob = f\"**/*{suffix}\" if suffix else \"**/*\"\n\n dirs = get_component_dirs(include_apps=False)\n component_filepaths = _search_dirs(dirs, search_glob)\n\n if hasattr(settings, \"BASE_DIR\") and settings.BASE_DIR:\n project_root = str(settings.BASE_DIR)\n else:\n # Fallback for getting the root dir, see https://stackoverflow.com/a/16413955/9788634\n project_root = os.path.abspath(os.path.dirname(__name__))\n\n # NOTE: We handle dirs from `COMPONENTS.dirs` and from individual apps separately.\n modules: List[ComponentFileEntry] = []\n\n # First let's handle the dirs from `COMPONENTS.dirs`\n #\n # Because for dirs in `COMPONENTS.dirs`, we assume they will be nested under `BASE_DIR`,\n # and that `BASE_DIR` is the current working dir (CWD). So the path relatively to `BASE_DIR`\n # is ALSO the python import path.\n for filepath in component_filepaths:\n module_path = _filepath_to_python_module(filepath, project_root, None)\n # Ignore files starting with dot `.` or files in dirs that start with dot.\n #\n # If any of the parts of the path start with a dot, e.g. the filesystem path\n # is `./abc/.def`, then this gets converted to python module as `abc..def`\n #\n # NOTE: This approach also ignores files:\n # - with two dots in the middle (ab..cd.py)\n # - an extra dot at the end (abcd..py)\n # - files outside of the parent component (../abcd.py).\n # But all these are NOT valid python modules so that's fine.\n if \"..\" in module_path:\n continue\n\n entry = ComponentFileEntry(dot_path=module_path, filepath=filepath)\n modules.append(entry)\n\n # For for apps, the directories may be outside of the project, e.g. in case of third party\n # apps. So we have to resolve the python import path relative to the package name / the root\n # import path for the app.\n # See https://github.com/EmilStenstrom/django-components/issues/669\n for conf in apps.get_app_configs():\n for app_dir in app_settings.APP_DIRS:\n comps_path = Path(conf.path).joinpath(app_dir)\n if not comps_path.exists():\n continue\n app_component_filepaths = _search_dirs([comps_path], search_glob)\n for filepath in app_component_filepaths:\n app_component_module = _filepath_to_python_module(filepath, conf.path, conf.name)\n entry = ComponentFileEntry(dot_path=app_component_module, filepath=filepath)\n modules.append(entry)\n\n return modules\n
import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Import modules set in
COMPONENTS.libraries
setting.See Autodiscovery.
Parameters:
-
map_module
(Callable[[str], str]
, default:None
) \u2013Map the module paths with
map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Returns:
-
List[str]
\u2013List[str]: A list of module paths of imported files.
Examples:
Normal usage - load libraries after Django has loaded
from django_components import import_libraries\n\nclass MyAppConfig(AppConfig):\n def ready(self):\n import_libraries()\n
Potential usage in tests
Source code infrom django_components import import_libraries\n\nimport_libraries(lambda path: path.replace(\"tests.\", \"myapp.\"))\n
src/django_components/autodiscovery.py
"},{"location":"reference/django_components/#django_components.register","title":"register","text":"def import_libraries(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Import modules set in\n [`COMPONENTS.libraries`](../settings#django_components.app_settings.ComponentsSettings.libraries)\n setting.\n\n See [Autodiscovery](../../concepts/fundamentals/autodiscovery).\n\n Args:\n map_module (Callable[[str], str], optional): Map the module paths with `map_module` function.\\\n This serves as an escape hatch for when you need to use this function in tests.\n\n Returns:\n List[str]: A list of module paths of imported files.\n\n **Examples:**\n\n Normal usage - load libraries after Django has loaded\n ```python\n from django_components import import_libraries\n\n class MyAppConfig(AppConfig):\n def ready(self):\n import_libraries()\n ```\n\n Potential usage in tests\n ```python\n from django_components import import_libraries\n\n import_libraries(lambda path: path.replace(\"tests.\", \"myapp.\"))\n ```\n \"\"\"\n from django_components.app_settings import app_settings\n\n return _import_modules(app_settings.LIBRARIES, map_module)\n
register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[\n [Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]]],\n Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]],\n]\n
Class decorator for registering a component to a component registry.
See Registering components.
Parameters:
-
name
(str
) \u2013Registered name. This is the name by which the component will be accessed from within a template when using the
{% component %}
tag. Required. -
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to which to register this component. If omitted, component is registered to the default registry.
Raises:
-
AlreadyRegistered
\u2013If there is already a component registered under the same name.
Examples:
from django_components import Component, register\n\n@register(\"my_component\")\nclass MyComponent(Component):\n ...\n
Specifing
ComponentRegistry
the component should be registered to by setting theregistry
kwarg:
Source code infrom django.template import Library\nfrom django_components import Component, ComponentRegistry, register\n\nmy_lib = Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n ...\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.render_dependencies","title":"render_dependencies","text":"def register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[\n [Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"]],\n Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"],\n]:\n \"\"\"\n Class decorator for registering a [component](./#django_components.Component)\n to a [component registry](./#django_components.ComponentRegistry).\n\n See [Registering components](../../concepts/advanced/component_registry).\n\n Args:\n name (str): Registered name. This is the name by which the component will be accessed\\\n from within a template when using the [`{% component %}`](../template_tags#component) tag. Required.\n registry (ComponentRegistry, optional): Specify the [registry](./#django_components.ComponentRegistry)\\\n to which to register this component. If omitted, component is registered to the default registry.\n\n Raises:\n AlreadyRegistered: If there is already a component registered under the same name.\n\n **Examples**:\n\n ```python\n from django_components import Component, register\n\n @register(\"my_component\")\n class MyComponent(Component):\n ...\n ```\n\n Specifing [`ComponentRegistry`](./#django_components.ComponentRegistry) the component\n should be registered to by setting the `registry` kwarg:\n\n ```python\n from django.template import Library\n from django_components import Component, ComponentRegistry, register\n\n my_lib = 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(\n component: Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"],\n ) -> Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"]:\n registry.register(name=name, component=component)\n return component\n\n return decorator\n
render_dependencies(content: TContent, type: RenderType = 'document') -> TContent\n
Given a string that contains parts that were rendered by components, this function inserts all used JS and CSS.
By default, the string is parsed as an HTML and: - CSS is inserted at the end of
<head>
(if present) - JS is inserted at the end of<body>
(if present)If you used
{% component_js_dependencies %}
or{% component_css_dependencies %}
, then the JS and CSS will be inserted only at these locations.Example:
Source code indef my_view(request):\n template = Template('''\n {% load components %}\n <!doctype html>\n <html>\n <head></head>\n <body>\n <h1>{{ table_name }}</h1>\n {% component \"table\" name=table_name / %}\n </body>\n </html>\n ''')\n\n html = template.render(\n Context({\n \"table_name\": request.GET[\"name\"],\n })\n )\n\n # This inserts components' JS and CSS\n processed_html = render_dependencies(html)\n\n return HttpResponse(processed_html)\n
src/django_components/dependencies.py
"},{"location":"reference/django_components/#django_components.app_settings","title":"app_settings","text":"def render_dependencies(content: TContent, type: RenderType = \"document\") -> TContent:\n \"\"\"\n Given a string that contains parts that were rendered by components,\n this function inserts all used JS and CSS.\n\n By default, the string is parsed as an HTML and:\n - CSS is inserted at the end of `<head>` (if present)\n - JS is inserted at the end of `<body>` (if present)\n\n If you used `{% component_js_dependencies %}` or `{% component_css_dependencies %}`,\n then the JS and CSS will be inserted only at these locations.\n\n Example:\n ```python\n def my_view(request):\n template = Template('''\n {% load components %}\n <!doctype html>\n <html>\n <head></head>\n <body>\n <h1>{{ table_name }}</h1>\n {% component \"table\" name=table_name / %}\n </body>\n </html>\n ''')\n\n html = template.render(\n Context({\n \"table_name\": request.GET[\"name\"],\n })\n )\n\n # This inserts components' JS and CSS\n processed_html = render_dependencies(html)\n\n return HttpResponse(processed_html)\n ```\n \"\"\"\n is_safestring = isinstance(content, SafeString)\n\n if isinstance(content, str):\n content_ = content.encode()\n else:\n content_ = cast(bytes, content)\n\n content_, js_dependencies, css_dependencies = _process_dep_declarations(content_, type)\n\n # Replace the placeholders with the actual content\n did_find_js_placeholder = False\n did_find_css_placeholder = False\n\n def on_replace_match(match: \"re.Match[bytes]\") -> bytes:\n nonlocal did_find_css_placeholder\n nonlocal did_find_js_placeholder\n\n if match[0] == CSS_PLACEHOLDER_BYTES:\n replacement = css_dependencies\n did_find_css_placeholder = True\n elif match[0] == JS_PLACEHOLDER_BYTES:\n replacement = js_dependencies\n did_find_js_placeholder = True\n else:\n raise RuntimeError(\n \"Unexpected error: Regex for component dependencies processing\"\n f\" matched unknown string '{match[0].decode()}'\"\n )\n return replacement\n\n content_ = PLACEHOLDER_REGEX.sub(on_replace_match, content_)\n\n # By default, if user didn't specify any `{% component_dependencies %}`,\n # then try to insert the JS scripts at the end of <body> and CSS sheets at the end\n # of <head>\n if type == \"document\" and (not did_find_js_placeholder or not did_find_css_placeholder):\n tree = parse_document_or_nodes(content_.decode())\n\n if isinstance(tree, LexborHTMLParser):\n did_modify_html = False\n\n if not did_find_css_placeholder and tree.head:\n css_elems = parse_multiroot_html(css_dependencies.decode())\n for css_elem in css_elems:\n tree.head.insert_child(css_elem) # type: ignore # TODO: Update to selectolax 0.3.25\n did_modify_html = True\n\n if not did_find_js_placeholder and tree.body:\n js_elems = parse_multiroot_html(js_dependencies.decode())\n for js_elem in js_elems:\n tree.body.insert_child(js_elem) # type: ignore # TODO: Update to selectolax 0.3.25\n did_modify_html = True\n\n transformed = cast(str, tree.html)\n if did_modify_html:\n content_ = transformed.encode()\n\n # Return the same type as we were given\n output = content_.decode() if isinstance(content, str) else content_\n output = mark_safe(output) if is_safestring else output\n return cast(TContent, output)\n
Classes:
-
ComponentsSettings
\u2013Settings available for django_components.
-
ContextBehavior
\u2013Configure how (and whether) the context is passed to the component fills
Bases:
NamedTuple
Settings available for django_components.
Example:
COMPONENTS = ComponentsSettings(\n autodiscover=False,\n dirs = [BASE_DIR / \"components\"],\n)\n
Attributes:
-
app_dirs
(Optional[Sequence[str]]
) \u2013Specify the app-level directories that contain your components.
-
autodiscover
(Optional[bool]
) \u2013Toggle whether to run autodiscovery at the Django server startup.
-
context_behavior
(Optional[ContextBehaviorType]
) \u2013Configure whether, inside a component template, you can use variables from the outside
-
dirs
(Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]]
) \u2013Specify the directories that contain your components.
-
dynamic_component_name
(Optional[str]
) \u2013By default, the dynamic component
-
forbidden_static_files
(Optional[List[Union[str, Pattern]]]
) \u2013Deprecated. Use
-
libraries
(Optional[List[str]]
) \u2013Configure extra python modules that should be loaded.
-
multiline_tags
(Optional[bool]
) \u2013Enable / disable
-
reload_on_file_change
(Optional[bool]
) \u2013This is relevant if you are using the project structure where
-
reload_on_template_change
(Optional[bool]
) \u2013Deprecated. Use
-
static_files_allowed
(Optional[List[Union[str, Pattern]]]
) \u2013A list of file extensions (including the leading dot) that define which files within
-
static_files_forbidden
(Optional[List[Union[str, Pattern]]]
) \u2013A list of file extensions (including the leading dot) that define which files within
-
tag_formatter
(Optional[Union[TagFormatterABC, str]]
) \u2013Configure what syntax is used inside Django templates to render components.
-
template_cache_size
(Optional[int]
) \u2013Configure the maximum amount of Django templates to be cached.
class-attribute
instance-attribute
","text":"app_dirs: Optional[Sequence[str]] = None\n
Specify the app-level directories that contain your components.
Defaults to
[\"components\"]
. That is, for each Django app, we search<app>/components/
for components.The paths must be relative to app, e.g.:
COMPONENTS = ComponentsSettings(\n app_dirs=[\"my_comps\"],\n)\n
To search for
<app>/my_comps/
.These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.
Set to empty list to disable app-level components:
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.autodiscover","title":"autodiscoverCOMPONENTS = ComponentsSettings(\n app_dirs=[],\n)\n
class-attribute
instance-attribute
","text":"autodiscover: Optional[bool] = None\n
Toggle whether to run autodiscovery at the Django server startup.
Defaults to
True
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.context_behavior","title":"context_behaviorCOMPONENTS = ComponentsSettings(\n autodiscover=False,\n)\n
class-attribute
instance-attribute
","text":"context_behavior: Optional[ContextBehaviorType] = None\n
Configure whether, inside a component template, you can use variables from the outside (
\"django\"
) or not (\"isolated\"
). This also affects what variables are available inside the{% fill %}
tags.Also see Component context and scope.
Defaults to
\"django\"
.COMPONENTS = ComponentsSettings(\n context_behavior=\"isolated\",\n)\n
NOTE:
context_behavior
andslot_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
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.dirs","title":"dirs\"django\"
. See the rationale for change here.class-attribute
instance-attribute
","text":"dirs: Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]] = None\n
Specify the directories that contain your components.
Defaults to
[Path(settings.BASE_DIR) / \"components\"]
. That is, the rootcomponents/
app.Directories must be full paths, same as with STATICFILES_DIRS.
These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.
COMPONENTS = ComponentsSettings(\n dirs=[BASE_DIR / \"components\"],\n)\n
Set to empty list to disable global components directories:
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.dynamic_component_name","title":"dynamic_component_nameCOMPONENTS = ComponentsSettings(\n dirs=[],\n)\n
class-attribute
instance-attribute
","text":"dynamic_component_name: Optional[str] = None\n
By default, the dynamic component is registered under the name
\"dynamic\"
.In case of a conflict, you can use this setting to change the component name used for the dynamic components.
# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.forbidden_static_files","title":"forbidden_static_files{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
class-attribute
instance-attribute
","text":"forbidden_static_files: Optional[List[Union[str, Pattern]]] = None\n
Deprecated. Use
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.libraries","title":"librariesCOMPONENTS.static_files_forbidden
instead.class-attribute
instance-attribute
","text":"libraries: Optional[List[str]] = None\n
Configure extra python modules that should be loaded.
This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.
Expects a list of python module paths. Defaults to empty list.
Example:
COMPONENTS = ComponentsSettings(\n libraries=[\n \"mysite.components.forms\",\n \"mysite.components.buttons\",\n \"mysite.components.cards\",\n ],\n)\n
This would be the equivalent of importing these modules from within Django's
AppConfig.ready()
:
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.libraries--manually-loading-libraries","title":"Manually loading libraries","text":"class MyAppConfig(AppConfig):\n def ready(self):\n import \"mysite.components.forms\"\n import \"mysite.components.buttons\"\n import \"mysite.components.cards\"\n
In the rare case that you need to manually trigger the import of libraries, you can use the
import_libraries()
function:
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.multiline_tags","title":"multiline_tagsfrom django_components import import_libraries\n\nimport_libraries()\n
class-attribute
instance-attribute
","text":"multiline_tags: Optional[bool] = None\n
Enable / disable multiline support for template tags. If
True
, template tags like{% component %}
or{{ my_var }}
can span multiple lines.Defaults to
True
.Disable this setting if you are making custom modifications to Django's regular expression for parsing templates at
django.template.base.tag_re
.
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.reload_on_file_change","title":"reload_on_file_changeCOMPONENTS = ComponentsSettings(\n multiline_tags=False,\n)\n
class-attribute
instance-attribute
","text":"reload_on_file_change: Optional[bool] = None\n
This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.
Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.
The setting
reload_on_file_change
fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.If
True
, django_components configures Django to reload when files insideCOMPONENTS.dirs
orCOMPONENTS.app_dirs
change.See Reload dev server on component file changes.
Defaults to
False
.Warning
This setting should be enabled only for the dev environment!
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.reload_on_template_change","title":"reload_on_template_changeclass-attribute
instance-attribute
","text":"reload_on_template_change: Optional[bool] = None\n
Deprecated. Use
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.static_files_allowed","title":"static_files_allowedCOMPONENTS.reload_on_file_change
instead.class-attribute
instance-attribute
","text":"static_files_allowed: Optional[List[Union[str, Pattern]]] = None\n
A list of file extensions (including the leading dot) that define which files within
COMPONENTS.dirs
orCOMPONENTS.app_dirs
are treated as static files.If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running
collectstatic
, and can be accessed under the static file endpoint.You can also pass in compiled regexes (
re.Pattern
) for more advanced patterns.By default, JS, CSS, and common image and font file formats are considered static files:
COMPONENTS = ComponentsSettings(\n static_files_allowed=[\n \".css\",\n \".js\", \".jsx\", \".ts\", \".tsx\",\n # Images\n \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n \".jpeg\", \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n # Fonts\n \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n ],\n)\n
Warning
Exposing your Python files can be a security vulnerability. See Security notes.
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.static_files_forbidden","title":"static_files_forbiddenclass-attribute
instance-attribute
","text":"static_files_forbidden: Optional[List[Union[str, Pattern]]] = None\n
A list of file extensions (including the leading dot) that define which files within
COMPONENTS.dirs
orCOMPONENTS.app_dirs
will NEVER be treated as static files.If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in
static_files_allowed
.Use this setting together with
static_files_allowed
for a fine control over what file types will be exposed.You can also pass in compiled regexes (
re.Pattern
) for more advanced patterns.By default, any HTML and Python are considered NOT static files:
COMPONENTS = ComponentsSettings(\n static_files_forbidden=[\n \".html\", \".django\", \".dj\", \".tpl\",\n # Python files\n \".py\", \".pyc\",\n ],\n)\n
Warning
Exposing your Python files can be a security vulnerability. See Security notes.
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.tag_formatter","title":"tag_formatterclass-attribute
instance-attribute
","text":"tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n
Configure what syntax is used inside Django templates to render components. See the available tag formatters.
Defaults to
\"django_components.component_formatter\"
.Learn more about Customizing component tags with TagFormatter.
Can be set either as direct reference:
from django_components import component_formatter\n\nCOMPONENTS = ComponentsSettings(\n \"tag_formatter\": component_formatter\n)\n
Or as an import string;
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_formatter\"\n)\n
Examples:
-
\"django_components.component_formatter\"
Set
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_formatter\"\n)\n
To write components like this:
{% component \"button\" href=\"...\" %}\n Click me!\n{% endcomponent %}\n
-
django_components.component_shorthand_formatter
Set
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_shorthand_formatter\"\n)\n
To write components like this:
{% button href=\"...\" %}\n Click me!\n{% endbutton %}\n
class-attribute
instance-attribute
","text":"template_cache_size: Optional[int] = None\n
Configure the maximum amount of Django templates to be cached.
Defaults to
128
.Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's
lru_cache
decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding
Component.get_template()
to render many dynamic templates, you can increase this number.COMPONENTS = ComponentsSettings(\n template_cache_size=256,\n)\n
To remove the cache limit altogether and cache everything, set
template_cache_size
toNone
.COMPONENTS = ComponentsSettings(\n template_cache_size=None,\n)\n
If you want to add templates to the cache yourself, you can use
cached_template()
:
"},{"location":"reference/django_components/#django_components.app_settings.ContextBehavior","title":"ContextBehavior","text":"from django_components import cached_template\n\ncached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n pass\n\ncached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n)\n
Bases:
str
,Enum
Configure how (and whether) the context is passed to the component fills and what variables are available inside the
{% fill %}
tags.Also see Component context and scope.
Options:
django
: With this setting, component fills behave as usual Django tags.isolated
: This setting makes the component fills behave similar to Vue or React.
Attributes:
-
DJANGO
\u2013With this setting, component fills behave as usual Django tags.
-
ISOLATED
\u2013This setting makes the component fills behave similar to Vue or React, where
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
Component.get_context_data()
are available to the component fill.
Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the
Component.get_context_data()
method{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
456 # my_var\nfeta # cheese\n
Because \"my_comp\" overrides the variable \"my_var\", so
{{ my_var }}
equals456
.And variable \"cheese\" will equal
"},{"location":"reference/django_components/#django_components.app_settings.ContextBehavior.ISOLATED","title":"ISOLATEDfeta
, because the fill CAN access the current context.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
Component.get_context_data()
.Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the
get_context_data()
method{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
123 # my_var\n # cheese\n
Because both variables \"my_var\" and \"cheese\" are taken from the root context. Since \"cheese\" is not defined in root context, it's empty.
"},{"location":"reference/django_components/#django_components.attributes","title":"attributes","text":"Functions:
-
append_attributes
\u2013Merges the key-value pairs and returns a new dictionary.
-
attributes_to_string
\u2013Convert a dict of attributes to a string.
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 insrc/django_components/attributes.py
"},{"location":"reference/django_components/#django_components.attributes.attributes_to_string","title":"attributes_to_string","text":"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
attributes_to_string(attributes: Mapping[str, Any]) -> str\n
Convert a dict of attributes to a string.
Source code insrc/django_components/attributes.py
"},{"location":"reference/django_components/#django_components.autodiscovery","title":"autodiscovery","text":"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
Functions:
-
autodiscover
\u2013Search for all python files in
-
import_libraries
\u2013Import modules set in
autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Search for all python files in
COMPONENTS.dirs
andCOMPONENTS.app_dirs
and import them.See Autodiscovery.
Parameters:
-
map_module
(Callable[[str], str]
, default:None
) \u2013Map the module paths with
map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Returns:
-
List[str]
\u2013List[str]: A list of module paths of imported files.
To get the same list of modules that
autodiscover()
would return, but without importing them, useget_component_files()
:
Source code infrom django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
src/django_components/autodiscovery.py
"},{"location":"reference/django_components/#django_components.autodiscovery.import_libraries","title":"import_libraries","text":"def autodiscover(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Search for all python files in\n [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n and\n [`COMPONENTS.app_dirs`](../settings#django_components.app_settings.ComponentsSettings.app_dirs)\n and import them.\n\n See [Autodiscovery](../../concepts/fundamentals/autodiscovery).\n\n Args:\n map_module (Callable[[str], str], optional): Map the module paths with `map_module` function.\\\n This serves as an escape hatch for when you need to use this function in tests.\n\n Returns:\n List[str]: A list of module paths of imported files.\n\n To get the same list of modules that `autodiscover()` would return, but without importing them, use\n [`get_component_files()`](../api#django_components.get_component_files):\n\n ```python\n from django_components import get_component_files\n\n modules = get_component_files(\".py\")\n ```\n \"\"\"\n modules = get_component_files(\".py\")\n logger.debug(f\"Autodiscover found {len(modules)} files in component directories.\")\n return _import_modules([entry.dot_path for entry in modules], map_module)\n
import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Import modules set in
COMPONENTS.libraries
setting.See Autodiscovery.
Parameters:
-
map_module
(Callable[[str], str]
, default:None
) \u2013Map the module paths with
map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Returns:
-
List[str]
\u2013List[str]: A list of module paths of imported files.
Examples:
Normal usage - load libraries after Django has loaded
from django_components import import_libraries\n\nclass MyAppConfig(AppConfig):\n def ready(self):\n import_libraries()\n
Potential usage in tests
Source code infrom django_components import import_libraries\n\nimport_libraries(lambda path: path.replace(\"tests.\", \"myapp.\"))\n
src/django_components/autodiscovery.py
"},{"location":"reference/django_components/#django_components.component","title":"component","text":"def import_libraries(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Import modules set in\n [`COMPONENTS.libraries`](../settings#django_components.app_settings.ComponentsSettings.libraries)\n setting.\n\n See [Autodiscovery](../../concepts/fundamentals/autodiscovery).\n\n Args:\n map_module (Callable[[str], str], optional): Map the module paths with `map_module` function.\\\n This serves as an escape hatch for when you need to use this function in tests.\n\n Returns:\n List[str]: A list of module paths of imported files.\n\n **Examples:**\n\n Normal usage - load libraries after Django has loaded\n ```python\n from django_components import import_libraries\n\n class MyAppConfig(AppConfig):\n def ready(self):\n import_libraries()\n ```\n\n Potential usage in tests\n ```python\n from django_components import import_libraries\n\n import_libraries(lambda path: path.replace(\"tests.\", \"myapp.\"))\n ```\n \"\"\"\n from django_components.app_settings import app_settings\n\n return _import_modules(app_settings.LIBRARIES, map_module)\n
Classes:
-
Component
\u2013 -
ComponentNode
\u2013Django.template.Node subclass that renders a django-components component
-
ComponentVars
\u2013Type for the variables available inside the component templates.
-
ComponentView
\u2013Subclass of
django.views.View
where theComponent
instance is available
Component(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Generic[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template
(Optional[Union[str, Template]]
) \u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.Component.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
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":"cssclass-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":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/#django_components.component.Component.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/#django_components.component.Component.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.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":"mediainstance-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_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/#django_components.component.Component.template","title":"templaterender_to_response
class-attribute
instance-attribute
","text":"template: Optional[Union[str, Template]] = None\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
"},{"location":"reference/django_components/#django_components.component.Component.template_name","title":"template_nametemplate_name
,get_template_name
,template
orget_template
must be defined.class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/#django_components.component.Component.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.Component.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.Component.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.Component.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.Component.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.Component.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.Component.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.Component.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.ComponentNode","title":"ComponentNode","text":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
ComponentNode(\n name: str,\n args: List[Expression],\n kwargs: RuntimeKwargs,\n registry: ComponentRegistry,\n isolated_context: bool = False,\n nodelist: Optional[NodeList] = None,\n node_id: Optional[str] = None,\n)\n
Bases:
BaseNode
Django.template.Node subclass that renders a django-components component
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.ComponentVars","title":"ComponentVars","text":"def __init__(\n self,\n name: str,\n args: List[Expression],\n kwargs: RuntimeKwargs,\n registry: ComponentRegistry, # noqa F811\n isolated_context: bool = False,\n nodelist: Optional[NodeList] = None,\n node_id: Optional[str] = None,\n) -> None:\n super().__init__(nodelist=nodelist or NodeList(), args=args, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.isolated_context = isolated_context\n self.registry = registry\n
Bases:
NamedTuple
Type for the variables available inside the component templates.
All variables here are scoped under
component_vars.
, so e.g. attributeis_filled
on this class is accessible inside the template as:{{ component_vars.is_filled }}\n
Attributes:
-
is_filled
(Dict[str, bool]
) \u2013Dictonary describing which component slots are filled (
True
) or are not (False
).
instance-attribute
","text":"is_filled: Dict[str, bool]\n
Dictonary describing which component slots are filled (
True
) or are not (False
).New in version 0.70
Use as
{{ component_vars.is_filled }}
Example:
"},{"location":"reference/django_components/#django_components.component.ComponentView","title":"ComponentView","text":"{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n <div class=\"slot-wrapper\">\n {% slot \"my_slot\" / %}\n </div>\n{% endif %}\n
ComponentView(component: Component, **kwargs: Any)\n
Bases:
View
Subclass of
Source code indjango.views.View
where theComponent
instance is available viaself.component
.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.component_media","title":"component_media","text":"def __init__(self, component: \"Component\", **kwargs: Any) -> None:\n super().__init__(**kwargs)\n self.component = component\n
Classes:
-
ComponentMediaInput
\u2013Defines JS and CSS media files associated with this component.
-
MediaMeta
\u2013Metaclass for handling media files for components.
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 ofMedia
attribute to define associated JS/CSS files, which are then available undermedia
attribute as a instance ofMedia
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
E.g. if in a directory
my_comp
you havescript.js
andmy_comp.py
, andmy_comp.py
looks like this:class MyComponent(Component):\n class Media:\n js = \"script.js\"\n
Then
"},{"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":"script.js
will be resolved asmy_comp/script.js
.E.g.:
"},{"location":"reference/django_components/#django_components.component_media.MediaMeta--4-subclass-media-class-with-media_class","title":"4. Subclassdef 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
Media
class withmedia_class
","text":"Normal
MediaDefiningClass
creates an instance ofMedia
class under themedia
attribute. This class allows to override which class will be instantiated withmedia_class
attribute:
"},{"location":"reference/django_components/#django_components.component_registry","title":"component_registry","text":"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
Classes:
-
AlreadyRegistered
\u2013Raised when you try to register a Component,
-
ComponentRegistry
\u2013Manages components and makes them available
-
NotRegistered
\u2013Raised when you try to access a Component,
-
RegistrySettings
\u2013Configuration for a
ComponentRegistry
.
Functions:
-
register
\u2013Class decorator for registering a component
Attributes:
-
registry
(ComponentRegistry
) \u2013The default and global component registry.
module-attribute
","text":"registry: ComponentRegistry = ComponentRegistry()\n
The default and global component registry. Use this instance to directly register or remove components:
See Registering components.
"},{"location":"reference/django_components/#django_components.component_registry.AlreadyRegistered","title":"AlreadyRegistered","text":"# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get single\nregistry.get(\"button\")\n\n# Get all\nregistry.all()\n\n# Unregister single\nregistry.unregister(\"button\")\n\n# Unregister all\nregistry.clear()\n
Bases:
Exception
Raised when you try to register a Component, but it's already registered with given ComponentRegistry.
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry","title":"ComponentRegistry","text":"ComponentRegistry(\n library: Optional[Library] = None, settings: Optional[Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]] = None\n)\n
Manages components and makes them available in the template, by default as
{% component %}
tags.{% component \"my_comp\" key=value %}\n{% endcomponent %}\n
To enable a component to be used in a template, the component must be registered with a component registry.
When you register a component to a registry, behind the scenes the registry automatically adds the component's template tag (e.g.
{% component %}
to theLibrary
. And the opposite happens when you unregister a component - the tag is removed.See Registering components.
Parameters:
-
library
(Library
, default:None
) \u2013Django
Library
associated with this registry. If omitted, the default Library instance from django_components is used. -
settings
(Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]
, default:None
) \u2013Configure how the components registered with this registry will behave when rendered. See
RegistrySettings
. Can be either a static value or a callable that returns the settings. If omitted, the settings fromCOMPONENTS
are used.
Notes:
- The default registry is available as
django_components.registry
. - The default registry is used when registering components with
@register
decorator.
Example:
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry--using-registry-to-share-components","title":"Using registry to share components","text":"# 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
You can use component registry for isolating or \"packaging\" components:
-
Create new instance of
ComponentRegistry
and Library:my_comps = Library()\nmy_comps_reg = ComponentRegistry(library=my_comps)\n
-
Register components to the registry:
my_comps_reg.register(\"my_button\", ButtonComponent)\nmy_comps_reg.register(\"my_card\", CardComponent)\n
-
In your target project, load the Library associated with the registry:
{% load my_comps %}\n
-
Use the registered components in your templates:
{% component \"button\" %}\n{% endcomponent %}\n
Methods:
-
all
\u2013Retrieve all registered
Component
classes. -
clear
\u2013Clears the registry, unregistering all components.
-
get
\u2013Retrieve a
Component
-
register
\u2013Register a
Component
class -
unregister
\u2013Unregister the
Component
class
Attributes:
-
library
(Library
) \u2013The template tag
Library
-
settings
(InternalRegistrySettings
) \u2013Registry settings configured for this registry.
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.library","title":"librarydef __init__(\n self,\n library: Optional[Library] = None,\n settings: Optional[Union[RegistrySettings, Callable[[\"ComponentRegistry\"], RegistrySettings]]] = None,\n) -> None:\n self._registry: Dict[str, ComponentRegistryEntry] = {} # component name -> component_entry mapping\n self._tags: Dict[str, Set[str]] = {} # tag -> list[component names]\n self._library = library\n self._settings_input = settings\n self._settings: Optional[Callable[[], InternalRegistrySettings]] = None\n\n all_registries.append(self)\n
property
","text":"library: Library\n
The template tag
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.settings","title":"settingsLibrary
that is associated with the registry.property
","text":"settings: InternalRegistrySettings\n
Registry settings configured for this registry.
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.all","title":"all","text":"all() -> Dict[str, Type[Component]]\n
Retrieve all registered
Component
classes.Returns:
-
Dict[str, Type[Component]]
\u2013Dict[str, Type[Component]]: A dictionary of component names to component classes
Example:
Source code in# 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
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.clear","title":"clear","text":"def all(self) -> Dict[str, Type[\"Component\"]]:\n \"\"\"\n Retrieve all registered [`Component`](../api#django_components.Component) classes.\n\n Returns:\n Dict[str, Type[Component]]: A dictionary of component names to component classes\n\n **Example:**\n\n ```python\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
clear() -> None\n
Clears the registry, unregistering all components.
Example:
Source code in# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then clear\nregistry.clear()\n# Then get all\nregistry.all()\n# > {}\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.get","title":"get","text":"def clear(self) -> None:\n \"\"\"\n Clears the registry, unregistering all components.\n\n Example:\n\n ```python\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
get(name: str) -> Type[Component]\n
Retrieve a
Component
class registered under the given name.Parameters:
-
name
(str
) \u2013The name under which the component was registered. Required.
Returns:
-
Type[Component]
\u2013Type[Component]: The component class registered under the given name.
Raises:
NotRegistered
if the given name is not registered.
Example:
Source code in# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then get\nregistry.get(\"button\")\n# > ButtonComponent\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.register","title":"register","text":"def get(self, name: str) -> Type[\"Component\"]:\n \"\"\"\n Retrieve a [`Component`](../api#django_components.Component)\n class registered under the given name.\n\n Args:\n name (str): The name under which the component was registered. Required.\n\n Returns:\n Type[Component]: The component class registered under the given name.\n\n **Raises:**\n\n - [`NotRegistered`](../exceptions#django_components.NotRegistered)\n if the given name is not registered.\n\n **Example:**\n\n ```python\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
register(name: str, component: Type[Component]) -> None\n
Register a
Component
class with this registry under the given name.A component MUST be registered before it can be used in a template such as:
{% component \"my_comp\" %}\n{% endcomponent %}\n
Parameters:
-
name
(str
) \u2013The name under which the component will be registered. Required.
-
component
(Type[Component]
) \u2013The component class to register. Required.
Raises:
AlreadyRegistered
if a different component was already registered under the same name.
Example:
Source code inregistry.register(\"button\", ButtonComponent)\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.unregister","title":"unregister","text":"def register(self, name: str, component: Type[\"Component\"]) -> None:\n \"\"\"\n Register a [`Component`](../api#django_components.Component) class\n 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\" %}\n {% endcomponent %}\n ```\n\n Args:\n name (str): The name under which the component will be registered. Required.\n component (Type[Component]): The component class to register. Required.\n\n **Raises:**\n\n - [`AlreadyRegistered`](../exceptions#django_components.AlreadyRegistered)\n if a different component was already registered under the same name.\n\n **Example:**\n\n ```python\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
unregister(name: str) -> None\n
Unregister the
Component
class that was registered under the given name.Once a component is unregistered, it is no longer available in the templates.
Parameters:
-
name
(str
) \u2013The name under which the component is registered. Required.
Raises:
NotRegistered
if the given name is not registered.
Example:
Source code in# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.component_registry.NotRegistered","title":"NotRegistered","text":"def unregister(self, name: str) -> None:\n \"\"\"\n Unregister the [`Component`](../api#django_components.Component) class\n that was registered under the given name.\n\n Once a component is unregistered, it is no longer available in the templates.\n\n Args:\n name (str): The name under which the component is registered. Required.\n\n **Raises:**\n\n - [`NotRegistered`](../exceptions#django_components.NotRegistered)\n if the given name is not registered.\n\n **Example:**\n\n ```python\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
Bases:
Exception
Raised when you try to access a Component, but it's NOT registered with given ComponentRegistry.
"},{"location":"reference/django_components/#django_components.component_registry.RegistrySettings","title":"RegistrySettings","text":"Bases:
NamedTuple
Configuration for a
ComponentRegistry
.These settings define how the components registered with this registry will behave when rendered.
from django_components import ComponentRegistry, RegistrySettings\n\nregistry_settings = RegistrySettings(\n context_behavior=\"django\",\n tag_formatter=\"django_components.component_shorthand_formatter\",\n)\n\nregistry = ComponentRegistry(settings=registry_settings)\n
Attributes:
-
CONTEXT_BEHAVIOR
(Optional[ContextBehaviorType]
) \u2013Deprecated. Use
context_behavior
instead. Will be removed in v1. -
TAG_FORMATTER
(Optional[Union[TagFormatterABC, str]]
) \u2013Deprecated. Use
tag_formatter
instead. Will be removed in v1. -
context_behavior
(Optional[ContextBehaviorType]
) \u2013Same as the global
-
tag_formatter
(Optional[Union[TagFormatterABC, str]]
) \u2013Same as the global
class-attribute
instance-attribute
","text":"CONTEXT_BEHAVIOR: Optional[ContextBehaviorType] = None\n
Deprecated. Use
context_behavior
instead. Will be removed in v1.Same as the global
COMPONENTS.context_behavior
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/#django_components.component_registry.RegistrySettings.TAG_FORMATTER","title":"TAG_FORMATTERCOMPONENTS.context_behavior
setting.class-attribute
instance-attribute
","text":"TAG_FORMATTER: Optional[Union[TagFormatterABC, str]] = None\n
Deprecated. Use
tag_formatter
instead. Will be removed in v1.Same as the global
COMPONENTS.tag_formatter
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/#django_components.component_registry.RegistrySettings.context_behavior","title":"context_behaviorCOMPONENTS.tag_formatter
setting.class-attribute
instance-attribute
","text":"context_behavior: Optional[ContextBehaviorType] = None\n
Same as the global
COMPONENTS.context_behavior
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/#django_components.component_registry.RegistrySettings.tag_formatter","title":"tag_formatterCOMPONENTS.context_behavior
setting.class-attribute
instance-attribute
","text":"tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n
Same as the global
COMPONENTS.tag_formatter
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/#django_components.component_registry.register","title":"register","text":"COMPONENTS.tag_formatter
setting.register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[\n [Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]]],\n Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]],\n]\n
Class decorator for registering a component to a component registry.
See Registering components.
Parameters:
-
name
(str
) \u2013Registered name. This is the name by which the component will be accessed from within a template when using the
{% component %}
tag. Required. -
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to which to register this component. If omitted, component is registered to the default registry.
Raises:
-
AlreadyRegistered
\u2013If there is already a component registered under the same name.
Examples:
from django_components import Component, register\n\n@register(\"my_component\")\nclass MyComponent(Component):\n ...\n
Specifing
ComponentRegistry
the component should be registered to by setting theregistry
kwarg:
Source code infrom django.template import Library\nfrom django_components import Component, ComponentRegistry, register\n\nmy_lib = Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n ...\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.components","title":"components","text":"def register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[\n [Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"]],\n Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"],\n]:\n \"\"\"\n Class decorator for registering a [component](./#django_components.Component)\n to a [component registry](./#django_components.ComponentRegistry).\n\n See [Registering components](../../concepts/advanced/component_registry).\n\n Args:\n name (str): Registered name. This is the name by which the component will be accessed\\\n from within a template when using the [`{% component %}`](../template_tags#component) tag. Required.\n registry (ComponentRegistry, optional): Specify the [registry](./#django_components.ComponentRegistry)\\\n to which to register this component. If omitted, component is registered to the default registry.\n\n Raises:\n AlreadyRegistered: If there is already a component registered under the same name.\n\n **Examples**:\n\n ```python\n from django_components import Component, register\n\n @register(\"my_component\")\n class MyComponent(Component):\n ...\n ```\n\n Specifing [`ComponentRegistry`](./#django_components.ComponentRegistry) the component\n should be registered to by setting the `registry` kwarg:\n\n ```python\n from django.template import Library\n from django_components import Component, ComponentRegistry, register\n\n my_lib = 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(\n component: Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"],\n ) -> Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"]:\n registry.register(name=name, component=component)\n return component\n\n return decorator\n
Modules:
-
dynamic
\u2013
Classes:
-
DynamicComponent
\u2013This component is given a registered name or a reference to another component,
DynamicComponent(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Component
This component is given a registered name or a reference to another component, and behaves as if the other component was in its place.
The args, kwargs, and slot fills are all passed down to the underlying component.
Parameters:
-
is
(str | Type[Component]
) \u2013Component that should be rendered. Either a registered name of a component, or a Component class directly. Required.
-
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to search for the registered name. If omitted, all registries are searched until the first match.
-
*args
\u2013Additional data passed to the component.
-
**kwargs
\u2013Additional data passed to the component.
Slots:
- Any slots, depending on the actual component.
Examples:
Django
{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Python
"},{"location":"reference/django_components/#django_components.components.DynamicComponent--use-cases","title":"Use cases","text":"from django_components import DynamicComponent\n\nDynamicComponent.render(\n kwargs={\n \"is\": table_comp,\n \"data\": table_data,\n \"headers\": table_headers,\n },\n slots={\n \"pagination\": PaginationComponent.render(\n render_dependencies=False,\n ),\n },\n)\n
Dynamic components are suitable if you are writing something like a form component. You may design it such that users give you a list of input types, and you render components depending on the input types.
While you could handle this with a series of if / else statements, that's not an extensible approach. Instead, you can use the dynamic component in place of normal components.
"},{"location":"reference/django_components/#django_components.components.DynamicComponent--component-name","title":"Component name","text":"By default, the dynamic component is registered under the name
\"dynamic\"
. In case of a conflict, you can set theCOMPONENTS.dynamic_component_name
setting to change the name used for the dynamic components.# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
class-attribute
instance-attribute
","text":"Media = ComponentMediaInput\n
Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.css","title":"cssclass-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.input","title":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.media","title":"mediainstance-attribute
","text":"media: Media\n
Normalized definition of JS and CSS media files associated with this component.
NOTE: This field is generated from Component.Media class.
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.response_class","title":"response_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.template_name","title":"template_namerender_to_response
class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic","title":"dynamic","text":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
Modules:
-
types
\u2013Helper types for IDEs.
Classes:
-
DynamicComponent
\u2013This component is given a registered name or a reference to another component,
DynamicComponent(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Component
This component is given a registered name or a reference to another component, and behaves as if the other component was in its place.
The args, kwargs, and slot fills are all passed down to the underlying component.
Parameters:
-
is
(str | Type[Component]
) \u2013Component that should be rendered. Either a registered name of a component, or a Component class directly. Required.
-
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to search for the registered name. If omitted, all registries are searched until the first match.
-
*args
\u2013Additional data passed to the component.
-
**kwargs
\u2013Additional data passed to the component.
Slots:
- Any slots, depending on the actual component.
Examples:
Django
{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Python
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent--use-cases","title":"Use cases","text":"from django_components import DynamicComponent\n\nDynamicComponent.render(\n kwargs={\n \"is\": table_comp,\n \"data\": table_data,\n \"headers\": table_headers,\n },\n slots={\n \"pagination\": PaginationComponent.render(\n render_dependencies=False,\n ),\n },\n)\n
Dynamic components are suitable if you are writing something like a form component. You may design it such that users give you a list of input types, and you render components depending on the input types.
While you could handle this with a series of if / else statements, that's not an extensible approach. Instead, you can use the dynamic component in place of normal components.
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent--component-name","title":"Component name","text":"By default, the dynamic component is registered under the name
\"dynamic\"
. In case of a conflict, you can set theCOMPONENTS.dynamic_component_name
setting to change the name used for the dynamic components.# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
class-attribute
instance-attribute
","text":"Media = ComponentMediaInput\n
Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.css","title":"cssclass-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.input","title":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.media","title":"mediainstance-attribute
","text":"media: Media\n
Normalized definition of JS and CSS media files associated with this component.
NOTE: This field is generated from Component.Media class.
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.response_class","title":"response_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.template_name","title":"template_namerender_to_response
class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.context","title":"context","text":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
This file centralizes various ways we use Django's Context class pass data across components, nodes, slots, and contexts.
You can think of the Context as our storage system.
Functions:
-
copy_forloop_context
\u2013Forward the info about the current loop
-
get_injected_context_var
\u2013Retrieve a 'provided' field. The field MUST have been previously 'provided'
-
set_provided_context_var
\u2013'Provide' given data under given key. In other words, this data can be retrieved
copy_forloop_context(from_context: Context, to_context: Context) -> None\n
Forward the info about the current loop
Source code insrc/django_components/context.py
"},{"location":"reference/django_components/#django_components.context.get_injected_context_var","title":"get_injected_context_var","text":"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
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
Source code in{% provide %}
template tag.src/django_components/context.py
"},{"location":"reference/django_components/#django_components.context.set_provided_context_var","title":"set_provided_context_var","text":"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
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
Source code inself.inject(key)
inside ofget_context_data()
method of components that are nested inside the{% provide %}
tag.src/django_components/context.py
"},{"location":"reference/django_components/#django_components.dependencies","title":"dependencies","text":"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
All code related to management of component dependencies (JS and CSS scripts)
Modules:
-
types
\u2013Helper types for IDEs.
Classes:
-
ComponentDependencyMiddleware
\u2013Middleware that inserts CSS/JS dependencies for all rendered
Functions:
-
render_dependencies
\u2013Given a string that contains parts that were rendered by components,
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 insrc/django_components/dependencies.py
"},{"location":"reference/django_components/#django_components.dependencies.render_dependencies","title":"render_dependencies","text":"def __init__(self, get_response: \"Callable[[HttpRequest], HttpResponse]\") -> None:\n self.get_response = get_response\n\n # NOTE: Required to work with async\n if iscoroutinefunction(self.get_response):\n markcoroutinefunction(self)\n
render_dependencies(content: TContent, type: RenderType = 'document') -> TContent\n
Given a string that contains parts that were rendered by components, this function inserts all used JS and CSS.
By default, the string is parsed as an HTML and: - CSS is inserted at the end of
<head>
(if present) - JS is inserted at the end of<body>
(if present)If you used
{% component_js_dependencies %}
or{% component_css_dependencies %}
, then the JS and CSS will be inserted only at these locations.Example:
Source code indef my_view(request):\n template = Template('''\n {% load components %}\n <!doctype html>\n <html>\n <head></head>\n <body>\n <h1>{{ table_name }}</h1>\n {% component \"table\" name=table_name / %}\n </body>\n </html>\n ''')\n\n html = template.render(\n Context({\n \"table_name\": request.GET[\"name\"],\n })\n )\n\n # This inserts components' JS and CSS\n processed_html = render_dependencies(html)\n\n return HttpResponse(processed_html)\n
src/django_components/dependencies.py
"},{"location":"reference/django_components/#django_components.expression","title":"expression","text":"def render_dependencies(content: TContent, type: RenderType = \"document\") -> TContent:\n \"\"\"\n Given a string that contains parts that were rendered by components,\n this function inserts all used JS and CSS.\n\n By default, the string is parsed as an HTML and:\n - CSS is inserted at the end of `<head>` (if present)\n - JS is inserted at the end of `<body>` (if present)\n\n If you used `{% component_js_dependencies %}` or `{% component_css_dependencies %}`,\n then the JS and CSS will be inserted only at these locations.\n\n Example:\n ```python\n def my_view(request):\n template = Template('''\n {% load components %}\n <!doctype html>\n <html>\n <head></head>\n <body>\n <h1>{{ table_name }}</h1>\n {% component \"table\" name=table_name / %}\n </body>\n </html>\n ''')\n\n html = template.render(\n Context({\n \"table_name\": request.GET[\"name\"],\n })\n )\n\n # This inserts components' JS and CSS\n processed_html = render_dependencies(html)\n\n return HttpResponse(processed_html)\n ```\n \"\"\"\n is_safestring = isinstance(content, SafeString)\n\n if isinstance(content, str):\n content_ = content.encode()\n else:\n content_ = cast(bytes, content)\n\n content_, js_dependencies, css_dependencies = _process_dep_declarations(content_, type)\n\n # Replace the placeholders with the actual content\n did_find_js_placeholder = False\n did_find_css_placeholder = False\n\n def on_replace_match(match: \"re.Match[bytes]\") -> bytes:\n nonlocal did_find_css_placeholder\n nonlocal did_find_js_placeholder\n\n if match[0] == CSS_PLACEHOLDER_BYTES:\n replacement = css_dependencies\n did_find_css_placeholder = True\n elif match[0] == JS_PLACEHOLDER_BYTES:\n replacement = js_dependencies\n did_find_js_placeholder = True\n else:\n raise RuntimeError(\n \"Unexpected error: Regex for component dependencies processing\"\n f\" matched unknown string '{match[0].decode()}'\"\n )\n return replacement\n\n content_ = PLACEHOLDER_REGEX.sub(on_replace_match, content_)\n\n # By default, if user didn't specify any `{% component_dependencies %}`,\n # then try to insert the JS scripts at the end of <body> and CSS sheets at the end\n # of <head>\n if type == \"document\" and (not did_find_js_placeholder or not did_find_css_placeholder):\n tree = parse_document_or_nodes(content_.decode())\n\n if isinstance(tree, LexborHTMLParser):\n did_modify_html = False\n\n if not did_find_css_placeholder and tree.head:\n css_elems = parse_multiroot_html(css_dependencies.decode())\n for css_elem in css_elems:\n tree.head.insert_child(css_elem) # type: ignore # TODO: Update to selectolax 0.3.25\n did_modify_html = True\n\n if not did_find_js_placeholder and tree.body:\n js_elems = parse_multiroot_html(js_dependencies.decode())\n for js_elem in js_elems:\n tree.body.insert_child(js_elem) # type: ignore # TODO: Update to selectolax 0.3.25\n did_modify_html = True\n\n transformed = cast(str, tree.html)\n if did_modify_html:\n content_ = transformed.encode()\n\n # Return the same type as we were given\n output = content_.decode() if isinstance(content, str) else content_\n output = mark_safe(output) if is_safestring else output\n return cast(TContent, output)\n
Classes:
-
Operator
\u2013Operator describes something that somehow changes the inputs
-
SpreadOperator
\u2013Operator that inserts one or more kwargs at the specified location.
Functions:
-
process_aggregate_kwargs
\u2013This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs
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 insrc/django_components/expression.py
"},{"location":"reference/django_components/#django_components.expression.process_aggregate_kwargs","title":"process_aggregate_kwargs","text":"def __init__(self, expr: Expression) -> None:\n self.expr = expr\n
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 theattrs
dict.So, instead, we allow to \"aggregate\" props into a dict. So all props that start with
attrs:
, likeattrs:class=\"text-red\"
, will be collected into a dict at keyattrs
.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 insrc/django_components/expression.py
"},{"location":"reference/django_components/#django_components.finders","title":"finders","text":"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
Classes:
-
ComponentsFileSystemFinder
\u2013A static files finder based on
FileSystemFinder
.
ComponentsFileSystemFinder(app_names: Any = None, *args: Any, **kwargs: Any)\n
Bases:
BaseFinder
A static files finder based on
FileSystemFinder
.Differences: - This finder uses
COMPONENTS.dirs
setting to locate files instead ofSTATICFILES_DIRS
. - Whether a file withinCOMPONENTS.dirs
is considered a STATIC file is configured byCOMPONENTS.static_files_allowed
andCOMPONENTS.static_files_forbidden
. - IfCOMPONENTS.dirs
is not set, defaults tosettings.BASE_DIR / \"components\"
Methods:
-
find
\u2013Look for files in the extra locations as defined in COMPONENTS.dirs.
-
find_location
\u2013Find a requested static file in a location and return the found
-
list
\u2013List all files in all locations.
src/django_components/finders.py
"},{"location":"reference/django_components/#django_components.finders.ComponentsFileSystemFinder.find","title":"find","text":"def __init__(self, app_names: Any = None, *args: Any, **kwargs: Any) -> None:\n component_dirs = [str(p) for p in get_component_dirs()]\n\n # NOTE: The rest of the __init__ is the same as `django.contrib.staticfiles.finders.FileSystemFinder`,\n # but using our locations instead of STATICFILES_DIRS.\n\n # List of locations with static files\n self.locations: List[Tuple[str, str]] = []\n\n # Maps dir paths to an appropriate storage instance\n self.storages: Dict[str, FileSystemStorage] = {}\n for root in component_dirs:\n if isinstance(root, (list, tuple)):\n prefix, root = root\n else:\n prefix = \"\"\n if (prefix, root) not in self.locations:\n self.locations.append((prefix, root))\n for prefix, root in self.locations:\n filesystem_storage = FileSystemStorage(location=root)\n filesystem_storage.prefix = prefix\n self.storages[root] = filesystem_storage\n\n super().__init__(*args, **kwargs)\n
find(path: str, all: bool = False) -> Union[List[str], str]\n
Look for files in the extra locations as defined in COMPONENTS.dirs.
Source code insrc/django_components/finders.py
"},{"location":"reference/django_components/#django_components.finders.ComponentsFileSystemFinder.find_location","title":"find_location","text":"def find(self, path: str, all: bool = False) -> Union[List[str], str]:\n \"\"\"\n Look for files in the extra locations as defined in COMPONENTS.dirs.\n \"\"\"\n matches: List[str] = []\n for prefix, root in self.locations:\n if root not in searched_locations:\n searched_locations.append(root)\n matched_path = self.find_location(root, path, prefix)\n if matched_path:\n if not all:\n return matched_path\n matches.append(matched_path)\n return matches\n
find_location(root: str, path: str, prefix: Optional[str] = None) -> Optional[str]\n
Find a requested static file in a location and return the found absolute path (or
Source code inNone
if no match).src/django_components/finders.py
"},{"location":"reference/django_components/#django_components.finders.ComponentsFileSystemFinder.list","title":"list","text":"def find_location(self, root: str, path: str, prefix: Optional[str] = None) -> Optional[str]:\n \"\"\"\n Find a requested static file in a location and return the found\n absolute path (or ``None`` if no match).\n \"\"\"\n if prefix:\n prefix = \"%s%s\" % (prefix, os.sep)\n if not path.startswith(prefix):\n return None\n path = path.removeprefix(prefix)\n path = safe_join(root, path)\n\n if os.path.exists(path) and self._is_path_valid(path):\n return path\n return None\n
list(ignore_patterns: List[str]) -> Iterable[Tuple[str, FileSystemStorage]]\n
List all files in all locations.
Source code insrc/django_components/finders.py
"},{"location":"reference/django_components/#django_components.library","title":"library","text":"def list(self, ignore_patterns: List[str]) -> Iterable[Tuple[str, FileSystemStorage]]:\n \"\"\"\n List all files in all locations.\n \"\"\"\n for prefix, root in self.locations:\n # Skip nonexistent directories.\n if os.path.isdir(root):\n storage = self.storages[root]\n for path in get_files(storage, ignore_patterns):\n if self._is_path_valid(path):\n yield path, storage\n
Module for interfacing with Django's Library (
django.template.library
)Classes:
-
TagProtectedError
\u2013The way the
TagFormatter
works is that,
Attributes:
-
PROTECTED_TAGS
\u2013These are the names that users cannot choose for their components,
module-attribute
","text":"PROTECTED_TAGS = ['component_css_dependencies', 'component_js_dependencies', 'fill', 'html_attrs', 'provide', 'slot']\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.library.TagProtectedError","title":"TagProtectedError","text":"Bases:
Exception
The way the
TagFormatter
works is that, based on which start and end tags are used for rendering components, theComponentRegistry
behind the scenes un-/registers the template tags with the associated instance of Django'sLibrary
.In other words, if I have registered a component
\"table\"
, and I use the shorthand syntax:{% table ... %}\n{% endtable %}\n
Then
ComponentRegistry
registers the tagtable
onto the Django's Library instance.However, that means that if we registered a component
\"slot\"
, then we would overwrite the{% slot %}
tag from django_components.Thus, this exception is raised when a component is attempted to be registered under a forbidden name, such that it would overwrite one of django_component's own template tags.
"},{"location":"reference/django_components/#django_components.management","title":"management","text":"Modules:
-
commands
\u2013
Modules:
-
startcomponent
\u2013
Classes:
-
Command
\u2013
Bases:
"},{"location":"reference/django_components/#django_components.management.commands.startcomponent.Command--management-command-usage","title":"Management Command Usage","text":"BaseCommand
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
"},{"location":"reference/django_components/#django_components.management.commands.startcomponent.Command--management-command-examples","title":"Management Command Examples","text":"<name>
,<path>
,<js_filename>
,<css_filename>
, and<template_filename>
with your desired values.Here are some examples of how you can use the command:
"},{"location":"reference/django_components/#django_components.management.commands.startcomponent.Command--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
"},{"location":"reference/django_components/#django_components.management.commands.startcomponent.Command--creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"my_component
in thecomponents
directory of your Django project. The JavaScript, CSS, and template files will be namedscript.js
,style.css
, andtemplate.html
, respectively.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
"},{"location":"reference/django_components/#django_components.management.commands.startcomponent.Command--overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"new_component
in themy_components
directory. The JavaScript, CSS, and template files will be namedmy_script.js
,my_style.css
, andmy_template.html
, respectively.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
"},{"location":"reference/django_components/#django_components.management.commands.startcomponent.Command--simulating-component-creation","title":"Simulating Component Creation","text":"my_component
if it exists.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
"},{"location":"reference/django_components/#django_components.middleware","title":"middleware","text":"my_component
without creating any files.Classes:
-
ComponentDependencyMiddleware
\u2013Middleware that inserts CSS/JS dependencies for all rendered
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 insrc/django_components/dependencies.py
"},{"location":"reference/django_components/#django_components.node","title":"node","text":"def __init__(self, get_response: \"Callable[[HttpRequest], HttpResponse]\") -> None:\n self.get_response = get_response\n\n # NOTE: Required to work with async\n if iscoroutinefunction(self.get_response):\n markcoroutinefunction(self)\n
Classes:
-
BaseNode
\u2013Shared behavior for our subclasses of Django's
Node
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
Source code inNode
src/django_components/node.py
"},{"location":"reference/django_components/#django_components.provide","title":"provide","text":"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
Classes:
-
ProvideNode
\u2013Implementation of the
{% provide %}
tag.
ProvideNode(nodelist: NodeList, trace_id: str, node_id: Optional[str] = None, kwargs: Optional[RuntimeKwargs] = None)\n
Bases:
BaseNode
Implementation of the
Source code in{% provide %}
tag. For more info seeComponent.inject
.src/django_components/provide.py
"},{"location":"reference/django_components/#django_components.slots","title":"slots","text":"def __init__(\n self,\n nodelist: NodeList,\n trace_id: str,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.nodelist = nodelist\n self.node_id = node_id or gen_id()\n self.trace_id = trace_id\n self.kwargs = kwargs or RuntimeKwargs({})\n
Classes:
-
FillNode
\u2013Node corresponding to
{% fill %}
-
Slot
\u2013This class holds the slot content function along with related metadata.
-
SlotFill
\u2013SlotFill describes what WILL be rendered.
-
SlotIsFilled
\u2013Dictionary that returns
True
if the slot is filled (key is found),False
otherwise. -
SlotNode
\u2013Node corresponding to
{% slot %}
-
SlotRef
\u2013SlotRef allows to treat a slot as a variable. The slot is rendered only once
Functions:
-
resolve_fills
\u2013Given a component body (
django.template.NodeList
), find all slot fills,
FillNode(nodelist: NodeList, kwargs: RuntimeKwargs, trace_id: str, node_id: Optional[str] = None)\n
Bases:
BaseNode
Node corresponding to
Source code in{% fill %}
src/django_components/slots.py
"},{"location":"reference/django_components/#django_components.slots.Slot","title":"Slotdef __init__(\n self,\n nodelist: NodeList,\n kwargs: RuntimeKwargs,\n trace_id: str,\n node_id: Optional[str] = None,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.trace_id = trace_id\n
dataclass
","text":"Slot(content_func: SlotFunc[TSlotData])\n
Bases:
Generic[TSlotData]
This class holds the slot content function along with related metadata.
"},{"location":"reference/django_components/#django_components.slots.SlotFill","title":"SlotFilldataclass
","text":"SlotFill(name: str, is_filled: bool, slot: Slot[TSlotData])\n
Bases:
Generic[TSlotData]
SlotFill describes what WILL be rendered.
The fill may be provided by the user from the outside (
is_filled=True
), or it may be the default content of the slot (is_filled=False
).Attributes:
-
name
(str
) \u2013Name of the slot.
instance-attribute
","text":"name: str\n
Name of the slot.
"},{"location":"reference/django_components/#django_components.slots.SlotIsFilled","title":"SlotIsFilled","text":"SlotIsFilled(fills: Dict, *args: Any, **kwargs: Any)\n
Bases:
dict
Dictionary that returns
Source code inTrue
if the slot is filled (key is found),False
otherwise.src/django_components/slots.py
"},{"location":"reference/django_components/#django_components.slots.SlotNode","title":"SlotNode","text":"def __init__(self, fills: Dict, *args: Any, **kwargs: Any) -> None:\n escaped_fill_names = {_escape_slot_name(fill_name): True for fill_name in fills.keys()}\n super().__init__(escaped_fill_names, *args, **kwargs)\n
SlotNode(\n nodelist: NodeList,\n trace_id: str,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n is_required: bool = False,\n is_default: bool = False,\n)\n
Bases:
BaseNode
Node corresponding to
Source code in{% slot %}
src/django_components/slots.py
"},{"location":"reference/django_components/#django_components.slots.SlotRef","title":"SlotRef","text":"def __init__(\n self,\n nodelist: NodeList,\n trace_id: str,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n is_required: bool = False,\n is_default: bool = False,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.is_required = is_required\n self.is_default = is_default\n self.trace_id = trace_id\n
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
Source code in{{ my_lazy_slot }}
, it will output the contents of the slot.src/django_components/slots.py
"},{"location":"reference/django_components/#django_components.slots.resolve_fills","title":"resolve_fills","text":"def __init__(self, slot: \"SlotNode\", context: Context):\n self._slot = slot\n self._context = context\n
resolve_fills(context: Context, nodelist: NodeList, component_name: str) -> Dict[SlotName, Slot]\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 finds 2 fill nodes: \"first_fill\" and \"second_fill\", and formats them as slot functions, returning:
{\n \"first_fill\": SlotFunc(...),\n \"second_fill\": SlotFunc(...),\n}\n
If no fill nodes are found, then the content is treated as default slot content.
{\n DEFAULT_SLOT_KEY: SlotFunc(...),\n}\n
This function also handles for-loops, if/else statements, or include tags to generate fill tags:
Source code in{% component \"mycomponent\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name %}\n {% slot name=slot_name / %}\n {% endfill %}\n {% endfor %}\n{% endcomponent %}\n
src/django_components/slots.py
"},{"location":"reference/django_components/#django_components.tag_formatter","title":"tag_formatter","text":"def resolve_fills(\n context: Context,\n nodelist: NodeList,\n component_name: str,\n) -> Dict[SlotName, Slot]:\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\n Then this function finds 2 fill nodes: \"first_fill\" and \"second_fill\",\n and formats them as slot functions, returning:\n\n ```python\n {\n \"first_fill\": SlotFunc(...),\n \"second_fill\": SlotFunc(...),\n }\n ```\n\n If no fill nodes are found, then the content is treated as default slot content.\n\n ```python\n {\n DEFAULT_SLOT_KEY: SlotFunc(...),\n }\n ```\n\n This function also handles for-loops, if/else statements, or include tags to generate fill tags:\n\n ```django\n {% component \"mycomponent\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name %}\n {% slot name=slot_name / %}\n {% endfill %}\n {% endfor %}\n {% endcomponent %}\n ```\n \"\"\"\n slots: Dict[SlotName, Slot] = {}\n\n if not nodelist:\n return slots\n\n maybe_fills = _extract_fill_content(nodelist, context, component_name)\n\n # The content has no fills, so treat it as default slot, e.g.:\n # {% component \"mycomponent\" %}\n # Hello!\n # {% if True %} 123 {% endif %}\n # {% endcomponent %}\n if maybe_fills is False:\n # Ignore empty content between `{% component %} ... {% endcomponent %}` tags\n nodelist_is_empty = not len(nodelist) or all(\n isinstance(node, TextNode) and not node.s.strip() for node in nodelist\n )\n\n if not nodelist_is_empty:\n slots[DEFAULT_SLOT_KEY] = _nodelist_to_slot_render_func(\n DEFAULT_SLOT_KEY,\n nodelist,\n data_var=None,\n default_var=None,\n )\n\n # The content has fills\n else:\n # NOTE: If slot fills are explicitly defined, we use them even if they are empty (or only whitespace).\n # This is different from the default slot, where we ignore empty content.\n for fill in maybe_fills:\n slots[fill.name] = _nodelist_to_slot_render_func(\n slot_name=fill.name,\n nodelist=fill.fill.nodelist,\n data_var=fill.data_var,\n default_var=fill.default_var,\n extra_context=fill.extra_context,\n )\n\n return slots\n
Classes:
-
ComponentFormatter
\u2013The original django_component's component tag formatter, it uses the
{% component %}
-
InternalTagFormatter
\u2013Internal wrapper around user-provided TagFormatters, so that we validate the outputs.
-
ShorthandComponentFormatter
\u2013The component tag formatter that uses
{% <name> %}
/{% end<name> %}
tags. -
TagFormatterABC
\u2013Abstract base class for defining custom tag formatters.
-
TagResult
\u2013The return value from
TagFormatter.parse()
.
Functions:
-
get_tag_formatter
\u2013Returns an instance of the currently configured component tag formatter.
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 given as the first positional arg.Example as block:
{% component \"mycomp\" abc=123 %}\n {% fill \"myfill\" %}\n ...\n {% endfill %}\n{% endcomponent %}\n
Example as inlined tag:
Source code in{% component \"mycomp\" abc=123 / %}\n
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.tag_formatter.InternalTagFormatter","title":"InternalTagFormatter","text":"def __init__(self, tag: str):\n self.tag = tag\n
InternalTagFormatter(tag_formatter: TagFormatterABC)\n
Internal wrapper around user-provided TagFormatters, so that we validate the outputs.
Source code insrc/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.tag_formatter.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":"def __init__(self, tag_formatter: TagFormatterABC):\n self.tag_formatter = tag_formatter\n
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:
"},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC","title":"TagFormatterABC","text":"{% mycomp abc=123 / %}\n
Bases:
ABC
Abstract base class for defining custom tag formatters.
Tag formatters define how the component tags are used in the template.
Read more about Tag formatter.
For example, with the default tag formatter (
ComponentFormatter
), components are written as:{% component \"comp_name\" %}\n{% endcomponent %}\n
While with the shorthand tag formatter (
ShorthandComponentFormatter
), components are written as:{% comp_name %}\n{% endcomp_name %}\n
Example:
Implementation for
ShorthandComponentFormatter
:from djagno_components import TagFormatterABC, TagResult\n\nclass ShorthandComponentFormatter(TagFormatterABC):\n def start_tag(self, name: str) -> str:\n return name\n\n def end_tag(self, name: str) -> str:\n return f\"end{name}\"\n\n def parse(self, tokens: List[str]) -> TagResult:\n tokens = [*tokens]\n name = tokens.pop(0)\n return TagResult(name, tokens)\n
Methods:
-
end_tag
\u2013Formats the end tag of a block component.
-
parse
\u2013Given the tokens (words) passed to a component start tag, this function extracts
-
start_tag
\u2013Formats the start tag of a component.
abstractmethod
","text":"end_tag(name: str) -> str\n
Formats the end tag of a block component.
Parameters:
-
name
(str
) \u2013Component's registered name. Required.
Returns:
-
str
(str
) \u2013The formatted end tag.
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC.parse","title":"parse@abc.abstractmethod\ndef end_tag(self, name: str) -> str:\n \"\"\"\n Formats the end tag of a block component.\n\n Args:\n name (str): Component's registered name. Required.\n\n Returns:\n str: The formatted end tag.\n \"\"\"\n ...\n
abstractmethod
","text":"parse(tokens: List[str]) -> TagResult\n
Given the tokens (words) passed to a component start tag, this function extracts the component name from the tokens list, and returns
TagResult
, which is a tuple of(component_name, remaining_tokens)
.Parameters:
-
tokens
([List(str]
) \u2013List of tokens passed to the component tag.
Returns:
-
TagResult
(TagResult
) \u2013Parsed component name and remaining tokens.
Example:
Assuming we used a component in a template like this:
{% component \"my_comp\" key=val key2=val2 %}\n{% endcomponent %}\n
This function receives a list of tokens:
['component', '\"my_comp\"', 'key=val', 'key2=val2']\n
component
is the tag name, which we drop.\"my_comp\"
is the component name, but we must remove the extra quotes.- The remaining tokens we pass unmodified, as that's the input to the component.
So in the end, we return:
Source code inTagResult('my_comp', ['key=val', 'key2=val2'])\n
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC.start_tag","title":"start_tag@abc.abstractmethod\ndef parse(self, tokens: List[str]) -> TagResult:\n \"\"\"\n Given the tokens (words) passed to a component start tag, this function extracts\n the component name from the tokens list, and returns\n [`TagResult`](../api#django_components.TagResult),\n which is a tuple of `(component_name, remaining_tokens)`.\n\n Args:\n tokens [List(str]): List of tokens passed to the component tag.\n\n Returns:\n TagResult: Parsed component name and remaining tokens.\n\n **Example:**\n\n Assuming we used a component in a template like this:\n\n ```django\n {% component \"my_comp\" key=val key2=val2 %}\n {% endcomponent %}\n ```\n\n This function receives a list of tokens:\n\n ```python\n ['component', '\"my_comp\"', 'key=val', 'key2=val2']\n ```\n\n - `component` is the tag name, which we drop.\n - `\"my_comp\"` is the component name, but we must remove the extra quotes.\n - The remaining tokens we pass unmodified, as that's the input to the component.\n\n So in the end, we return:\n\n ```python\n TagResult('my_comp', ['key=val', 'key2=val2'])\n ```\n \"\"\"\n ...\n
abstractmethod
","text":"start_tag(name: str) -> str\n
Formats the start tag of a component.
Parameters:
-
name
(str
) \u2013Component's registered name. Required.
Returns:
-
str
(str
) \u2013The formatted start tag.
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.tag_formatter.TagResult","title":"TagResult","text":"@abc.abstractmethod\ndef start_tag(self, name: str) -> str:\n \"\"\"\n Formats the start tag of a component.\n\n Args:\n name (str): Component's registered name. Required.\n\n Returns:\n str: The formatted start tag.\n \"\"\"\n ...\n
Bases:
NamedTuple
The return value from
TagFormatter.parse()
.Read more about Tag formatter.
Attributes:
-
component_name
(str
) \u2013Component name extracted from the template tag
-
tokens
(List[str]
) \u2013Remaining tokens (words) that were passed to the tag, with component name removed
instance-attribute
","text":"component_name: str\n
Component name extracted from the template tag
For example, if we had tag
{% component \"my_comp\" key=val key2=val2 %}\n
Then
"},{"location":"reference/django_components/#django_components.tag_formatter.TagResult.tokens","title":"tokenscomponent_name
would bemy_comp
.instance-attribute
","text":"tokens: List[str]\n
Remaining tokens (words) that were passed to the tag, with component name removed
For example, if we had tag
{% component \"my_comp\" key=val key2=val2 %}\n
Then
"},{"location":"reference/django_components/#django_components.tag_formatter.get_tag_formatter","title":"get_tag_formatter","text":"tokens
would be['key=val', 'key2=val2']
.get_tag_formatter(registry: ComponentRegistry) -> InternalTagFormatter\n
Returns an instance of the currently configured component tag formatter.
Source code insrc/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.template","title":"template","text":"def get_tag_formatter(registry: \"ComponentRegistry\") -> InternalTagFormatter:\n \"\"\"Returns an instance of the currently configured component tag formatter.\"\"\"\n # Allow users to configure the component TagFormatter\n formatter_cls_or_str = registry.settings.tag_formatter\n\n if isinstance(formatter_cls_or_str, str):\n tag_formatter: TagFormatterABC = import_string(formatter_cls_or_str)\n else:\n tag_formatter = formatter_cls_or_str\n\n return InternalTagFormatter(tag_formatter)\n
Functions:
-
cached_template
\u2013Create a Template instance that will be cached as per the
cached_template(\n template_string: str,\n template_cls: Optional[Type[Template]] = None,\n origin: Optional[Origin] = None,\n name: Optional[str] = None,\n engine: Optional[Any] = None,\n) -> Template\n
Create a Template instance that will be cached as per the
COMPONENTS.template_cache_size
setting.Parameters:
-
template_string
(str
) \u2013Template as a string, same as the first argument to Django's
Template
. Required. -
template_cls
(Type[Template]
, default:None
) \u2013Specify the Template class that should be instantiated. Defaults to Django's
Template
class. -
origin
(Type[Origin]
, default:None
) \u2013Sets
Template.Origin
. -
name
(Type[str]
, default:None
) \u2013Sets
Template.name
-
engine
(Type[Any]
, default:None
) \u2013Sets
Template.engine
Source code infrom django_components import cached_template\n\ntemplate = cached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n pass\n\ntemplate = cached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n)\n
src/django_components/template.py
"},{"location":"reference/django_components/#django_components.template_loader","title":"template_loader","text":"def cached_template(\n template_string: str,\n template_cls: Optional[Type[Template]] = None,\n origin: Optional[Origin] = None,\n name: Optional[str] = None,\n engine: Optional[Any] = None,\n) -> Template:\n \"\"\"\n Create a Template instance that will be cached as per the\n [`COMPONENTS.template_cache_size`](../settings#django_components.app_settings.ComponentsSettings.template_cache_size)\n setting.\n\n Args:\n template_string (str): Template as a string, same as the first argument to Django's\\\n [`Template`](https://docs.djangoproject.com/en/5.1/topics/templates/#template). Required.\n template_cls (Type[Template], optional): Specify the Template class that should be instantiated.\\\n Defaults to Django's [`Template`](https://docs.djangoproject.com/en/5.1/topics/templates/#template) class.\n origin (Type[Origin], optional): Sets \\\n [`Template.Origin`](https://docs.djangoproject.com/en/5.1/howto/custom-template-backend/#origin-api-and-3rd-party-integration).\n name (Type[str], optional): Sets `Template.name`\n engine (Type[Any], optional): Sets `Template.engine`\n\n ```python\n from django_components import cached_template\n\n template = cached_template(\"Variable: {{ variable }}\")\n\n # You can optionally specify Template class, and other Template inputs:\n class MyTemplate(Template):\n pass\n\n template = cached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n )\n ```\n \"\"\" # noqa: E501\n template = _create_template(template_cls or Template, template_string, engine)\n\n # Assign the origin and name separately, so the caching doesn't depend on them\n # Since we might be accessing a template from cache, we want to define these only once\n if not getattr(template, \"_dc_cached\", False):\n template.origin = origin or Origin(UNKNOWN_SOURCE)\n template.name = name\n template._dc_cached = True\n\n return template\n
Template loader that loads templates from each Django app's \"components\" directory.
Classes:
-
Loader
\u2013
Bases:
Loader
Methods:
-
get_dirs
\u2013Prepare directories that may contain component files:
get_dirs(include_apps: bool = True) -> List[Path]\n
Prepare directories that may contain component files:
Searches for dirs set in
COMPONENTS.dirs
settings. If none set, defaults to searching for a \"components\" app. The dirs inCOMPONENTS.dirs
must be absolute paths.In addition to that, also all apps are checked for
[app]/components
dirs.Paths are accepted only if they resolve to a directory. E.g.
/path/to/django_project/my_app/components/
.
Source code inBASE_DIR
setting is required.src/django_components/template_loader.py
"},{"location":"reference/django_components/#django_components.template_parser","title":"template_parser","text":"def get_dirs(self, include_apps: bool = True) -> List[Path]:\n \"\"\"\n Prepare directories that may contain component files:\n\n Searches for dirs set in `COMPONENTS.dirs` settings. If none set, defaults to searching\n for a \"components\" app. The dirs in `COMPONENTS.dirs` must be absolute paths.\n\n In addition to that, also all apps are checked for `[app]/components` dirs.\n\n Paths are accepted only if they resolve to a directory.\n E.g. `/path/to/django_project/my_app/components/`.\n\n `BASE_DIR` setting is required.\n \"\"\"\n return get_component_dirs(include_apps)\n
Overrides for the Django Template system to allow finer control over template parsing.
Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py
Functions:
-
parse_bits
\u2013Parse bits for template tag helpers simple_tag and inclusion_tag, in
-
token_kwargs
\u2013Parse token keyword arguments and return a dictionary of the arguments
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 insrc/django_components/template_parser.py
"},{"location":"reference/django_components/#django_components.template_parser.token_kwargs","title":"token_kwargs","text":"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
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
Source code inbits
to be keyword arguments, so return the dictionary as soon as an invalid argument format is reached.src/django_components/template_parser.py
"},{"location":"reference/django_components/#django_components.templatetags","title":"templatetags","text":"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
Modules:
-
component_tags
\u2013
Functions:
-
component
\u2013Renders one of the components that was previously registered with
-
component_css_dependencies
\u2013Marks location where CSS link tags should be rendered after the whole HTML has been generated.
-
component_js_dependencies
\u2013Marks location where JS link tags should be rendered after the whole HTML has been generated.
-
fill
\u2013Use this tag to insert content into component's slots.
-
html_attrs
\u2013Generate HTML attributes (
key=\"value\"
), combining data from multiple sources, -
provide
\u2013The \"provider\" part of the provide / inject feature.
-
slot
\u2013Slot tag marks a place inside a component where content can be inserted
Bases:
NamedTuple
Definition of args, kwargs, flags, etc, for a template tag.
Attributes:
-
end_tag
(Optional[str]
) \u2013End tag.
-
flags
(Optional[List[str]]
) \u2013List of allowed flags.
-
keywordonly_args
(Optional[Union[bool, List[str]]]
) \u2013Parameters that MUST be given only as kwargs (not accounting for
pos_or_keyword_args
). -
optional_kwargs
(Optional[List[str]]
) \u2013Specify which kwargs can be optional.
-
pos_or_keyword_args
(Optional[List[str]]
) \u2013Like regular Python kwargs, these can be given EITHER as positional OR as keyword arguments.
-
positional_args_allow_extra
(bool
) \u2013If
True
, allows variable number of positional args, e.g.{% mytag val1 1234 val2 890 ... %}
-
positional_only_args
(Optional[List[str]]
) \u2013Arguments that MUST be given as positional args.
-
repeatable_kwargs
(Optional[Union[bool, List[str]]]
) \u2013Whether this tag allows all or certain kwargs to be repeated.
-
tag
(str
) \u2013Tag name. E.g.
\"slot\"
means the tag is written like so{% slot ... %}
class-attribute
instance-attribute
","text":"end_tag: Optional[str] = None\n
End tag.
E.g.
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.TagSpec.flags","title":"flags\"endslot\"
means anything between the start tag and{% endslot %}
is considered the slot's body.class-attribute
instance-attribute
","text":"flags: Optional[List[str]] = None\n
List of allowed flags.
Flags are like kwargs, but without the value part. E.g. in
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.TagSpec.keywordonly_args","title":"keywordonly_args{% mytag only required %}
: -only
andrequired
are treated asonly=True
andrequired=True
if present - and treated asonly=False
andrequired=False
if omittedclass-attribute
instance-attribute
","text":"keywordonly_args: Optional[Union[bool, List[str]]] = False\n
Parameters that MUST be given only as kwargs (not accounting for
pos_or_keyword_args
).- If
False
, NO extra kwargs allowed. - If
True
, ANY number of extra kwargs allowed. - If a list of strings, e.g.
[\"class\", \"style\"]
, then only those kwargs are allowed.
class-attribute
instance-attribute
","text":"optional_kwargs: Optional[List[str]] = None\n
Specify which kwargs can be optional.
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.TagSpec.pos_or_keyword_args","title":"pos_or_keyword_argsclass-attribute
instance-attribute
","text":"pos_or_keyword_args: Optional[List[str]] = None\n
Like regular Python kwargs, these can be given EITHER as positional OR as keyword arguments.
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.TagSpec.positional_args_allow_extra","title":"positional_args_allow_extraclass-attribute
instance-attribute
","text":"positional_args_allow_extra: bool = False\n
If
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.TagSpec.positional_only_args","title":"positional_only_argsTrue
, allows variable number of positional args, e.g.{% mytag val1 1234 val2 890 ... %}
class-attribute
instance-attribute
","text":"positional_only_args: Optional[List[str]] = None\n
Arguments that MUST be given as positional args.
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.TagSpec.repeatable_kwargs","title":"repeatable_kwargsclass-attribute
instance-attribute
","text":"repeatable_kwargs: Optional[Union[bool, List[str]]] = False\n
Whether this tag allows all or certain kwargs to be repeated.
- If
False
, NO kwargs can repeat. - If
True
, ALL kwargs can repeat. - If a list of strings, e.g.
[\"class\", \"style\"]
, then only those kwargs can repeat.
E.g.
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.TagSpec.tag","title":"tag[\"class\"]
means one can write{% mytag class=\"one\" class=\"two\" %}
instance-attribute
","text":"tag: str\n
Tag name. E.g.
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.component","title":"component","text":"\"slot\"
means the tag is written like so{% slot ... %}
component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str, tag_spec: TagSpec) -> ComponentNode\n
Renders one of the components that was previously registered with
@register()
decorator.Args:
name
(str, required): Registered name of the component to render- All other args and kwargs are defined based on the component itself.
If you defined a component
\"my_table\"
from django_component import Component, register\n\n@register(\"my_table\")\nclass MyTable(Component):\n template = \"\"\"\n <table>\n <thead>\n {% for header in headers %}\n <th>{{ header }}</th>\n {% endfor %}\n </thead>\n <tbody>\n {% for row in rows %}\n <tr>\n {% for cell in row %}\n <td>{{ cell }}</td>\n {% endfor %}\n </tr>\n {% endfor %}\n <tbody>\n </table>\n \"\"\"\n\n def get_context_data(self, rows: List, headers: List):\n return {\n \"rows\": rows,\n \"headers\": headers,\n }\n
Then you can render this component by referring to
MyTable
via its registered name\"my_table\"
:
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.component--component-input","title":"Component input","text":"{% component \"my_table\" rows=rows headers=headers ... / %}\n
Positional and keyword arguments can be literals or template variables.
The component name must be a single- or double-quotes string and must be either:
-
The first positional argument after
component
:{% component \"my_table\" rows=rows headers=headers ... / %}\n
-
Passed as kwarg
name
:{% component rows=rows headers=headers name=\"my_table\" ... / %}\n
If the component defined any slots, you can pass in the content to be placed inside those slots by inserting
{% fill %}
tags, directly within the{% component %}
tag:
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.component--isolating-components","title":"Isolating components","text":"{% component \"my_table\" rows=rows headers=headers ... / %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n{% endcomponent %}\n
By default, components behave similarly to Django's
{% include %}
, and the template inside the component has access to the variables defined in the outer template.You can selectively isolate a component, using the
only
flag, so that the inner template can access only the data that was explicitly passed to it:
Source code in{% component \"name\" positional_arg keyword_arg=value ... only %}\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"@with_tag_spec(\n TagSpec(\n tag=\"component\",\n end_tag=\"endcomponent\",\n positional_only_args=[],\n positional_args_allow_extra=True, # Allow many args\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[COMP_ONLY_FLAG],\n )\n)\ndef component(\n parser: Parser,\n token: Token,\n registry: ComponentRegistry,\n tag_name: str,\n tag_spec: TagSpec,\n) -> ComponentNode:\n \"\"\"\n Renders one of the components that was previously registered with\n [`@register()`](./api.md#django_components.register)\n decorator.\n\n **Args:**\n\n - `name` (str, required): Registered name of the component to render\n - All other args and kwargs are defined based on the component itself.\n\n If you defined a component `\"my_table\"`\n\n ```python\n from django_component import Component, register\n\n @register(\"my_table\")\n class MyTable(Component):\n template = \\\"\\\"\\\"\n <table>\n <thead>\n {% for header in headers %}\n <th>{{ header }}</th>\n {% endfor %}\n </thead>\n <tbody>\n {% for row in rows %}\n <tr>\n {% for cell in row %}\n <td>{{ cell }}</td>\n {% endfor %}\n </tr>\n {% endfor %}\n <tbody>\n </table>\n \\\"\\\"\\\"\n\n def get_context_data(self, rows: List, headers: List):\n return {\n \"rows\": rows,\n \"headers\": headers,\n }\n ```\n\n Then you can render this component by referring to `MyTable` via its\n registered name `\"my_table\"`:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n ```\n\n ### Component input\n\n Positional and keyword arguments can be literals or template variables.\n\n The component name must be a single- or double-quotes string and must\n be either:\n\n - The first positional argument after `component`:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n ```\n\n - Passed as kwarg `name`:\n\n ```django\n {% component rows=rows headers=headers name=\"my_table\" ... / %}\n ```\n\n ### Inserting into slots\n\n If the component defined any [slots](../concepts/fundamentals/slots.md), you can\n pass in the content to be placed inside those slots by inserting [`{% fill %}`](#fill) tags,\n directly within the `{% component %}` tag:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Isolating components\n\n By default, components behave similarly to Django's\n [`{% include %}`](https://docs.djangoproject.com/en/5.1/ref/templates/builtins/#include),\n and the template inside the component has access to the variables defined in the outer template.\n\n You can selectively isolate a component, using the `only` flag, so that the inner template\n can access only the data that was explicitly passed to it:\n\n ```django\n {% component \"name\" positional_arg keyword_arg=value ... only %}\n ```\n \"\"\"\n _fix_nested_tags(parser, token)\n bits = token.split_contents()\n\n # Let the TagFormatter pre-process the tokens\n formatter = get_tag_formatter(registry)\n result = formatter.parse([*bits])\n end_tag = formatter.end_tag(result.component_name)\n\n # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n bits = [bits[0], *result.tokens]\n token.contents = \" \".join(bits)\n\n tag = _parse_tag(\n parser,\n token,\n TagSpec(\n **{\n **tag_spec._asdict(),\n \"tag\": tag_name,\n \"end_tag\": end_tag,\n }\n ),\n )\n\n # Check for isolated context keyword\n isolated_context = tag.flags[COMP_ONLY_FLAG]\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n body = tag.parse_body()\n\n component_node = ComponentNode(\n name=result.component_name,\n args=tag.args,\n kwargs=tag.kwargs,\n isolated_context=isolated_context,\n nodelist=body,\n node_id=tag.id,\n registry=registry,\n )\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n return component_node\n
component_css_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode\n
Marks location where CSS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted into the
<head>
tag of the HTML.If the generated HTML does NOT contain any
{% component_css_dependencies %}
tags, CSS links are by default inserted into the<head>
tag of the HTML. (See JS and CSS output locations)Note that there should be only one
Source code in{% component_css_dependencies %}
for the whole HTML document. If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"@register.tag(\"component_css_dependencies\")\n@with_tag_spec(\n TagSpec(\n tag=\"component_css_dependencies\",\n end_tag=None, # inline-only\n )\n)\ndef component_css_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode:\n \"\"\"\n Marks location where CSS link tags should be rendered after the whole HTML has been generated.\n\n Generally, this should be inserted into the `<head>` tag of the HTML.\n\n If the generated HTML does NOT contain any `{% component_css_dependencies %}` tags, CSS links\n are by default inserted into the `<head>` tag of the HTML. (See\n [JS and CSS output locations](../../concepts/advanced/rendering_js_css/#js-and-css-output-locations))\n\n Note that there should be only one `{% component_css_dependencies %}` for the whole HTML document.\n If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.\n \"\"\"\n # Parse to check that the syntax is valid\n _parse_tag(parser, token, tag_spec)\n return _component_dependencies(\"css\")\n
component_js_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode\n
Marks location where JS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted at the end of the
<body>
tag of the HTML.If the generated HTML does NOT contain any
{% component_js_dependencies %}
tags, JS scripts are by default inserted at the end of the<body>
tag of the HTML. (See JS and CSS output locations)Note that there should be only one
Source code in{% component_js_dependencies %}
for the whole HTML document. If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.fill","title":"fill","text":"@register.tag(name=\"component_js_dependencies\")\n@with_tag_spec(\n TagSpec(\n tag=\"component_js_dependencies\",\n end_tag=None, # inline-only\n )\n)\ndef component_js_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode:\n \"\"\"\n Marks location where JS link tags should be rendered after the whole HTML has been generated.\n\n Generally, this should be inserted at the end of the `<body>` tag of the HTML.\n\n If the generated HTML does NOT contain any `{% component_js_dependencies %}` tags, JS scripts\n are by default inserted at the end of the `<body>` tag of the HTML. (See\n [JS and CSS output locations](../../concepts/advanced/rendering_js_css/#js-and-css-output-locations))\n\n Note that there should be only one `{% component_js_dependencies %}` for the whole HTML document.\n If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.\n \"\"\"\n # Parse to check that the syntax is valid\n _parse_tag(parser, token, tag_spec)\n return _component_dependencies(\"js\")\n
fill(parser: Parser, token: Token, tag_spec: TagSpec) -> FillNode\n
Use this tag to insert content into component's slots.
{% fill %}
tag may be used only within a{% component %}..{% endcomponent %}
block. Runtime checks should prohibit other usages.Args:
name
(str, required): Name of the slot to insert this content into. Use\"default\"
for the default slot.default
(str, optional): This argument allows you to access the original content of the slot under the specified variable name. See Accessing original content of slotsdata
(str, optional): This argument allows you to access the data passed to the slot under the specified variable name. See Scoped slots
Examples:
Basic usage:
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.fill--accessing-slots-default-content-with-the-default-kwarg","title":"Accessing slot's default content with the{% component \"my_table\" %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n{% endcomponent %}\n
default
kwarg","text":"{# my_table.html #}\n<table>\n ...\n {% slot \"pagination\" %}\n < 1 | 2 | 3 >\n {% endslot %}\n</table>\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.fill--accessing-slots-data-with-the-data-kwarg","title":"Accessing slot's data with the{% component \"my_table\" %}\n {% fill \"pagination\" default=\"default_pag\" %}\n <div class=\"my-class\">\n {{ default_pag }}\n </div>\n {% endfill %}\n{% endcomponent %}\n
data
kwarg","text":"{# my_table.html #}\n<table>\n ...\n {% slot \"pagination\" pages=pages %}\n < 1 | 2 | 3 >\n {% endslot %}\n</table>\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.fill--accessing-slot-data-and-default-content-on-the-default-slot","title":"Accessing slot data and default content on the default slot","text":"{% component \"my_table\" %}\n {% fill \"pagination\" data=\"slot_data\" %}\n {% for page in slot_data.pages %}\n <a href=\"{{ page.link }}\">\n {{ page.index }}\n </a>\n {% endfor %}\n {% endfill %}\n{% endcomponent %}\n
To access slot data and the default slot content on the default slot, use
{% fill %}
withname
set to\"default\"
:
Source code in{% component \"button\" %}\n {% fill name=\"default\" data=\"slot_data\" default=\"default_slot\" %}\n You clicked me {{ slot_data.count }} times!\n {{ default_slot }}\n {% endfill %}\n{% endcomponent %}\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"@register.tag(\"fill\")\n@with_tag_spec(\n TagSpec(\n tag=\"fill\",\n end_tag=\"endfill\",\n positional_only_args=[],\n pos_or_keyword_args=[SLOT_NAME_KWARG],\n keywordonly_args=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n optional_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n repeatable_kwargs=False,\n )\n)\ndef fill(parser: Parser, token: Token, tag_spec: TagSpec) -> FillNode:\n \"\"\"\n Use this tag to insert content into component's slots.\n\n `{% fill %}` tag may be used only within a `{% component %}..{% endcomponent %}` block.\n Runtime checks should prohibit other usages.\n\n **Args:**\n\n - `name` (str, required): Name of the slot to insert this content into. Use `\"default\"` for\n the default slot.\n - `default` (str, optional): This argument allows you to access the original content of the slot\n under the specified variable name. See\n [Accessing original content of slots](../../concepts/fundamentals/slots#accessing-original-content-of-slots)\n - `data` (str, optional): This argument allows you to access the data passed to the slot\n under the specified variable name. See [Scoped slots](../../concepts/fundamentals/slots#scoped-slots)\n\n **Examples:**\n\n Basic usage:\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot's default content with the `default` kwarg\n\n ```django\n {# my_table.html #}\n <table>\n ...\n {% slot \"pagination\" %}\n < 1 | 2 | 3 >\n {% endslot %}\n </table>\n ```\n\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" default=\"default_pag\" %}\n <div class=\"my-class\">\n {{ default_pag }}\n </div>\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot's data with the `data` kwarg\n\n ```django\n {# my_table.html #}\n <table>\n ...\n {% slot \"pagination\" pages=pages %}\n < 1 | 2 | 3 >\n {% endslot %}\n </table>\n ```\n\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" data=\"slot_data\" %}\n {% for page in slot_data.pages %}\n <a href=\"{{ page.link }}\">\n {{ page.index }}\n </a>\n {% endfor %}\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot data and default content on the default slot\n\n To access slot data and the default slot content on the default slot,\n use `{% fill %}` with `name` set to `\"default\"`:\n\n ```django\n {% component \"button\" %}\n {% fill name=\"default\" data=\"slot_data\" default=\"default_slot\" %}\n You clicked me {{ slot_data.count }} times!\n {{ default_slot }}\n {% endfill %}\n {% endcomponent %}\n ```\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n fill_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n trace_id = f\"fill-id-{tag.id} ({fill_name_kwarg})\" if fill_name_kwarg else f\"fill-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id)\n\n body = tag.parse_body()\n fill_node = FillNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id, \"...Done!\")\n return fill_node\n
html_attrs(parser: Parser, token: Token, tag_spec: TagSpec) -> HtmlAttrsNode\n
Generate HTML attributes (
key=\"value\"
), combining data from multiple sources, whether its template variables or static text.It is designed to easily merge HTML attributes passed from outside with the internal. See how to in Passing HTML attributes to components.
Args:
attrs
(dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides values in thedefault
dictionary.default
(str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden with values in theattrs
dictionary.- Any extra kwargs will be appended to the corresponding keys
The attributes in
attrs
anddefaults
are merged and resulting dict is rendered as HTML attributes (key=\"value\"
).Extra kwargs (
key=value
) are concatenated to existing keys. So if we haveattrs = {\"class\": \"my-class\"}\n
Then
{% html_attrs attrs class=\"extra-class\" %}\n
will result in
class=\"my-class extra-class\"
.Example:
<div {% html_attrs\n attrs\n defaults:class=\"default-class\"\n class=\"extra-class\"\n data-id=\"123\"\n%}>\n
renders
<div class=\"my-class extra-class\" data-id=\"123\">\n
See more usage examples in HTML attributes.
Source code insrc/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.provide","title":"provide","text":"@register.tag(\"html_attrs\")\n@with_tag_spec(\n TagSpec(\n tag=\"html_attrs\",\n end_tag=None, # inline-only\n positional_only_args=[],\n pos_or_keyword_args=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n optional_kwargs=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n keywordonly_args=True,\n repeatable_kwargs=True,\n flags=[],\n )\n)\ndef html_attrs(parser: Parser, token: Token, tag_spec: TagSpec) -> HtmlAttrsNode:\n \"\"\"\n Generate HTML attributes (`key=\"value\"`), combining data from multiple sources,\n whether its template variables or static text.\n\n It is designed to easily merge HTML attributes passed from outside with the internal.\n See how to in [Passing HTML attributes to components](../../guides/howto/passing_html_attrs/).\n\n **Args:**\n\n - `attrs` (dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides\n values in the `default` dictionary.\n - `default` (str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden\n with values in the `attrs` dictionary.\n - Any extra kwargs will be appended to the corresponding keys\n\n The attributes in `attrs` and `defaults` are merged and resulting dict is rendered as HTML attributes\n (`key=\"value\"`).\n\n Extra kwargs (`key=value`) are concatenated to existing keys. So if we have\n\n ```python\n attrs = {\"class\": \"my-class\"}\n ```\n\n Then\n\n ```django\n {% html_attrs attrs class=\"extra-class\" %}\n ```\n\n will result in `class=\"my-class extra-class\"`.\n\n **Example:**\n ```django\n <div {% html_attrs\n attrs\n defaults:class=\"default-class\"\n class=\"extra-class\"\n data-id=\"123\"\n %}>\n ```\n\n renders\n\n ```html\n <div class=\"my-class extra-class\" data-id=\"123\">\n ```\n\n **See more usage examples in\n [HTML attributes](../../concepts/fundamentals/html_attributes#examples-for-html_attrs).**\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n return HtmlAttrsNode(\n kwargs=tag.kwargs,\n kwarg_pairs=tag.kwarg_pairs,\n )\n
provide(parser: Parser, token: Token, tag_spec: TagSpec) -> ProvideNode\n
The \"provider\" part of the provide / inject feature. Pass kwargs to this tag to define the provider's data. Any components defined within the
{% provide %}..{% endprovide %}
tags will be able to access this data withComponent.inject()
.This is similar to React's
ContextProvider
, or Vue'sprovide()
.Args:
name
(str, required): Provider name. This is the name you will then use inComponent.inject()
.**kwargs
: Any extra kwargs will be passed as the provided data.
Example:
Provide the \"user_data\" in parent component:
@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n <div>\n {% provide \"user_data\" user=user %}\n {% component \"child\" / %}\n {% endprovide %}\n </div>\n \"\"\"\n\n def get_context_data(self, user: User):\n return {\n \"user\": user,\n }\n
Since the \"child\" component is used within the
{% provide %} / {% endprovide %}
tags, we can request the \"user_data\" usingComponent.inject(\"user_data\")
:@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n User is: {{ user }}\n </div>\n \"\"\"\n\n def get_context_data(self):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n
Notice that the keys defined on the
{% provide %}
tag are then accessed as attributes when accessing them withComponent.inject()
.\u2705 Do this
user = self.inject(\"user_data\").user\n
\u274c Don't do this
Source code inuser = self.inject(\"user_data\")[\"user\"]\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.slot","title":"slot","text":"@register.tag(\"provide\")\n@with_tag_spec(\n TagSpec(\n tag=\"provide\",\n end_tag=\"endprovide\",\n positional_only_args=[],\n pos_or_keyword_args=[PROVIDE_NAME_KWARG],\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[],\n )\n)\ndef provide(parser: Parser, token: Token, tag_spec: TagSpec) -> ProvideNode:\n \"\"\"\n The \"provider\" part of the [provide / inject feature](../../concepts/advanced/provide_inject).\n Pass kwargs to this tag to define the provider's data.\n Any components defined within the `{% provide %}..{% endprovide %}` tags will be able to access this data\n with [`Component.inject()`](../api#django_components.Component.inject).\n\n This is similar to React's [`ContextProvider`](https://react.dev/learn/passing-data-deeply-with-context),\n or Vue's [`provide()`](https://vuejs.org/guide/components/provide-inject).\n\n **Args:**\n\n - `name` (str, required): Provider name. This is the name you will then use in\n [`Component.inject()`](../api#django_components.Component.inject).\n - `**kwargs`: Any extra kwargs will be passed as the provided data.\n\n **Example:**\n\n Provide the \"user_data\" in parent component:\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n <div>\n {% provide \"user_data\" user=user %}\n {% component \"child\" / %}\n {% endprovide %}\n </div>\n \\\"\\\"\\\"\n\n def get_context_data(self, user: User):\n return {\n \"user\": user,\n }\n ```\n\n Since the \"child\" component is used within the `{% provide %} / {% endprovide %}` tags,\n we can request the \"user_data\" using `Component.inject(\"user_data\")`:\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n User is: {{ user }}\n </div>\n \\\"\\\"\\\"\n\n def get_context_data(self):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n ```\n\n Notice that the keys defined on the `{% provide %}` tag are then accessed as attributes\n when accessing them with [`Component.inject()`](../api#django_components.Component.inject).\n\n \u2705 Do this\n ```python\n user = self.inject(\"user_data\").user\n ```\n\n \u274c Don't do this\n ```python\n user = self.inject(\"user_data\")[\"user\"]\n ```\n \"\"\"\n # e.g. {% provide <name> key=val key2=val2 %}\n tag = _parse_tag(parser, token, tag_spec)\n\n name_kwarg = tag.kwargs.kwargs.get(PROVIDE_NAME_KWARG, None)\n trace_id = f\"provide-id-{tag.id} ({name_kwarg})\" if name_kwarg else f\"fill-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"PROVIDE\", trace_id, tag.id)\n\n body = tag.parse_body()\n provide_node = ProvideNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"PROVIDE\", trace_id, tag.id, \"...Done!\")\n return provide_node\n
slot(parser: Parser, token: Token, tag_spec: TagSpec) -> SlotNode\n
Slot tag marks a place inside a component where content can be inserted from outside.
Learn more about using slots.
This is similar to slots as seen in Web components, Vue or React's
children
.Args:
name
(str, required): Registered name of the component to renderdefault
: Optional flag. If there is a default slot, you can pass the component slot content without using the{% fill %}
tag. See Default slotrequired
: Optional flag. Will raise an error if a slot is required but not given.**kwargs
: Any extra kwargs will be passed as the slot data.
Example:
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" default %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n <aside>\n {% slot \"sidebar\" required / %}\n </aside>\n \"\"\"\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.slot--passing-data-to-slots","title":"Passing data to slots","text":"@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n <div>\n {% component \"child\" %}\n {% fill \"content\" %}\n \ud83d\uddde\ufe0f\ud83d\udcf0\n {% endfill %}\n\n {% fill \"sidebar\" %}\n \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n {% endfill %}\n {% endcomponent %}\n </div>\n \"\"\"\n
Any extra kwargs will be considered as slot data, and will be accessible in the
{% fill %}
tag via fill'sdata
kwarg:@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \"\"\"\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.slot--accessing-default-slot-content","title":"Accessing default slot content","text":"@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
The content between the
{% slot %}..{% endslot %}
tags is the default content that will be rendered if no fill is given for the slot.This default content can then be accessed from within the
{% fill %}
tag using the fill'sdefault
kwarg. This is useful if you need to wrap / prepend / append the original slot's content.@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" %}\n This is default content!\n {% endslot %}\n </div>\n \"\"\"\n
Source code in@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot's default content #}\n {% component \"child\" %}\n {% fill \"content\" default=\"default\" %}\n {{ default }}\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.with_tag_spec","title":"with_tag_spec","text":"@register.tag(\"slot\")\n@with_tag_spec(\n TagSpec(\n tag=\"slot\",\n end_tag=\"endslot\",\n positional_only_args=[],\n pos_or_keyword_args=[SLOT_NAME_KWARG],\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[SLOT_DEFAULT_KEYWORD, SLOT_REQUIRED_KEYWORD],\n )\n)\ndef slot(parser: Parser, token: Token, tag_spec: TagSpec) -> SlotNode:\n \"\"\"\n Slot tag marks a place inside a component where content can be inserted\n from outside.\n\n [Learn more](../../concepts/fundamentals/slots) about using slots.\n\n This is similar to slots as seen in\n [Web components](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot),\n [Vue](https://vuejs.org/guide/components/slots.html)\n or [React's `children`](https://react.dev/learn/passing-props-to-a-component#passing-jsx-as-children).\n\n **Args:**\n\n - `name` (str, required): Registered name of the component to render\n - `default`: Optional flag. If there is a default slot, you can pass the component slot content\n without using the [`{% fill %}`](#fill) tag. See\n [Default slot](../../concepts/fundamentals/slots#default-slot)\n - `required`: Optional flag. Will raise an error if a slot is required but not given.\n - `**kwargs`: Any extra kwargs will be passed as the slot data.\n\n **Example:**\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {% slot \"content\" default %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n <aside>\n {% slot \"sidebar\" required / %}\n </aside>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n <div>\n {% component \"child\" %}\n {% fill \"content\" %}\n \ud83d\uddde\ufe0f\ud83d\udcf0\n {% endfill %}\n\n {% fill \"sidebar\" %}\n \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n {% endfill %}\n {% endcomponent %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ### Passing data to slots\n\n Any extra kwargs will be considered as slot data, and will be accessible in the [`{% fill %}`](#fill)\n tag via fill's `data` kwarg:\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \\\"\\\"\\\"\n ```\n\n ### Accessing default slot content\n\n The content between the `{% slot %}..{% endslot %}` tags is the default content that\n will be rendered if no fill is given for the slot.\n\n This default content can then be accessed from within the [`{% fill %}`](#fill) tag using\n the fill's `default` kwarg.\n This is useful if you need to wrap / prepend / append the original slot's content.\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {% slot \"content\" %}\n This is default content!\n {% endslot %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n {# Parent can access the slot's default content #}\n {% component \"child\" %}\n {% fill \"content\" default=\"default\" %}\n {{ default }}\n {% endfill %}\n {% endcomponent %}\n \\\"\\\"\\\"\n ```\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n slot_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n trace_id = f\"slot-id-{tag.id} ({slot_name_kwarg})\" if slot_name_kwarg else f\"slot-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"SLOT\", trace_id, tag.id)\n\n body = tag.parse_body()\n slot_node = SlotNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n is_required=tag.flags[SLOT_REQUIRED_KEYWORD],\n is_default=tag.flags[SLOT_DEFAULT_KEYWORD],\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"SLOT\", trace_id, tag.id, \"...Done!\")\n return slot_node\n
Source code inwith_tag_spec(tag_spec: TagSpec) -> Callable\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/#django_components.types","title":"types","text":"def with_tag_spec(tag_spec: TagSpec) -> Callable:\n \"\"\"\"\"\"\n\n def decorator(fn: Callable) -> Any:\n fn._tag_spec = tag_spec # type: ignore[attr-defined]\n\n @functools.wraps(fn)\n def wrapper(*args: Any, **kwargs: Any) -> Any:\n return fn(*args, **kwargs, tag_spec=tag_spec)\n\n return wrapper\n\n return decorator\n
Helper types for IDEs.
"},{"location":"reference/django_components/#django_components.util","title":"util","text":"Modules:
-
cache
\u2013 -
html
\u2013 -
loader
\u2013 -
logger
\u2013 -
misc
\u2013 -
tag_parser
\u2013 -
types
\u2013
Functions:
-
lazy_cache
\u2013Decorator that caches the given function similarly to
functools.lru_cache
.
lazy_cache(make_cache: Callable[[], Callable[[Callable], Callable]]) -> Callable[[TFunc], TFunc]\n
Decorator that caches the given function similarly to
functools.lru_cache
. But the cache is instantiated only at first invocation.
Source code incache
argument is a function that generates the cache function, e.g.functools.lru_cache()
.src/django_components/util/cache.py
"},{"location":"reference/django_components/#django_components.util.html","title":"html","text":"def lazy_cache(\n make_cache: Callable[[], Callable[[Callable], Callable]],\n) -> Callable[[TFunc], TFunc]:\n \"\"\"\n Decorator that caches the given function similarly to `functools.lru_cache`.\n But the cache is instantiated only at first invocation.\n\n `cache` argument is a function that generates the cache function,\n e.g. `functools.lru_cache()`.\n \"\"\"\n _cached_fn = None\n\n def decorator(fn: TFunc) -> TFunc:\n @functools.wraps(fn)\n def wrapper(*args: Any, **kwargs: Any) -> Any:\n # Lazily initialize the cache\n nonlocal _cached_fn\n if not _cached_fn:\n # E.g. `lambda: functools.lru_cache(maxsize=app_settings.TEMPLATE_CACHE_SIZE)`\n cache = make_cache()\n _cached_fn = cache(fn)\n\n return _cached_fn(*args, **kwargs)\n\n # Allow to access the LRU cache methods\n # See https://stackoverflow.com/a/37654201/9788634\n wrapper.cache_info = lambda: _cached_fn.cache_info() # type: ignore\n wrapper.cache_clear = lambda: _cached_fn.cache_clear() # type: ignore\n\n # And allow to remove the cache instance (mostly for tests)\n def cache_remove() -> None:\n nonlocal _cached_fn\n _cached_fn = None\n\n wrapper.cache_remove = cache_remove # type: ignore\n\n return cast(TFunc, wrapper)\n\n return decorator\n
Functions:
-
parse_document_or_nodes
\u2013Use this if you do NOT know whether the given HTML is a full document
-
parse_multiroot_html
\u2013Use this when you know the given HTML is a multiple nodes like
-
parse_node
\u2013Use this when you know the given HTML is a single node like
parse_document_or_nodes(html: str) -> Union[List[LexborNode], LexborHTMLParser]\n
Use this if you do NOT know whether the given HTML is a full document with
Source code in<html>
,<head>
, and<body>
tags, or an HTML fragment.src/django_components/util/html.py
"},{"location":"reference/django_components/#django_components.util.html.parse_multiroot_html","title":"parse_multiroot_html","text":"def parse_document_or_nodes(html: str) -> Union[List[LexborNode], LexborHTMLParser]:\n \"\"\"\n Use this if you do NOT know whether the given HTML is a full document\n with `<html>`, `<head>`, and `<body>` tags, or an HTML fragment.\n \"\"\"\n html = html.strip()\n tree = LexborHTMLParser(html)\n is_fragment = is_html_parser_fragment(html, tree)\n\n if is_fragment:\n nodes = parse_multiroot_html(html)\n return nodes\n else:\n return tree\n
parse_multiroot_html(html: str) -> List[LexborNode]\n
Use this when you know the given HTML is a multiple nodes like
Source code in<div> Hi </div> <span> Hello </span>
src/django_components/util/html.py
"},{"location":"reference/django_components/#django_components.util.html.parse_node","title":"parse_node","text":"def parse_multiroot_html(html: str) -> List[LexborNode]:\n \"\"\"\n Use this when you know the given HTML is a multiple nodes like\n\n `<div> Hi </div> <span> Hello </span>`\n \"\"\"\n # NOTE: HTML / XML MUST have a single root. So, to support multiple\n # top-level elements, we wrap them in a dummy singular root.\n parser = LexborHTMLParser(f\"<root>{html}</root>\")\n\n # Get all contents of the root\n root_elem = parser.css_first(\"root\")\n elems = [*root_elem.iter()] if root_elem else []\n return elems\n
parse_node(html: str) -> LexborNode\n
Use this when you know the given HTML is a single node like
Source code in<div> Hi </div>
src/django_components/util/html.py
"},{"location":"reference/django_components/#django_components.util.loader","title":"loader","text":"def parse_node(html: str) -> LexborNode:\n \"\"\"\n Use this when you know the given HTML is a single node like\n\n `<div> Hi </div>`\n \"\"\"\n tree = LexborHTMLParser(html)\n # NOTE: The parser automatically places <style> tags inside <head>\n # while <script> tags are inside <body>.\n return tree.body.child or tree.head.child # type: ignore[union-attr, return-value]\n
Classes:
-
ComponentFileEntry
\u2013Result returned by
get_component_files()
.
Functions:
-
get_component_dirs
\u2013Get directories that may contain component files.
-
get_component_files
\u2013Search for files within the component directories (as defined in
Bases:
NamedTuple
Result returned by
get_component_files()
.Attributes:
-
dot_path
(str
) \u2013The python import path for the module. E.g.
app.components.mycomp
-
filepath
(Path
) \u2013The filesystem path to the module. E.g.
/path/to/project/app/components/mycomp.py
instance-attribute
","text":"dot_path: str\n
The python import path for the module. E.g.
"},{"location":"reference/django_components/#django_components.util.loader.ComponentFileEntry.filepath","title":"filepathapp.components.mycomp
instance-attribute
","text":"filepath: Path\n
The filesystem path to the module. E.g.
"},{"location":"reference/django_components/#django_components.util.loader.get_component_dirs","title":"get_component_dirs","text":"/path/to/project/app/components/mycomp.py
get_component_dirs(include_apps: bool = True) -> List[Path]\n
Get directories that may contain component files.
This is the heart of all features that deal with filesystem and file lookup. Autodiscovery, Django template resolution, static file resolution - They all use this.
Parameters:
-
include_apps
(bool
, default:True
) \u2013Include directories from installed Django apps. Defaults to
True
.
Returns:
-
List[Path]
\u2013List[Path]: A list of directories that may contain component files.
get_component_dirs()
searches for dirs set inCOMPONENTS.dirs
settings. If none set, defaults to searching for a\"components\"
app.In addition to that, also all installed Django apps are checked whether they contain directories as set in
COMPONENTS.app_dirs
(e.g.[app]/components
).Notes:
-
Paths that do not point to directories are ignored.
-
BASE_DIR
setting is required. -
The paths in
COMPONENTS.dirs
must be absolute paths.
src/django_components/util/loader.py
"},{"location":"reference/django_components/#django_components.util.loader.get_component_files","title":"get_component_files","text":"def get_component_dirs(include_apps: bool = True) -> List[Path]:\n \"\"\"\n Get directories that may contain component files.\n\n This is the heart of all features that deal with filesystem and file lookup.\n Autodiscovery, Django template resolution, static file resolution - They all use this.\n\n Args:\n include_apps (bool, optional): Include directories from installed Django apps.\\\n Defaults to `True`.\n\n Returns:\n List[Path]: A list of directories that may contain component files.\n\n `get_component_dirs()` searches for dirs set in\n [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n settings. If none set, defaults to searching for a `\"components\"` app.\n\n In addition to that, also all installed Django apps are checked whether they contain\n directories as set in\n [`COMPONENTS.app_dirs`](../settings#django_components.app_settings.ComponentsSettings.app_dirs)\n (e.g. `[app]/components`).\n\n **Notes:**\n\n - Paths that do not point to directories are ignored.\n\n - `BASE_DIR` setting is required.\n\n - The paths in [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n must be absolute paths.\n \"\"\"\n # Allow to configure from settings which dirs should be checked for components\n component_dirs = app_settings.DIRS\n\n # TODO_REMOVE_IN_V1\n raw_component_settings = getattr(settings, \"COMPONENTS\", {})\n if isinstance(raw_component_settings, dict):\n raw_dirs_value = raw_component_settings.get(\"dirs\", None)\n elif isinstance(raw_component_settings, ComponentsSettings):\n raw_dirs_value = raw_component_settings.dirs\n else:\n raw_dirs_value = None\n is_component_dirs_set = raw_dirs_value is not None\n is_legacy_paths = (\n # Use value of `STATICFILES_DIRS` ONLY if `COMPONENT.dirs` not set\n not is_component_dirs_set\n and hasattr(settings, \"STATICFILES_DIRS\")\n and settings.STATICFILES_DIRS\n )\n if is_legacy_paths:\n # NOTE: For STATICFILES_DIRS, we use the defaults even for empty list.\n # We don't do this for COMPONENTS.dirs, so user can explicitly specify \"NO dirs\".\n component_dirs = settings.STATICFILES_DIRS or [settings.BASE_DIR / \"components\"]\n # END TODO_REMOVE_IN_V1\n\n source = \"STATICFILES_DIRS\" if is_legacy_paths else \"COMPONENTS.dirs\"\n\n logger.debug(\n \"get_component_dirs will search for valid dirs from following options:\\n\"\n + \"\\n\".join([f\" - {str(d)}\" for d in component_dirs])\n )\n\n # Add `[app]/[APP_DIR]` to the directories. This is, by default `[app]/components`\n app_paths: List[Path] = []\n if include_apps:\n for conf in apps.get_app_configs():\n for app_dir in app_settings.APP_DIRS:\n comps_path = Path(conf.path).joinpath(app_dir)\n if comps_path.exists():\n app_paths.append(comps_path)\n\n directories: Set[Path] = set(app_paths)\n\n # Validate and add other values from the config\n for component_dir in component_dirs:\n # Consider tuples for STATICFILES_DIRS (See #489)\n # See https://docs.djangoproject.com/en/5.0/ref/settings/#prefixes-optional\n if isinstance(component_dir, (tuple, list)):\n component_dir = component_dir[1]\n try:\n Path(component_dir)\n except TypeError:\n logger.warning(\n f\"{source} expected str, bytes or os.PathLike object, or tuple/list of length 2. \"\n f\"See Django documentation for STATICFILES_DIRS. Got {type(component_dir)} : {component_dir}\"\n )\n continue\n\n if not Path(component_dir).is_absolute():\n raise ValueError(f\"{source} must contain absolute paths, got '{component_dir}'\")\n else:\n directories.add(Path(component_dir).resolve())\n\n logger.debug(\n \"get_component_dirs matched following template dirs:\\n\" + \"\\n\".join([f\" - {str(d)}\" for d in directories])\n )\n return list(directories)\n
get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]\n
Search for files within the component directories (as defined in
get_component_dirs()
).Requires
BASE_DIR
setting to be set.Parameters:
-
suffix
(Optional[str]
, default:None
) \u2013The suffix to search for. E.g.
.py
,.js
,.css
. Defaults toNone
, which will search for all files.
Returns:
-
List[ComponentFileEntry]
\u2013List[ComponentFileEntry] A list of entries that contain both the filesystem path and the python import path (dot path).
Example:
Source code infrom django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
src/django_components/util/loader.py
"},{"location":"reference/django_components/#django_components.util.logger","title":"logger","text":"def get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]:\n \"\"\"\n Search for files within the component directories (as defined in\n [`get_component_dirs()`](../api#django_components.get_component_dirs)).\n\n Requires `BASE_DIR` setting to be set.\n\n Args:\n suffix (Optional[str], optional): The suffix to search for. E.g. `.py`, `.js`, `.css`.\\\n Defaults to `None`, which will search for all files.\n\n Returns:\n List[ComponentFileEntry] A list of entries that contain both the filesystem path and \\\n the python import path (dot path).\n\n **Example:**\n\n ```python\n from django_components import get_component_files\n\n modules = get_component_files(\".py\")\n ```\n \"\"\"\n search_glob = f\"**/*{suffix}\" if suffix else \"**/*\"\n\n dirs = get_component_dirs(include_apps=False)\n component_filepaths = _search_dirs(dirs, search_glob)\n\n if hasattr(settings, \"BASE_DIR\") and settings.BASE_DIR:\n project_root = str(settings.BASE_DIR)\n else:\n # Fallback for getting the root dir, see https://stackoverflow.com/a/16413955/9788634\n project_root = os.path.abspath(os.path.dirname(__name__))\n\n # NOTE: We handle dirs from `COMPONENTS.dirs` and from individual apps separately.\n modules: List[ComponentFileEntry] = []\n\n # First let's handle the dirs from `COMPONENTS.dirs`\n #\n # Because for dirs in `COMPONENTS.dirs`, we assume they will be nested under `BASE_DIR`,\n # and that `BASE_DIR` is the current working dir (CWD). So the path relatively to `BASE_DIR`\n # is ALSO the python import path.\n for filepath in component_filepaths:\n module_path = _filepath_to_python_module(filepath, project_root, None)\n # Ignore files starting with dot `.` or files in dirs that start with dot.\n #\n # If any of the parts of the path start with a dot, e.g. the filesystem path\n # is `./abc/.def`, then this gets converted to python module as `abc..def`\n #\n # NOTE: This approach also ignores files:\n # - with two dots in the middle (ab..cd.py)\n # - an extra dot at the end (abcd..py)\n # - files outside of the parent component (../abcd.py).\n # But all these are NOT valid python modules so that's fine.\n if \"..\" in module_path:\n continue\n\n entry = ComponentFileEntry(dot_path=module_path, filepath=filepath)\n modules.append(entry)\n\n # For for apps, the directories may be outside of the project, e.g. in case of third party\n # apps. So we have to resolve the python import path relative to the package name / the root\n # import path for the app.\n # See https://github.com/EmilStenstrom/django-components/issues/669\n for conf in apps.get_app_configs():\n for app_dir in app_settings.APP_DIRS:\n comps_path = Path(conf.path).joinpath(app_dir)\n if not comps_path.exists():\n continue\n app_component_filepaths = _search_dirs([comps_path], search_glob)\n for filepath in app_component_filepaths:\n app_component_module = _filepath_to_python_module(filepath, conf.path, conf.name)\n entry = ComponentFileEntry(dot_path=app_component_module, filepath=filepath)\n modules.append(entry)\n\n return modules\n
Functions:
-
trace
\u2013TRACE level logger.
-
trace_msg
\u2013TRACE level logger with opinionated format for tracing interaction of components,
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:
Source code inLOGGING = {\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
src/django_components/util/logger.py
"},{"location":"reference/django_components/#django_components.util.logger.trace_msg","title":"trace_msg","text":"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
trace_msg(\n action: Literal[\"PARSE\", \"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:
Source code in\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"
src/django_components/util/logger.py
"},{"location":"reference/django_components/#django_components.util.misc","title":"misc","text":"def trace_msg(\n action: Literal[\"PARSE\", \"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 == \"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
Functions:
-
gen_id
\u2013Generate a unique ID that can be associated with a Node
-
get_import_path
\u2013Get the full import path for a class or a function, e.g.
\"path.to.MyClass\"
gen_id() -> str\n
Generate a unique ID that can be associated with a Node
Source code insrc/django_components/util/misc.py
"},{"location":"reference/django_components/#django_components.util.misc.get_import_path","title":"get_import_path","text":"def gen_id() -> str:\n \"\"\"Generate a unique ID that can be associated with a Node\"\"\"\n # Alphabet is only alphanumeric. Compared to the default alphabet used by nanoid,\n # we've omitted `-` and `_`.\n # With this alphabet, at 6 chars, the chance of collision is 1 in 3.3M.\n # See https://zelark.github.io/nano-id-cc/\n return generate(\n \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\",\n size=6,\n )\n
get_import_path(cls_or_fn: Type[Any]) -> str\n
Get the full import path for a class or a function, e.g.
Source code in\"path.to.MyClass\"
src/django_components/util/misc.py
"},{"location":"reference/django_components/#django_components.util.tag_parser","title":"tag_parser","text":"def get_import_path(cls_or_fn: Type[Any]) -> str:\n \"\"\"\n Get the full import path for a class or a function, e.g. `\"path.to.MyClass\"`\n \"\"\"\n module = cls_or_fn.__module__\n if module == \"builtins\":\n return cls_or_fn.__qualname__ # avoid outputs like 'builtins.str'\n return module + \".\" + cls_or_fn.__qualname__\n
Classes:
-
TagAttr
\u2013
dataclass
","text":"TagAttr(key: Optional[str], value: str, start_index: int, quoted: bool)\n
Attributes:
-
quoted
(bool
) \u2013Whether the value is quoted (either with single or double quotes)
-
start_index
(int
) \u2013Start index of the attribute (include both key and value),
instance-attribute
","text":"quoted: bool\n
Whether the value is quoted (either with single or double quotes)
"},{"location":"reference/django_components/#django_components.util.tag_parser.TagAttr.start_index","title":"start_indexinstance-attribute
","text":"start_index: int\n
Start index of the attribute (include both key and value), relative to the start of the owner Tag.
"},{"location":"reference/django_components/#django_components.util.types","title":"types","text":"Classes:
-
EmptyDict
\u2013TypedDict with no members.
Attributes:
-
EmptyTuple
\u2013Tuple with no members.
module-attribute
","text":"EmptyTuple = Tuple[]\n
Tuple with no members.
You can use this to define a Component that accepts NO positional arguments:
from django_components import Component, EmptyTuple\n\nclass Table(Component(EmptyTuple, Any, Any, Any, Any, Any))\n ...\n
After that, when you call
Component.render()
orComponent.render_to_response()
, theargs
parameter will raise type error ifargs
is anything else than an empty tuple.Table.render(\n args: (),\n)\n
Omitting
args
is also fine:Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
"},{"location":"reference/django_components/#django_components.util.types.EmptyDict","title":"EmptyDict","text":"Table.render(\n args: (\"one\", 2, \"three\"),\n)\n
Bases:
TypedDict
TypedDict with no members.
You can use this to define a Component that accepts NO kwargs, or NO slots, or returns NO data from
Component.get_context_data()
/Component.get_js_data()
/Component.get_css_data()
:Accepts NO kwargs:
from django_components import Component, EmptyDict\n\nclass Table(Component(Any, EmptyDict, Any, Any, Any, Any))\n ...\n
Accepts NO slots:
from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, EmptyDict, Any, Any, Any))\n ...\n
Returns NO data from
get_context_data()
:from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, Any, EmptyDict, Any, Any))\n ...\n
Going back to the example with NO kwargs, when you then call
Component.render()
orComponent.render_to_response()
, thekwargs
parameter will raise type error ifkwargs
is anything else than an empty dict.Table.render(\n kwargs: {},\n)\n
Omitting
kwargs
is also fine:Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
"},{"location":"reference/django_components/app_settings/","title":"Table.render(\n kwargs: {\n \"one\": 2,\n \"three\": 4,\n },\n)\n
app_settings","text":""},{"location":"reference/django_components/app_settings/#django_components.app_settings","title":"app_settings","text":"
Classes:
-
ComponentsSettings
\u2013Settings available for django_components.
-
ContextBehavior
\u2013Configure how (and whether) the context is passed to the component fills
Bases:
NamedTuple
Settings available for django_components.
Example:
COMPONENTS = ComponentsSettings(\n autodiscover=False,\n dirs = [BASE_DIR / \"components\"],\n)\n
Attributes:
-
app_dirs
(Optional[Sequence[str]]
) \u2013Specify the app-level directories that contain your components.
-
autodiscover
(Optional[bool]
) \u2013Toggle whether to run autodiscovery at the Django server startup.
-
context_behavior
(Optional[ContextBehaviorType]
) \u2013Configure whether, inside a component template, you can use variables from the outside
-
dirs
(Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]]
) \u2013Specify the directories that contain your components.
-
dynamic_component_name
(Optional[str]
) \u2013By default, the dynamic component
-
forbidden_static_files
(Optional[List[Union[str, Pattern]]]
) \u2013Deprecated. Use
-
libraries
(Optional[List[str]]
) \u2013Configure extra python modules that should be loaded.
-
multiline_tags
(Optional[bool]
) \u2013Enable / disable
-
reload_on_file_change
(Optional[bool]
) \u2013This is relevant if you are using the project structure where
-
reload_on_template_change
(Optional[bool]
) \u2013Deprecated. Use
-
static_files_allowed
(Optional[List[Union[str, Pattern]]]
) \u2013A list of file extensions (including the leading dot) that define which files within
-
static_files_forbidden
(Optional[List[Union[str, Pattern]]]
) \u2013A list of file extensions (including the leading dot) that define which files within
-
tag_formatter
(Optional[Union[TagFormatterABC, str]]
) \u2013Configure what syntax is used inside Django templates to render components.
-
template_cache_size
(Optional[int]
) \u2013Configure the maximum amount of Django templates to be cached.
class-attribute
instance-attribute
","text":"app_dirs: Optional[Sequence[str]] = None\n
Specify the app-level directories that contain your components.
Defaults to
[\"components\"]
. That is, for each Django app, we search<app>/components/
for components.The paths must be relative to app, e.g.:
COMPONENTS = ComponentsSettings(\n app_dirs=[\"my_comps\"],\n)\n
To search for
<app>/my_comps/
.These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.
Set to empty list to disable app-level components:
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.autodiscover","title":"autodiscoverCOMPONENTS = ComponentsSettings(\n app_dirs=[],\n)\n
class-attribute
instance-attribute
","text":"autodiscover: Optional[bool] = None\n
Toggle whether to run autodiscovery at the Django server startup.
Defaults to
True
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.context_behavior","title":"context_behaviorCOMPONENTS = ComponentsSettings(\n autodiscover=False,\n)\n
class-attribute
instance-attribute
","text":"context_behavior: Optional[ContextBehaviorType] = None\n
Configure whether, inside a component template, you can use variables from the outside (
\"django\"
) or not (\"isolated\"
). This also affects what variables are available inside the{% fill %}
tags.Also see Component context and scope.
Defaults to
\"django\"
.COMPONENTS = ComponentsSettings(\n context_behavior=\"isolated\",\n)\n
NOTE:
context_behavior
andslot_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
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.dirs","title":"dirs\"django\"
. See the rationale for change here.class-attribute
instance-attribute
","text":"dirs: Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]] = None\n
Specify the directories that contain your components.
Defaults to
[Path(settings.BASE_DIR) / \"components\"]
. That is, the rootcomponents/
app.Directories must be full paths, same as with STATICFILES_DIRS.
These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.
COMPONENTS = ComponentsSettings(\n dirs=[BASE_DIR / \"components\"],\n)\n
Set to empty list to disable global components directories:
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.dynamic_component_name","title":"dynamic_component_nameCOMPONENTS = ComponentsSettings(\n dirs=[],\n)\n
class-attribute
instance-attribute
","text":"dynamic_component_name: Optional[str] = None\n
By default, the dynamic component is registered under the name
\"dynamic\"
.In case of a conflict, you can use this setting to change the component name used for the dynamic components.
# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.forbidden_static_files","title":"forbidden_static_files{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
class-attribute
instance-attribute
","text":"forbidden_static_files: Optional[List[Union[str, Pattern]]] = None\n
Deprecated. Use
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.libraries","title":"librariesCOMPONENTS.static_files_forbidden
instead.class-attribute
instance-attribute
","text":"libraries: Optional[List[str]] = None\n
Configure extra python modules that should be loaded.
This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.
Expects a list of python module paths. Defaults to empty list.
Example:
COMPONENTS = ComponentsSettings(\n libraries=[\n \"mysite.components.forms\",\n \"mysite.components.buttons\",\n \"mysite.components.cards\",\n ],\n)\n
This would be the equivalent of importing these modules from within Django's
AppConfig.ready()
:
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.libraries--manually-loading-libraries","title":"Manually loading libraries","text":"class MyAppConfig(AppConfig):\n def ready(self):\n import \"mysite.components.forms\"\n import \"mysite.components.buttons\"\n import \"mysite.components.cards\"\n
In the rare case that you need to manually trigger the import of libraries, you can use the
import_libraries()
function:
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.multiline_tags","title":"multiline_tagsfrom django_components import import_libraries\n\nimport_libraries()\n
class-attribute
instance-attribute
","text":"multiline_tags: Optional[bool] = None\n
Enable / disable multiline support for template tags. If
True
, template tags like{% component %}
or{{ my_var }}
can span multiple lines.Defaults to
True
.Disable this setting if you are making custom modifications to Django's regular expression for parsing templates at
django.template.base.tag_re
.
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.reload_on_file_change","title":"reload_on_file_changeCOMPONENTS = ComponentsSettings(\n multiline_tags=False,\n)\n
class-attribute
instance-attribute
","text":"reload_on_file_change: Optional[bool] = None\n
This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.
Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.
The setting
reload_on_file_change
fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.If
True
, django_components configures Django to reload when files insideCOMPONENTS.dirs
orCOMPONENTS.app_dirs
change.See Reload dev server on component file changes.
Defaults to
False
.Warning
This setting should be enabled only for the dev environment!
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.reload_on_template_change","title":"reload_on_template_changeclass-attribute
instance-attribute
","text":"reload_on_template_change: Optional[bool] = None\n
Deprecated. Use
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.static_files_allowed","title":"static_files_allowedCOMPONENTS.reload_on_file_change
instead.class-attribute
instance-attribute
","text":"static_files_allowed: Optional[List[Union[str, Pattern]]] = None\n
A list of file extensions (including the leading dot) that define which files within
COMPONENTS.dirs
orCOMPONENTS.app_dirs
are treated as static files.If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running
collectstatic
, and can be accessed under the static file endpoint.You can also pass in compiled regexes (
re.Pattern
) for more advanced patterns.By default, JS, CSS, and common image and font file formats are considered static files:
COMPONENTS = ComponentsSettings(\n static_files_allowed=[\n \".css\",\n \".js\", \".jsx\", \".ts\", \".tsx\",\n # Images\n \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n \".jpeg\", \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n # Fonts\n \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n ],\n)\n
Warning
Exposing your Python files can be a security vulnerability. See Security notes.
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.static_files_forbidden","title":"static_files_forbiddenclass-attribute
instance-attribute
","text":"static_files_forbidden: Optional[List[Union[str, Pattern]]] = None\n
A list of file extensions (including the leading dot) that define which files within
COMPONENTS.dirs
orCOMPONENTS.app_dirs
will NEVER be treated as static files.If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in
static_files_allowed
.Use this setting together with
static_files_allowed
for a fine control over what file types will be exposed.You can also pass in compiled regexes (
re.Pattern
) for more advanced patterns.By default, any HTML and Python are considered NOT static files:
COMPONENTS = ComponentsSettings(\n static_files_forbidden=[\n \".html\", \".django\", \".dj\", \".tpl\",\n # Python files\n \".py\", \".pyc\",\n ],\n)\n
Warning
Exposing your Python files can be a security vulnerability. See Security notes.
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.tag_formatter","title":"tag_formatterclass-attribute
instance-attribute
","text":"tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n
Configure what syntax is used inside Django templates to render components. See the available tag formatters.
Defaults to
\"django_components.component_formatter\"
.Learn more about Customizing component tags with TagFormatter.
Can be set either as direct reference:
from django_components import component_formatter\n\nCOMPONENTS = ComponentsSettings(\n \"tag_formatter\": component_formatter\n)\n
Or as an import string;
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_formatter\"\n)\n
Examples:
-
\"django_components.component_formatter\"
Set
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_formatter\"\n)\n
To write components like this:
{% component \"button\" href=\"...\" %}\n Click me!\n{% endcomponent %}\n
-
django_components.component_shorthand_formatter
Set
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_shorthand_formatter\"\n)\n
To write components like this:
{% button href=\"...\" %}\n Click me!\n{% endbutton %}\n
class-attribute
instance-attribute
","text":"template_cache_size: Optional[int] = None\n
Configure the maximum amount of Django templates to be cached.
Defaults to
128
.Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's
lru_cache
decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding
Component.get_template()
to render many dynamic templates, you can increase this number.COMPONENTS = ComponentsSettings(\n template_cache_size=256,\n)\n
To remove the cache limit altogether and cache everything, set
template_cache_size
toNone
.COMPONENTS = ComponentsSettings(\n template_cache_size=None,\n)\n
If you want to add templates to the cache yourself, you can use
cached_template()
:
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ContextBehavior","title":"ContextBehavior","text":"from django_components import cached_template\n\ncached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n pass\n\ncached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n)\n
Bases:
str
,Enum
Configure how (and whether) the context is passed to the component fills and what variables are available inside the
{% fill %}
tags.Also see Component context and scope.
Options:
django
: With this setting, component fills behave as usual Django tags.isolated
: This setting makes the component fills behave similar to Vue or React.
Attributes:
-
DJANGO
\u2013With this setting, component fills behave as usual Django tags.
-
ISOLATED
\u2013This setting makes the component fills behave similar to Vue or React, where
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
Component.get_context_data()
are available to the component fill.
Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the
Component.get_context_data()
method{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
456 # my_var\nfeta # cheese\n
Because \"my_comp\" overrides the variable \"my_var\", so
{{ my_var }}
equals456
.And variable \"cheese\" will equal
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ContextBehavior.ISOLATED","title":"ISOLATEDfeta
, because the fill CAN access the current context.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
Component.get_context_data()
.Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the
get_context_data()
method{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
123 # my_var\n # cheese\n
Because both variables \"my_var\" and \"cheese\" are taken from the root context. Since \"cheese\" is not defined in root context, it's empty.
"},{"location":"reference/django_components/apps/","title":"apps","text":""},{"location":"reference/django_components/apps/#django_components.apps","title":"apps","text":""},{"location":"reference/django_components/attributes/","title":"
attributes","text":""},{"location":"reference/django_components/attributes/#django_components.attributes","title":"attributes","text":"
Functions:
-
append_attributes
\u2013Merges the key-value pairs and returns a new dictionary.
-
attributes_to_string
\u2013Convert a dict of attributes to a string.
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 insrc/django_components/attributes.py
"},{"location":"reference/django_components/attributes/#django_components.attributes.attributes_to_string","title":"attributes_to_string","text":"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
attributes_to_string(attributes: Mapping[str, Any]) -> str\n
Convert a dict of attributes to a string.
Source code insrc/django_components/attributes.py
"},{"location":"reference/django_components/autodiscovery/","title":"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
autodiscovery","text":""},{"location":"reference/django_components/autodiscovery/#django_components.autodiscovery","title":"autodiscovery","text":"
Functions:
-
autodiscover
\u2013Search for all python files in
-
import_libraries
\u2013Import modules set in
autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Search for all python files in
COMPONENTS.dirs
andCOMPONENTS.app_dirs
and import them.See Autodiscovery.
Parameters:
-
map_module
(Callable[[str], str]
, default:None
) \u2013Map the module paths with
map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Returns:
-
List[str]
\u2013List[str]: A list of module paths of imported files.
To get the same list of modules that
autodiscover()
would return, but without importing them, useget_component_files()
:
Source code infrom django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
src/django_components/autodiscovery.py
"},{"location":"reference/django_components/autodiscovery/#django_components.autodiscovery.import_libraries","title":"import_libraries","text":"def autodiscover(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Search for all python files in\n [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n and\n [`COMPONENTS.app_dirs`](../settings#django_components.app_settings.ComponentsSettings.app_dirs)\n and import them.\n\n See [Autodiscovery](../../concepts/fundamentals/autodiscovery).\n\n Args:\n map_module (Callable[[str], str], optional): Map the module paths with `map_module` function.\\\n This serves as an escape hatch for when you need to use this function in tests.\n\n Returns:\n List[str]: A list of module paths of imported files.\n\n To get the same list of modules that `autodiscover()` would return, but without importing them, use\n [`get_component_files()`](../api#django_components.get_component_files):\n\n ```python\n from django_components import get_component_files\n\n modules = get_component_files(\".py\")\n ```\n \"\"\"\n modules = get_component_files(\".py\")\n logger.debug(f\"Autodiscover found {len(modules)} files in component directories.\")\n return _import_modules([entry.dot_path for entry in modules], map_module)\n
import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Import modules set in
COMPONENTS.libraries
setting.See Autodiscovery.
Parameters:
-
map_module
(Callable[[str], str]
, default:None
) \u2013Map the module paths with
map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Returns:
-
List[str]
\u2013List[str]: A list of module paths of imported files.
Examples:
Normal usage - load libraries after Django has loaded
from django_components import import_libraries\n\nclass MyAppConfig(AppConfig):\n def ready(self):\n import_libraries()\n
Potential usage in tests
Source code infrom django_components import import_libraries\n\nimport_libraries(lambda path: path.replace(\"tests.\", \"myapp.\"))\n
src/django_components/autodiscovery.py
"},{"location":"reference/django_components/component/","title":"def import_libraries(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Import modules set in\n [`COMPONENTS.libraries`](../settings#django_components.app_settings.ComponentsSettings.libraries)\n setting.\n\n See [Autodiscovery](../../concepts/fundamentals/autodiscovery).\n\n Args:\n map_module (Callable[[str], str], optional): Map the module paths with `map_module` function.\\\n This serves as an escape hatch for when you need to use this function in tests.\n\n Returns:\n List[str]: A list of module paths of imported files.\n\n **Examples:**\n\n Normal usage - load libraries after Django has loaded\n ```python\n from django_components import import_libraries\n\n class MyAppConfig(AppConfig):\n def ready(self):\n import_libraries()\n ```\n\n Potential usage in tests\n ```python\n from django_components import import_libraries\n\n import_libraries(lambda path: path.replace(\"tests.\", \"myapp.\"))\n ```\n \"\"\"\n from django_components.app_settings import app_settings\n\n return _import_modules(app_settings.LIBRARIES, map_module)\n
component","text":""},{"location":"reference/django_components/component/#django_components.component","title":"component","text":"
Classes:
-
Component
\u2013 -
ComponentNode
\u2013Django.template.Node subclass that renders a django-components component
-
ComponentVars
\u2013Type for the variables available inside the component templates.
-
ComponentView
\u2013Subclass of
django.views.View
where theComponent
instance is available
Component(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Generic[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template
(Optional[Union[str, Template]]
) \u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.Component.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
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":"cssclass-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":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/component/#django_components.component.Component.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/component/#django_components.component.Component.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.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":"mediainstance-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_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/component/#django_components.component.Component.template","title":"templaterender_to_response
class-attribute
instance-attribute
","text":"template: Optional[Union[str, Template]] = None\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
"},{"location":"reference/django_components/component/#django_components.component.Component.template_name","title":"template_nametemplate_name
,get_template_name
,template
orget_template
must be defined.class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/component/#django_components.component.Component.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.Component.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.Component.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.Component.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.Component.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.Component.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.Component.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.Component.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.ComponentNode","title":"ComponentNode","text":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
ComponentNode(\n name: str,\n args: List[Expression],\n kwargs: RuntimeKwargs,\n registry: ComponentRegistry,\n isolated_context: bool = False,\n nodelist: Optional[NodeList] = None,\n node_id: Optional[str] = None,\n)\n
Bases:
BaseNode
Django.template.Node subclass that renders a django-components component
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.ComponentVars","title":"ComponentVars","text":"def __init__(\n self,\n name: str,\n args: List[Expression],\n kwargs: RuntimeKwargs,\n registry: ComponentRegistry, # noqa F811\n isolated_context: bool = False,\n nodelist: Optional[NodeList] = None,\n node_id: Optional[str] = None,\n) -> None:\n super().__init__(nodelist=nodelist or NodeList(), args=args, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.isolated_context = isolated_context\n self.registry = registry\n
Bases:
NamedTuple
Type for the variables available inside the component templates.
All variables here are scoped under
component_vars.
, so e.g. attributeis_filled
on this class is accessible inside the template as:{{ component_vars.is_filled }}\n
Attributes:
-
is_filled
(Dict[str, bool]
) \u2013Dictonary describing which component slots are filled (
True
) or are not (False
).
instance-attribute
","text":"is_filled: Dict[str, bool]\n
Dictonary describing which component slots are filled (
True
) or are not (False
).New in version 0.70
Use as
{{ component_vars.is_filled }}
Example:
"},{"location":"reference/django_components/component/#django_components.component.ComponentView","title":"ComponentView","text":"{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n <div class=\"slot-wrapper\">\n {% slot \"my_slot\" / %}\n </div>\n{% endif %}\n
ComponentView(component: Component, **kwargs: Any)\n
Bases:
View
Subclass of
Source code indjango.views.View
where theComponent
instance is available viaself.component
.src/django_components/component.py
"},{"location":"reference/django_components/component_media/","title":"def __init__(self, component: \"Component\", **kwargs: Any) -> None:\n super().__init__(**kwargs)\n self.component = component\n
component_media","text":""},{"location":"reference/django_components/component_media/#django_components.component_media","title":"component_media","text":"
Classes:
-
ComponentMediaInput
\u2013Defines JS and CSS media files associated with this component.
-
MediaMeta
\u2013Metaclass for handling media files for components.
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 ofMedia
attribute to define associated JS/CSS files, which are then available undermedia
attribute as a instance ofMedia
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
E.g. if in a directory
my_comp
you havescript.js
andmy_comp.py
, andmy_comp.py
looks like this:class MyComponent(Component):\n class Media:\n js = \"script.js\"\n
Then
"},{"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":"script.js
will be resolved asmy_comp/script.js
.E.g.:
"},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--4-subclass-media-class-with-media_class","title":"4. Subclassdef 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
Media
class withmedia_class
","text":"Normal
MediaDefiningClass
creates an instance ofMedia
class under themedia
attribute. This class allows to override which class will be instantiated withmedia_class
attribute:
"},{"location":"reference/django_components/component_registry/","title":"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
component_registry","text":""},{"location":"reference/django_components/component_registry/#django_components.component_registry","title":"component_registry","text":"
Classes:
-
AlreadyRegistered
\u2013Raised when you try to register a Component,
-
ComponentRegistry
\u2013Manages components and makes them available
-
NotRegistered
\u2013Raised when you try to access a Component,
-
RegistrySettings
\u2013Configuration for a
ComponentRegistry
.
Functions:
-
register
\u2013Class decorator for registering a component
Attributes:
-
registry
(ComponentRegistry
) \u2013The default and global component registry.
module-attribute
","text":"registry: ComponentRegistry = ComponentRegistry()\n
The default and global component registry. Use this instance to directly register or remove components:
See Registering components.
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.AlreadyRegistered","title":"AlreadyRegistered","text":"# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get single\nregistry.get(\"button\")\n\n# Get all\nregistry.all()\n\n# Unregister single\nregistry.unregister(\"button\")\n\n# Unregister all\nregistry.clear()\n
Bases:
Exception
Raised when you try to register a Component, but it's already registered with given ComponentRegistry.
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry","title":"ComponentRegistry","text":"ComponentRegistry(\n library: Optional[Library] = None, settings: Optional[Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]] = None\n)\n
Manages components and makes them available in the template, by default as
{% component %}
tags.{% component \"my_comp\" key=value %}\n{% endcomponent %}\n
To enable a component to be used in a template, the component must be registered with a component registry.
When you register a component to a registry, behind the scenes the registry automatically adds the component's template tag (e.g.
{% component %}
to theLibrary
. And the opposite happens when you unregister a component - the tag is removed.See Registering components.
Parameters:
-
library
(Library
, default:None
) \u2013Django
Library
associated with this registry. If omitted, the default Library instance from django_components is used. -
settings
(Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]
, default:None
) \u2013Configure how the components registered with this registry will behave when rendered. See
RegistrySettings
. Can be either a static value or a callable that returns the settings. If omitted, the settings fromCOMPONENTS
are used.
Notes:
- The default registry is available as
django_components.registry
. - The default registry is used when registering components with
@register
decorator.
Example:
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry--using-registry-to-share-components","title":"Using registry to share components","text":"# 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
You can use component registry for isolating or \"packaging\" components:
-
Create new instance of
ComponentRegistry
and Library:my_comps = Library()\nmy_comps_reg = ComponentRegistry(library=my_comps)\n
-
Register components to the registry:
my_comps_reg.register(\"my_button\", ButtonComponent)\nmy_comps_reg.register(\"my_card\", CardComponent)\n
-
In your target project, load the Library associated with the registry:
{% load my_comps %}\n
-
Use the registered components in your templates:
{% component \"button\" %}\n{% endcomponent %}\n
Methods:
-
all
\u2013Retrieve all registered
Component
classes. -
clear
\u2013Clears the registry, unregistering all components.
-
get
\u2013Retrieve a
Component
-
register
\u2013Register a
Component
class -
unregister
\u2013Unregister the
Component
class
Attributes:
-
library
(Library
) \u2013The template tag
Library
-
settings
(InternalRegistrySettings
) \u2013Registry settings configured for this registry.
src/django_components/component_registry.py
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.library","title":"librarydef __init__(\n self,\n library: Optional[Library] = None,\n settings: Optional[Union[RegistrySettings, Callable[[\"ComponentRegistry\"], RegistrySettings]]] = None,\n) -> None:\n self._registry: Dict[str, ComponentRegistryEntry] = {} # component name -> component_entry mapping\n self._tags: Dict[str, Set[str]] = {} # tag -> list[component names]\n self._library = library\n self._settings_input = settings\n self._settings: Optional[Callable[[], InternalRegistrySettings]] = None\n\n all_registries.append(self)\n
property
","text":"library: Library\n
The template tag
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.settings","title":"settingsLibrary
that is associated with the registry.property
","text":"settings: InternalRegistrySettings\n
Registry settings configured for this registry.
"},{"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.Returns:
-
Dict[str, Type[Component]]
\u2013Dict[str, Type[Component]]: A dictionary of component names to component classes
Example:
Source code in# 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
src/django_components/component_registry.py
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.clear","title":"clear","text":"def all(self) -> Dict[str, Type[\"Component\"]]:\n \"\"\"\n Retrieve all registered [`Component`](../api#django_components.Component) classes.\n\n Returns:\n Dict[str, Type[Component]]: A dictionary of component names to component classes\n\n **Example:**\n\n ```python\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
clear() -> None\n
Clears the registry, unregistering all components.
Example:
Source code in# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then clear\nregistry.clear()\n# Then get all\nregistry.all()\n# > {}\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.get","title":"get","text":"def clear(self) -> None:\n \"\"\"\n Clears the registry, unregistering all components.\n\n Example:\n\n ```python\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
get(name: str) -> Type[Component]\n
Retrieve a
Component
class registered under the given name.Parameters:
-
name
(str
) \u2013The name under which the component was registered. Required.
Returns:
-
Type[Component]
\u2013Type[Component]: The component class registered under the given name.
Raises:
NotRegistered
if the given name is not registered.
Example:
Source code in# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then get\nregistry.get(\"button\")\n# > ButtonComponent\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.register","title":"register","text":"def get(self, name: str) -> Type[\"Component\"]:\n \"\"\"\n Retrieve a [`Component`](../api#django_components.Component)\n class registered under the given name.\n\n Args:\n name (str): The name under which the component was registered. Required.\n\n Returns:\n Type[Component]: The component class registered under the given name.\n\n **Raises:**\n\n - [`NotRegistered`](../exceptions#django_components.NotRegistered)\n if the given name is not registered.\n\n **Example:**\n\n ```python\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
register(name: str, component: Type[Component]) -> None\n
Register a
Component
class with this registry under the given name.A component MUST be registered before it can be used in a template such as:
{% component \"my_comp\" %}\n{% endcomponent %}\n
Parameters:
-
name
(str
) \u2013The name under which the component will be registered. Required.
-
component
(Type[Component]
) \u2013The component class to register. Required.
Raises:
AlreadyRegistered
if a different component was already registered under the same name.
Example:
Source code inregistry.register(\"button\", ButtonComponent)\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.unregister","title":"unregister","text":"def register(self, name: str, component: Type[\"Component\"]) -> None:\n \"\"\"\n Register a [`Component`](../api#django_components.Component) class\n 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\" %}\n {% endcomponent %}\n ```\n\n Args:\n name (str): The name under which the component will be registered. Required.\n component (Type[Component]): The component class to register. Required.\n\n **Raises:**\n\n - [`AlreadyRegistered`](../exceptions#django_components.AlreadyRegistered)\n if a different component was already registered under the same name.\n\n **Example:**\n\n ```python\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
unregister(name: str) -> None\n
Unregister the
Component
class that was registered under the given name.Once a component is unregistered, it is no longer available in the templates.
Parameters:
-
name
(str
) \u2013The name under which the component is registered. Required.
Raises:
NotRegistered
if the given name is not registered.
Example:
Source code in# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.NotRegistered","title":"NotRegistered","text":"def unregister(self, name: str) -> None:\n \"\"\"\n Unregister the [`Component`](../api#django_components.Component) class\n that was registered under the given name.\n\n Once a component is unregistered, it is no longer available in the templates.\n\n Args:\n name (str): The name under which the component is registered. Required.\n\n **Raises:**\n\n - [`NotRegistered`](../exceptions#django_components.NotRegistered)\n if the given name is not registered.\n\n **Example:**\n\n ```python\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
Bases:
Exception
Raised when you try to access a Component, but it's NOT registered with given ComponentRegistry.
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.RegistrySettings","title":"RegistrySettings","text":"Bases:
NamedTuple
Configuration for a
ComponentRegistry
.These settings define how the components registered with this registry will behave when rendered.
from django_components import ComponentRegistry, RegistrySettings\n\nregistry_settings = RegistrySettings(\n context_behavior=\"django\",\n tag_formatter=\"django_components.component_shorthand_formatter\",\n)\n\nregistry = ComponentRegistry(settings=registry_settings)\n
Attributes:
-
CONTEXT_BEHAVIOR
(Optional[ContextBehaviorType]
) \u2013Deprecated. Use
context_behavior
instead. Will be removed in v1. -
TAG_FORMATTER
(Optional[Union[TagFormatterABC, str]]
) \u2013Deprecated. Use
tag_formatter
instead. Will be removed in v1. -
context_behavior
(Optional[ContextBehaviorType]
) \u2013Same as the global
-
tag_formatter
(Optional[Union[TagFormatterABC, str]]
) \u2013Same as the global
class-attribute
instance-attribute
","text":"CONTEXT_BEHAVIOR: Optional[ContextBehaviorType] = None\n
Deprecated. Use
context_behavior
instead. Will be removed in v1.Same as the global
COMPONENTS.context_behavior
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.RegistrySettings.TAG_FORMATTER","title":"TAG_FORMATTERCOMPONENTS.context_behavior
setting.class-attribute
instance-attribute
","text":"TAG_FORMATTER: Optional[Union[TagFormatterABC, str]] = None\n
Deprecated. Use
tag_formatter
instead. Will be removed in v1.Same as the global
COMPONENTS.tag_formatter
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.RegistrySettings.context_behavior","title":"context_behaviorCOMPONENTS.tag_formatter
setting.class-attribute
instance-attribute
","text":"context_behavior: Optional[ContextBehaviorType] = None\n
Same as the global
COMPONENTS.context_behavior
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.RegistrySettings.tag_formatter","title":"tag_formatterCOMPONENTS.context_behavior
setting.class-attribute
instance-attribute
","text":"tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n
Same as the global
COMPONENTS.tag_formatter
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.register","title":"register","text":"COMPONENTS.tag_formatter
setting.register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[\n [Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]]],\n Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]],\n]\n
Class decorator for registering a component to a component registry.
See Registering components.
Parameters:
-
name
(str
) \u2013Registered name. This is the name by which the component will be accessed from within a template when using the
{% component %}
tag. Required. -
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to which to register this component. If omitted, component is registered to the default registry.
Raises:
-
AlreadyRegistered
\u2013If there is already a component registered under the same name.
Examples:
from django_components import Component, register\n\n@register(\"my_component\")\nclass MyComponent(Component):\n ...\n
Specifing
ComponentRegistry
the component should be registered to by setting theregistry
kwarg:
Source code infrom django.template import Library\nfrom django_components import Component, ComponentRegistry, register\n\nmy_lib = Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n ...\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/components/","title":"Index","text":""},{"location":"reference/django_components/components/#django_components.components","title":"components","text":"def register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[\n [Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"]],\n Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"],\n]:\n \"\"\"\n Class decorator for registering a [component](./#django_components.Component)\n to a [component registry](./#django_components.ComponentRegistry).\n\n See [Registering components](../../concepts/advanced/component_registry).\n\n Args:\n name (str): Registered name. This is the name by which the component will be accessed\\\n from within a template when using the [`{% component %}`](../template_tags#component) tag. Required.\n registry (ComponentRegistry, optional): Specify the [registry](./#django_components.ComponentRegistry)\\\n to which to register this component. If omitted, component is registered to the default registry.\n\n Raises:\n AlreadyRegistered: If there is already a component registered under the same name.\n\n **Examples**:\n\n ```python\n from django_components import Component, register\n\n @register(\"my_component\")\n class MyComponent(Component):\n ...\n ```\n\n Specifing [`ComponentRegistry`](./#django_components.ComponentRegistry) the component\n should be registered to by setting the `registry` kwarg:\n\n ```python\n from django.template import Library\n from django_components import Component, ComponentRegistry, register\n\n my_lib = 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(\n component: Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"],\n ) -> Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"]:\n registry.register(name=name, component=component)\n return component\n\n return decorator\n
Modules:
-
dynamic
\u2013
Classes:
-
DynamicComponent
\u2013This component is given a registered name or a reference to another component,
DynamicComponent(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Component
This component is given a registered name or a reference to another component, and behaves as if the other component was in its place.
The args, kwargs, and slot fills are all passed down to the underlying component.
Parameters:
-
is
(str | Type[Component]
) \u2013Component that should be rendered. Either a registered name of a component, or a Component class directly. Required.
-
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to search for the registered name. If omitted, all registries are searched until the first match.
-
*args
\u2013Additional data passed to the component.
-
**kwargs
\u2013Additional data passed to the component.
Slots:
- Any slots, depending on the actual component.
Examples:
Django
{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Python
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent--use-cases","title":"Use cases","text":"from django_components import DynamicComponent\n\nDynamicComponent.render(\n kwargs={\n \"is\": table_comp,\n \"data\": table_data,\n \"headers\": table_headers,\n },\n slots={\n \"pagination\": PaginationComponent.render(\n render_dependencies=False,\n ),\n },\n)\n
Dynamic components are suitable if you are writing something like a form component. You may design it such that users give you a list of input types, and you render components depending on the input types.
While you could handle this with a series of if / else statements, that's not an extensible approach. Instead, you can use the dynamic component in place of normal components.
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent--component-name","title":"Component name","text":"By default, the dynamic component is registered under the name
\"dynamic\"
. In case of a conflict, you can set theCOMPONENTS.dynamic_component_name
setting to change the name used for the dynamic components.# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
class-attribute
instance-attribute
","text":"Media = ComponentMediaInput\n
Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.css","title":"cssclass-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.input","title":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.media","title":"mediainstance-attribute
","text":"media: Media\n
Normalized definition of JS and CSS media files associated with this component.
NOTE: This field is generated from Component.Media class.
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.response_class","title":"response_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.template_name","title":"template_namerender_to_response
class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic","title":"dynamic","text":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
Modules:
-
types
\u2013Helper types for IDEs.
Classes:
-
DynamicComponent
\u2013This component is given a registered name or a reference to another component,
DynamicComponent(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Component
This component is given a registered name or a reference to another component, and behaves as if the other component was in its place.
The args, kwargs, and slot fills are all passed down to the underlying component.
Parameters:
-
is
(str | Type[Component]
) \u2013Component that should be rendered. Either a registered name of a component, or a Component class directly. Required.
-
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to search for the registered name. If omitted, all registries are searched until the first match.
-
*args
\u2013Additional data passed to the component.
-
**kwargs
\u2013Additional data passed to the component.
Slots:
- Any slots, depending on the actual component.
Examples:
Django
{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Python
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent--use-cases","title":"Use cases","text":"from django_components import DynamicComponent\n\nDynamicComponent.render(\n kwargs={\n \"is\": table_comp,\n \"data\": table_data,\n \"headers\": table_headers,\n },\n slots={\n \"pagination\": PaginationComponent.render(\n render_dependencies=False,\n ),\n },\n)\n
Dynamic components are suitable if you are writing something like a form component. You may design it such that users give you a list of input types, and you render components depending on the input types.
While you could handle this with a series of if / else statements, that's not an extensible approach. Instead, you can use the dynamic component in place of normal components.
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent--component-name","title":"Component name","text":"By default, the dynamic component is registered under the name
\"dynamic\"
. In case of a conflict, you can set theCOMPONENTS.dynamic_component_name
setting to change the name used for the dynamic components.# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
class-attribute
instance-attribute
","text":"Media = ComponentMediaInput\n
Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.css","title":"cssclass-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.input","title":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.media","title":"mediainstance-attribute
","text":"media: Media\n
Normalized definition of JS and CSS media files associated with this component.
NOTE: This field is generated from Component.Media class.
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.response_class","title":"response_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.template_name","title":"template_namerender_to_response
class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/","title":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
dynamic","text":""},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic","title":"dynamic","text":"
Modules:
-
types
\u2013Helper types for IDEs.
Classes:
-
DynamicComponent
\u2013This component is given a registered name or a reference to another component,
DynamicComponent(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Component
This component is given a registered name or a reference to another component, and behaves as if the other component was in its place.
The args, kwargs, and slot fills are all passed down to the underlying component.
Parameters:
-
is
(str | Type[Component]
) \u2013Component that should be rendered. Either a registered name of a component, or a Component class directly. Required.
-
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to search for the registered name. If omitted, all registries are searched until the first match.
-
*args
\u2013Additional data passed to the component.
-
**kwargs
\u2013Additional data passed to the component.
Slots:
- Any slots, depending on the actual component.
Examples:
Django
{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Python
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent--use-cases","title":"Use cases","text":"from django_components import DynamicComponent\n\nDynamicComponent.render(\n kwargs={\n \"is\": table_comp,\n \"data\": table_data,\n \"headers\": table_headers,\n },\n slots={\n \"pagination\": PaginationComponent.render(\n render_dependencies=False,\n ),\n },\n)\n
Dynamic components are suitable if you are writing something like a form component. You may design it such that users give you a list of input types, and you render components depending on the input types.
While you could handle this with a series of if / else statements, that's not an extensible approach. Instead, you can use the dynamic component in place of normal components.
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent--component-name","title":"Component name","text":"By default, the dynamic component is registered under the name
\"dynamic\"
. In case of a conflict, you can set theCOMPONENTS.dynamic_component_name
setting to change the name used for the dynamic components.# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
class-attribute
instance-attribute
","text":"Media = ComponentMediaInput\n
Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.css","title":"cssclass-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.input","title":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.media","title":"mediainstance-attribute
","text":"media: Media\n
Normalized definition of JS and CSS media files associated with this component.
NOTE: This field is generated from Component.Media class.
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.response_class","title":"response_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.template_name","title":"template_namerender_to_response
class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/context/","title":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
context","text":""},{"location":"reference/django_components/context/#django_components.context","title":"context","text":"
This file centralizes various ways we use Django's Context class pass data across components, nodes, slots, and contexts.
You can think of the Context as our storage system.
Functions:
-
copy_forloop_context
\u2013Forward the info about the current loop
-
get_injected_context_var
\u2013Retrieve a 'provided' field. The field MUST have been previously 'provided'
-
set_provided_context_var
\u2013'Provide' given data under given key. In other words, this data can be retrieved
copy_forloop_context(from_context: Context, to_context: Context) -> None\n
Forward the info about the current loop
Source code insrc/django_components/context.py
"},{"location":"reference/django_components/context/#django_components.context.get_injected_context_var","title":"get_injected_context_var","text":"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
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
Source code in{% provide %}
template tag.src/django_components/context.py
"},{"location":"reference/django_components/context/#django_components.context.set_provided_context_var","title":"set_provided_context_var","text":"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
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
Source code inself.inject(key)
inside ofget_context_data()
method of components that are nested inside the{% provide %}
tag.src/django_components/context.py
"},{"location":"reference/django_components/dependencies/","title":"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
dependencies","text":""},{"location":"reference/django_components/dependencies/#django_components.dependencies","title":"dependencies","text":"
All code related to management of component dependencies (JS and CSS scripts)
Modules:
-
types
\u2013Helper types for IDEs.
Classes:
-
ComponentDependencyMiddleware
\u2013Middleware that inserts CSS/JS dependencies for all rendered
Functions:
-
render_dependencies
\u2013Given a string that contains parts that were rendered by components,
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 insrc/django_components/dependencies.py
"},{"location":"reference/django_components/dependencies/#django_components.dependencies.render_dependencies","title":"render_dependencies","text":"def __init__(self, get_response: \"Callable[[HttpRequest], HttpResponse]\") -> None:\n self.get_response = get_response\n\n # NOTE: Required to work with async\n if iscoroutinefunction(self.get_response):\n markcoroutinefunction(self)\n
render_dependencies(content: TContent, type: RenderType = 'document') -> TContent\n
Given a string that contains parts that were rendered by components, this function inserts all used JS and CSS.
By default, the string is parsed as an HTML and: - CSS is inserted at the end of
<head>
(if present) - JS is inserted at the end of<body>
(if present)If you used
{% component_js_dependencies %}
or{% component_css_dependencies %}
, then the JS and CSS will be inserted only at these locations.Example:
Source code indef my_view(request):\n template = Template('''\n {% load components %}\n <!doctype html>\n <html>\n <head></head>\n <body>\n <h1>{{ table_name }}</h1>\n {% component \"table\" name=table_name / %}\n </body>\n </html>\n ''')\n\n html = template.render(\n Context({\n \"table_name\": request.GET[\"name\"],\n })\n )\n\n # This inserts components' JS and CSS\n processed_html = render_dependencies(html)\n\n return HttpResponse(processed_html)\n
src/django_components/dependencies.py
"},{"location":"reference/django_components/expression/","title":"def render_dependencies(content: TContent, type: RenderType = \"document\") -> TContent:\n \"\"\"\n Given a string that contains parts that were rendered by components,\n this function inserts all used JS and CSS.\n\n By default, the string is parsed as an HTML and:\n - CSS is inserted at the end of `<head>` (if present)\n - JS is inserted at the end of `<body>` (if present)\n\n If you used `{% component_js_dependencies %}` or `{% component_css_dependencies %}`,\n then the JS and CSS will be inserted only at these locations.\n\n Example:\n ```python\n def my_view(request):\n template = Template('''\n {% load components %}\n <!doctype html>\n <html>\n <head></head>\n <body>\n <h1>{{ table_name }}</h1>\n {% component \"table\" name=table_name / %}\n </body>\n </html>\n ''')\n\n html = template.render(\n Context({\n \"table_name\": request.GET[\"name\"],\n })\n )\n\n # This inserts components' JS and CSS\n processed_html = render_dependencies(html)\n\n return HttpResponse(processed_html)\n ```\n \"\"\"\n is_safestring = isinstance(content, SafeString)\n\n if isinstance(content, str):\n content_ = content.encode()\n else:\n content_ = cast(bytes, content)\n\n content_, js_dependencies, css_dependencies = _process_dep_declarations(content_, type)\n\n # Replace the placeholders with the actual content\n did_find_js_placeholder = False\n did_find_css_placeholder = False\n\n def on_replace_match(match: \"re.Match[bytes]\") -> bytes:\n nonlocal did_find_css_placeholder\n nonlocal did_find_js_placeholder\n\n if match[0] == CSS_PLACEHOLDER_BYTES:\n replacement = css_dependencies\n did_find_css_placeholder = True\n elif match[0] == JS_PLACEHOLDER_BYTES:\n replacement = js_dependencies\n did_find_js_placeholder = True\n else:\n raise RuntimeError(\n \"Unexpected error: Regex for component dependencies processing\"\n f\" matched unknown string '{match[0].decode()}'\"\n )\n return replacement\n\n content_ = PLACEHOLDER_REGEX.sub(on_replace_match, content_)\n\n # By default, if user didn't specify any `{% component_dependencies %}`,\n # then try to insert the JS scripts at the end of <body> and CSS sheets at the end\n # of <head>\n if type == \"document\" and (not did_find_js_placeholder or not did_find_css_placeholder):\n tree = parse_document_or_nodes(content_.decode())\n\n if isinstance(tree, LexborHTMLParser):\n did_modify_html = False\n\n if not did_find_css_placeholder and tree.head:\n css_elems = parse_multiroot_html(css_dependencies.decode())\n for css_elem in css_elems:\n tree.head.insert_child(css_elem) # type: ignore # TODO: Update to selectolax 0.3.25\n did_modify_html = True\n\n if not did_find_js_placeholder and tree.body:\n js_elems = parse_multiroot_html(js_dependencies.decode())\n for js_elem in js_elems:\n tree.body.insert_child(js_elem) # type: ignore # TODO: Update to selectolax 0.3.25\n did_modify_html = True\n\n transformed = cast(str, tree.html)\n if did_modify_html:\n content_ = transformed.encode()\n\n # Return the same type as we were given\n output = content_.decode() if isinstance(content, str) else content_\n output = mark_safe(output) if is_safestring else output\n return cast(TContent, output)\n
expression","text":""},{"location":"reference/django_components/expression/#django_components.expression","title":"expression","text":"
Classes:
-
Operator
\u2013Operator describes something that somehow changes the inputs
-
SpreadOperator
\u2013Operator that inserts one or more kwargs at the specified location.
Functions:
-
process_aggregate_kwargs
\u2013This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs
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 insrc/django_components/expression.py
"},{"location":"reference/django_components/expression/#django_components.expression.process_aggregate_kwargs","title":"process_aggregate_kwargs","text":"def __init__(self, expr: Expression) -> None:\n self.expr = expr\n
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 theattrs
dict.So, instead, we allow to \"aggregate\" props into a dict. So all props that start with
attrs:
, likeattrs:class=\"text-red\"
, will be collected into a dict at keyattrs
.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 insrc/django_components/expression.py
"},{"location":"reference/django_components/finders/","title":"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
finders","text":""},{"location":"reference/django_components/finders/#django_components.finders","title":"finders","text":"
Classes:
-
ComponentsFileSystemFinder
\u2013A static files finder based on
FileSystemFinder
.
ComponentsFileSystemFinder(app_names: Any = None, *args: Any, **kwargs: Any)\n
Bases:
BaseFinder
A static files finder based on
FileSystemFinder
.Differences: - This finder uses
COMPONENTS.dirs
setting to locate files instead ofSTATICFILES_DIRS
. - Whether a file withinCOMPONENTS.dirs
is considered a STATIC file is configured byCOMPONENTS.static_files_allowed
andCOMPONENTS.static_files_forbidden
. - IfCOMPONENTS.dirs
is not set, defaults tosettings.BASE_DIR / \"components\"
Methods:
-
find
\u2013Look for files in the extra locations as defined in COMPONENTS.dirs.
-
find_location
\u2013Find a requested static file in a location and return the found
-
list
\u2013List all files in all locations.
src/django_components/finders.py
"},{"location":"reference/django_components/finders/#django_components.finders.ComponentsFileSystemFinder.find","title":"find","text":"def __init__(self, app_names: Any = None, *args: Any, **kwargs: Any) -> None:\n component_dirs = [str(p) for p in get_component_dirs()]\n\n # NOTE: The rest of the __init__ is the same as `django.contrib.staticfiles.finders.FileSystemFinder`,\n # but using our locations instead of STATICFILES_DIRS.\n\n # List of locations with static files\n self.locations: List[Tuple[str, str]] = []\n\n # Maps dir paths to an appropriate storage instance\n self.storages: Dict[str, FileSystemStorage] = {}\n for root in component_dirs:\n if isinstance(root, (list, tuple)):\n prefix, root = root\n else:\n prefix = \"\"\n if (prefix, root) not in self.locations:\n self.locations.append((prefix, root))\n for prefix, root in self.locations:\n filesystem_storage = FileSystemStorage(location=root)\n filesystem_storage.prefix = prefix\n self.storages[root] = filesystem_storage\n\n super().__init__(*args, **kwargs)\n
find(path: str, all: bool = False) -> Union[List[str], str]\n
Look for files in the extra locations as defined in COMPONENTS.dirs.
Source code insrc/django_components/finders.py
"},{"location":"reference/django_components/finders/#django_components.finders.ComponentsFileSystemFinder.find_location","title":"find_location","text":"def find(self, path: str, all: bool = False) -> Union[List[str], str]:\n \"\"\"\n Look for files in the extra locations as defined in COMPONENTS.dirs.\n \"\"\"\n matches: List[str] = []\n for prefix, root in self.locations:\n if root not in searched_locations:\n searched_locations.append(root)\n matched_path = self.find_location(root, path, prefix)\n if matched_path:\n if not all:\n return matched_path\n matches.append(matched_path)\n return matches\n
find_location(root: str, path: str, prefix: Optional[str] = None) -> Optional[str]\n
Find a requested static file in a location and return the found absolute path (or
Source code inNone
if no match).src/django_components/finders.py
"},{"location":"reference/django_components/finders/#django_components.finders.ComponentsFileSystemFinder.list","title":"list","text":"def find_location(self, root: str, path: str, prefix: Optional[str] = None) -> Optional[str]:\n \"\"\"\n Find a requested static file in a location and return the found\n absolute path (or ``None`` if no match).\n \"\"\"\n if prefix:\n prefix = \"%s%s\" % (prefix, os.sep)\n if not path.startswith(prefix):\n return None\n path = path.removeprefix(prefix)\n path = safe_join(root, path)\n\n if os.path.exists(path) and self._is_path_valid(path):\n return path\n return None\n
list(ignore_patterns: List[str]) -> Iterable[Tuple[str, FileSystemStorage]]\n
List all files in all locations.
Source code insrc/django_components/finders.py
"},{"location":"reference/django_components/library/","title":"def list(self, ignore_patterns: List[str]) -> Iterable[Tuple[str, FileSystemStorage]]:\n \"\"\"\n List all files in all locations.\n \"\"\"\n for prefix, root in self.locations:\n # Skip nonexistent directories.\n if os.path.isdir(root):\n storage = self.storages[root]\n for path in get_files(storage, ignore_patterns):\n if self._is_path_valid(path):\n yield path, storage\n
library","text":""},{"location":"reference/django_components/library/#django_components.library","title":"library","text":"
Module for interfacing with Django's Library (
django.template.library
)Classes:
-
TagProtectedError
\u2013The way the
TagFormatter
works is that,
Attributes:
-
PROTECTED_TAGS
\u2013These are the names that users cannot choose for their components,
module-attribute
","text":"PROTECTED_TAGS = ['component_css_dependencies', 'component_js_dependencies', 'fill', 'html_attrs', 'provide', 'slot']\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/library/#django_components.library.TagProtectedError","title":"TagProtectedError","text":"Bases:
Exception
The way the
TagFormatter
works is that, based on which start and end tags are used for rendering components, theComponentRegistry
behind the scenes un-/registers the template tags with the associated instance of Django'sLibrary
.In other words, if I have registered a component
\"table\"
, and I use the shorthand syntax:{% table ... %}\n{% endtable %}\n
Then
ComponentRegistry
registers the tagtable
onto the Django's Library instance.However, that means that if we registered a component
\"slot\"
, then we would overwrite the{% slot %}
tag from django_components.Thus, this exception is raised when a component is attempted to be registered under a forbidden name, such that it would overwrite one of django_component's own template tags.
"},{"location":"reference/django_components/management/","title":"Index","text":""},{"location":"reference/django_components/management/#django_components.management","title":"management","text":"Modules:
-
commands
\u2013
Modules:
-
startcomponent
\u2013
Classes:
-
Command
\u2013
Bases:
"},{"location":"reference/django_components/management/#django_components.management.commands.startcomponent.Command--management-command-usage","title":"Management Command Usage","text":"BaseCommand
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
"},{"location":"reference/django_components/management/#django_components.management.commands.startcomponent.Command--management-command-examples","title":"Management Command Examples","text":"<name>
,<path>
,<js_filename>
,<css_filename>
, and<template_filename>
with your desired values.Here are some examples of how you can use the command:
"},{"location":"reference/django_components/management/#django_components.management.commands.startcomponent.Command--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
"},{"location":"reference/django_components/management/#django_components.management.commands.startcomponent.Command--creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"my_component
in thecomponents
directory of your Django project. The JavaScript, CSS, and template files will be namedscript.js
,style.css
, andtemplate.html
, respectively.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
"},{"location":"reference/django_components/management/#django_components.management.commands.startcomponent.Command--overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"new_component
in themy_components
directory. The JavaScript, CSS, and template files will be namedmy_script.js
,my_style.css
, andmy_template.html
, respectively.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
"},{"location":"reference/django_components/management/#django_components.management.commands.startcomponent.Command--simulating-component-creation","title":"Simulating Component Creation","text":"my_component
if it exists.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
"},{"location":"reference/django_components/management/commands/","title":"Index","text":""},{"location":"reference/django_components/management/commands/#django_components.management.commands","title":"commands","text":"my_component
without creating any files.Modules:
-
startcomponent
\u2013
Classes:
-
Command
\u2013
Bases:
"},{"location":"reference/django_components/management/commands/#django_components.management.commands.startcomponent.Command--management-command-usage","title":"Management Command Usage","text":"BaseCommand
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
"},{"location":"reference/django_components/management/commands/#django_components.management.commands.startcomponent.Command--management-command-examples","title":"Management Command Examples","text":"<name>
,<path>
,<js_filename>
,<css_filename>
, and<template_filename>
with your desired values.Here are some examples of how you can use the command:
"},{"location":"reference/django_components/management/commands/#django_components.management.commands.startcomponent.Command--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
"},{"location":"reference/django_components/management/commands/#django_components.management.commands.startcomponent.Command--creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"my_component
in thecomponents
directory of your Django project. The JavaScript, CSS, and template files will be namedscript.js
,style.css
, andtemplate.html
, respectively.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
"},{"location":"reference/django_components/management/commands/#django_components.management.commands.startcomponent.Command--overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"new_component
in themy_components
directory. The JavaScript, CSS, and template files will be namedmy_script.js
,my_style.css
, andmy_template.html
, respectively.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
"},{"location":"reference/django_components/management/commands/#django_components.management.commands.startcomponent.Command--simulating-component-creation","title":"Simulating Component Creation","text":"my_component
if it exists.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
"},{"location":"reference/django_components/management/commands/startcomponent/","title":"my_component
without creating any files.startcomponent","text":""},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent","title":"startcomponent","text":"
Classes:
-
Command
\u2013
Bases:
"},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent.Command--management-command-usage","title":"Management Command Usage","text":"BaseCommand
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
"},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent.Command--management-command-examples","title":"Management Command Examples","text":"<name>
,<path>
,<js_filename>
,<css_filename>
, and<template_filename>
with your desired values.Here are some examples of how you can use the command:
"},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent.Command--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
"},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent.Command--creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"my_component
in thecomponents
directory of your Django project. The JavaScript, CSS, and template files will be namedscript.js
,style.css
, andtemplate.html
, respectively.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
"},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent.Command--overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"new_component
in themy_components
directory. The JavaScript, CSS, and template files will be namedmy_script.js
,my_style.css
, andmy_template.html
, respectively.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
"},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent.Command--simulating-component-creation","title":"Simulating Component Creation","text":"my_component
if it exists.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
"},{"location":"reference/django_components/management/commands/upgradecomponent/","title":"my_component
without creating any files.upgradecomponent","text":""},{"location":"reference/django_components/management/commands/upgradecomponent/#django_components.management.commands.upgradecomponent","title":"upgradecomponent","text":""},{"location":"reference/django_components/middleware/","title":"
middleware","text":""},{"location":"reference/django_components/middleware/#django_components.middleware","title":"middleware","text":"
Classes:
-
ComponentDependencyMiddleware
\u2013Middleware that inserts CSS/JS dependencies for all rendered
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 insrc/django_components/dependencies.py
"},{"location":"reference/django_components/node/","title":"def __init__(self, get_response: \"Callable[[HttpRequest], HttpResponse]\") -> None:\n self.get_response = get_response\n\n # NOTE: Required to work with async\n if iscoroutinefunction(self.get_response):\n markcoroutinefunction(self)\n
node","text":""},{"location":"reference/django_components/node/#django_components.node","title":"node","text":"
Classes:
-
BaseNode
\u2013Shared behavior for our subclasses of Django's
Node
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
Source code inNode
src/django_components/node.py
"},{"location":"reference/django_components/provide/","title":"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
provide","text":""},{"location":"reference/django_components/provide/#django_components.provide","title":"provide","text":"
Classes:
-
ProvideNode
\u2013Implementation of the
{% provide %}
tag.
ProvideNode(nodelist: NodeList, trace_id: str, node_id: Optional[str] = None, kwargs: Optional[RuntimeKwargs] = None)\n
Bases:
BaseNode
Implementation of the
Source code in{% provide %}
tag. For more info seeComponent.inject
.src/django_components/provide.py
"},{"location":"reference/django_components/slots/","title":"def __init__(\n self,\n nodelist: NodeList,\n trace_id: str,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.nodelist = nodelist\n self.node_id = node_id or gen_id()\n self.trace_id = trace_id\n self.kwargs = kwargs or RuntimeKwargs({})\n
slots","text":""},{"location":"reference/django_components/slots/#django_components.slots","title":"slots","text":"
Classes:
-
FillNode
\u2013Node corresponding to
{% fill %}
-
Slot
\u2013This class holds the slot content function along with related metadata.
-
SlotFill
\u2013SlotFill describes what WILL be rendered.
-
SlotIsFilled
\u2013Dictionary that returns
True
if the slot is filled (key is found),False
otherwise. -
SlotNode
\u2013Node corresponding to
{% slot %}
-
SlotRef
\u2013SlotRef allows to treat a slot as a variable. The slot is rendered only once
Functions:
-
resolve_fills
\u2013Given a component body (
django.template.NodeList
), find all slot fills,
FillNode(nodelist: NodeList, kwargs: RuntimeKwargs, trace_id: str, node_id: Optional[str] = None)\n
Bases:
BaseNode
Node corresponding to
Source code in{% fill %}
src/django_components/slots.py
"},{"location":"reference/django_components/slots/#django_components.slots.Slot","title":"Slotdef __init__(\n self,\n nodelist: NodeList,\n kwargs: RuntimeKwargs,\n trace_id: str,\n node_id: Optional[str] = None,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.trace_id = trace_id\n
dataclass
","text":"Slot(content_func: SlotFunc[TSlotData])\n
Bases:
Generic[TSlotData]
This class holds the slot content function along with related metadata.
"},{"location":"reference/django_components/slots/#django_components.slots.SlotFill","title":"SlotFilldataclass
","text":"SlotFill(name: str, is_filled: bool, slot: Slot[TSlotData])\n
Bases:
Generic[TSlotData]
SlotFill describes what WILL be rendered.
The fill may be provided by the user from the outside (
is_filled=True
), or it may be the default content of the slot (is_filled=False
).Attributes:
-
name
(str
) \u2013Name of the slot.
instance-attribute
","text":"name: str\n
Name of the slot.
"},{"location":"reference/django_components/slots/#django_components.slots.SlotIsFilled","title":"SlotIsFilled","text":"SlotIsFilled(fills: Dict, *args: Any, **kwargs: Any)\n
Bases:
dict
Dictionary that returns
Source code inTrue
if the slot is filled (key is found),False
otherwise.src/django_components/slots.py
"},{"location":"reference/django_components/slots/#django_components.slots.SlotNode","title":"SlotNode","text":"def __init__(self, fills: Dict, *args: Any, **kwargs: Any) -> None:\n escaped_fill_names = {_escape_slot_name(fill_name): True for fill_name in fills.keys()}\n super().__init__(escaped_fill_names, *args, **kwargs)\n
SlotNode(\n nodelist: NodeList,\n trace_id: str,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n is_required: bool = False,\n is_default: bool = False,\n)\n
Bases:
BaseNode
Node corresponding to
Source code in{% slot %}
src/django_components/slots.py
"},{"location":"reference/django_components/slots/#django_components.slots.SlotRef","title":"SlotRef","text":"def __init__(\n self,\n nodelist: NodeList,\n trace_id: str,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n is_required: bool = False,\n is_default: bool = False,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.is_required = is_required\n self.is_default = is_default\n self.trace_id = trace_id\n
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
Source code in{{ my_lazy_slot }}
, it will output the contents of the slot.src/django_components/slots.py
"},{"location":"reference/django_components/slots/#django_components.slots.resolve_fills","title":"resolve_fills","text":"def __init__(self, slot: \"SlotNode\", context: Context):\n self._slot = slot\n self._context = context\n
resolve_fills(context: Context, nodelist: NodeList, component_name: str) -> Dict[SlotName, Slot]\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 finds 2 fill nodes: \"first_fill\" and \"second_fill\", and formats them as slot functions, returning:
{\n \"first_fill\": SlotFunc(...),\n \"second_fill\": SlotFunc(...),\n}\n
If no fill nodes are found, then the content is treated as default slot content.
{\n DEFAULT_SLOT_KEY: SlotFunc(...),\n}\n
This function also handles for-loops, if/else statements, or include tags to generate fill tags:
Source code in{% component \"mycomponent\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name %}\n {% slot name=slot_name / %}\n {% endfill %}\n {% endfor %}\n{% endcomponent %}\n
src/django_components/slots.py
"},{"location":"reference/django_components/tag_formatter/","title":"def resolve_fills(\n context: Context,\n nodelist: NodeList,\n component_name: str,\n) -> Dict[SlotName, Slot]:\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\n Then this function finds 2 fill nodes: \"first_fill\" and \"second_fill\",\n and formats them as slot functions, returning:\n\n ```python\n {\n \"first_fill\": SlotFunc(...),\n \"second_fill\": SlotFunc(...),\n }\n ```\n\n If no fill nodes are found, then the content is treated as default slot content.\n\n ```python\n {\n DEFAULT_SLOT_KEY: SlotFunc(...),\n }\n ```\n\n This function also handles for-loops, if/else statements, or include tags to generate fill tags:\n\n ```django\n {% component \"mycomponent\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name %}\n {% slot name=slot_name / %}\n {% endfill %}\n {% endfor %}\n {% endcomponent %}\n ```\n \"\"\"\n slots: Dict[SlotName, Slot] = {}\n\n if not nodelist:\n return slots\n\n maybe_fills = _extract_fill_content(nodelist, context, component_name)\n\n # The content has no fills, so treat it as default slot, e.g.:\n # {% component \"mycomponent\" %}\n # Hello!\n # {% if True %} 123 {% endif %}\n # {% endcomponent %}\n if maybe_fills is False:\n # Ignore empty content between `{% component %} ... {% endcomponent %}` tags\n nodelist_is_empty = not len(nodelist) or all(\n isinstance(node, TextNode) and not node.s.strip() for node in nodelist\n )\n\n if not nodelist_is_empty:\n slots[DEFAULT_SLOT_KEY] = _nodelist_to_slot_render_func(\n DEFAULT_SLOT_KEY,\n nodelist,\n data_var=None,\n default_var=None,\n )\n\n # The content has fills\n else:\n # NOTE: If slot fills are explicitly defined, we use them even if they are empty (or only whitespace).\n # This is different from the default slot, where we ignore empty content.\n for fill in maybe_fills:\n slots[fill.name] = _nodelist_to_slot_render_func(\n slot_name=fill.name,\n nodelist=fill.fill.nodelist,\n data_var=fill.data_var,\n default_var=fill.default_var,\n extra_context=fill.extra_context,\n )\n\n return slots\n
tag_formatter","text":""},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter","title":"tag_formatter","text":"
Classes:
-
ComponentFormatter
\u2013The original django_component's component tag formatter, it uses the
{% component %}
-
InternalTagFormatter
\u2013Internal wrapper around user-provided TagFormatters, so that we validate the outputs.
-
ShorthandComponentFormatter
\u2013The component tag formatter that uses
{% <name> %}
/{% end<name> %}
tags. -
TagFormatterABC
\u2013Abstract base class for defining custom tag formatters.
-
TagResult
\u2013The return value from
TagFormatter.parse()
.
Functions:
-
get_tag_formatter
\u2013Returns an instance of the currently configured component tag formatter.
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 given as the first positional arg.Example as block:
{% component \"mycomp\" abc=123 %}\n {% fill \"myfill\" %}\n ...\n {% endfill %}\n{% endcomponent %}\n
Example as inlined tag:
Source code in{% component \"mycomp\" abc=123 / %}\n
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.InternalTagFormatter","title":"InternalTagFormatter","text":"def __init__(self, tag: str):\n self.tag = tag\n
InternalTagFormatter(tag_formatter: TagFormatterABC)\n
Internal wrapper around user-provided TagFormatters, so that we validate the outputs.
Source code insrc/django_components/tag_formatter.py
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":"def __init__(self, tag_formatter: TagFormatterABC):\n self.tag_formatter = tag_formatter\n
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:
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC","title":"TagFormatterABC","text":"{% mycomp abc=123 / %}\n
Bases:
ABC
Abstract base class for defining custom tag formatters.
Tag formatters define how the component tags are used in the template.
Read more about Tag formatter.
For example, with the default tag formatter (
ComponentFormatter
), components are written as:{% component \"comp_name\" %}\n{% endcomponent %}\n
While with the shorthand tag formatter (
ShorthandComponentFormatter
), components are written as:{% comp_name %}\n{% endcomp_name %}\n
Example:
Implementation for
ShorthandComponentFormatter
:from djagno_components import TagFormatterABC, TagResult\n\nclass ShorthandComponentFormatter(TagFormatterABC):\n def start_tag(self, name: str) -> str:\n return name\n\n def end_tag(self, name: str) -> str:\n return f\"end{name}\"\n\n def parse(self, tokens: List[str]) -> TagResult:\n tokens = [*tokens]\n name = tokens.pop(0)\n return TagResult(name, tokens)\n
Methods:
-
end_tag
\u2013Formats the end tag of a block component.
-
parse
\u2013Given the tokens (words) passed to a component start tag, this function extracts
-
start_tag
\u2013Formats the start tag of a component.
abstractmethod
","text":"end_tag(name: str) -> str\n
Formats the end tag of a block component.
Parameters:
-
name
(str
) \u2013Component's registered name. Required.
Returns:
-
str
(str
) \u2013The formatted end tag.
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC.parse","title":"parse@abc.abstractmethod\ndef end_tag(self, name: str) -> str:\n \"\"\"\n Formats the end tag of a block component.\n\n Args:\n name (str): Component's registered name. Required.\n\n Returns:\n str: The formatted end tag.\n \"\"\"\n ...\n
abstractmethod
","text":"parse(tokens: List[str]) -> TagResult\n
Given the tokens (words) passed to a component start tag, this function extracts the component name from the tokens list, and returns
TagResult
, which is a tuple of(component_name, remaining_tokens)
.Parameters:
-
tokens
([List(str]
) \u2013List of tokens passed to the component tag.
Returns:
-
TagResult
(TagResult
) \u2013Parsed component name and remaining tokens.
Example:
Assuming we used a component in a template like this:
{% component \"my_comp\" key=val key2=val2 %}\n{% endcomponent %}\n
This function receives a list of tokens:
['component', '\"my_comp\"', 'key=val', 'key2=val2']\n
component
is the tag name, which we drop.\"my_comp\"
is the component name, but we must remove the extra quotes.- The remaining tokens we pass unmodified, as that's the input to the component.
So in the end, we return:
Source code inTagResult('my_comp', ['key=val', 'key2=val2'])\n
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC.start_tag","title":"start_tag@abc.abstractmethod\ndef parse(self, tokens: List[str]) -> TagResult:\n \"\"\"\n Given the tokens (words) passed to a component start tag, this function extracts\n the component name from the tokens list, and returns\n [`TagResult`](../api#django_components.TagResult),\n which is a tuple of `(component_name, remaining_tokens)`.\n\n Args:\n tokens [List(str]): List of tokens passed to the component tag.\n\n Returns:\n TagResult: Parsed component name and remaining tokens.\n\n **Example:**\n\n Assuming we used a component in a template like this:\n\n ```django\n {% component \"my_comp\" key=val key2=val2 %}\n {% endcomponent %}\n ```\n\n This function receives a list of tokens:\n\n ```python\n ['component', '\"my_comp\"', 'key=val', 'key2=val2']\n ```\n\n - `component` is the tag name, which we drop.\n - `\"my_comp\"` is the component name, but we must remove the extra quotes.\n - The remaining tokens we pass unmodified, as that's the input to the component.\n\n So in the end, we return:\n\n ```python\n TagResult('my_comp', ['key=val', 'key2=val2'])\n ```\n \"\"\"\n ...\n
abstractmethod
","text":"start_tag(name: str) -> str\n
Formats the start tag of a component.
Parameters:
-
name
(str
) \u2013Component's registered name. Required.
Returns:
-
str
(str
) \u2013The formatted start tag.
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagResult","title":"TagResult","text":"@abc.abstractmethod\ndef start_tag(self, name: str) -> str:\n \"\"\"\n Formats the start tag of a component.\n\n Args:\n name (str): Component's registered name. Required.\n\n Returns:\n str: The formatted start tag.\n \"\"\"\n ...\n
Bases:
NamedTuple
The return value from
TagFormatter.parse()
.Read more about Tag formatter.
Attributes:
-
component_name
(str
) \u2013Component name extracted from the template tag
-
tokens
(List[str]
) \u2013Remaining tokens (words) that were passed to the tag, with component name removed
instance-attribute
","text":"component_name: str\n
Component name extracted from the template tag
For example, if we had tag
{% component \"my_comp\" key=val key2=val2 %}\n
Then
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagResult.tokens","title":"tokenscomponent_name
would bemy_comp
.instance-attribute
","text":"tokens: List[str]\n
Remaining tokens (words) that were passed to the tag, with component name removed
For example, if we had tag
{% component \"my_comp\" key=val key2=val2 %}\n
Then
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.get_tag_formatter","title":"get_tag_formatter","text":"tokens
would be['key=val', 'key2=val2']
.get_tag_formatter(registry: ComponentRegistry) -> InternalTagFormatter\n
Returns an instance of the currently configured component tag formatter.
Source code insrc/django_components/tag_formatter.py
"},{"location":"reference/django_components/template/","title":"def get_tag_formatter(registry: \"ComponentRegistry\") -> InternalTagFormatter:\n \"\"\"Returns an instance of the currently configured component tag formatter.\"\"\"\n # Allow users to configure the component TagFormatter\n formatter_cls_or_str = registry.settings.tag_formatter\n\n if isinstance(formatter_cls_or_str, str):\n tag_formatter: TagFormatterABC = import_string(formatter_cls_or_str)\n else:\n tag_formatter = formatter_cls_or_str\n\n return InternalTagFormatter(tag_formatter)\n
template","text":""},{"location":"reference/django_components/template/#django_components.template","title":"template","text":"
Functions:
-
cached_template
\u2013Create a Template instance that will be cached as per the
cached_template(\n template_string: str,\n template_cls: Optional[Type[Template]] = None,\n origin: Optional[Origin] = None,\n name: Optional[str] = None,\n engine: Optional[Any] = None,\n) -> Template\n
Create a Template instance that will be cached as per the
COMPONENTS.template_cache_size
setting.Parameters:
-
template_string
(str
) \u2013Template as a string, same as the first argument to Django's
Template
. Required. -
template_cls
(Type[Template]
, default:None
) \u2013Specify the Template class that should be instantiated. Defaults to Django's
Template
class. -
origin
(Type[Origin]
, default:None
) \u2013Sets
Template.Origin
. -
name
(Type[str]
, default:None
) \u2013Sets
Template.name
-
engine
(Type[Any]
, default:None
) \u2013Sets
Template.engine
Source code infrom django_components import cached_template\n\ntemplate = cached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n pass\n\ntemplate = cached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n)\n
src/django_components/template.py
"},{"location":"reference/django_components/template_loader/","title":"def cached_template(\n template_string: str,\n template_cls: Optional[Type[Template]] = None,\n origin: Optional[Origin] = None,\n name: Optional[str] = None,\n engine: Optional[Any] = None,\n) -> Template:\n \"\"\"\n Create a Template instance that will be cached as per the\n [`COMPONENTS.template_cache_size`](../settings#django_components.app_settings.ComponentsSettings.template_cache_size)\n setting.\n\n Args:\n template_string (str): Template as a string, same as the first argument to Django's\\\n [`Template`](https://docs.djangoproject.com/en/5.1/topics/templates/#template). Required.\n template_cls (Type[Template], optional): Specify the Template class that should be instantiated.\\\n Defaults to Django's [`Template`](https://docs.djangoproject.com/en/5.1/topics/templates/#template) class.\n origin (Type[Origin], optional): Sets \\\n [`Template.Origin`](https://docs.djangoproject.com/en/5.1/howto/custom-template-backend/#origin-api-and-3rd-party-integration).\n name (Type[str], optional): Sets `Template.name`\n engine (Type[Any], optional): Sets `Template.engine`\n\n ```python\n from django_components import cached_template\n\n template = cached_template(\"Variable: {{ variable }}\")\n\n # You can optionally specify Template class, and other Template inputs:\n class MyTemplate(Template):\n pass\n\n template = cached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n )\n ```\n \"\"\" # noqa: E501\n template = _create_template(template_cls or Template, template_string, engine)\n\n # Assign the origin and name separately, so the caching doesn't depend on them\n # Since we might be accessing a template from cache, we want to define these only once\n if not getattr(template, \"_dc_cached\", False):\n template.origin = origin or Origin(UNKNOWN_SOURCE)\n template.name = name\n template._dc_cached = True\n\n return template\n
template_loader","text":""},{"location":"reference/django_components/template_loader/#django_components.template_loader","title":"template_loader","text":"
Template loader that loads templates from each Django app's \"components\" directory.
Classes:
-
Loader
\u2013
Bases:
Loader
Methods:
-
get_dirs
\u2013Prepare directories that may contain component files:
get_dirs(include_apps: bool = True) -> List[Path]\n
Prepare directories that may contain component files:
Searches for dirs set in
COMPONENTS.dirs
settings. If none set, defaults to searching for a \"components\" app. The dirs inCOMPONENTS.dirs
must be absolute paths.In addition to that, also all apps are checked for
[app]/components
dirs.Paths are accepted only if they resolve to a directory. E.g.
/path/to/django_project/my_app/components/
.
Source code inBASE_DIR
setting is required.src/django_components/template_loader.py
"},{"location":"reference/django_components/template_parser/","title":"def get_dirs(self, include_apps: bool = True) -> List[Path]:\n \"\"\"\n Prepare directories that may contain component files:\n\n Searches for dirs set in `COMPONENTS.dirs` settings. If none set, defaults to searching\n for a \"components\" app. The dirs in `COMPONENTS.dirs` must be absolute paths.\n\n In addition to that, also all apps are checked for `[app]/components` dirs.\n\n Paths are accepted only if they resolve to a directory.\n E.g. `/path/to/django_project/my_app/components/`.\n\n `BASE_DIR` setting is required.\n \"\"\"\n return get_component_dirs(include_apps)\n
template_parser","text":""},{"location":"reference/django_components/template_parser/#django_components.template_parser","title":"template_parser","text":"
Overrides for the Django Template system to allow finer control over template parsing.
Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py
Functions:
-
parse_bits
\u2013Parse bits for template tag helpers simple_tag and inclusion_tag, in
-
token_kwargs
\u2013Parse token keyword arguments and return a dictionary of the arguments
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 insrc/django_components/template_parser.py
"},{"location":"reference/django_components/template_parser/#django_components.template_parser.token_kwargs","title":"token_kwargs","text":"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
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
Source code inbits
to be keyword arguments, so return the dictionary as soon as an invalid argument format is reached.src/django_components/template_parser.py
"},{"location":"reference/django_components/templatetags/","title":"Index","text":""},{"location":"reference/django_components/templatetags/#django_components.templatetags","title":"templatetags","text":"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
Modules:
-
component_tags
\u2013
Functions:
-
component
\u2013Renders one of the components that was previously registered with
-
component_css_dependencies
\u2013Marks location where CSS link tags should be rendered after the whole HTML has been generated.
-
component_js_dependencies
\u2013Marks location where JS link tags should be rendered after the whole HTML has been generated.
-
fill
\u2013Use this tag to insert content into component's slots.
-
html_attrs
\u2013Generate HTML attributes (
key=\"value\"
), combining data from multiple sources, -
provide
\u2013The \"provider\" part of the provide / inject feature.
-
slot
\u2013Slot tag marks a place inside a component where content can be inserted
Bases:
NamedTuple
Definition of args, kwargs, flags, etc, for a template tag.
Attributes:
-
end_tag
(Optional[str]
) \u2013End tag.
-
flags
(Optional[List[str]]
) \u2013List of allowed flags.
-
keywordonly_args
(Optional[Union[bool, List[str]]]
) \u2013Parameters that MUST be given only as kwargs (not accounting for
pos_or_keyword_args
). -
optional_kwargs
(Optional[List[str]]
) \u2013Specify which kwargs can be optional.
-
pos_or_keyword_args
(Optional[List[str]]
) \u2013Like regular Python kwargs, these can be given EITHER as positional OR as keyword arguments.
-
positional_args_allow_extra
(bool
) \u2013If
True
, allows variable number of positional args, e.g.{% mytag val1 1234 val2 890 ... %}
-
positional_only_args
(Optional[List[str]]
) \u2013Arguments that MUST be given as positional args.
-
repeatable_kwargs
(Optional[Union[bool, List[str]]]
) \u2013Whether this tag allows all or certain kwargs to be repeated.
-
tag
(str
) \u2013Tag name. E.g.
\"slot\"
means the tag is written like so{% slot ... %}
class-attribute
instance-attribute
","text":"end_tag: Optional[str] = None\n
End tag.
E.g.
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.TagSpec.flags","title":"flags\"endslot\"
means anything between the start tag and{% endslot %}
is considered the slot's body.class-attribute
instance-attribute
","text":"flags: Optional[List[str]] = None\n
List of allowed flags.
Flags are like kwargs, but without the value part. E.g. in
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.TagSpec.keywordonly_args","title":"keywordonly_args{% mytag only required %}
: -only
andrequired
are treated asonly=True
andrequired=True
if present - and treated asonly=False
andrequired=False
if omittedclass-attribute
instance-attribute
","text":"keywordonly_args: Optional[Union[bool, List[str]]] = False\n
Parameters that MUST be given only as kwargs (not accounting for
pos_or_keyword_args
).- If
False
, NO extra kwargs allowed. - If
True
, ANY number of extra kwargs allowed. - If a list of strings, e.g.
[\"class\", \"style\"]
, then only those kwargs are allowed.
class-attribute
instance-attribute
","text":"optional_kwargs: Optional[List[str]] = None\n
Specify which kwargs can be optional.
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.TagSpec.pos_or_keyword_args","title":"pos_or_keyword_argsclass-attribute
instance-attribute
","text":"pos_or_keyword_args: Optional[List[str]] = None\n
Like regular Python kwargs, these can be given EITHER as positional OR as keyword arguments.
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.TagSpec.positional_args_allow_extra","title":"positional_args_allow_extraclass-attribute
instance-attribute
","text":"positional_args_allow_extra: bool = False\n
If
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.TagSpec.positional_only_args","title":"positional_only_argsTrue
, allows variable number of positional args, e.g.{% mytag val1 1234 val2 890 ... %}
class-attribute
instance-attribute
","text":"positional_only_args: Optional[List[str]] = None\n
Arguments that MUST be given as positional args.
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.TagSpec.repeatable_kwargs","title":"repeatable_kwargsclass-attribute
instance-attribute
","text":"repeatable_kwargs: Optional[Union[bool, List[str]]] = False\n
Whether this tag allows all or certain kwargs to be repeated.
- If
False
, NO kwargs can repeat. - If
True
, ALL kwargs can repeat. - If a list of strings, e.g.
[\"class\", \"style\"]
, then only those kwargs can repeat.
E.g.
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.TagSpec.tag","title":"tag[\"class\"]
means one can write{% mytag class=\"one\" class=\"two\" %}
instance-attribute
","text":"tag: str\n
Tag name. E.g.
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component","title":"component","text":"\"slot\"
means the tag is written like so{% slot ... %}
component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str, tag_spec: TagSpec) -> ComponentNode\n
Renders one of the components that was previously registered with
@register()
decorator.Args:
name
(str, required): Registered name of the component to render- All other args and kwargs are defined based on the component itself.
If you defined a component
\"my_table\"
from django_component import Component, register\n\n@register(\"my_table\")\nclass MyTable(Component):\n template = \"\"\"\n <table>\n <thead>\n {% for header in headers %}\n <th>{{ header }}</th>\n {% endfor %}\n </thead>\n <tbody>\n {% for row in rows %}\n <tr>\n {% for cell in row %}\n <td>{{ cell }}</td>\n {% endfor %}\n </tr>\n {% endfor %}\n <tbody>\n </table>\n \"\"\"\n\n def get_context_data(self, rows: List, headers: List):\n return {\n \"rows\": rows,\n \"headers\": headers,\n }\n
Then you can render this component by referring to
MyTable
via its registered name\"my_table\"
:
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component--component-input","title":"Component input","text":"{% component \"my_table\" rows=rows headers=headers ... / %}\n
Positional and keyword arguments can be literals or template variables.
The component name must be a single- or double-quotes string and must be either:
-
The first positional argument after
component
:{% component \"my_table\" rows=rows headers=headers ... / %}\n
-
Passed as kwarg
name
:{% component rows=rows headers=headers name=\"my_table\" ... / %}\n
If the component defined any slots, you can pass in the content to be placed inside those slots by inserting
{% fill %}
tags, directly within the{% component %}
tag:
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component--isolating-components","title":"Isolating components","text":"{% component \"my_table\" rows=rows headers=headers ... / %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n{% endcomponent %}\n
By default, components behave similarly to Django's
{% include %}
, and the template inside the component has access to the variables defined in the outer template.You can selectively isolate a component, using the
only
flag, so that the inner template can access only the data that was explicitly passed to it:
Source code in{% component \"name\" positional_arg keyword_arg=value ... only %}\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"@with_tag_spec(\n TagSpec(\n tag=\"component\",\n end_tag=\"endcomponent\",\n positional_only_args=[],\n positional_args_allow_extra=True, # Allow many args\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[COMP_ONLY_FLAG],\n )\n)\ndef component(\n parser: Parser,\n token: Token,\n registry: ComponentRegistry,\n tag_name: str,\n tag_spec: TagSpec,\n) -> ComponentNode:\n \"\"\"\n Renders one of the components that was previously registered with\n [`@register()`](./api.md#django_components.register)\n decorator.\n\n **Args:**\n\n - `name` (str, required): Registered name of the component to render\n - All other args and kwargs are defined based on the component itself.\n\n If you defined a component `\"my_table\"`\n\n ```python\n from django_component import Component, register\n\n @register(\"my_table\")\n class MyTable(Component):\n template = \\\"\\\"\\\"\n <table>\n <thead>\n {% for header in headers %}\n <th>{{ header }}</th>\n {% endfor %}\n </thead>\n <tbody>\n {% for row in rows %}\n <tr>\n {% for cell in row %}\n <td>{{ cell }}</td>\n {% endfor %}\n </tr>\n {% endfor %}\n <tbody>\n </table>\n \\\"\\\"\\\"\n\n def get_context_data(self, rows: List, headers: List):\n return {\n \"rows\": rows,\n \"headers\": headers,\n }\n ```\n\n Then you can render this component by referring to `MyTable` via its\n registered name `\"my_table\"`:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n ```\n\n ### Component input\n\n Positional and keyword arguments can be literals or template variables.\n\n The component name must be a single- or double-quotes string and must\n be either:\n\n - The first positional argument after `component`:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n ```\n\n - Passed as kwarg `name`:\n\n ```django\n {% component rows=rows headers=headers name=\"my_table\" ... / %}\n ```\n\n ### Inserting into slots\n\n If the component defined any [slots](../concepts/fundamentals/slots.md), you can\n pass in the content to be placed inside those slots by inserting [`{% fill %}`](#fill) tags,\n directly within the `{% component %}` tag:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Isolating components\n\n By default, components behave similarly to Django's\n [`{% include %}`](https://docs.djangoproject.com/en/5.1/ref/templates/builtins/#include),\n and the template inside the component has access to the variables defined in the outer template.\n\n You can selectively isolate a component, using the `only` flag, so that the inner template\n can access only the data that was explicitly passed to it:\n\n ```django\n {% component \"name\" positional_arg keyword_arg=value ... only %}\n ```\n \"\"\"\n _fix_nested_tags(parser, token)\n bits = token.split_contents()\n\n # Let the TagFormatter pre-process the tokens\n formatter = get_tag_formatter(registry)\n result = formatter.parse([*bits])\n end_tag = formatter.end_tag(result.component_name)\n\n # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n bits = [bits[0], *result.tokens]\n token.contents = \" \".join(bits)\n\n tag = _parse_tag(\n parser,\n token,\n TagSpec(\n **{\n **tag_spec._asdict(),\n \"tag\": tag_name,\n \"end_tag\": end_tag,\n }\n ),\n )\n\n # Check for isolated context keyword\n isolated_context = tag.flags[COMP_ONLY_FLAG]\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n body = tag.parse_body()\n\n component_node = ComponentNode(\n name=result.component_name,\n args=tag.args,\n kwargs=tag.kwargs,\n isolated_context=isolated_context,\n nodelist=body,\n node_id=tag.id,\n registry=registry,\n )\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n return component_node\n
component_css_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode\n
Marks location where CSS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted into the
<head>
tag of the HTML.If the generated HTML does NOT contain any
{% component_css_dependencies %}
tags, CSS links are by default inserted into the<head>
tag of the HTML. (See JS and CSS output locations)Note that there should be only one
Source code in{% component_css_dependencies %}
for the whole HTML document. If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"@register.tag(\"component_css_dependencies\")\n@with_tag_spec(\n TagSpec(\n tag=\"component_css_dependencies\",\n end_tag=None, # inline-only\n )\n)\ndef component_css_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode:\n \"\"\"\n Marks location where CSS link tags should be rendered after the whole HTML has been generated.\n\n Generally, this should be inserted into the `<head>` tag of the HTML.\n\n If the generated HTML does NOT contain any `{% component_css_dependencies %}` tags, CSS links\n are by default inserted into the `<head>` tag of the HTML. (See\n [JS and CSS output locations](../../concepts/advanced/rendering_js_css/#js-and-css-output-locations))\n\n Note that there should be only one `{% component_css_dependencies %}` for the whole HTML document.\n If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.\n \"\"\"\n # Parse to check that the syntax is valid\n _parse_tag(parser, token, tag_spec)\n return _component_dependencies(\"css\")\n
component_js_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode\n
Marks location where JS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted at the end of the
<body>
tag of the HTML.If the generated HTML does NOT contain any
{% component_js_dependencies %}
tags, JS scripts are by default inserted at the end of the<body>
tag of the HTML. (See JS and CSS output locations)Note that there should be only one
Source code in{% component_js_dependencies %}
for the whole HTML document. If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.fill","title":"fill","text":"@register.tag(name=\"component_js_dependencies\")\n@with_tag_spec(\n TagSpec(\n tag=\"component_js_dependencies\",\n end_tag=None, # inline-only\n )\n)\ndef component_js_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode:\n \"\"\"\n Marks location where JS link tags should be rendered after the whole HTML has been generated.\n\n Generally, this should be inserted at the end of the `<body>` tag of the HTML.\n\n If the generated HTML does NOT contain any `{% component_js_dependencies %}` tags, JS scripts\n are by default inserted at the end of the `<body>` tag of the HTML. (See\n [JS and CSS output locations](../../concepts/advanced/rendering_js_css/#js-and-css-output-locations))\n\n Note that there should be only one `{% component_js_dependencies %}` for the whole HTML document.\n If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.\n \"\"\"\n # Parse to check that the syntax is valid\n _parse_tag(parser, token, tag_spec)\n return _component_dependencies(\"js\")\n
fill(parser: Parser, token: Token, tag_spec: TagSpec) -> FillNode\n
Use this tag to insert content into component's slots.
{% fill %}
tag may be used only within a{% component %}..{% endcomponent %}
block. Runtime checks should prohibit other usages.Args:
name
(str, required): Name of the slot to insert this content into. Use\"default\"
for the default slot.default
(str, optional): This argument allows you to access the original content of the slot under the specified variable name. See Accessing original content of slotsdata
(str, optional): This argument allows you to access the data passed to the slot under the specified variable name. See Scoped slots
Examples:
Basic usage:
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.fill--accessing-slots-default-content-with-the-default-kwarg","title":"Accessing slot's default content with the{% component \"my_table\" %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n{% endcomponent %}\n
default
kwarg","text":"{# my_table.html #}\n<table>\n ...\n {% slot \"pagination\" %}\n < 1 | 2 | 3 >\n {% endslot %}\n</table>\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.fill--accessing-slots-data-with-the-data-kwarg","title":"Accessing slot's data with the{% component \"my_table\" %}\n {% fill \"pagination\" default=\"default_pag\" %}\n <div class=\"my-class\">\n {{ default_pag }}\n </div>\n {% endfill %}\n{% endcomponent %}\n
data
kwarg","text":"{# my_table.html #}\n<table>\n ...\n {% slot \"pagination\" pages=pages %}\n < 1 | 2 | 3 >\n {% endslot %}\n</table>\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.fill--accessing-slot-data-and-default-content-on-the-default-slot","title":"Accessing slot data and default content on the default slot","text":"{% component \"my_table\" %}\n {% fill \"pagination\" data=\"slot_data\" %}\n {% for page in slot_data.pages %}\n <a href=\"{{ page.link }}\">\n {{ page.index }}\n </a>\n {% endfor %}\n {% endfill %}\n{% endcomponent %}\n
To access slot data and the default slot content on the default slot, use
{% fill %}
withname
set to\"default\"
:
Source code in{% component \"button\" %}\n {% fill name=\"default\" data=\"slot_data\" default=\"default_slot\" %}\n You clicked me {{ slot_data.count }} times!\n {{ default_slot }}\n {% endfill %}\n{% endcomponent %}\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"@register.tag(\"fill\")\n@with_tag_spec(\n TagSpec(\n tag=\"fill\",\n end_tag=\"endfill\",\n positional_only_args=[],\n pos_or_keyword_args=[SLOT_NAME_KWARG],\n keywordonly_args=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n optional_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n repeatable_kwargs=False,\n )\n)\ndef fill(parser: Parser, token: Token, tag_spec: TagSpec) -> FillNode:\n \"\"\"\n Use this tag to insert content into component's slots.\n\n `{% fill %}` tag may be used only within a `{% component %}..{% endcomponent %}` block.\n Runtime checks should prohibit other usages.\n\n **Args:**\n\n - `name` (str, required): Name of the slot to insert this content into. Use `\"default\"` for\n the default slot.\n - `default` (str, optional): This argument allows you to access the original content of the slot\n under the specified variable name. See\n [Accessing original content of slots](../../concepts/fundamentals/slots#accessing-original-content-of-slots)\n - `data` (str, optional): This argument allows you to access the data passed to the slot\n under the specified variable name. See [Scoped slots](../../concepts/fundamentals/slots#scoped-slots)\n\n **Examples:**\n\n Basic usage:\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot's default content with the `default` kwarg\n\n ```django\n {# my_table.html #}\n <table>\n ...\n {% slot \"pagination\" %}\n < 1 | 2 | 3 >\n {% endslot %}\n </table>\n ```\n\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" default=\"default_pag\" %}\n <div class=\"my-class\">\n {{ default_pag }}\n </div>\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot's data with the `data` kwarg\n\n ```django\n {# my_table.html #}\n <table>\n ...\n {% slot \"pagination\" pages=pages %}\n < 1 | 2 | 3 >\n {% endslot %}\n </table>\n ```\n\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" data=\"slot_data\" %}\n {% for page in slot_data.pages %}\n <a href=\"{{ page.link }}\">\n {{ page.index }}\n </a>\n {% endfor %}\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot data and default content on the default slot\n\n To access slot data and the default slot content on the default slot,\n use `{% fill %}` with `name` set to `\"default\"`:\n\n ```django\n {% component \"button\" %}\n {% fill name=\"default\" data=\"slot_data\" default=\"default_slot\" %}\n You clicked me {{ slot_data.count }} times!\n {{ default_slot }}\n {% endfill %}\n {% endcomponent %}\n ```\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n fill_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n trace_id = f\"fill-id-{tag.id} ({fill_name_kwarg})\" if fill_name_kwarg else f\"fill-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id)\n\n body = tag.parse_body()\n fill_node = FillNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id, \"...Done!\")\n return fill_node\n
html_attrs(parser: Parser, token: Token, tag_spec: TagSpec) -> HtmlAttrsNode\n
Generate HTML attributes (
key=\"value\"
), combining data from multiple sources, whether its template variables or static text.It is designed to easily merge HTML attributes passed from outside with the internal. See how to in Passing HTML attributes to components.
Args:
attrs
(dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides values in thedefault
dictionary.default
(str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden with values in theattrs
dictionary.- Any extra kwargs will be appended to the corresponding keys
The attributes in
attrs
anddefaults
are merged and resulting dict is rendered as HTML attributes (key=\"value\"
).Extra kwargs (
key=value
) are concatenated to existing keys. So if we haveattrs = {\"class\": \"my-class\"}\n
Then
{% html_attrs attrs class=\"extra-class\" %}\n
will result in
class=\"my-class extra-class\"
.Example:
<div {% html_attrs\n attrs\n defaults:class=\"default-class\"\n class=\"extra-class\"\n data-id=\"123\"\n%}>\n
renders
<div class=\"my-class extra-class\" data-id=\"123\">\n
See more usage examples in HTML attributes.
Source code insrc/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.provide","title":"provide","text":"@register.tag(\"html_attrs\")\n@with_tag_spec(\n TagSpec(\n tag=\"html_attrs\",\n end_tag=None, # inline-only\n positional_only_args=[],\n pos_or_keyword_args=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n optional_kwargs=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n keywordonly_args=True,\n repeatable_kwargs=True,\n flags=[],\n )\n)\ndef html_attrs(parser: Parser, token: Token, tag_spec: TagSpec) -> HtmlAttrsNode:\n \"\"\"\n Generate HTML attributes (`key=\"value\"`), combining data from multiple sources,\n whether its template variables or static text.\n\n It is designed to easily merge HTML attributes passed from outside with the internal.\n See how to in [Passing HTML attributes to components](../../guides/howto/passing_html_attrs/).\n\n **Args:**\n\n - `attrs` (dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides\n values in the `default` dictionary.\n - `default` (str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden\n with values in the `attrs` dictionary.\n - Any extra kwargs will be appended to the corresponding keys\n\n The attributes in `attrs` and `defaults` are merged and resulting dict is rendered as HTML attributes\n (`key=\"value\"`).\n\n Extra kwargs (`key=value`) are concatenated to existing keys. So if we have\n\n ```python\n attrs = {\"class\": \"my-class\"}\n ```\n\n Then\n\n ```django\n {% html_attrs attrs class=\"extra-class\" %}\n ```\n\n will result in `class=\"my-class extra-class\"`.\n\n **Example:**\n ```django\n <div {% html_attrs\n attrs\n defaults:class=\"default-class\"\n class=\"extra-class\"\n data-id=\"123\"\n %}>\n ```\n\n renders\n\n ```html\n <div class=\"my-class extra-class\" data-id=\"123\">\n ```\n\n **See more usage examples in\n [HTML attributes](../../concepts/fundamentals/html_attributes#examples-for-html_attrs).**\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n return HtmlAttrsNode(\n kwargs=tag.kwargs,\n kwarg_pairs=tag.kwarg_pairs,\n )\n
provide(parser: Parser, token: Token, tag_spec: TagSpec) -> ProvideNode\n
The \"provider\" part of the provide / inject feature. Pass kwargs to this tag to define the provider's data. Any components defined within the
{% provide %}..{% endprovide %}
tags will be able to access this data withComponent.inject()
.This is similar to React's
ContextProvider
, or Vue'sprovide()
.Args:
name
(str, required): Provider name. This is the name you will then use inComponent.inject()
.**kwargs
: Any extra kwargs will be passed as the provided data.
Example:
Provide the \"user_data\" in parent component:
@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n <div>\n {% provide \"user_data\" user=user %}\n {% component \"child\" / %}\n {% endprovide %}\n </div>\n \"\"\"\n\n def get_context_data(self, user: User):\n return {\n \"user\": user,\n }\n
Since the \"child\" component is used within the
{% provide %} / {% endprovide %}
tags, we can request the \"user_data\" usingComponent.inject(\"user_data\")
:@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n User is: {{ user }}\n </div>\n \"\"\"\n\n def get_context_data(self):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n
Notice that the keys defined on the
{% provide %}
tag are then accessed as attributes when accessing them withComponent.inject()
.\u2705 Do this
user = self.inject(\"user_data\").user\n
\u274c Don't do this
Source code inuser = self.inject(\"user_data\")[\"user\"]\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.slot","title":"slot","text":"@register.tag(\"provide\")\n@with_tag_spec(\n TagSpec(\n tag=\"provide\",\n end_tag=\"endprovide\",\n positional_only_args=[],\n pos_or_keyword_args=[PROVIDE_NAME_KWARG],\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[],\n )\n)\ndef provide(parser: Parser, token: Token, tag_spec: TagSpec) -> ProvideNode:\n \"\"\"\n The \"provider\" part of the [provide / inject feature](../../concepts/advanced/provide_inject).\n Pass kwargs to this tag to define the provider's data.\n Any components defined within the `{% provide %}..{% endprovide %}` tags will be able to access this data\n with [`Component.inject()`](../api#django_components.Component.inject).\n\n This is similar to React's [`ContextProvider`](https://react.dev/learn/passing-data-deeply-with-context),\n or Vue's [`provide()`](https://vuejs.org/guide/components/provide-inject).\n\n **Args:**\n\n - `name` (str, required): Provider name. This is the name you will then use in\n [`Component.inject()`](../api#django_components.Component.inject).\n - `**kwargs`: Any extra kwargs will be passed as the provided data.\n\n **Example:**\n\n Provide the \"user_data\" in parent component:\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n <div>\n {% provide \"user_data\" user=user %}\n {% component \"child\" / %}\n {% endprovide %}\n </div>\n \\\"\\\"\\\"\n\n def get_context_data(self, user: User):\n return {\n \"user\": user,\n }\n ```\n\n Since the \"child\" component is used within the `{% provide %} / {% endprovide %}` tags,\n we can request the \"user_data\" using `Component.inject(\"user_data\")`:\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n User is: {{ user }}\n </div>\n \\\"\\\"\\\"\n\n def get_context_data(self):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n ```\n\n Notice that the keys defined on the `{% provide %}` tag are then accessed as attributes\n when accessing them with [`Component.inject()`](../api#django_components.Component.inject).\n\n \u2705 Do this\n ```python\n user = self.inject(\"user_data\").user\n ```\n\n \u274c Don't do this\n ```python\n user = self.inject(\"user_data\")[\"user\"]\n ```\n \"\"\"\n # e.g. {% provide <name> key=val key2=val2 %}\n tag = _parse_tag(parser, token, tag_spec)\n\n name_kwarg = tag.kwargs.kwargs.get(PROVIDE_NAME_KWARG, None)\n trace_id = f\"provide-id-{tag.id} ({name_kwarg})\" if name_kwarg else f\"fill-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"PROVIDE\", trace_id, tag.id)\n\n body = tag.parse_body()\n provide_node = ProvideNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"PROVIDE\", trace_id, tag.id, \"...Done!\")\n return provide_node\n
slot(parser: Parser, token: Token, tag_spec: TagSpec) -> SlotNode\n
Slot tag marks a place inside a component where content can be inserted from outside.
Learn more about using slots.
This is similar to slots as seen in Web components, Vue or React's
children
.Args:
name
(str, required): Registered name of the component to renderdefault
: Optional flag. If there is a default slot, you can pass the component slot content without using the{% fill %}
tag. See Default slotrequired
: Optional flag. Will raise an error if a slot is required but not given.**kwargs
: Any extra kwargs will be passed as the slot data.
Example:
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" default %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n <aside>\n {% slot \"sidebar\" required / %}\n </aside>\n \"\"\"\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.slot--passing-data-to-slots","title":"Passing data to slots","text":"@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n <div>\n {% component \"child\" %}\n {% fill \"content\" %}\n \ud83d\uddde\ufe0f\ud83d\udcf0\n {% endfill %}\n\n {% fill \"sidebar\" %}\n \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n {% endfill %}\n {% endcomponent %}\n </div>\n \"\"\"\n
Any extra kwargs will be considered as slot data, and will be accessible in the
{% fill %}
tag via fill'sdata
kwarg:@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \"\"\"\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.slot--accessing-default-slot-content","title":"Accessing default slot content","text":"@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
The content between the
{% slot %}..{% endslot %}
tags is the default content that will be rendered if no fill is given for the slot.This default content can then be accessed from within the
{% fill %}
tag using the fill'sdefault
kwarg. This is useful if you need to wrap / prepend / append the original slot's content.@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" %}\n This is default content!\n {% endslot %}\n </div>\n \"\"\"\n
Source code in@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot's default content #}\n {% component \"child\" %}\n {% fill \"content\" default=\"default\" %}\n {{ default }}\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.with_tag_spec","title":"with_tag_spec","text":"@register.tag(\"slot\")\n@with_tag_spec(\n TagSpec(\n tag=\"slot\",\n end_tag=\"endslot\",\n positional_only_args=[],\n pos_or_keyword_args=[SLOT_NAME_KWARG],\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[SLOT_DEFAULT_KEYWORD, SLOT_REQUIRED_KEYWORD],\n )\n)\ndef slot(parser: Parser, token: Token, tag_spec: TagSpec) -> SlotNode:\n \"\"\"\n Slot tag marks a place inside a component where content can be inserted\n from outside.\n\n [Learn more](../../concepts/fundamentals/slots) about using slots.\n\n This is similar to slots as seen in\n [Web components](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot),\n [Vue](https://vuejs.org/guide/components/slots.html)\n or [React's `children`](https://react.dev/learn/passing-props-to-a-component#passing-jsx-as-children).\n\n **Args:**\n\n - `name` (str, required): Registered name of the component to render\n - `default`: Optional flag. If there is a default slot, you can pass the component slot content\n without using the [`{% fill %}`](#fill) tag. See\n [Default slot](../../concepts/fundamentals/slots#default-slot)\n - `required`: Optional flag. Will raise an error if a slot is required but not given.\n - `**kwargs`: Any extra kwargs will be passed as the slot data.\n\n **Example:**\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {% slot \"content\" default %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n <aside>\n {% slot \"sidebar\" required / %}\n </aside>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n <div>\n {% component \"child\" %}\n {% fill \"content\" %}\n \ud83d\uddde\ufe0f\ud83d\udcf0\n {% endfill %}\n\n {% fill \"sidebar\" %}\n \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n {% endfill %}\n {% endcomponent %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ### Passing data to slots\n\n Any extra kwargs will be considered as slot data, and will be accessible in the [`{% fill %}`](#fill)\n tag via fill's `data` kwarg:\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \\\"\\\"\\\"\n ```\n\n ### Accessing default slot content\n\n The content between the `{% slot %}..{% endslot %}` tags is the default content that\n will be rendered if no fill is given for the slot.\n\n This default content can then be accessed from within the [`{% fill %}`](#fill) tag using\n the fill's `default` kwarg.\n This is useful if you need to wrap / prepend / append the original slot's content.\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {% slot \"content\" %}\n This is default content!\n {% endslot %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n {# Parent can access the slot's default content #}\n {% component \"child\" %}\n {% fill \"content\" default=\"default\" %}\n {{ default }}\n {% endfill %}\n {% endcomponent %}\n \\\"\\\"\\\"\n ```\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n slot_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n trace_id = f\"slot-id-{tag.id} ({slot_name_kwarg})\" if slot_name_kwarg else f\"slot-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"SLOT\", trace_id, tag.id)\n\n body = tag.parse_body()\n slot_node = SlotNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n is_required=tag.flags[SLOT_REQUIRED_KEYWORD],\n is_default=tag.flags[SLOT_DEFAULT_KEYWORD],\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"SLOT\", trace_id, tag.id, \"...Done!\")\n return slot_node\n
Source code inwith_tag_spec(tag_spec: TagSpec) -> Callable\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/component_tags/","title":"def with_tag_spec(tag_spec: TagSpec) -> Callable:\n \"\"\"\"\"\"\n\n def decorator(fn: Callable) -> Any:\n fn._tag_spec = tag_spec # type: ignore[attr-defined]\n\n @functools.wraps(fn)\n def wrapper(*args: Any, **kwargs: Any) -> Any:\n return fn(*args, **kwargs, tag_spec=tag_spec)\n\n return wrapper\n\n return decorator\n
component_tags","text":""},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags","title":"component_tags","text":"
Functions:
-
component
\u2013Renders one of the components that was previously registered with
-
component_css_dependencies
\u2013Marks location where CSS link tags should be rendered after the whole HTML has been generated.
-
component_js_dependencies
\u2013Marks location where JS link tags should be rendered after the whole HTML has been generated.
-
fill
\u2013Use this tag to insert content into component's slots.
-
html_attrs
\u2013Generate HTML attributes (
key=\"value\"
), combining data from multiple sources, -
provide
\u2013The \"provider\" part of the provide / inject feature.
-
slot
\u2013Slot tag marks a place inside a component where content can be inserted
Bases:
NamedTuple
Definition of args, kwargs, flags, etc, for a template tag.
Attributes:
-
end_tag
(Optional[str]
) \u2013End tag.
-
flags
(Optional[List[str]]
) \u2013List of allowed flags.
-
keywordonly_args
(Optional[Union[bool, List[str]]]
) \u2013Parameters that MUST be given only as kwargs (not accounting for
pos_or_keyword_args
). -
optional_kwargs
(Optional[List[str]]
) \u2013Specify which kwargs can be optional.
-
pos_or_keyword_args
(Optional[List[str]]
) \u2013Like regular Python kwargs, these can be given EITHER as positional OR as keyword arguments.
-
positional_args_allow_extra
(bool
) \u2013If
True
, allows variable number of positional args, e.g.{% mytag val1 1234 val2 890 ... %}
-
positional_only_args
(Optional[List[str]]
) \u2013Arguments that MUST be given as positional args.
-
repeatable_kwargs
(Optional[Union[bool, List[str]]]
) \u2013Whether this tag allows all or certain kwargs to be repeated.
-
tag
(str
) \u2013Tag name. E.g.
\"slot\"
means the tag is written like so{% slot ... %}
class-attribute
instance-attribute
","text":"end_tag: Optional[str] = None\n
End tag.
E.g.
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.TagSpec.flags","title":"flags\"endslot\"
means anything between the start tag and{% endslot %}
is considered the slot's body.class-attribute
instance-attribute
","text":"flags: Optional[List[str]] = None\n
List of allowed flags.
Flags are like kwargs, but without the value part. E.g. in
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.TagSpec.keywordonly_args","title":"keywordonly_args{% mytag only required %}
: -only
andrequired
are treated asonly=True
andrequired=True
if present - and treated asonly=False
andrequired=False
if omittedclass-attribute
instance-attribute
","text":"keywordonly_args: Optional[Union[bool, List[str]]] = False\n
Parameters that MUST be given only as kwargs (not accounting for
pos_or_keyword_args
).- If
False
, NO extra kwargs allowed. - If
True
, ANY number of extra kwargs allowed. - If a list of strings, e.g.
[\"class\", \"style\"]
, then only those kwargs are allowed.
class-attribute
instance-attribute
","text":"optional_kwargs: Optional[List[str]] = None\n
Specify which kwargs can be optional.
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.TagSpec.pos_or_keyword_args","title":"pos_or_keyword_argsclass-attribute
instance-attribute
","text":"pos_or_keyword_args: Optional[List[str]] = None\n
Like regular Python kwargs, these can be given EITHER as positional OR as keyword arguments.
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.TagSpec.positional_args_allow_extra","title":"positional_args_allow_extraclass-attribute
instance-attribute
","text":"positional_args_allow_extra: bool = False\n
If
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.TagSpec.positional_only_args","title":"positional_only_argsTrue
, allows variable number of positional args, e.g.{% mytag val1 1234 val2 890 ... %}
class-attribute
instance-attribute
","text":"positional_only_args: Optional[List[str]] = None\n
Arguments that MUST be given as positional args.
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.TagSpec.repeatable_kwargs","title":"repeatable_kwargsclass-attribute
instance-attribute
","text":"repeatable_kwargs: Optional[Union[bool, List[str]]] = False\n
Whether this tag allows all or certain kwargs to be repeated.
- If
False
, NO kwargs can repeat. - If
True
, ALL kwargs can repeat. - If a list of strings, e.g.
[\"class\", \"style\"]
, then only those kwargs can repeat.
E.g.
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.TagSpec.tag","title":"tag[\"class\"]
means one can write{% mytag class=\"one\" class=\"two\" %}
instance-attribute
","text":"tag: str\n
Tag name. E.g.
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component","title":"component","text":"\"slot\"
means the tag is written like so{% slot ... %}
component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str, tag_spec: TagSpec) -> ComponentNode\n
Renders one of the components that was previously registered with
@register()
decorator.Args:
name
(str, required): Registered name of the component to render- All other args and kwargs are defined based on the component itself.
If you defined a component
\"my_table\"
from django_component import Component, register\n\n@register(\"my_table\")\nclass MyTable(Component):\n template = \"\"\"\n <table>\n <thead>\n {% for header in headers %}\n <th>{{ header }}</th>\n {% endfor %}\n </thead>\n <tbody>\n {% for row in rows %}\n <tr>\n {% for cell in row %}\n <td>{{ cell }}</td>\n {% endfor %}\n </tr>\n {% endfor %}\n <tbody>\n </table>\n \"\"\"\n\n def get_context_data(self, rows: List, headers: List):\n return {\n \"rows\": rows,\n \"headers\": headers,\n }\n
Then you can render this component by referring to
MyTable
via its registered name\"my_table\"
:
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component--component-input","title":"Component input","text":"{% component \"my_table\" rows=rows headers=headers ... / %}\n
Positional and keyword arguments can be literals or template variables.
The component name must be a single- or double-quotes string and must be either:
-
The first positional argument after
component
:{% component \"my_table\" rows=rows headers=headers ... / %}\n
-
Passed as kwarg
name
:{% component rows=rows headers=headers name=\"my_table\" ... / %}\n
If the component defined any slots, you can pass in the content to be placed inside those slots by inserting
{% fill %}
tags, directly within the{% component %}
tag:
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component--isolating-components","title":"Isolating components","text":"{% component \"my_table\" rows=rows headers=headers ... / %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n{% endcomponent %}\n
By default, components behave similarly to Django's
{% include %}
, and the template inside the component has access to the variables defined in the outer template.You can selectively isolate a component, using the
only
flag, so that the inner template can access only the data that was explicitly passed to it:
Source code in{% component \"name\" positional_arg keyword_arg=value ... only %}\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"@with_tag_spec(\n TagSpec(\n tag=\"component\",\n end_tag=\"endcomponent\",\n positional_only_args=[],\n positional_args_allow_extra=True, # Allow many args\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[COMP_ONLY_FLAG],\n )\n)\ndef component(\n parser: Parser,\n token: Token,\n registry: ComponentRegistry,\n tag_name: str,\n tag_spec: TagSpec,\n) -> ComponentNode:\n \"\"\"\n Renders one of the components that was previously registered with\n [`@register()`](./api.md#django_components.register)\n decorator.\n\n **Args:**\n\n - `name` (str, required): Registered name of the component to render\n - All other args and kwargs are defined based on the component itself.\n\n If you defined a component `\"my_table\"`\n\n ```python\n from django_component import Component, register\n\n @register(\"my_table\")\n class MyTable(Component):\n template = \\\"\\\"\\\"\n <table>\n <thead>\n {% for header in headers %}\n <th>{{ header }}</th>\n {% endfor %}\n </thead>\n <tbody>\n {% for row in rows %}\n <tr>\n {% for cell in row %}\n <td>{{ cell }}</td>\n {% endfor %}\n </tr>\n {% endfor %}\n <tbody>\n </table>\n \\\"\\\"\\\"\n\n def get_context_data(self, rows: List, headers: List):\n return {\n \"rows\": rows,\n \"headers\": headers,\n }\n ```\n\n Then you can render this component by referring to `MyTable` via its\n registered name `\"my_table\"`:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n ```\n\n ### Component input\n\n Positional and keyword arguments can be literals or template variables.\n\n The component name must be a single- or double-quotes string and must\n be either:\n\n - The first positional argument after `component`:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n ```\n\n - Passed as kwarg `name`:\n\n ```django\n {% component rows=rows headers=headers name=\"my_table\" ... / %}\n ```\n\n ### Inserting into slots\n\n If the component defined any [slots](../concepts/fundamentals/slots.md), you can\n pass in the content to be placed inside those slots by inserting [`{% fill %}`](#fill) tags,\n directly within the `{% component %}` tag:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Isolating components\n\n By default, components behave similarly to Django's\n [`{% include %}`](https://docs.djangoproject.com/en/5.1/ref/templates/builtins/#include),\n and the template inside the component has access to the variables defined in the outer template.\n\n You can selectively isolate a component, using the `only` flag, so that the inner template\n can access only the data that was explicitly passed to it:\n\n ```django\n {% component \"name\" positional_arg keyword_arg=value ... only %}\n ```\n \"\"\"\n _fix_nested_tags(parser, token)\n bits = token.split_contents()\n\n # Let the TagFormatter pre-process the tokens\n formatter = get_tag_formatter(registry)\n result = formatter.parse([*bits])\n end_tag = formatter.end_tag(result.component_name)\n\n # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n bits = [bits[0], *result.tokens]\n token.contents = \" \".join(bits)\n\n tag = _parse_tag(\n parser,\n token,\n TagSpec(\n **{\n **tag_spec._asdict(),\n \"tag\": tag_name,\n \"end_tag\": end_tag,\n }\n ),\n )\n\n # Check for isolated context keyword\n isolated_context = tag.flags[COMP_ONLY_FLAG]\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n body = tag.parse_body()\n\n component_node = ComponentNode(\n name=result.component_name,\n args=tag.args,\n kwargs=tag.kwargs,\n isolated_context=isolated_context,\n nodelist=body,\n node_id=tag.id,\n registry=registry,\n )\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n return component_node\n
component_css_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode\n
Marks location where CSS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted into the
<head>
tag of the HTML.If the generated HTML does NOT contain any
{% component_css_dependencies %}
tags, CSS links are by default inserted into the<head>
tag of the HTML. (See JS and CSS output locations)Note that there should be only one
Source code in{% component_css_dependencies %}
for the whole HTML document. If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"@register.tag(\"component_css_dependencies\")\n@with_tag_spec(\n TagSpec(\n tag=\"component_css_dependencies\",\n end_tag=None, # inline-only\n )\n)\ndef component_css_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode:\n \"\"\"\n Marks location where CSS link tags should be rendered after the whole HTML has been generated.\n\n Generally, this should be inserted into the `<head>` tag of the HTML.\n\n If the generated HTML does NOT contain any `{% component_css_dependencies %}` tags, CSS links\n are by default inserted into the `<head>` tag of the HTML. (See\n [JS and CSS output locations](../../concepts/advanced/rendering_js_css/#js-and-css-output-locations))\n\n Note that there should be only one `{% component_css_dependencies %}` for the whole HTML document.\n If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.\n \"\"\"\n # Parse to check that the syntax is valid\n _parse_tag(parser, token, tag_spec)\n return _component_dependencies(\"css\")\n
component_js_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode\n
Marks location where JS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted at the end of the
<body>
tag of the HTML.If the generated HTML does NOT contain any
{% component_js_dependencies %}
tags, JS scripts are by default inserted at the end of the<body>
tag of the HTML. (See JS and CSS output locations)Note that there should be only one
Source code in{% component_js_dependencies %}
for the whole HTML document. If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.fill","title":"fill","text":"@register.tag(name=\"component_js_dependencies\")\n@with_tag_spec(\n TagSpec(\n tag=\"component_js_dependencies\",\n end_tag=None, # inline-only\n )\n)\ndef component_js_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode:\n \"\"\"\n Marks location where JS link tags should be rendered after the whole HTML has been generated.\n\n Generally, this should be inserted at the end of the `<body>` tag of the HTML.\n\n If the generated HTML does NOT contain any `{% component_js_dependencies %}` tags, JS scripts\n are by default inserted at the end of the `<body>` tag of the HTML. (See\n [JS and CSS output locations](../../concepts/advanced/rendering_js_css/#js-and-css-output-locations))\n\n Note that there should be only one `{% component_js_dependencies %}` for the whole HTML document.\n If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.\n \"\"\"\n # Parse to check that the syntax is valid\n _parse_tag(parser, token, tag_spec)\n return _component_dependencies(\"js\")\n
fill(parser: Parser, token: Token, tag_spec: TagSpec) -> FillNode\n
Use this tag to insert content into component's slots.
{% fill %}
tag may be used only within a{% component %}..{% endcomponent %}
block. Runtime checks should prohibit other usages.Args:
name
(str, required): Name of the slot to insert this content into. Use\"default\"
for the default slot.default
(str, optional): This argument allows you to access the original content of the slot under the specified variable name. See Accessing original content of slotsdata
(str, optional): This argument allows you to access the data passed to the slot under the specified variable name. See Scoped slots
Examples:
Basic usage:
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.fill--accessing-slots-default-content-with-the-default-kwarg","title":"Accessing slot's default content with the{% component \"my_table\" %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n{% endcomponent %}\n
default
kwarg","text":"{# my_table.html #}\n<table>\n ...\n {% slot \"pagination\" %}\n < 1 | 2 | 3 >\n {% endslot %}\n</table>\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.fill--accessing-slots-data-with-the-data-kwarg","title":"Accessing slot's data with the{% component \"my_table\" %}\n {% fill \"pagination\" default=\"default_pag\" %}\n <div class=\"my-class\">\n {{ default_pag }}\n </div>\n {% endfill %}\n{% endcomponent %}\n
data
kwarg","text":"{# my_table.html #}\n<table>\n ...\n {% slot \"pagination\" pages=pages %}\n < 1 | 2 | 3 >\n {% endslot %}\n</table>\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.fill--accessing-slot-data-and-default-content-on-the-default-slot","title":"Accessing slot data and default content on the default slot","text":"{% component \"my_table\" %}\n {% fill \"pagination\" data=\"slot_data\" %}\n {% for page in slot_data.pages %}\n <a href=\"{{ page.link }}\">\n {{ page.index }}\n </a>\n {% endfor %}\n {% endfill %}\n{% endcomponent %}\n
To access slot data and the default slot content on the default slot, use
{% fill %}
withname
set to\"default\"
:
Source code in{% component \"button\" %}\n {% fill name=\"default\" data=\"slot_data\" default=\"default_slot\" %}\n You clicked me {{ slot_data.count }} times!\n {{ default_slot }}\n {% endfill %}\n{% endcomponent %}\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"@register.tag(\"fill\")\n@with_tag_spec(\n TagSpec(\n tag=\"fill\",\n end_tag=\"endfill\",\n positional_only_args=[],\n pos_or_keyword_args=[SLOT_NAME_KWARG],\n keywordonly_args=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n optional_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n repeatable_kwargs=False,\n )\n)\ndef fill(parser: Parser, token: Token, tag_spec: TagSpec) -> FillNode:\n \"\"\"\n Use this tag to insert content into component's slots.\n\n `{% fill %}` tag may be used only within a `{% component %}..{% endcomponent %}` block.\n Runtime checks should prohibit other usages.\n\n **Args:**\n\n - `name` (str, required): Name of the slot to insert this content into. Use `\"default\"` for\n the default slot.\n - `default` (str, optional): This argument allows you to access the original content of the slot\n under the specified variable name. See\n [Accessing original content of slots](../../concepts/fundamentals/slots#accessing-original-content-of-slots)\n - `data` (str, optional): This argument allows you to access the data passed to the slot\n under the specified variable name. See [Scoped slots](../../concepts/fundamentals/slots#scoped-slots)\n\n **Examples:**\n\n Basic usage:\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot's default content with the `default` kwarg\n\n ```django\n {# my_table.html #}\n <table>\n ...\n {% slot \"pagination\" %}\n < 1 | 2 | 3 >\n {% endslot %}\n </table>\n ```\n\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" default=\"default_pag\" %}\n <div class=\"my-class\">\n {{ default_pag }}\n </div>\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot's data with the `data` kwarg\n\n ```django\n {# my_table.html #}\n <table>\n ...\n {% slot \"pagination\" pages=pages %}\n < 1 | 2 | 3 >\n {% endslot %}\n </table>\n ```\n\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" data=\"slot_data\" %}\n {% for page in slot_data.pages %}\n <a href=\"{{ page.link }}\">\n {{ page.index }}\n </a>\n {% endfor %}\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot data and default content on the default slot\n\n To access slot data and the default slot content on the default slot,\n use `{% fill %}` with `name` set to `\"default\"`:\n\n ```django\n {% component \"button\" %}\n {% fill name=\"default\" data=\"slot_data\" default=\"default_slot\" %}\n You clicked me {{ slot_data.count }} times!\n {{ default_slot }}\n {% endfill %}\n {% endcomponent %}\n ```\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n fill_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n trace_id = f\"fill-id-{tag.id} ({fill_name_kwarg})\" if fill_name_kwarg else f\"fill-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id)\n\n body = tag.parse_body()\n fill_node = FillNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id, \"...Done!\")\n return fill_node\n
html_attrs(parser: Parser, token: Token, tag_spec: TagSpec) -> HtmlAttrsNode\n
Generate HTML attributes (
key=\"value\"
), combining data from multiple sources, whether its template variables or static text.It is designed to easily merge HTML attributes passed from outside with the internal. See how to in Passing HTML attributes to components.
Args:
attrs
(dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides values in thedefault
dictionary.default
(str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden with values in theattrs
dictionary.- Any extra kwargs will be appended to the corresponding keys
The attributes in
attrs
anddefaults
are merged and resulting dict is rendered as HTML attributes (key=\"value\"
).Extra kwargs (
key=value
) are concatenated to existing keys. So if we haveattrs = {\"class\": \"my-class\"}\n
Then
{% html_attrs attrs class=\"extra-class\" %}\n
will result in
class=\"my-class extra-class\"
.Example:
<div {% html_attrs\n attrs\n defaults:class=\"default-class\"\n class=\"extra-class\"\n data-id=\"123\"\n%}>\n
renders
<div class=\"my-class extra-class\" data-id=\"123\">\n
See more usage examples in HTML attributes.
Source code insrc/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.provide","title":"provide","text":"@register.tag(\"html_attrs\")\n@with_tag_spec(\n TagSpec(\n tag=\"html_attrs\",\n end_tag=None, # inline-only\n positional_only_args=[],\n pos_or_keyword_args=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n optional_kwargs=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n keywordonly_args=True,\n repeatable_kwargs=True,\n flags=[],\n )\n)\ndef html_attrs(parser: Parser, token: Token, tag_spec: TagSpec) -> HtmlAttrsNode:\n \"\"\"\n Generate HTML attributes (`key=\"value\"`), combining data from multiple sources,\n whether its template variables or static text.\n\n It is designed to easily merge HTML attributes passed from outside with the internal.\n See how to in [Passing HTML attributes to components](../../guides/howto/passing_html_attrs/).\n\n **Args:**\n\n - `attrs` (dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides\n values in the `default` dictionary.\n - `default` (str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden\n with values in the `attrs` dictionary.\n - Any extra kwargs will be appended to the corresponding keys\n\n The attributes in `attrs` and `defaults` are merged and resulting dict is rendered as HTML attributes\n (`key=\"value\"`).\n\n Extra kwargs (`key=value`) are concatenated to existing keys. So if we have\n\n ```python\n attrs = {\"class\": \"my-class\"}\n ```\n\n Then\n\n ```django\n {% html_attrs attrs class=\"extra-class\" %}\n ```\n\n will result in `class=\"my-class extra-class\"`.\n\n **Example:**\n ```django\n <div {% html_attrs\n attrs\n defaults:class=\"default-class\"\n class=\"extra-class\"\n data-id=\"123\"\n %}>\n ```\n\n renders\n\n ```html\n <div class=\"my-class extra-class\" data-id=\"123\">\n ```\n\n **See more usage examples in\n [HTML attributes](../../concepts/fundamentals/html_attributes#examples-for-html_attrs).**\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n return HtmlAttrsNode(\n kwargs=tag.kwargs,\n kwarg_pairs=tag.kwarg_pairs,\n )\n
provide(parser: Parser, token: Token, tag_spec: TagSpec) -> ProvideNode\n
The \"provider\" part of the provide / inject feature. Pass kwargs to this tag to define the provider's data. Any components defined within the
{% provide %}..{% endprovide %}
tags will be able to access this data withComponent.inject()
.This is similar to React's
ContextProvider
, or Vue'sprovide()
.Args:
name
(str, required): Provider name. This is the name you will then use inComponent.inject()
.**kwargs
: Any extra kwargs will be passed as the provided data.
Example:
Provide the \"user_data\" in parent component:
@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n <div>\n {% provide \"user_data\" user=user %}\n {% component \"child\" / %}\n {% endprovide %}\n </div>\n \"\"\"\n\n def get_context_data(self, user: User):\n return {\n \"user\": user,\n }\n
Since the \"child\" component is used within the
{% provide %} / {% endprovide %}
tags, we can request the \"user_data\" usingComponent.inject(\"user_data\")
:@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n User is: {{ user }}\n </div>\n \"\"\"\n\n def get_context_data(self):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n
Notice that the keys defined on the
{% provide %}
tag are then accessed as attributes when accessing them withComponent.inject()
.\u2705 Do this
user = self.inject(\"user_data\").user\n
\u274c Don't do this
Source code inuser = self.inject(\"user_data\")[\"user\"]\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.slot","title":"slot","text":"@register.tag(\"provide\")\n@with_tag_spec(\n TagSpec(\n tag=\"provide\",\n end_tag=\"endprovide\",\n positional_only_args=[],\n pos_or_keyword_args=[PROVIDE_NAME_KWARG],\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[],\n )\n)\ndef provide(parser: Parser, token: Token, tag_spec: TagSpec) -> ProvideNode:\n \"\"\"\n The \"provider\" part of the [provide / inject feature](../../concepts/advanced/provide_inject).\n Pass kwargs to this tag to define the provider's data.\n Any components defined within the `{% provide %}..{% endprovide %}` tags will be able to access this data\n with [`Component.inject()`](../api#django_components.Component.inject).\n\n This is similar to React's [`ContextProvider`](https://react.dev/learn/passing-data-deeply-with-context),\n or Vue's [`provide()`](https://vuejs.org/guide/components/provide-inject).\n\n **Args:**\n\n - `name` (str, required): Provider name. This is the name you will then use in\n [`Component.inject()`](../api#django_components.Component.inject).\n - `**kwargs`: Any extra kwargs will be passed as the provided data.\n\n **Example:**\n\n Provide the \"user_data\" in parent component:\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n <div>\n {% provide \"user_data\" user=user %}\n {% component \"child\" / %}\n {% endprovide %}\n </div>\n \\\"\\\"\\\"\n\n def get_context_data(self, user: User):\n return {\n \"user\": user,\n }\n ```\n\n Since the \"child\" component is used within the `{% provide %} / {% endprovide %}` tags,\n we can request the \"user_data\" using `Component.inject(\"user_data\")`:\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n User is: {{ user }}\n </div>\n \\\"\\\"\\\"\n\n def get_context_data(self):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n ```\n\n Notice that the keys defined on the `{% provide %}` tag are then accessed as attributes\n when accessing them with [`Component.inject()`](../api#django_components.Component.inject).\n\n \u2705 Do this\n ```python\n user = self.inject(\"user_data\").user\n ```\n\n \u274c Don't do this\n ```python\n user = self.inject(\"user_data\")[\"user\"]\n ```\n \"\"\"\n # e.g. {% provide <name> key=val key2=val2 %}\n tag = _parse_tag(parser, token, tag_spec)\n\n name_kwarg = tag.kwargs.kwargs.get(PROVIDE_NAME_KWARG, None)\n trace_id = f\"provide-id-{tag.id} ({name_kwarg})\" if name_kwarg else f\"fill-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"PROVIDE\", trace_id, tag.id)\n\n body = tag.parse_body()\n provide_node = ProvideNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"PROVIDE\", trace_id, tag.id, \"...Done!\")\n return provide_node\n
slot(parser: Parser, token: Token, tag_spec: TagSpec) -> SlotNode\n
Slot tag marks a place inside a component where content can be inserted from outside.
Learn more about using slots.
This is similar to slots as seen in Web components, Vue or React's
children
.Args:
name
(str, required): Registered name of the component to renderdefault
: Optional flag. If there is a default slot, you can pass the component slot content without using the{% fill %}
tag. See Default slotrequired
: Optional flag. Will raise an error if a slot is required but not given.**kwargs
: Any extra kwargs will be passed as the slot data.
Example:
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" default %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n <aside>\n {% slot \"sidebar\" required / %}\n </aside>\n \"\"\"\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.slot--passing-data-to-slots","title":"Passing data to slots","text":"@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n <div>\n {% component \"child\" %}\n {% fill \"content\" %}\n \ud83d\uddde\ufe0f\ud83d\udcf0\n {% endfill %}\n\n {% fill \"sidebar\" %}\n \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n {% endfill %}\n {% endcomponent %}\n </div>\n \"\"\"\n
Any extra kwargs will be considered as slot data, and will be accessible in the
{% fill %}
tag via fill'sdata
kwarg:@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \"\"\"\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.slot--accessing-default-slot-content","title":"Accessing default slot content","text":"@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
The content between the
{% slot %}..{% endslot %}
tags is the default content that will be rendered if no fill is given for the slot.This default content can then be accessed from within the
{% fill %}
tag using the fill'sdefault
kwarg. This is useful if you need to wrap / prepend / append the original slot's content.@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" %}\n This is default content!\n {% endslot %}\n </div>\n \"\"\"\n
Source code in@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot's default content #}\n {% component \"child\" %}\n {% fill \"content\" default=\"default\" %}\n {{ default }}\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.with_tag_spec","title":"with_tag_spec","text":"@register.tag(\"slot\")\n@with_tag_spec(\n TagSpec(\n tag=\"slot\",\n end_tag=\"endslot\",\n positional_only_args=[],\n pos_or_keyword_args=[SLOT_NAME_KWARG],\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[SLOT_DEFAULT_KEYWORD, SLOT_REQUIRED_KEYWORD],\n )\n)\ndef slot(parser: Parser, token: Token, tag_spec: TagSpec) -> SlotNode:\n \"\"\"\n Slot tag marks a place inside a component where content can be inserted\n from outside.\n\n [Learn more](../../concepts/fundamentals/slots) about using slots.\n\n This is similar to slots as seen in\n [Web components](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot),\n [Vue](https://vuejs.org/guide/components/slots.html)\n or [React's `children`](https://react.dev/learn/passing-props-to-a-component#passing-jsx-as-children).\n\n **Args:**\n\n - `name` (str, required): Registered name of the component to render\n - `default`: Optional flag. If there is a default slot, you can pass the component slot content\n without using the [`{% fill %}`](#fill) tag. See\n [Default slot](../../concepts/fundamentals/slots#default-slot)\n - `required`: Optional flag. Will raise an error if a slot is required but not given.\n - `**kwargs`: Any extra kwargs will be passed as the slot data.\n\n **Example:**\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {% slot \"content\" default %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n <aside>\n {% slot \"sidebar\" required / %}\n </aside>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n <div>\n {% component \"child\" %}\n {% fill \"content\" %}\n \ud83d\uddde\ufe0f\ud83d\udcf0\n {% endfill %}\n\n {% fill \"sidebar\" %}\n \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n {% endfill %}\n {% endcomponent %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ### Passing data to slots\n\n Any extra kwargs will be considered as slot data, and will be accessible in the [`{% fill %}`](#fill)\n tag via fill's `data` kwarg:\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \\\"\\\"\\\"\n ```\n\n ### Accessing default slot content\n\n The content between the `{% slot %}..{% endslot %}` tags is the default content that\n will be rendered if no fill is given for the slot.\n\n This default content can then be accessed from within the [`{% fill %}`](#fill) tag using\n the fill's `default` kwarg.\n This is useful if you need to wrap / prepend / append the original slot's content.\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {% slot \"content\" %}\n This is default content!\n {% endslot %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n {# Parent can access the slot's default content #}\n {% component \"child\" %}\n {% fill \"content\" default=\"default\" %}\n {{ default }}\n {% endfill %}\n {% endcomponent %}\n \\\"\\\"\\\"\n ```\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n slot_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n trace_id = f\"slot-id-{tag.id} ({slot_name_kwarg})\" if slot_name_kwarg else f\"slot-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"SLOT\", trace_id, tag.id)\n\n body = tag.parse_body()\n slot_node = SlotNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n is_required=tag.flags[SLOT_REQUIRED_KEYWORD],\n is_default=tag.flags[SLOT_DEFAULT_KEYWORD],\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"SLOT\", trace_id, tag.id, \"...Done!\")\n return slot_node\n
Source code inwith_tag_spec(tag_spec: TagSpec) -> Callable\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/types/","title":"def with_tag_spec(tag_spec: TagSpec) -> Callable:\n \"\"\"\"\"\"\n\n def decorator(fn: Callable) -> Any:\n fn._tag_spec = tag_spec # type: ignore[attr-defined]\n\n @functools.wraps(fn)\n def wrapper(*args: Any, **kwargs: Any) -> Any:\n return fn(*args, **kwargs, tag_spec=tag_spec)\n\n return wrapper\n\n return decorator\n
types","text":""},{"location":"reference/django_components/types/#django_components.types","title":"types","text":"
Helper types for IDEs.
"},{"location":"reference/django_components/urls/","title":"urls","text":""},{"location":"reference/django_components/urls/#django_components.urls","title":"urls","text":""},{"location":"reference/django_components/util/","title":"Index","text":""},{"location":"reference/django_components/util/#django_components.util","title":"util","text":"
Modules:
-
cache
\u2013 -
html
\u2013 -
loader
\u2013 -
logger
\u2013 -
misc
\u2013 -
tag_parser
\u2013 -
types
\u2013
Functions:
-
lazy_cache
\u2013Decorator that caches the given function similarly to
functools.lru_cache
.
lazy_cache(make_cache: Callable[[], Callable[[Callable], Callable]]) -> Callable[[TFunc], TFunc]\n
Decorator that caches the given function similarly to
functools.lru_cache
. But the cache is instantiated only at first invocation.
Source code incache
argument is a function that generates the cache function, e.g.functools.lru_cache()
.src/django_components/util/cache.py
"},{"location":"reference/django_components/util/#django_components.util.html","title":"html","text":"def lazy_cache(\n make_cache: Callable[[], Callable[[Callable], Callable]],\n) -> Callable[[TFunc], TFunc]:\n \"\"\"\n Decorator that caches the given function similarly to `functools.lru_cache`.\n But the cache is instantiated only at first invocation.\n\n `cache` argument is a function that generates the cache function,\n e.g. `functools.lru_cache()`.\n \"\"\"\n _cached_fn = None\n\n def decorator(fn: TFunc) -> TFunc:\n @functools.wraps(fn)\n def wrapper(*args: Any, **kwargs: Any) -> Any:\n # Lazily initialize the cache\n nonlocal _cached_fn\n if not _cached_fn:\n # E.g. `lambda: functools.lru_cache(maxsize=app_settings.TEMPLATE_CACHE_SIZE)`\n cache = make_cache()\n _cached_fn = cache(fn)\n\n return _cached_fn(*args, **kwargs)\n\n # Allow to access the LRU cache methods\n # See https://stackoverflow.com/a/37654201/9788634\n wrapper.cache_info = lambda: _cached_fn.cache_info() # type: ignore\n wrapper.cache_clear = lambda: _cached_fn.cache_clear() # type: ignore\n\n # And allow to remove the cache instance (mostly for tests)\n def cache_remove() -> None:\n nonlocal _cached_fn\n _cached_fn = None\n\n wrapper.cache_remove = cache_remove # type: ignore\n\n return cast(TFunc, wrapper)\n\n return decorator\n
Functions:
-
parse_document_or_nodes
\u2013Use this if you do NOT know whether the given HTML is a full document
-
parse_multiroot_html
\u2013Use this when you know the given HTML is a multiple nodes like
-
parse_node
\u2013Use this when you know the given HTML is a single node like
parse_document_or_nodes(html: str) -> Union[List[LexborNode], LexborHTMLParser]\n
Use this if you do NOT know whether the given HTML is a full document with
Source code in<html>
,<head>
, and<body>
tags, or an HTML fragment.src/django_components/util/html.py
"},{"location":"reference/django_components/util/#django_components.util.html.parse_multiroot_html","title":"parse_multiroot_html","text":"def parse_document_or_nodes(html: str) -> Union[List[LexborNode], LexborHTMLParser]:\n \"\"\"\n Use this if you do NOT know whether the given HTML is a full document\n with `<html>`, `<head>`, and `<body>` tags, or an HTML fragment.\n \"\"\"\n html = html.strip()\n tree = LexborHTMLParser(html)\n is_fragment = is_html_parser_fragment(html, tree)\n\n if is_fragment:\n nodes = parse_multiroot_html(html)\n return nodes\n else:\n return tree\n
parse_multiroot_html(html: str) -> List[LexborNode]\n
Use this when you know the given HTML is a multiple nodes like
Source code in<div> Hi </div> <span> Hello </span>
src/django_components/util/html.py
"},{"location":"reference/django_components/util/#django_components.util.html.parse_node","title":"parse_node","text":"def parse_multiroot_html(html: str) -> List[LexborNode]:\n \"\"\"\n Use this when you know the given HTML is a multiple nodes like\n\n `<div> Hi </div> <span> Hello </span>`\n \"\"\"\n # NOTE: HTML / XML MUST have a single root. So, to support multiple\n # top-level elements, we wrap them in a dummy singular root.\n parser = LexborHTMLParser(f\"<root>{html}</root>\")\n\n # Get all contents of the root\n root_elem = parser.css_first(\"root\")\n elems = [*root_elem.iter()] if root_elem else []\n return elems\n
parse_node(html: str) -> LexborNode\n
Use this when you know the given HTML is a single node like
Source code in<div> Hi </div>
src/django_components/util/html.py
"},{"location":"reference/django_components/util/#django_components.util.loader","title":"loader","text":"def parse_node(html: str) -> LexborNode:\n \"\"\"\n Use this when you know the given HTML is a single node like\n\n `<div> Hi </div>`\n \"\"\"\n tree = LexborHTMLParser(html)\n # NOTE: The parser automatically places <style> tags inside <head>\n # while <script> tags are inside <body>.\n return tree.body.child or tree.head.child # type: ignore[union-attr, return-value]\n
Classes:
-
ComponentFileEntry
\u2013Result returned by
get_component_files()
.
Functions:
-
get_component_dirs
\u2013Get directories that may contain component files.
-
get_component_files
\u2013Search for files within the component directories (as defined in
Bases:
NamedTuple
Result returned by
get_component_files()
.Attributes:
-
dot_path
(str
) \u2013The python import path for the module. E.g.
app.components.mycomp
-
filepath
(Path
) \u2013The filesystem path to the module. E.g.
/path/to/project/app/components/mycomp.py
instance-attribute
","text":"dot_path: str\n
The python import path for the module. E.g.
"},{"location":"reference/django_components/util/#django_components.util.loader.ComponentFileEntry.filepath","title":"filepathapp.components.mycomp
instance-attribute
","text":"filepath: Path\n
The filesystem path to the module. E.g.
"},{"location":"reference/django_components/util/#django_components.util.loader.get_component_dirs","title":"get_component_dirs","text":"/path/to/project/app/components/mycomp.py
get_component_dirs(include_apps: bool = True) -> List[Path]\n
Get directories that may contain component files.
This is the heart of all features that deal with filesystem and file lookup. Autodiscovery, Django template resolution, static file resolution - They all use this.
Parameters:
-
include_apps
(bool
, default:True
) \u2013Include directories from installed Django apps. Defaults to
True
.
Returns:
-
List[Path]
\u2013List[Path]: A list of directories that may contain component files.
get_component_dirs()
searches for dirs set inCOMPONENTS.dirs
settings. If none set, defaults to searching for a\"components\"
app.In addition to that, also all installed Django apps are checked whether they contain directories as set in
COMPONENTS.app_dirs
(e.g.[app]/components
).Notes:
-
Paths that do not point to directories are ignored.
-
BASE_DIR
setting is required. -
The paths in
COMPONENTS.dirs
must be absolute paths.
src/django_components/util/loader.py
"},{"location":"reference/django_components/util/#django_components.util.loader.get_component_files","title":"get_component_files","text":"def get_component_dirs(include_apps: bool = True) -> List[Path]:\n \"\"\"\n Get directories that may contain component files.\n\n This is the heart of all features that deal with filesystem and file lookup.\n Autodiscovery, Django template resolution, static file resolution - They all use this.\n\n Args:\n include_apps (bool, optional): Include directories from installed Django apps.\\\n Defaults to `True`.\n\n Returns:\n List[Path]: A list of directories that may contain component files.\n\n `get_component_dirs()` searches for dirs set in\n [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n settings. If none set, defaults to searching for a `\"components\"` app.\n\n In addition to that, also all installed Django apps are checked whether they contain\n directories as set in\n [`COMPONENTS.app_dirs`](../settings#django_components.app_settings.ComponentsSettings.app_dirs)\n (e.g. `[app]/components`).\n\n **Notes:**\n\n - Paths that do not point to directories are ignored.\n\n - `BASE_DIR` setting is required.\n\n - The paths in [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n must be absolute paths.\n \"\"\"\n # Allow to configure from settings which dirs should be checked for components\n component_dirs = app_settings.DIRS\n\n # TODO_REMOVE_IN_V1\n raw_component_settings = getattr(settings, \"COMPONENTS\", {})\n if isinstance(raw_component_settings, dict):\n raw_dirs_value = raw_component_settings.get(\"dirs\", None)\n elif isinstance(raw_component_settings, ComponentsSettings):\n raw_dirs_value = raw_component_settings.dirs\n else:\n raw_dirs_value = None\n is_component_dirs_set = raw_dirs_value is not None\n is_legacy_paths = (\n # Use value of `STATICFILES_DIRS` ONLY if `COMPONENT.dirs` not set\n not is_component_dirs_set\n and hasattr(settings, \"STATICFILES_DIRS\")\n and settings.STATICFILES_DIRS\n )\n if is_legacy_paths:\n # NOTE: For STATICFILES_DIRS, we use the defaults even for empty list.\n # We don't do this for COMPONENTS.dirs, so user can explicitly specify \"NO dirs\".\n component_dirs = settings.STATICFILES_DIRS or [settings.BASE_DIR / \"components\"]\n # END TODO_REMOVE_IN_V1\n\n source = \"STATICFILES_DIRS\" if is_legacy_paths else \"COMPONENTS.dirs\"\n\n logger.debug(\n \"get_component_dirs will search for valid dirs from following options:\\n\"\n + \"\\n\".join([f\" - {str(d)}\" for d in component_dirs])\n )\n\n # Add `[app]/[APP_DIR]` to the directories. This is, by default `[app]/components`\n app_paths: List[Path] = []\n if include_apps:\n for conf in apps.get_app_configs():\n for app_dir in app_settings.APP_DIRS:\n comps_path = Path(conf.path).joinpath(app_dir)\n if comps_path.exists():\n app_paths.append(comps_path)\n\n directories: Set[Path] = set(app_paths)\n\n # Validate and add other values from the config\n for component_dir in component_dirs:\n # Consider tuples for STATICFILES_DIRS (See #489)\n # See https://docs.djangoproject.com/en/5.0/ref/settings/#prefixes-optional\n if isinstance(component_dir, (tuple, list)):\n component_dir = component_dir[1]\n try:\n Path(component_dir)\n except TypeError:\n logger.warning(\n f\"{source} expected str, bytes or os.PathLike object, or tuple/list of length 2. \"\n f\"See Django documentation for STATICFILES_DIRS. Got {type(component_dir)} : {component_dir}\"\n )\n continue\n\n if not Path(component_dir).is_absolute():\n raise ValueError(f\"{source} must contain absolute paths, got '{component_dir}'\")\n else:\n directories.add(Path(component_dir).resolve())\n\n logger.debug(\n \"get_component_dirs matched following template dirs:\\n\" + \"\\n\".join([f\" - {str(d)}\" for d in directories])\n )\n return list(directories)\n
get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]\n
Search for files within the component directories (as defined in
get_component_dirs()
).Requires
BASE_DIR
setting to be set.Parameters:
-
suffix
(Optional[str]
, default:None
) \u2013The suffix to search for. E.g.
.py
,.js
,.css
. Defaults toNone
, which will search for all files.
Returns:
-
List[ComponentFileEntry]
\u2013List[ComponentFileEntry] A list of entries that contain both the filesystem path and the python import path (dot path).
Example:
Source code infrom django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
src/django_components/util/loader.py
"},{"location":"reference/django_components/util/#django_components.util.logger","title":"logger","text":"def get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]:\n \"\"\"\n Search for files within the component directories (as defined in\n [`get_component_dirs()`](../api#django_components.get_component_dirs)).\n\n Requires `BASE_DIR` setting to be set.\n\n Args:\n suffix (Optional[str], optional): The suffix to search for. E.g. `.py`, `.js`, `.css`.\\\n Defaults to `None`, which will search for all files.\n\n Returns:\n List[ComponentFileEntry] A list of entries that contain both the filesystem path and \\\n the python import path (dot path).\n\n **Example:**\n\n ```python\n from django_components import get_component_files\n\n modules = get_component_files(\".py\")\n ```\n \"\"\"\n search_glob = f\"**/*{suffix}\" if suffix else \"**/*\"\n\n dirs = get_component_dirs(include_apps=False)\n component_filepaths = _search_dirs(dirs, search_glob)\n\n if hasattr(settings, \"BASE_DIR\") and settings.BASE_DIR:\n project_root = str(settings.BASE_DIR)\n else:\n # Fallback for getting the root dir, see https://stackoverflow.com/a/16413955/9788634\n project_root = os.path.abspath(os.path.dirname(__name__))\n\n # NOTE: We handle dirs from `COMPONENTS.dirs` and from individual apps separately.\n modules: List[ComponentFileEntry] = []\n\n # First let's handle the dirs from `COMPONENTS.dirs`\n #\n # Because for dirs in `COMPONENTS.dirs`, we assume they will be nested under `BASE_DIR`,\n # and that `BASE_DIR` is the current working dir (CWD). So the path relatively to `BASE_DIR`\n # is ALSO the python import path.\n for filepath in component_filepaths:\n module_path = _filepath_to_python_module(filepath, project_root, None)\n # Ignore files starting with dot `.` or files in dirs that start with dot.\n #\n # If any of the parts of the path start with a dot, e.g. the filesystem path\n # is `./abc/.def`, then this gets converted to python module as `abc..def`\n #\n # NOTE: This approach also ignores files:\n # - with two dots in the middle (ab..cd.py)\n # - an extra dot at the end (abcd..py)\n # - files outside of the parent component (../abcd.py).\n # But all these are NOT valid python modules so that's fine.\n if \"..\" in module_path:\n continue\n\n entry = ComponentFileEntry(dot_path=module_path, filepath=filepath)\n modules.append(entry)\n\n # For for apps, the directories may be outside of the project, e.g. in case of third party\n # apps. So we have to resolve the python import path relative to the package name / the root\n # import path for the app.\n # See https://github.com/EmilStenstrom/django-components/issues/669\n for conf in apps.get_app_configs():\n for app_dir in app_settings.APP_DIRS:\n comps_path = Path(conf.path).joinpath(app_dir)\n if not comps_path.exists():\n continue\n app_component_filepaths = _search_dirs([comps_path], search_glob)\n for filepath in app_component_filepaths:\n app_component_module = _filepath_to_python_module(filepath, conf.path, conf.name)\n entry = ComponentFileEntry(dot_path=app_component_module, filepath=filepath)\n modules.append(entry)\n\n return modules\n
Functions:
-
trace
\u2013TRACE level logger.
-
trace_msg
\u2013TRACE level logger with opinionated format for tracing interaction of components,
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:
Source code inLOGGING = {\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
src/django_components/util/logger.py
"},{"location":"reference/django_components/util/#django_components.util.logger.trace_msg","title":"trace_msg","text":"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
trace_msg(\n action: Literal[\"PARSE\", \"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:
Source code in\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"
src/django_components/util/logger.py
"},{"location":"reference/django_components/util/#django_components.util.misc","title":"misc","text":"def trace_msg(\n action: Literal[\"PARSE\", \"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 == \"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
Functions:
-
gen_id
\u2013Generate a unique ID that can be associated with a Node
-
get_import_path
\u2013Get the full import path for a class or a function, e.g.
\"path.to.MyClass\"
gen_id() -> str\n
Generate a unique ID that can be associated with a Node
Source code insrc/django_components/util/misc.py
"},{"location":"reference/django_components/util/#django_components.util.misc.get_import_path","title":"get_import_path","text":"def gen_id() -> str:\n \"\"\"Generate a unique ID that can be associated with a Node\"\"\"\n # Alphabet is only alphanumeric. Compared to the default alphabet used by nanoid,\n # we've omitted `-` and `_`.\n # With this alphabet, at 6 chars, the chance of collision is 1 in 3.3M.\n # See https://zelark.github.io/nano-id-cc/\n return generate(\n \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\",\n size=6,\n )\n
get_import_path(cls_or_fn: Type[Any]) -> str\n
Get the full import path for a class or a function, e.g.
Source code in\"path.to.MyClass\"
src/django_components/util/misc.py
"},{"location":"reference/django_components/util/#django_components.util.tag_parser","title":"tag_parser","text":"def get_import_path(cls_or_fn: Type[Any]) -> str:\n \"\"\"\n Get the full import path for a class or a function, e.g. `\"path.to.MyClass\"`\n \"\"\"\n module = cls_or_fn.__module__\n if module == \"builtins\":\n return cls_or_fn.__qualname__ # avoid outputs like 'builtins.str'\n return module + \".\" + cls_or_fn.__qualname__\n
Classes:
-
TagAttr
\u2013
dataclass
","text":"TagAttr(key: Optional[str], value: str, start_index: int, quoted: bool)\n
Attributes:
-
quoted
(bool
) \u2013Whether the value is quoted (either with single or double quotes)
-
start_index
(int
) \u2013Start index of the attribute (include both key and value),
instance-attribute
","text":"quoted: bool\n
Whether the value is quoted (either with single or double quotes)
"},{"location":"reference/django_components/util/#django_components.util.tag_parser.TagAttr.start_index","title":"start_indexinstance-attribute
","text":"start_index: int\n
Start index of the attribute (include both key and value), relative to the start of the owner Tag.
"},{"location":"reference/django_components/util/#django_components.util.types","title":"types","text":"Classes:
-
EmptyDict
\u2013TypedDict with no members.
Attributes:
-
EmptyTuple
\u2013Tuple with no members.
module-attribute
","text":"EmptyTuple = Tuple[]\n
Tuple with no members.
You can use this to define a Component that accepts NO positional arguments:
from django_components import Component, EmptyTuple\n\nclass Table(Component(EmptyTuple, Any, Any, Any, Any, Any))\n ...\n
After that, when you call
Component.render()
orComponent.render_to_response()
, theargs
parameter will raise type error ifargs
is anything else than an empty tuple.Table.render(\n args: (),\n)\n
Omitting
args
is also fine:Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
"},{"location":"reference/django_components/util/#django_components.util.types.EmptyDict","title":"EmptyDict","text":"Table.render(\n args: (\"one\", 2, \"three\"),\n)\n
Bases:
TypedDict
TypedDict with no members.
You can use this to define a Component that accepts NO kwargs, or NO slots, or returns NO data from
Component.get_context_data()
/Component.get_js_data()
/Component.get_css_data()
:Accepts NO kwargs:
from django_components import Component, EmptyDict\n\nclass Table(Component(Any, EmptyDict, Any, Any, Any, Any))\n ...\n
Accepts NO slots:
from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, EmptyDict, Any, Any, Any))\n ...\n
Returns NO data from
get_context_data()
:from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, Any, EmptyDict, Any, Any))\n ...\n
Going back to the example with NO kwargs, when you then call
Component.render()
orComponent.render_to_response()
, thekwargs
parameter will raise type error ifkwargs
is anything else than an empty dict.Table.render(\n kwargs: {},\n)\n
Omitting
kwargs
is also fine:Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
"},{"location":"reference/django_components/util/cache/","title":"Table.render(\n kwargs: {\n \"one\": 2,\n \"three\": 4,\n },\n)\n
cache","text":""},{"location":"reference/django_components/util/cache/#django_components.util.cache","title":"cache","text":"
Functions:
-
lazy_cache
\u2013Decorator that caches the given function similarly to
functools.lru_cache
.
lazy_cache(make_cache: Callable[[], Callable[[Callable], Callable]]) -> Callable[[TFunc], TFunc]\n
Decorator that caches the given function similarly to
functools.lru_cache
. But the cache is instantiated only at first invocation.
Source code incache
argument is a function that generates the cache function, e.g.functools.lru_cache()
.src/django_components/util/cache.py
"},{"location":"reference/django_components/util/html/","title":"def lazy_cache(\n make_cache: Callable[[], Callable[[Callable], Callable]],\n) -> Callable[[TFunc], TFunc]:\n \"\"\"\n Decorator that caches the given function similarly to `functools.lru_cache`.\n But the cache is instantiated only at first invocation.\n\n `cache` argument is a function that generates the cache function,\n e.g. `functools.lru_cache()`.\n \"\"\"\n _cached_fn = None\n\n def decorator(fn: TFunc) -> TFunc:\n @functools.wraps(fn)\n def wrapper(*args: Any, **kwargs: Any) -> Any:\n # Lazily initialize the cache\n nonlocal _cached_fn\n if not _cached_fn:\n # E.g. `lambda: functools.lru_cache(maxsize=app_settings.TEMPLATE_CACHE_SIZE)`\n cache = make_cache()\n _cached_fn = cache(fn)\n\n return _cached_fn(*args, **kwargs)\n\n # Allow to access the LRU cache methods\n # See https://stackoverflow.com/a/37654201/9788634\n wrapper.cache_info = lambda: _cached_fn.cache_info() # type: ignore\n wrapper.cache_clear = lambda: _cached_fn.cache_clear() # type: ignore\n\n # And allow to remove the cache instance (mostly for tests)\n def cache_remove() -> None:\n nonlocal _cached_fn\n _cached_fn = None\n\n wrapper.cache_remove = cache_remove # type: ignore\n\n return cast(TFunc, wrapper)\n\n return decorator\n
html","text":""},{"location":"reference/django_components/util/html/#django_components.util.html","title":"html","text":"
Functions:
-
parse_document_or_nodes
\u2013Use this if you do NOT know whether the given HTML is a full document
-
parse_multiroot_html
\u2013Use this when you know the given HTML is a multiple nodes like
-
parse_node
\u2013Use this when you know the given HTML is a single node like
parse_document_or_nodes(html: str) -> Union[List[LexborNode], LexborHTMLParser]\n
Use this if you do NOT know whether the given HTML is a full document with
Source code in<html>
,<head>
, and<body>
tags, or an HTML fragment.src/django_components/util/html.py
"},{"location":"reference/django_components/util/html/#django_components.util.html.parse_multiroot_html","title":"parse_multiroot_html","text":"def parse_document_or_nodes(html: str) -> Union[List[LexborNode], LexborHTMLParser]:\n \"\"\"\n Use this if you do NOT know whether the given HTML is a full document\n with `<html>`, `<head>`, and `<body>` tags, or an HTML fragment.\n \"\"\"\n html = html.strip()\n tree = LexborHTMLParser(html)\n is_fragment = is_html_parser_fragment(html, tree)\n\n if is_fragment:\n nodes = parse_multiroot_html(html)\n return nodes\n else:\n return tree\n
parse_multiroot_html(html: str) -> List[LexborNode]\n
Use this when you know the given HTML is a multiple nodes like
Source code in<div> Hi </div> <span> Hello </span>
src/django_components/util/html.py
"},{"location":"reference/django_components/util/html/#django_components.util.html.parse_node","title":"parse_node","text":"def parse_multiroot_html(html: str) -> List[LexborNode]:\n \"\"\"\n Use this when you know the given HTML is a multiple nodes like\n\n `<div> Hi </div> <span> Hello </span>`\n \"\"\"\n # NOTE: HTML / XML MUST have a single root. So, to support multiple\n # top-level elements, we wrap them in a dummy singular root.\n parser = LexborHTMLParser(f\"<root>{html}</root>\")\n\n # Get all contents of the root\n root_elem = parser.css_first(\"root\")\n elems = [*root_elem.iter()] if root_elem else []\n return elems\n
parse_node(html: str) -> LexborNode\n
Use this when you know the given HTML is a single node like
Source code in<div> Hi </div>
src/django_components/util/html.py
"},{"location":"reference/django_components/util/loader/","title":"def parse_node(html: str) -> LexborNode:\n \"\"\"\n Use this when you know the given HTML is a single node like\n\n `<div> Hi </div>`\n \"\"\"\n tree = LexborHTMLParser(html)\n # NOTE: The parser automatically places <style> tags inside <head>\n # while <script> tags are inside <body>.\n return tree.body.child or tree.head.child # type: ignore[union-attr, return-value]\n
loader","text":""},{"location":"reference/django_components/util/loader/#django_components.util.loader","title":"loader","text":"
Classes:
-
ComponentFileEntry
\u2013Result returned by
get_component_files()
.
Functions:
-
get_component_dirs
\u2013Get directories that may contain component files.
-
get_component_files
\u2013Search for files within the component directories (as defined in
Bases:
NamedTuple
Result returned by
get_component_files()
.Attributes:
-
dot_path
(str
) \u2013The python import path for the module. E.g.
app.components.mycomp
-
filepath
(Path
) \u2013The filesystem path to the module. E.g.
/path/to/project/app/components/mycomp.py
instance-attribute
","text":"dot_path: str\n
The python import path for the module. E.g.
"},{"location":"reference/django_components/util/loader/#django_components.util.loader.ComponentFileEntry.filepath","title":"filepathapp.components.mycomp
instance-attribute
","text":"filepath: Path\n
The filesystem path to the module. E.g.
"},{"location":"reference/django_components/util/loader/#django_components.util.loader.get_component_dirs","title":"get_component_dirs","text":"/path/to/project/app/components/mycomp.py
get_component_dirs(include_apps: bool = True) -> List[Path]\n
Get directories that may contain component files.
This is the heart of all features that deal with filesystem and file lookup. Autodiscovery, Django template resolution, static file resolution - They all use this.
Parameters:
-
include_apps
(bool
, default:True
) \u2013Include directories from installed Django apps. Defaults to
True
.
Returns:
-
List[Path]
\u2013List[Path]: A list of directories that may contain component files.
get_component_dirs()
searches for dirs set inCOMPONENTS.dirs
settings. If none set, defaults to searching for a\"components\"
app.In addition to that, also all installed Django apps are checked whether they contain directories as set in
COMPONENTS.app_dirs
(e.g.[app]/components
).Notes:
-
Paths that do not point to directories are ignored.
-
BASE_DIR
setting is required. -
The paths in
COMPONENTS.dirs
must be absolute paths.
src/django_components/util/loader.py
"},{"location":"reference/django_components/util/loader/#django_components.util.loader.get_component_files","title":"get_component_files","text":"def get_component_dirs(include_apps: bool = True) -> List[Path]:\n \"\"\"\n Get directories that may contain component files.\n\n This is the heart of all features that deal with filesystem and file lookup.\n Autodiscovery, Django template resolution, static file resolution - They all use this.\n\n Args:\n include_apps (bool, optional): Include directories from installed Django apps.\\\n Defaults to `True`.\n\n Returns:\n List[Path]: A list of directories that may contain component files.\n\n `get_component_dirs()` searches for dirs set in\n [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n settings. If none set, defaults to searching for a `\"components\"` app.\n\n In addition to that, also all installed Django apps are checked whether they contain\n directories as set in\n [`COMPONENTS.app_dirs`](../settings#django_components.app_settings.ComponentsSettings.app_dirs)\n (e.g. `[app]/components`).\n\n **Notes:**\n\n - Paths that do not point to directories are ignored.\n\n - `BASE_DIR` setting is required.\n\n - The paths in [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n must be absolute paths.\n \"\"\"\n # Allow to configure from settings which dirs should be checked for components\n component_dirs = app_settings.DIRS\n\n # TODO_REMOVE_IN_V1\n raw_component_settings = getattr(settings, \"COMPONENTS\", {})\n if isinstance(raw_component_settings, dict):\n raw_dirs_value = raw_component_settings.get(\"dirs\", None)\n elif isinstance(raw_component_settings, ComponentsSettings):\n raw_dirs_value = raw_component_settings.dirs\n else:\n raw_dirs_value = None\n is_component_dirs_set = raw_dirs_value is not None\n is_legacy_paths = (\n # Use value of `STATICFILES_DIRS` ONLY if `COMPONENT.dirs` not set\n not is_component_dirs_set\n and hasattr(settings, \"STATICFILES_DIRS\")\n and settings.STATICFILES_DIRS\n )\n if is_legacy_paths:\n # NOTE: For STATICFILES_DIRS, we use the defaults even for empty list.\n # We don't do this for COMPONENTS.dirs, so user can explicitly specify \"NO dirs\".\n component_dirs = settings.STATICFILES_DIRS or [settings.BASE_DIR / \"components\"]\n # END TODO_REMOVE_IN_V1\n\n source = \"STATICFILES_DIRS\" if is_legacy_paths else \"COMPONENTS.dirs\"\n\n logger.debug(\n \"get_component_dirs will search for valid dirs from following options:\\n\"\n + \"\\n\".join([f\" - {str(d)}\" for d in component_dirs])\n )\n\n # Add `[app]/[APP_DIR]` to the directories. This is, by default `[app]/components`\n app_paths: List[Path] = []\n if include_apps:\n for conf in apps.get_app_configs():\n for app_dir in app_settings.APP_DIRS:\n comps_path = Path(conf.path).joinpath(app_dir)\n if comps_path.exists():\n app_paths.append(comps_path)\n\n directories: Set[Path] = set(app_paths)\n\n # Validate and add other values from the config\n for component_dir in component_dirs:\n # Consider tuples for STATICFILES_DIRS (See #489)\n # See https://docs.djangoproject.com/en/5.0/ref/settings/#prefixes-optional\n if isinstance(component_dir, (tuple, list)):\n component_dir = component_dir[1]\n try:\n Path(component_dir)\n except TypeError:\n logger.warning(\n f\"{source} expected str, bytes or os.PathLike object, or tuple/list of length 2. \"\n f\"See Django documentation for STATICFILES_DIRS. Got {type(component_dir)} : {component_dir}\"\n )\n continue\n\n if not Path(component_dir).is_absolute():\n raise ValueError(f\"{source} must contain absolute paths, got '{component_dir}'\")\n else:\n directories.add(Path(component_dir).resolve())\n\n logger.debug(\n \"get_component_dirs matched following template dirs:\\n\" + \"\\n\".join([f\" - {str(d)}\" for d in directories])\n )\n return list(directories)\n
get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]\n
Search for files within the component directories (as defined in
get_component_dirs()
).Requires
BASE_DIR
setting to be set.Parameters:
-
suffix
(Optional[str]
, default:None
) \u2013The suffix to search for. E.g.
.py
,.js
,.css
. Defaults toNone
, which will search for all files.
Returns:
-
List[ComponentFileEntry]
\u2013List[ComponentFileEntry] A list of entries that contain both the filesystem path and the python import path (dot path).
Example:
Source code infrom django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
src/django_components/util/loader.py
"},{"location":"reference/django_components/util/logger/","title":"def get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]:\n \"\"\"\n Search for files within the component directories (as defined in\n [`get_component_dirs()`](../api#django_components.get_component_dirs)).\n\n Requires `BASE_DIR` setting to be set.\n\n Args:\n suffix (Optional[str], optional): The suffix to search for. E.g. `.py`, `.js`, `.css`.\\\n Defaults to `None`, which will search for all files.\n\n Returns:\n List[ComponentFileEntry] A list of entries that contain both the filesystem path and \\\n the python import path (dot path).\n\n **Example:**\n\n ```python\n from django_components import get_component_files\n\n modules = get_component_files(\".py\")\n ```\n \"\"\"\n search_glob = f\"**/*{suffix}\" if suffix else \"**/*\"\n\n dirs = get_component_dirs(include_apps=False)\n component_filepaths = _search_dirs(dirs, search_glob)\n\n if hasattr(settings, \"BASE_DIR\") and settings.BASE_DIR:\n project_root = str(settings.BASE_DIR)\n else:\n # Fallback for getting the root dir, see https://stackoverflow.com/a/16413955/9788634\n project_root = os.path.abspath(os.path.dirname(__name__))\n\n # NOTE: We handle dirs from `COMPONENTS.dirs` and from individual apps separately.\n modules: List[ComponentFileEntry] = []\n\n # First let's handle the dirs from `COMPONENTS.dirs`\n #\n # Because for dirs in `COMPONENTS.dirs`, we assume they will be nested under `BASE_DIR`,\n # and that `BASE_DIR` is the current working dir (CWD). So the path relatively to `BASE_DIR`\n # is ALSO the python import path.\n for filepath in component_filepaths:\n module_path = _filepath_to_python_module(filepath, project_root, None)\n # Ignore files starting with dot `.` or files in dirs that start with dot.\n #\n # If any of the parts of the path start with a dot, e.g. the filesystem path\n # is `./abc/.def`, then this gets converted to python module as `abc..def`\n #\n # NOTE: This approach also ignores files:\n # - with two dots in the middle (ab..cd.py)\n # - an extra dot at the end (abcd..py)\n # - files outside of the parent component (../abcd.py).\n # But all these are NOT valid python modules so that's fine.\n if \"..\" in module_path:\n continue\n\n entry = ComponentFileEntry(dot_path=module_path, filepath=filepath)\n modules.append(entry)\n\n # For for apps, the directories may be outside of the project, e.g. in case of third party\n # apps. So we have to resolve the python import path relative to the package name / the root\n # import path for the app.\n # See https://github.com/EmilStenstrom/django-components/issues/669\n for conf in apps.get_app_configs():\n for app_dir in app_settings.APP_DIRS:\n comps_path = Path(conf.path).joinpath(app_dir)\n if not comps_path.exists():\n continue\n app_component_filepaths = _search_dirs([comps_path], search_glob)\n for filepath in app_component_filepaths:\n app_component_module = _filepath_to_python_module(filepath, conf.path, conf.name)\n entry = ComponentFileEntry(dot_path=app_component_module, filepath=filepath)\n modules.append(entry)\n\n return modules\n
logger","text":""},{"location":"reference/django_components/util/logger/#django_components.util.logger","title":"logger","text":"
Functions:
-
trace
\u2013TRACE level logger.
-
trace_msg
\u2013TRACE level logger with opinionated format for tracing interaction of components,
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:
Source code inLOGGING = {\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
src/django_components/util/logger.py
"},{"location":"reference/django_components/util/logger/#django_components.util.logger.trace_msg","title":"trace_msg","text":"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
trace_msg(\n action: Literal[\"PARSE\", \"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:
Source code in\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"
src/django_components/util/logger.py
"},{"location":"reference/django_components/util/misc/","title":"def trace_msg(\n action: Literal[\"PARSE\", \"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 == \"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
misc","text":""},{"location":"reference/django_components/util/misc/#django_components.util.misc","title":"misc","text":"
Functions:
-
gen_id
\u2013Generate a unique ID that can be associated with a Node
-
get_import_path
\u2013Get the full import path for a class or a function, e.g.
\"path.to.MyClass\"
gen_id() -> str\n
Generate a unique ID that can be associated with a Node
Source code insrc/django_components/util/misc.py
"},{"location":"reference/django_components/util/misc/#django_components.util.misc.get_import_path","title":"get_import_path","text":"def gen_id() -> str:\n \"\"\"Generate a unique ID that can be associated with a Node\"\"\"\n # Alphabet is only alphanumeric. Compared to the default alphabet used by nanoid,\n # we've omitted `-` and `_`.\n # With this alphabet, at 6 chars, the chance of collision is 1 in 3.3M.\n # See https://zelark.github.io/nano-id-cc/\n return generate(\n \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\",\n size=6,\n )\n
get_import_path(cls_or_fn: Type[Any]) -> str\n
Get the full import path for a class or a function, e.g.
Source code in\"path.to.MyClass\"
src/django_components/util/misc.py
"},{"location":"reference/django_components/util/nanoid/","title":"def get_import_path(cls_or_fn: Type[Any]) -> str:\n \"\"\"\n Get the full import path for a class or a function, e.g. `\"path.to.MyClass\"`\n \"\"\"\n module = cls_or_fn.__module__\n if module == \"builtins\":\n return cls_or_fn.__qualname__ # avoid outputs like 'builtins.str'\n return module + \".\" + cls_or_fn.__qualname__\n
nanoid","text":""},{"location":"reference/django_components/util/nanoid/#django_components.util.nanoid","title":"nanoid","text":""},{"location":"reference/django_components/util/tag_parser/","title":"
tag_parser","text":""},{"location":"reference/django_components/util/tag_parser/#django_components.util.tag_parser","title":"tag_parser","text":"
Classes:
-
TagAttr
\u2013
dataclass
","text":"TagAttr(key: Optional[str], value: str, start_index: int, quoted: bool)\n
Attributes:
-
quoted
(bool
) \u2013Whether the value is quoted (either with single or double quotes)
-
start_index
(int
) \u2013Start index of the attribute (include both key and value),
instance-attribute
","text":"quoted: bool\n
Whether the value is quoted (either with single or double quotes)
"},{"location":"reference/django_components/util/tag_parser/#django_components.util.tag_parser.TagAttr.start_index","title":"start_indexinstance-attribute
","text":"start_index: int\n
Start index of the attribute (include both key and value), relative to the start of the owner Tag.
"},{"location":"reference/django_components/util/types/","title":"types","text":""},{"location":"reference/django_components/util/types/#django_components.util.types","title":"types","text":"
Classes:
-
EmptyDict
\u2013TypedDict with no members.
Attributes:
-
EmptyTuple
\u2013Tuple with no members.
module-attribute
","text":"EmptyTuple = Tuple[]\n
Tuple with no members.
You can use this to define a Component that accepts NO positional arguments:
from django_components import Component, EmptyTuple\n\nclass Table(Component(EmptyTuple, Any, Any, Any, Any, Any))\n ...\n
After that, when you call
Component.render()
orComponent.render_to_response()
, theargs
parameter will raise type error ifargs
is anything else than an empty tuple.Table.render(\n args: (),\n)\n
Omitting
args
is also fine:Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
"},{"location":"reference/django_components/util/types/#django_components.util.types.EmptyDict","title":"EmptyDict","text":"Table.render(\n args: (\"one\", 2, \"three\"),\n)\n
Bases:
TypedDict
TypedDict with no members.
You can use this to define a Component that accepts NO kwargs, or NO slots, or returns NO data from
Component.get_context_data()
/Component.get_js_data()
/Component.get_css_data()
:Accepts NO kwargs:
from django_components import Component, EmptyDict\n\nclass Table(Component(Any, EmptyDict, Any, Any, Any, Any))\n ...\n
Accepts NO slots:
from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, EmptyDict, Any, Any, Any))\n ...\n
Returns NO data from
get_context_data()
:from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, Any, EmptyDict, Any, Any))\n ...\n
Going back to the example with NO kwargs, when you then call
Component.render()
orComponent.render_to_response()
, thekwargs
parameter will raise type error ifkwargs
is anything else than an empty dict.Table.render(\n kwargs: {},\n)\n
Omitting
kwargs
is also fine:Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
"},{"location":"reference/django_components/util/validation/","title":"Table.render(\n kwargs: {\n \"one\": 2,\n \"three\": 4,\n },\n)\n
validation","text":""},{"location":"reference/django_components/util/validation/#django_components.util.validation","title":"validation","text":""},{"location":"reference/django_components_js/build/","title":"
build","text":""},{"location":"reference/django_components_js/build/#django_components_js.build","title":"build","text":""},{"location":"reference/docs/","title":"Index","text":""},{"location":"reference/docs/#docs","title":"docs","text":"
Modules:
-
scripts
\u2013
Modules:
-
reference
\u2013Generate the code reference pages and navigation.
Generate the code reference pages and navigation.
No need to run this script manually, it is called by mkdocs-material during the build process.
You can run it manually to test the output.
"},{"location":"reference/docs/scripts/","title":"Index","text":""},{"location":"reference/docs/scripts/#docs.scripts","title":"scripts","text":"Modules:
-
reference
\u2013Generate the code reference pages and navigation.
Generate the code reference pages and navigation.
No need to run this script manually, it is called by mkdocs-material during the build process.
You can run it manually to test the output.
"},{"location":"reference/docs/scripts/reference/","title":"reference","text":""},{"location":"reference/docs/scripts/reference/#docs.scripts.reference","title":"reference","text":"
Generate the code reference pages and navigation.
No need to run this script manually, it is called by mkdocs-material during the build process.
You can run it manually to test the output.
"}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Index","text":"Docs (Work in progress)
Django-components is a package that introduces component-based architecture to Django's server-side rendering. It aims to combine Django's templating system with the modularity seen in modern frontend frameworks.
"},{"location":"#features","title":"Features","text":"- \ud83e\udde9 Reusability: Allows creation of self-contained, reusable UI elements.
- \ud83d\udce6 Encapsulation: Each component can include its own HTML, CSS, and JavaScript.
- \ud83d\ude80 Server-side rendering: Components render on the server, improving initial load times and SEO.
- \ud83d\udc0d Django integration: Works within the Django ecosystem, using familiar concepts like template tags.
- \u26a1 Asynchronous loading: Components can render independently opening up for integration with JS frameworks like HTMX or AlpineJS.
Potential benefits:
- \ud83d\udd04 Reduced code duplication
- \ud83d\udee0\ufe0f Improved maintainability through modular design
- \ud83e\udde0 Easier management of complex UIs
- \ud83e\udd1d Enhanced collaboration between frontend and backend developers
Django-components can be particularly useful for larger Django projects that require a more structured approach to UI development, without necessitating a shift to a separate frontend framework.
"},{"location":"#quickstart","title":"Quickstart","text":"django-components lets you create reusable blocks of code needed to generate the front end code you need for a modern app.
Define a component in
components/calendar/calendar.py
like this:@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"template.html\"\n\n def get_context_data(self, date):\n return {\"date\": date}\n
With this
template.html
file:<div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n
Use the component like this:
{% component \"calendar\" date=\"2024-11-06\" %}{% endcomponent %}\n
And this is what gets rendered:
<div class=\"calendar-component\">Today's date is <span>2024-11-06</span></div>\n
Read on to learn about all the exciting details and configuration possibilities!
(If you instead prefer to jump right into the code, check out the example project)
"},{"location":"#table-of-contents","title":"Table of Contents","text":"- Release notes
- Security notes \ud83d\udea8
- Installation
- Compatibility
- Create your first component
- Using single-file components
- Use components in templates
- Use components outside of templates
- Use components as views
- Typing and validating components
- Pre-defined components
- Registering components
- Autodiscovery
- Using slots in templates
- Accessing data passed to the component
- Rendering HTML attributes
- Template tag syntax
- Prop drilling and dependency injection (provide / inject)
- Component hooks
- Component context and scope
- Pre-defined template variables
- Customizing component tags with TagFormatter
- Defining HTML/JS/CSS files
- Rendering JS/CSS dependencies
- Available settings
- Running with development server
- Logging and debugging
- Management Command
- Writing and sharing component libraries
- Community examples
- Running django-components project locally
- Development guides
Read the Release Notes to see the latest features and fixes.
"},{"location":"#security-notes","title":"Security notes \ud83d\udea8","text":"It is strongly recommended to read this section before using django-components in production.
"},{"location":"#static-files","title":"Static files","text":"Components can be organized however you prefer. That said, our prefered way is to keep the files of a component close together by bundling them in the same directory.
This means that files containing backend logic, such as Python modules and HTML templates, live in the same directory as static files, e.g. JS and CSS.
From v0.100 onwards, we keep component files (as defined by
COMPONENTS.dirs
andCOMPONENTS.app_dirs
) separate from the rest of the static files (defined bySTATICFILES_DIRS
). That way, the Python and HTML files are NOT exposed by the server. Only the static JS, CSS, and other common formats.NOTE: If you need to expose different file formats, you can configure these with
"},{"location":"#static-files-prior-to-v0100","title":"Static files prior to v0.100","text":"COMPONENTS.static_files_allowed
andCOMPONENTS.static_files_forbidden
.Prior to v0.100, if your were using django.contrib.staticfiles to collect static files, no distinction was made between the different kinds of files.
As a result, your Python code and templates may inadvertently become available on your static file server. You probably don't want this, as parts of your backend logic will be exposed, posing a potential security vulnerability.
From v0.27 until v0.100, django-components shipped with an additional installable app django_components.safer_staticfiles. It was a drop-in replacement for django.contrib.staticfiles. Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server. To use it, add it to INSTALLED_APPS and remove django.contrib.staticfiles.
INSTALLED_APPS = [\n # 'django.contrib.staticfiles', # <-- REMOVE\n 'django_components',\n 'django_components.safer_staticfiles' # <-- ADD\n]\n
If you are on an older version of django-components, your alternatives are a) passing
--ignore <pattern>
options to the collecstatic CLI command, or b) defining a subclass of StaticFilesConfig. Both routes are described in the official docs of the staticfiles app.Note that
safer_staticfiles
excludes the.py
and.html
files for collectstatic command:python manage.py collectstatic\n
but it is ignored on the development server:
python manage.py runserver\n
For a step-by-step guide on deploying production server with static files, see the demo project.
"},{"location":"#installation","title":"Installation","text":"- Install
django_components
into your environment:
pip install django_components
- Load
django_components
into Django by adding it intoINSTALLED_APPS
in settings.py:
INSTALLED_APPS = [\n ...,\n 'django_components',\n]\n
BASE_DIR
setting is required. Ensure that it is defined in settings.py:
BASE_DIR = Path(__file__).resolve().parent.parent\n
- Add / modify
COMPONENTS.dirs
and / orCOMPONENTS.app_dirs
so django_components knows where to find component HTML, JS and CSS files:
COMPONENTS = {\n \"dirs\": [\n ...,\n os.path.join(BASE_DIR, \"components\"),\n ],\n}\n
If
COMPONENTS.dirs
is omitted, django-components will by default look for a top-level/components
directory,{BASE_DIR}/components
.In addition to
COMPONENTS.dirs
, django_components will also load components from app-level directories, such asmy-app/components/
. The directories within apps are configured withCOMPONENTS.app_dirs
, and the default is[app]/components
.NOTE: The input to
COMPONENTS.dirs
is the same as forSTATICFILES_DIRS
, and the paths must be full paths. See Django docs.-
Next, to make Django load component HTML files as Django templates, modify
TEMPLATES
section of settings.py as follows: -
Remove
'APP_DIRS': True,
- NOTE: Instead of APP_DIRS, for the same effect, we will use
django.template.loaders.app_directories.Loader
- NOTE: Instead of APP_DIRS, for the same effect, we will use
- Add
loaders
toOPTIONS
list and set it to following value:
TEMPLATES = [\n {\n ...,\n 'OPTIONS': {\n 'context_processors': [\n ...\n ],\n 'loaders':[(\n 'django.template.loaders.cached.Loader', [\n # Default Django loader\n 'django.template.loaders.filesystem.Loader',\n # Inluding this is the same as APP_DIRS=True\n 'django.template.loaders.app_directories.Loader',\n # Components loader\n 'django_components.template_loader.Loader',\n ]\n )],\n },\n },\n]\n
- Lastly, be able to serve the component JS and CSS files as static files, modify
STATICFILES_FINDERS
section of settings.py as follows:
"},{"location":"#adding-support-for-js-and-css","title":"Adding support for JS and CSS","text":"STATICFILES_FINDERS = [\n # Default finders\n \"django.contrib.staticfiles.finders.FileSystemFinder\",\n \"django.contrib.staticfiles.finders.AppDirectoriesFinder\",\n # Django components\n \"django_components.finders.ComponentsFileSystemFinder\",\n]\n
If you want to use JS or CSS with components, you will need to:
- Add
ComponentDependencyMiddleware
toMIDDLEWARE
setting.
The middleware searches the outgoing HTML for all components that were rendered to generate the HTML, and adds the JS and CSS associated with those components.
MIDDLEWARE = [\n ...\n \"django_components.middleware.ComponentDependencyMiddleware\",\n]\n
Read more in Rendering JS/CSS dependencies.
- Add django-component's URL paths to your
urlpatterns
:
"},{"location":"#optional","title":"Optional","text":"from django.urls import include, path\n\nurlpatterns = [\n ...\n path(\"\", include(\"django_components.urls\")),\n]\n
To avoid loading the app in each template using
{% load component_tags %}
, you can add the tag as a 'builtin' in settings.pyTEMPLATES = [\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
[project root]/components/calendar/calendar.htmldate
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.{# In a file called [project root]/components/calendar/template.html #}\n<div class=\"calendar-component\">Today's date is <span>{{ date }}</span></div>\n
Finally, we use django-components to tie this together. Start by creating a file called
calendar.py
in your component calendar directory. It will be auto-detected and loaded by the app.Inside this file we create a Component by inheriting from the Component class and specifying the context method. We also register the global component registry so that we easily can render it anywhere in our templates.
[project root]/components/calendar/calendar.py# In a file called [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n # Templates inside `[your apps]/components` dir and `[project root]/components` dir\n # will be automatically found.\n #\n # `template_name` can be relative to dir where `calendar.py` is, or relative to COMPONENTS.dirs\n template_name = \"template.html\"\n # Or\n def get_template_name(context):\n return f\"template-{context['name']}.html\"\n\n # This component takes one parameter, a date string to show in the template\n def get_context_data(self, date):\n return {\n \"date\": date,\n }\n\n # Both `css` and `js` can be relative to dir where `calendar.py` is, or relative to COMPONENTS.dirs\n class Media:\n css = \"style.css\"\n js = \"script.js\"\n
And voil\u00e1!! We've created our first component.
"},{"location":"#using-single-file-components","title":"Using single-file components","text":"Components can also be defined in a single file, which is useful for small components. To do this, you can use the
[project root]/components/calendar.pytemplate
,js
, andcss
class attributes instead of thetemplate_name
andMedia
. For example, here's the calendar component from above, defined in a single file:# 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
"},{"location":"#pycharm-or-other-jetbrains-ides","title":"Pycharm (or other Jetbrains IDEs)","text":"t.django_html
,t.css
, andt.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.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
"},{"location":"#use-components-in-templates","title":"Use components in templates","text":"types.django_html
,types.css
,types.js
since Pycharm uses language injections. You only need to write the comments# language=<lang>
above the variables.First load the
component_tags
tag library, then use thecomponent_[js/css]_dependencies
andcomponent
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
andrender_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:
"},{"location":"#inputs-of-render-and-render_to_response","title":"Inputs ofhello: world\nfoo: bar\nkwargs: {'kw1': 'test', 'kw2': 'ooo'}\nslot_first: FIRST_SLOT\n
render
andrender_to_response
","text":"Both
render
andrender_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 }
whereslot_content
can be a string orSlotFunc
. -
escape_slots_content
- Whether the content fromslots
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.
SlotFunc
","text":"When rendering components with slots in
render
orrender_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:
"},{"location":"#response-class-of-render_to_response","title":"Response class ofdef 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
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 isdjango.http.HttpResponse
.If you want to use a different Response class in
render_to_response
, set theComponent.response_class
attribute:
"},{"location":"#use-components-as-views","title":"Use components as views","text":"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
New in version 0.34
Note: Since 0.92, Component no longer subclasses View. To configure the View class, set the nested
Component.View
classComponents can now be used as views: - Components define the
Component.as_view()
class method that can be used the same asView.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
andpost
to handle GET and POST requests, respectively. -
In addition,
Component
now has arender_to_response
method that renders the component template based on the provided context and slots' data and returns anHttpResponse
object.
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 callingView.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 theurls.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 therender_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
"},{"location":"#modifying-the-view-class","title":"Modifying the View class","text":"format_html
andmark_safe
.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()
orComponent.View.post()
methods. However, by default,Component.View.get()
points toComponent.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 asComponent.View
2. Subclass fromComponentView
, so the View instance has access to the component instance.In the example below, we added extra logic into
View.setup()
.Note that the POST handler is still defined at the top. This is because
View
subclassesComponentView
, which defines thepost()
method that callsComponent.post()
.If you were to overwrite the
View.post()
method, thenComponent.post()
would be ignored.
"},{"location":"#typing-and-validating-components","title":"Typing and validating components","text":""},{"location":"#adding-type-hints-with-generics","title":"Adding type hints with Generics","text":"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
New in version 0.92
The
Component
class optionally accepts type parameters that allow you to specify the types of args, kwargs, slots, and data:class Button(Component[Args, Kwargs, Slots, Data, JsData, CssData]):\n ...\n
Args
- Must be aTuple
orAny
Kwargs
- Must be aTypedDict
orAny
Data
- Must be aTypedDict
orAny
Slots
- Must be aTypedDict
orAny
Here's a full example:
from typing import NotRequired, Tuple, TypedDict, SlotContent, SlotFunc\n\n# Positional inputs\nArgs = Tuple[int, str]\n\n# Kwargs inputs\nclass Kwargs(TypedDict):\n variable: str\n another: int\n maybe_var: NotRequired[int] # May be ommited\n\n# Data returned from `get_context_data`\nclass Data(TypedDict):\n variable: str\n\n# The data available to the `my_slot` scoped slot\nclass MySlotData(TypedDict):\n value: int\n\n# Slots\nclass Slots(TypedDict):\n # Use SlotFunc for slot functions.\n # The generic specifies the `data` dictionary\n my_slot: NotRequired[SlotFunc[MySlotData]]\n # SlotContent == Union[str, SafeString]\n another_slot: SlotContent\n\nclass Button(Component[Args, Kwargs, Slots, Data, JsData, CssData]):\n def get_context_data(self, variable, another):\n return {\n \"variable\": variable,\n }\n
When you then call
Component.render
orComponent.render_to_response
, you will get type hints:
"},{"location":"#usage-for-python-311","title":"Usage for Python <3.11","text":"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
On Python 3.8-3.10, use
typing_extensions
from typing_extensions import TypedDict, NotRequired\n
Additionally on Python 3.8-3.9, also import
annotations
:from __future__ import annotations\n
Moreover, on 3.10 and less, you may not be able to use
NotRequired
, and instead you will need to mark either all keys are required, or all keys as optional, using TypeDict'stotal
kwarg.See PEP-655 for more info.
"},{"location":"#passing-additional-args-or-kwargs","title":"Passing additional args or kwargs","text":"You may have a function that supports any number of args or kwargs:
def get_context_data(self, *args, **kwargs):\n ...\n
This is not supported with the typed components.
As a workaround: - For
*args
, set a positional argument that accepts a list of values:```py\n# Tuple of one member of list of strings\nArgs = Tuple[List[str]]\n```\n
-
For
*kwargs
, set a keyword argument that accepts a dictionary of values:class Kwargs(TypedDict):\n variable: str\n another: int\n # Pass any extra keys under `extra`\n extra: Dict[str, any]\n
To declare that a component accepts no Args, Kwargs, etc, you can use
EmptyTuple
andEmptyDict
types:
"},{"location":"#runtime-input-validation-with-types","title":"Runtime input validation with types","text":"from django_components import Component, EmptyDict, EmptyTuple\n\nArgs = EmptyTuple\nKwargs = Data = Slots = EmptyDict\n\nclass Button(Component[Args, Kwargs, Slots, Data, JsData, CssData]):\n ...\n
New in version 0.96
NOTE: Kwargs, slots, and data validation is supported only for Python >=3.11
In Python 3.11 and later, when you specify the component types, you will get also runtime validation of the inputs you pass to
Component.render
orComponent.render_to_response
.So, using the example from before, if you ignored the type errors and still ran the following code:
Button.render(\n # Error: First arg must be `int`, got `float`\n args=(1.25, \"abc\"),\n # Error: Key \"another\" is missing\n kwargs={\n \"variable\": \"text\",\n },\n)\n
This would raise a
TypeError
:Component 'Button' expected positional argument at index 0 to be <class 'int'>, got 1.25 of type <class 'float'>\n
In case you need to skip these errors, you can either set the faulty member to
Any
, e.g.:# Changed `int` to `Any`\nArgs = Tuple[Any, str]\n
Or you can replace
Args
withAny
altogether, to skip the validation of args:# Replaced `Args` with `Any`\nclass Button(Component[Any, Kwargs, Slots, Data, JsData, CssData]):\n ...\n
Same applies to kwargs, data, and slots.
"},{"location":"#pre-defined-components","title":"Pre-defined components","text":""},{"location":"#dynamic-components","title":"Dynamic components","text":"If you are writing something like a form component, you may design it such that users give you the component names, and your component renders it.
While you can handle this with a series of if / else statements, this is not an extensible solution.
Instead, you can use dynamic components. Dynamic components are used in place of normal components.
{% load component_tags %}\n{% component \"dynamic\" is=component_name title=\"Cat Museum\" %}\n {% fill \"content\" %}\n HELLO_FROM_SLOT_1\n {% endfill %}\n {% fill \"sidebar\" %}\n HELLO_FROM_SLOT_2\n {% endfill %}\n{% endcomponent %}\n
or in case you use the
django_components.component_shorthand_formatter
tag formatter:{% dynamic is=component_name title=\"Cat Museu\" %}\n {% fill \"content\" %}\n HELLO_FROM_SLOT_1\n {% endfill %}\n {% fill \"sidebar\" %}\n HELLO_FROM_SLOT_2\n {% endfill %}\n{% enddynamic %}\n
These behave same way as regular components. You pass it the same args, kwargs, and slots as you would to the component that you want to render.
The only exception is that also you supply 1-2 additional inputs: -
is
- Required - The component name or a component class to render -registry
- Optional - TheComponentRegistry
that will be searched ifis
is a component name. If omitted, ALL registries are searched.By default, the dynamic component is registered under the name
\"dynamic\"
. In case of a conflict, you can change the name used for the dynamic components by defining theCOMPONENTS.dynamic_component_name
setting.If you need to use the dynamic components in Python, you can also import it from
django_components
:
"},{"location":"#registering-components","title":"Registering components","text":"from django_components import DynamicComponent\n\ncomp = SimpleTableComp if is_readonly else TableComp\n\noutput = DynamicComponent.render(\n kwargs={\n \"is\": comp,\n # Other kwargs...\n },\n # args: [...],\n # slots: {...},\n)\n
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,
"},{"location":"#what-is-componentregistry","title":"What is ComponentRegistry","text":"@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.The
@register
decorator is a shortcut for working with theComponentRegistry
.ComponentRegistry
manages which components can be used in the template tags.Each
ComponentRegistry
instance is associated with an instance of Django'sLibrary
. And Libraries are inserted into Django template using the{% load %}
tags.The
@register
decorator accepts an optional kwargregistry
, which specifies, theComponentRegistry
to register components into. If omitted, the defaultComponentRegistry
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 theLibrary
that you load when you call{% load component_tags %}
inside your template, or when you adddjango_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
"},{"location":"#working-with-componentregistry","title":"Working with ComponentRegistry","text":"{% component \"my_comp\" %}
.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:
"},{"location":"#registering-components-to-custom-componentregistry","title":"Registering components to custom ComponentRegistry","text":"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
If you are writing a component library to be shared with others, you may want to manage your own instance of
ComponentRegistry
and register components onto a differentLibrary
instance than the default one.The
Library
instance can be set at instantiation ofComponentRegistry
. 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 withmy_registry.register()
, or pass the registry to the@component.register()
decorator via theregistry
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
"},{"location":"#componentregistry-settings","title":"ComponentRegistry settings","text":"library
attribute ofComponentRegistry
.When you are creating an instance of
ComponentRegistry
, you can define the components' behavior within the template.The registry accepts these settings: -
context_behavior
-tag_formatter
from django.template import Library\nfrom django_components import ComponentRegistry, RegistrySettings\n\nregister = library = django.template.Library()\ncomp_registry = ComponentRegistry(\n library=library,\n settings=RegistrySettings(\n context_behavior=\"isolated\",\n tag_formatter=\"django_components.component_formatter\",\n ),\n)\n
These settings are the same as the ones you can set for django_components.
In fact, when you set
COMPONENT.tag_formatter
orCOMPONENT.context_behavior
, these are forwarded to the defaultComponentRegistry
.This makes it possible to have multiple registries with different settings in one projects, and makes sharing of component libraries possible.
"},{"location":"#autodiscovery","title":"Autodiscovery","text":"Every component that you want to use in the template with the
{% component %}
tag needs to be registered with the ComponentRegistry. Normally, we use the@register
decorator for that:from django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n ...\n
But for the component to be registered, the code needs to be executed - the file needs to be imported as a module.
One way to do that is by importing all your components in
apps.py
:from django.apps import AppConfig\n\nclass MyAppConfig(AppConfig):\n name = \"my_app\"\n\n def ready(self) -> None:\n from components.card.card import Card\n from components.list.list import List\n from components.menu.menu import Menu\n from components.button.button import Button\n ...\n
However, there's a simpler way!
By default, the Python files in the
COMPONENTS.dirs
directories (or app-level[app]/components/
) are auto-imported in order to auto-register the components.Autodiscovery occurs when Django is loaded, during the
ready
hook of theapps.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:
"},{"location":"#using-slots-in-templates","title":"Using slots in templates","text":"from django_components import autodiscover\n\nautodiscover()\n
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 theslot
tag.
Components support something called 'slots'. When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content. This mechanism makes components more reusable and composable. This behavior is similar to slots in Vue.
In the example below we introduce two block tags that work hand in hand to make this work. These are...
{% slot <name> %}
/{% endslot %}
: Declares a new slot in the component template.{% fill <name> %}
/{% endfill %}
: (Used inside a{% component %}
tag pair.) Fills a declared slot with the specified content.
Let's update our calendar component to support more customization. We'll add
slot
tag pairs to its template, template.html.<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" %}Calendar header{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"body\" %}Today's date is <span>{{ date }}</span>{% endslot %}\n </div>\n</div>\n
When using the component, you specify which slots you want to fill and where you want to use the defaults from the template. It looks like this:
{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"body\" %}\n Can you believe it's already <span>{{ date }}</span>??\n {% endfill %}\n{% endcomponent %}\n
Since the 'header' fill is unspecified, it's taken from the base template. If you put this in a template, and pass in
date=2020-06-06
, this is what gets rendered:
"},{"location":"#named-slots","title":"Named slots","text":"<div class=\"calendar-component\">\n <div class=\"header\">\n Calendar header\n </div>\n <div class=\"body\">\n Can you believe it's already <span>2020-06-06</span>??\n </div>\n</div>\n
As seen in the previouse section, you can use
{% fill slot_name %}
to insert content into a specific slot.You can define fills for multiple slot simply by defining them all within the
{% component %} {% endcomponent %}
tags:{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}\n Hi this is header!\n {% endfill %}\n {% fill \"body\" %}\n Can you believe it's already <span>{{ date }}</span>??\n {% endfill %}\n{% endcomponent %}\n
You can also use
{% for %}
,{% with %}
, or other non-component tags (even{% include %}
) to construct the{% fill %}
tags, as long as these other tags do not leave any text behind!
"},{"location":"#default-slot","title":"Default slot","text":"{% component \"table\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name %}\n {{ slot_name }}\n {% endfill %}\n {% endfor %}\n\n {% with slot_name=\"abc\" %}\n {% fill name=slot_name %}\n {{ slot_name }}\n {% endfill %}\n {% endwith %}\n{% endcomponent %}\n
Added in version 0.28
As you can see, component slots lets you write reusable containers that you fill in when you use a component. This makes for highly reusable components that can be used in different circumstances.
It can become tedious to use
fill
tags everywhere, especially when you're using a component that declares only one slot. To make things easier,slot
tags can be marked with an optional keyword:default
.When added to the tag (as shown below), this option lets you pass filling content directly in the body of a
component
tag pair \u2013 without using afill
tag. Choose carefully, though: a component template may contain at most one slot that is marked asdefault
. Thedefault
option can be combined with other slot options, e.g.required
.Here's the same example as before, except with default slots and implicit filling.
The template:
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"header\" %}Calendar header{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"body\" default %}Today's date is <span>{{ date }}</span>{% endslot %}\n </div>\n</div>\n
Including the component (notice how the
fill
tag is omitted):{% component \"calendar\" date=\"2020-06-06\" %}\n Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n
The rendered result (exactly the same as before):
<div class=\"calendar-component\">\n <div class=\"header\">Calendar header</div>\n <div class=\"body\">Can you believe it's already <span>2020-06-06</span>??</div>\n</div>\n
You may be tempted to combine implicit fills with explicit
fill
tags. This will not work. The following component template will raise an error when rendered.{# DON'T DO THIS #}\n{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}Totally new header!{% endfill %}\n Can you believe it's already <span>{{ date }}</span>??\n{% endcomponent %}\n
Instead, you can use a named fill with name
default
to target the default fill:{# THIS WORKS #}\n{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"header\" %}Totally new header!{% endfill %}\n {% fill \"default\" %}\n Can you believe it's already <span>{{ date }}</span>??\n {% endfill %}\n{% endcomponent %}\n
NOTE: If you doubly-fill a slot, that is, that both
"},{"location":"#accessing-default-slot-in-python","title":"Accessing default slot in Python","text":"{% fill \"default\" %}
and{% fill \"header\" %}
would point to the same slot, this will raise an error when rendered.Since the default slot is stored under the slot name
default
, you can access the default slot like so:
"},{"location":"#render-fill-in-multiple-places","title":"Render fill in multiple places","text":"class MyTable(Component):\n def get_context_data(self, *args, **kwargs):\n default_slot = self.input.slots[\"default\"]\n return {\n \"default_slot\": default_slot,\n }\n
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:
"},{"location":"#default-and-required-slots","title":"Default and required slots","text":"<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
If you use a slot multiple times, you can still mark the slot as
default
orrequired
. For that, you must mark each slot individually, e.g.:<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"image\" default required %}Image here{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"image\" default required %}Image here{% endslot %}\n </div>\n</div>\n
Which you can then use as regular default slot:
{% component \"calendar\" date=\"2020-06-06\" %}\n <img src=\"...\" />\n{% endcomponent %}\n
Since each slot is tagged individually, you can have multiple slots with the same name but different conditions.
E.g. in this example, we have a component that renders a user avatar - a small circular image with a profile picture of name initials.
If the component is given
image_src
orname_initials
variables, theimage
slot is optional. But if neither of those are provided, you MUST fill theimage
slot.
"},{"location":"#accessing-original-content-of-slots","title":"Accessing original content of slots","text":"<div class=\"avatar\">\n {% if image_src %}\n {% slot \"image\" default %}\n <img src=\"{{ image_src }}\" />\n {% endslot %}\n {% elif name_initials %}\n {% slot \"image\" default %}\n <div style=\"\n border-radius: 25px;\n width: 50px;\n height: 50px;\n background: blue;\n \">\n {{ name_initials }}\n </div>\n {% endslot %}\n {% else %}\n {% slot \"image\" default required / %}\n {% endif %}\n</div>\n
Added in version 0.26
NOTE: In version 0.77, the syntax was changed from
{% fill \"my_slot\" as \"alias\" %} {{ alias.default }}\n
to
{% fill \"my_slot\" default=\"slot_default\" %} {{ slot_default }}\n
Sometimes you may want to keep the original slot, but only wrap or prepend/append content to it. To do so, you can access the default slot via the
default
kwarg.Similarly to the
data
attribute, you specify the variable name through which the default slot will be made available.For instance, let's say you're filling a slot called 'body'. To render the original slot, assign it to a variable using the
'default'
keyword. You then render this variable to insert the default content:{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"body\" default=\"body_default\" %}\n {{ body_default }}. Have a great day!\n {% endfill %}\n{% endcomponent %}\n
This produces:
<div class=\"calendar-component\">\n <div class=\"header\">\n Calendar header\n </div>\n <div class=\"body\">\n Today's date is <span>2020-06-06</span>. Have a great day!\n </div>\n</div>\n
To access the original content of a default slot, set the name to
default
:
"},{"location":"#conditional-slots","title":"Conditional slots","text":"{% component \"calendar\" date=\"2020-06-06\" %}\n {% fill \"default\" default=\"slot_default\" %}\n {{ slot_default }}. Have a great day!\n {% endfill %}\n{% endcomponent %}\n
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 Accessingis_filled
of slot names with special characters.In certain circumstances, you may want the behavior of slot filling to depend on whether or not a particular slot is filled.
For example, suppose we have the following component template:
<div class=\"frontmatter-component\">\n <div class=\"title\">\n {% slot \"title\" %}Title{% endslot %}\n </div>\n <div class=\"subtitle\">\n {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n </div>\n</div>\n
By default the slot named 'subtitle' is empty. Yet when the component is used without explicit fills, the div containing the slot is still rendered, as shown below:
<div class=\"frontmatter-component\">\n <div class=\"title\">Title</div>\n <div class=\"subtitle\"></div>\n</div>\n
This may not be what you want. What if instead the outer 'subtitle' div should only be included when the inner slot is in fact filled?
The answer is to use the
{{ component_vars.is_filled.<name> }}
variable. You can use this together with Django's{% if/elif/else/endif %}
tags to define a block whose contents will be rendered only if the component slot with the corresponding 'name' is filled.This is what our example looks like with
component_vars.is_filled
.<div class=\"frontmatter-component\">\n <div class=\"title\">\n {% slot \"title\" %}Title{% endslot %}\n </div>\n {% if component_vars.is_filled.subtitle %}\n <div class=\"subtitle\">\n {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n </div>\n {% endif %}\n</div>\n
Here's our example with more complex branching.
<div class=\"frontmatter-component\">\n <div class=\"title\">\n {% slot \"title\" %}Title{% endslot %}\n </div>\n {% if component_vars.is_filled.subtitle %}\n <div class=\"subtitle\">\n {% slot \"subtitle\" %}{# Optional subtitle #}{% endslot %}\n </div>\n {% elif component_vars.is_filled.title %}\n ...\n {% elif component_vars.is_filled.<name> %}\n ...\n {% endif %}\n</div>\n
Sometimes you're not interested in whether a slot is filled, but rather that it isn't. To negate the meaning of
component_vars.is_filled
, simply treat it as boolean and negate it withnot
:
"},{"location":"#accessing-is_filled-of-slot-names-with-special-characters","title":"Accessing{% if not component_vars.is_filled.subtitle %}\n<div class=\"subtitle\">\n {% slot \"subtitle\" / %}\n</div>\n{% endif %}\n
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 ascomponent_vars.is_filled.my_super_slot___
.Same applies when you are accessing
is_filled
from within the Python, e.g.:
"},{"location":"#scoped-slots","title":"Scoped slots","text":"class MyTable(Component):\n def on_render_before(self, context, template) -> None:\n # \u2705 Works\n if self.is_filled[\"my_super_slot___\"]:\n # Do something\n\n # \u274c Does not work\n if self.is_filled[\"my super-slot :)\"]:\n # Do something\n
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
To pass the data to the
slot
tag, simply pass them as keyword attributes (key=value
):
"},{"location":"#accessing-slot-data-in-fill","title":"Accessing slot data in fill","text":"@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
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 todata
:{% component \"my_comp\" %}\n {% fill \"content\" data=\"slot_data\" %}\n {{ slot_data.input }}\n {% endfill %}\n{% endcomponent %}\n
To access slot data on a default slot, you have to explictly define the
{% fill %}
tags.So this works:
{% component \"my_comp\" %}\n {% fill \"default\" data=\"slot_data\" %}\n {{ slot_data.input }}\n {% endfill %}\n{% endcomponent %}\n
While this does not:
{% component \"my_comp\" data=\"data\" %}\n {{ data.input }}\n{% endcomponent %}\n
Note: You cannot set the
data
attribute anddefault
attribute) to the same name. This raises an error:
"},{"location":"#dynamic-slots-and-fills","title":"Dynamic slots and fills","text":"{% component \"my_comp\" %}\n {% fill \"content\" data=\"slot_var\" default=\"slot_var\" %}\n {{ slot_var.input }}\n {% endfill %}\n{% endcomponent %}\n
Until now, we were declaring slot and fill names statically, as a string literal, e.g.
{% slot \"content\" / %}\n
However, sometimes you may want to generate slots based on the given input. One example of this is a table component like that of Vuetify, which creates a header and an item slots for each user-defined column.
In django_components you can achieve the same, simply by using a variable (or a template expression) instead of a string literal:
<table>\n <tr>\n {% for header in headers %}\n <th>\n {% slot \"header-{{ header.key }}\" value=header.title %}\n {{ header.title }}\n {% endslot %}\n </th>\n {% endfor %}\n </tr>\n</table>\n
When using the component, you can either set the fill explicitly:
{% component \"table\" headers=headers items=items %}\n {% fill \"header-name\" data=\"data\" %}\n <b>{{ data.value }}</b>\n {% endfill %}\n{% endcomponent %}\n
Or also use a variable:
{% component \"table\" headers=headers items=items %}\n {# Make only the active column bold #}\n {% fill \"header-{{ active_header_name }}\" data=\"data\" %}\n <b>{{ data.value }}</b>\n {% endfill %}\n{% endcomponent %}\n
NOTE: It's better to use static slot names whenever possible for clarity. The dynamic slot names should be reserved for advanced use only.
Lastly, in rare cases, you can also pass the slot name via the spread operator. This is possible, because the slot name argument is actually a shortcut for a
name
keyword argument.So this:
{% slot \"content\" / %}\n
is the same as:
{% slot name=\"content\" / %}\n
So it's possible to define a
name
key on a dictionary, and then spread that onto the slot tag:
"},{"location":"#pass-through-all-the-slots","title":"Pass through all the slots","text":"{# slot_props = {\"name\": \"content\"} #}\n{% slot ...slot_props / %}\n
You can dynamically pass all slots to a child component. This is similar to passing all slots in Vue:
"},{"location":"#accessing-data-passed-to-the-component","title":"Accessing data passed to the component","text":"class MyTable(Component):\n def get_context_data(self, *args, **kwargs):\n return {\n \"slots\": self.input.slots,\n }\n\n template: \"\"\"\n <div>\n {% component \"child\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name data=\"data\" %}\n {% slot name=slot_name ...data / %}\n {% endfill %}\n {% endfor %}\n {% endcomponent %}\n </div>\n \"\"\"\n
When you call
Component.render
orComponent.render_to_response
, the inputs to these methods can be accessed from within the instance underself.input
.This means that you can use
self.input
inside: -get_context_data
-get_template_name
-get_template
-on_render_before
-on_render_after
self.input
is only defined during the execution ofComponent.render
, and raises aRuntimeError
when called outside of this context.self.input
has the same fields as the input toComponent.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\": ...}\n assert isinstance(self.input.context, Context)\n\n return {\n \"variable\": variable,\n }\n\nrendered = TestComponent.render(\n kwargs={\"variable\": \"test\", \"another\": 1},\n args=(123, \"str\"),\n slots={\"my_slot\": \"MY_SLOT\"},\n)\n
NOTE: The slots in
"},{"location":"#rendering-html-attributes","title":"Rendering HTML attributes","text":"self.input.slots
are normalized to slot functions.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
"},{"location":"#removing-atttributes","title":"Removing atttributes","text":"merge_attrs
tag of django-web-components and \"fallthrough attributes\" feature of Vue.Attributes that are set to
None
orFalse
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:
"},{"location":"#boolean-attributes","title":"Boolean attributes","text":"<div class=\"text-green\"></div>\n
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 orattributes_to_string
works the same way, wherekey=True
is rendered simply askey
, andkey=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:
"},{"location":"#default-attributes","title":"Default attributes","text":"<div disabled></div>\n
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. theclass
key,html_attrs
will render:class=\"{{ attrs.class }}\"
Otherwise,
html_attrs
will render:
"},{"location":"#appending-attributes","title":"Appending attributes","text":"class=\"{{ defaults.class }}\"
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 keyclass
:<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:
"},{"location":"#rules-for-html_attrs","title":"Rules for<div\n data-value=\"my-class pa-4 some-class another-class class-from-var text-red\"\n></div>\n
html_attrs
","text":"- Both
attrs
anddefaults
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
anddefaults
are optional (can be omitted) -
Both
attrs
anddefaults
are dictionaries, and we can define them the same way we define dictionaries for thecomponent
tag. So either asattrs=attrs
orattrs:key=value
. -
All other kwargs are appended and can be repeated.
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:
"},{"location":"#full-example-for-html_attrs","title":"Full example forclass=\"from-attrs added_class from-var\" type=\"submit\" data-id=123
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 attributedefaults:class=\"pa-4 text-red\"
So if
attrs
includes keyclass
, the default above will be ignored.MyComp
also definesclass
key twice. It means that whether theclass
attribute is taken fromattrs
ordefaults
, the twoclass
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
fromParent
component.MyComp
accepts aattrs
dictionary, that is passed tohtml_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 anattrs
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
ofMyComp
will receiveattrs
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 forclass
, whereas other keys will be merged.So in the end
MyComp
will render:
"},{"location":"#rendering-html-attributes-outside-of-templates","title":"Rendering HTML attributes outside of templates","text":"<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
If you need to use serialize HTML attributes outside of Django template and the
html_attrs
tag, you can useattributes_to_string
:
"},{"location":"#template-tag-syntax","title":"Template tag syntax","text":"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
All template tags in django_component, like
"},{"location":"#self-closing-tags","title":"Self-closing tags","text":"{% component %}
or{% slot %}
, and so on, support extra syntax that makes it possible to write components like in Vue or React (JSX).When you have a tag like
{% component %}
or{% slot %}
, but it has no content, you can simply append a forward slash/
at the end, instead of writing out the closing tags like{% endcomponent %}
or{% endslot %}
:So this:
{% component \"button\" %}{% endcomponent %}\n
becomes
"},{"location":"#special-characters","title":"Special characters","text":"{% component \"button\" / %}\n
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:
"},{"location":"#spread-operator","title":"Spread operator","text":"@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
New in version 0.93:
Instead of passing keyword arguments one-by-one:
{% component \"calendar\" title=\"How to abc\" date=\"2015-06-19\" author=\"John Wick\" / %}\n
You can use a spread operator
...dict
to apply key-value pairs from a dictionary:post_data = {\n \"title\": \"How to...\",\n \"date\": \"2015-06-19\",\n \"author\": \"John Wick\",\n}\n
{% component \"calendar\" ...post_data / %}\n
This behaves similar to JSX's spread operator or Vue's
v-bind
.Spread operators are treated as keyword arguments, which means that: 1. Spread operators must come after positional arguments. 2. You cannot use spread operators for positional-only arguments.
Other than that, you can use spread operators multiple times, and even put keyword arguments in-between or after them:
{% component \"calendar\" ...post_data id=post.id ...extra / %}\n
In a case of conflicts, the values added later (right-most) overwrite previous values.
"},{"location":"#use-template-tags-inside-component-inputs","title":"Use template tags inside component inputs","text":"New in version 0.93
When passing data around, sometimes you may need to do light transformations, like negating booleans or filtering lists.
Normally, what you would have to do is to define ALL the variables inside
get_context_data()
. But this can get messy if your components contain a lot of logic.@register(\"calendar\")\nclass Calendar(Component):\n def get_context_data(self, id: str, editable: bool):\n return {\n \"editable\": editable,\n \"readonly\": not editable,\n \"input_id\": f\"input-{id}\",\n \"icon_id\": f\"icon-{id}\",\n ...\n }\n
Instead, template tags in django_components (
{% component %}
,{% slot %}
,{% provide %}
, etc) allow you to treat literal string values as templates:{% component 'blog_post'\n \"As positional arg {# yay #}\"\n title=\"{{ person.first_name }} {{ person.last_name }}\"\n id=\"{% random_int 10 20 %}\"\n readonly=\"{{ editable|not }}\"\n author=\"John Wick {# TODO: parametrize #}\"\n/ %}\n
In the example above: - Component
test
receives a positional argument with value\"As positional arg \"
. The comment is omitted. - Kwargtitle
is passed as a string, e.g.John Doe
- Kwargid
is passed asint
, e.g.15
- Kwargreadonly
is passed asbool
, e.g.False
- Kwargauthor
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:
"},{"location":"#evaluating-python-expressions-in-template","title":"Evaluating Python expressions in template","text":"{% component 'cat_list' items=\"{{ cats|slice:':2' }} See more\" / %}\n
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 anexpr
tag and filter that you can use to evaluate Python expressions from within the template:{% component \"my_form\"\n value=\"{% expr 'input_value if is_enabled else None' %}\"\n/ %}\n
Note: Never use this feature to mix business logic and template logic. Business logic should still be in the view!
"},{"location":"#pass-dictonary-by-its-key-value-pairs","title":"Pass dictonary by its key-value pairs","text":"New in version 0.74:
Sometimes, a component may expect a dictionary as one of its inputs.
Most commonly, this happens when a component accepts a dictionary of HTML attributes (usually called
attrs
) to pass to the underlying template.In such cases, we may want to define some HTML attributes statically, and other dynamically. But for that, we need to define this dictionary on Python side:
@register(\"my_comp\")\nclass MyComp(Component):\n template = \"\"\"\n {% component \"other\" attrs=attrs / %}\n \"\"\"\n\n def get_context_data(self, some_id: str):\n attrs = {\n \"class\": \"pa-4 flex\",\n \"data-some-id\": some_id,\n \"@click.stop\": \"onClickHandler\",\n }\n return {\"attrs\": attrs}\n
But as you can see in the case above, the event handler
@click.stop
and stylingpa-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 keyclass
of inputattrs
becomesattrs: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:
"},{"location":"#multi-line-tags","title":"Multi-line tags","text":"{\"attrs\": {\"my_key:two\": 2}}\n
By default, Django expects a template tag to be defined on a single line.
However, this can become unwieldy if you have a component with a lot of inputs:
{% component \"card\" title=\"Joanne Arc\" subtitle=\"Head of Kitty Relations\" date_last_active=\"2024-09-03\" ... %}\n
Instead, when you install django_components, it automatically configures Django to suport multi-line tags.
So we can rewrite the above as:
{% component \"card\"\n title=\"Joanne Arc\"\n subtitle=\"Head of Kitty Relations\"\n date_last_active=\"2024-09-03\"\n ...\n%}\n
Much better!
To disable this behavior, set
"},{"location":"#prop-drilling-and-dependency-injection-provide-inject","title":"Prop drilling and dependency injection (provide / inject)","text":"COMPONENTS.multiline_tag
toFalse
New in version 0.80:
Django components supports dependency injection with the combination of:
{% provide %}
taginject()
method of theComponent
class
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 name must resolve to a valid identifier (AKA a valid Python variable name).Once you've set the name, you define the data you want to \"provide\" by passing it as keyword arguments. This is similar to how you pass data to the
{% with %}
tag.NOTE: Kwargs passed to
{% provide %}
are NOT added to the context. In the example below, the{{ key }}
won't render anything:{% provide \"my_data\" key=\"hi\" another=123 %}\n {{ key }}\n{% endprovide %}\n
Similarly to slots and fills, also provide's name argument can be set dynamically via a variable, a template expression, or a spread operator:
"},{"location":"#using-inject-method","title":"Using{% provide name=name ... %}\n ...\n{% provide %}\n</table>\n
inject()
method","text":"To \"inject\" (access) the data defined on the
provide
tag, you can use theinject()
method inside ofget_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
andanother
.class ChildComponent(Component):\n def get_context_data(self):\n my_data = self.inject(\"my_data\")\n print(my_data.key) # hi\n print(my_data.another) # 123\n return {}\n
First argument to
inject
is the key (or name) of the provided data. This must match the string that you used in theprovide
tag. If no provider with given key is found,inject
raises aKeyError
.To avoid the error, you can pass a second argument to
inject
to which will act as a default value, similar todict.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 ofNamedTuple
, so the instance is immutable. This ensures that the data returned frominject
will always have all the keys that were passed to theprovide
tag.NOTE:
"},{"location":"#full-example","title":"Full example","text":"inject()
works strictly only inget_context_data
. If you try to call it from elsewhere, it will raise an error.@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:
"},{"location":"#component-hooks","title":"Component hooks","text":"<div>hi</div>\n<div>123</div>\n
New in version 0.96
Component hooks are functions that allow you to intercept the rendering process at specific positions.
"},{"location":"#available-hooks","title":"Available hooks","text":"on_render_before
def on_render_before(\n self: Component,\n context: Context,\n template: Template\n) -> None:\n
Hook that runs just before the component's template is rendered.\n\nYou can use this hook to access or modify the context or the template:\n\n```py\ndef on_render_before(self, context, template) -> None:\n # Insert value into the Context\n context[\"from_on_before\"] = \":)\"\n\n # Append text into the Template\n template.nodelist.append(TextNode(\"FROM_ON_BEFORE\"))\n```\n
on_render_after
def on_render_after(\n self: Component,\n context: Context,\n template: Template,\n content: str\n) -> None | str | SafeString:\n
"},{"location":"#component-hooks-example","title":"Component hooks example","text":"Hook that runs just after the component's template was rendered.\nIt receives the rendered output as the last argument.\n\nYou can use this hook to access the context or the template, but modifying\nthem won't have any effect.\n\nTo override the content that gets rendered, you can return a string or SafeString from this hook:\n\n```py\ndef on_render_after(self, context, template, content):\n # Prepend text to the rendered content\n return \"Chocolate cookie recipe: \" + content\n```\n
You can use hooks together with provide / inject to create components that accept a list of items via a slot.
In the example below, each
tab_item
component will be rendered on a separate tab page, but they are all defined in the default slot of thetabs
component.See here for how it was done
"},{"location":"#component-context-and-scope","title":"Component context and scope","text":"{% component \"tabs\" %}\n {% component \"tab_item\" header=\"Tab 1\" %}\n <p>\n hello from tab 1\n </p>\n {% component \"button\" %}\n Click me!\n {% endcomponent %}\n {% endcomponent %}\n\n {% component \"tab_item\" header=\"Tab 2\" %}\n Hello this is tab 2\n {% endcomponent %}\n{% endcomponent %}\n
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, addonly
to the{% component %}
tag:{% component \"calendar\" date=\"2015-06-19\" only / %}\n
NOTE:
{% csrf_token %}
tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with theonly
modifier.If you find yourself using the
only
modifier often, you can set the context_behavior option to\"isolated\"
, which automatically applies theonly
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
"},{"location":"#example-of-accessing-outer-context","title":"Example of Accessing Outer Context","text":"get_context_data
by accessing the propertyself.outer_context
.<div>\n {% component \"calender\" / %}\n</div>\n
Assuming that the rendering context has variables such as
date
, you can useself.outer_context
to access them from withinget_context_data
. Here's how you might implement it:class Calender(Component):\n\n ...\n\n def get_context_data(self):\n outer_field = self.outer_context[\"date\"]\n return {\n \"date\": outer_fields,\n }\n
However, as a best practice, it\u2019s recommended not to rely on accessing the outer context directly through
"},{"location":"#pre-defined-template-variables","title":"Pre-defined template variables","text":"self.outer_context
. Instead, explicitly pass the variables to the component. For instance, continue passing the variables in the component tag as shown in the previous examples.Here is a list of all variables that are automatically available from within the component's template and
on_render_before
/on_render_after
hooks.-
component_vars.is_filled
New in version 0.70
Dictonary describing which slots are filled (
True
) or are not (False
).Example:
{% if component_vars.is_filled.my_slot %}\n {% slot \"my_slot\" / %}\n{% endif %}\n
This is equivalent to checking if a given key is among the slot fills:
class MyTable(Component):\n def get_context_data(self, *args, **kwargs):\n return {\n \"my_slot_filled\": \"my_slot\" in self.input.slots\n }\n
New in version 0.89
By default, components are rendered using the pair of
{% component %}
/{% endcomponent %}
template tags:{% component \"button\" href=\"...\" disabled %}\nClick me!\n{% endcomponent %}\n\n{# or #}\n\n{% component \"button\" href=\"...\" disabled / %}\n
You can change this behaviour in the settings under the
COMPONENTS.tag_formatter
.For example, if you set the tag formatter to
django_components.component_shorthand_formatter
, the components will use their name as the template tags:
"},{"location":"#available-tagformatters","title":"Available TagFormatters","text":"{% button href=\"...\" disabled %}\n Click me!\n{% endbutton %}\n\n{# or #}\n\n{% button href=\"...\" disabled / %}\n
django_components provides following predefined TagFormatters:
-
ComponentFormatter
(django_components.component_formatter
)Default
Uses the
component
andendcomponent
tags, and the component name is gives as the first positional argument.Example as block:
{% component \"button\" href=\"...\" %}\n {% fill \"content\" %}\n ...\n {% endfill %}\n{% endcomponent %}\n
Example as inlined tag:
{% component \"button\" href=\"...\" / %}\n
-
ShorthandComponentFormatter
(django_components.component_shorthand_formatter
)Uses the component name as start tag, and
end<component_name>
as an end tag.Example as block:
{% button href=\"...\" %}\n Click me!\n{% endbutton %}\n
Example as inlined tag:
{% button href=\"...\" / %}\n
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 tagcomponent
. 3. The tag handler passes the tag contents for pre-processing toTagFormatter.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:
5. The tag handler resumes, using the tokens returned fromTagResult(\n component_name=\"button\",\n tokens=['href=\"...\"', 'disabled']\n)\n
TagFormatter
.So, continuing the example, at this point the tag handler practically behaves as if you rendered:
6. Tag handler looks up the component{% component href=\"...\" disabled %}\n
button
, and passes the args, kwargs, and slots to it.
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
"},{"location":"#defining-htmljscss-files","title":"Defining HTML/JS/CSS files","text":"TagFormatter
is ready, don't forget to update the settings!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)
As seen in the getting started example, to associate HTML/JS/CSS files with a component, you set them as
template_name
,Media.js
andMedia.css
respectively:# In a file [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"template.html\"\n\n class Media:\n css = \"style.css\"\n js = \"script.js\"\n
In the example above, the files are defined relative to the directory where
component.py
is.Alternatively, you can specify the file paths relative to the directories set in
COMPONENTS.dirs
orCOMPONENTS.app_dirs
.Assuming that
COMPONENTS.dirs
contains path[project root]/components
, we can rewrite the example as:# In a file [project root]/components/calendar/calendar.py\nfrom django_components import Component, register\n\n@register(\"calendar\")\nclass Calendar(Component):\n template_name = \"calendar/template.html\"\n\n class Media:\n css = \"calendar/style.css\"\n js = \"calendar/script.js\"\n
NOTE: In case of conflict, the preference goes to resolving the files relative to the component's directory.
"},{"location":"#defining-multiple-paths","title":"Defining multiple paths","text":"Each component can have only a single template. However, you can define as many JS or CSS files as you want using a list.
"},{"location":"#configuring-css-media-types","title":"Configuring CSS Media Types","text":"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
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
"},{"location":"#supported-types-for-file-paths","title":"Supported types for file paths","text":"all
media type is implied.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__
)
"},{"location":"#path-as-objects","title":"Path as objects","text":"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
In the example above, you could see that when we used
mark_safe
to mark a string as aSafeString
, we had to define the full<script>
/<link>
tag.This is an extension of Django's Paths as objects feature, where \"safe\" strings are taken as is, and accessed only at render time.
Because of that, the paths defined as \"safe\" strings are NEVER resolved, neither relative to component's directory, nor relative to
COMPONENTS.dirs
.\"Safe\" strings can be used to lazily resolve a path, or to customize the
<script>
or<link>
tag for individual paths:
"},{"location":"#customize-how-paths-are-rendered-into-html-tags-with-media_class","title":"Customize how paths are rendered into HTML tags withclass 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
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'sMedia
class to component'smedia_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
andMedia.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
"},{"location":"#rendering-jscss-dependencies","title":"Rendering JS/CSS dependencies","text":"Media
class (or it's subclass) is available underComponent.media
after the class creation (__new__
).If: 1. Your components use JS and CSS, whether inlined via
Component.js/css
or viaComponent.Media.js/css
, 2. And you use theComponentDependencyMiddleware
middlewareThen, by default, the components' JS and CSS will be automatically inserted into the HTML: - CSS styles will be inserted at the end of the
<head>
- JS scripts will be inserted at the end of the<body>
If you want to place the dependencies elsewhere, you can override that with following Django template tags:
{% component_js_dependencies %}
- Renders only JS{% component_css_dependencies %}
- Renders only CSS
So if you have a component with JS and CSS:
from django_components import Component, types\n\nclass MyButton(Component):\n template: types.django_html = \"\"\"\n <button class=\"my-button\">\n Click me!\n </button>\n \"\"\"\n js: types.js = \"\"\"\n for (const btnEl of document.querySelectorAll(\".my-button\")) {\n btnEl.addEventListener(\"click\", () => {\n console.log(\"BUTTON CLICKED!\");\n });\n }\n \"\"\"\n css: types.css \"\"\"\n .my-button {\n background: green;\n }\n \"\"\"\n\n class Media:\n js = [\"/extra/script.js\"]\n css = [\"/extra/style.css\"]\n
Then the inlined JS and the scripts in
Media.js
will be rendered at the default place, or in{% component_js_dependencies %}
.And the inlined CSS and the styles in
Media.css
will be rendered at the default place, or in{% component_css_dependencies %}
.And if you don't specify
{% component_dependencies %}
tags, it is the equivalent of:
"},{"location":"#setting-up-componentdependencymiddleware","title":"Setting Up<!doctype html>\n<html>\n <head>\n <title>MyPage</title>\n ...\n {% component_css_dependencies %}\n </head>\n <body>\n <main>\n ...\n </main>\n {% component_js_dependencies %}\n </body>\n</html>\n
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:
"},{"location":"#render_dependencies-and-deep-dive-into-rendering-js-css-without-the-middleware","title":"MIDDLEWARE = [\n # ... other middleware classes ...\n 'django_components.middleware.ComponentDependencyMiddleware'\n # ... other middleware classes ...\n]\n
render_dependencies
and deep-dive into rendering JS / CSS without the middleware","text":"For most scenarios, using the
ComponentDependencyMiddleware
middleware will be just fine.However, this section is for you if you want to: - Render HTML that will NOT be sent as a server response - Insert pre-rendered HTML into another component - Render HTML fragments (partials)
Every time there is an HTML string that has parts which were rendered using components, and any of those components has JS / CSS, then this HTML string MUST be processed with
render_dependencies
.It is actually
"},{"location":"#render-js-css-without-the-middleware","title":"Render JS / CSS without the middleware","text":"render_dependencies
that finds all used components in the HTML string, and inserts the component's JS and CSS into{% component_dependencies %}
tags, or at the default locations.The
ComponentDependencyMiddleware
middleware just callsrender_dependencies
, passing in the HTML content. So if you rendered a template that contained{% components %}
tags, instead of the middleware, you MUST pass the result throughrender_dependencies
:from django.template.base import Template\nfrom django.template.context import Context\nfrom django_component import render_dependencies\n\ntemplate = Template(\"\"\"\n {% load component_tags %}\n <!doctype html>\n <html>\n <head>\n <title>MyPage</title>\n </head>\n <body>\n <main>\n {% component \"my_button\" %}\n Click me!\n {% endcomponent %}\n </main>\n </body>\n </html>\n\"\"\")\n\nrendered = template.render(Context({}))\nrendered = render_dependencies(rendered)\n
Same applies if you render a template using Django's
django.shortcuts.render
:from django.shortcuts import render\n\ndef my_view(request):\n rendered = render(request, \"pages/home.html\")\n rendered = render_dependencies(rendered)\n return rendered\n
Alternatively, when you render HTML with
Component.render()
orComponent.render_to_response()
, these automatically callrender_dependencies()
for you, so you don't have to:
"},{"location":"#inserting-pre-rendered-html-into-another-component","title":"Inserting pre-rendered HTML into another component","text":"from django_components import Component\n\nclass MyButton(Component):\n ...\n\n# No need to call `render_dependencies()`\nrendered = MyButton.render()\n
In previous section we've shown that
render_dependencies()
does NOT need to be called when you render a component viaComponent.render()
.API of django-components makes it possible to compose components in a \"React-like\" way, where we pre-render a piece of HTML and then insert it into a larger structure.
To do this, you must add
render_dependencies=False
to the nested components:card_actions = CardActions.render(\n kwargs={\"editable\": editable},\n render_dependencies=False,\n)\n\ncard = Card.render(\n slots={\"actions\": card_actions},\n render_dependencies=False,\n)\n\npage = MyPage.render(\n slots={\"card\": card},\n)\n
Why is
render_dependencies=False
required?As mentioned earlier, each time we call
Component.render()
, we also callrender_dependencies()
.However, there is a problem here - When we call
render_dependencies()
insideCardActions.render()
, we extract the info on components' JS and CSS from the HTML. But the template ofCardActions
contains no{% component_depedencies %}
tags, and nor<head>
nor<body>
HTML tags. So the component's JS and CSS will NOT be inserted, and will be lost.To work around this, you must set
"},{"location":"#available-settings","title":"Available settings","text":"render_dependencies=False
when rendering pieces of HTML withComponent.render()
and inserting them into larger structures.All library settings are handled from a global
COMPONENTS
variable that is read fromsettings.py
. By default you don't need it set, there are resonable defaults.Here's overview of all available settings and their defaults:
"},{"location":"#libraries-load-component-modules","title":"COMPONENTS = {\n \"autodiscover\": True,\n \"context_behavior\": \"django\", # \"django\" | \"isolated\"\n \"dirs\": [BASE_DIR / \"components\"], # Root-level \"components\" dirs, e.g. `/path/to/proj/components/`\n \"app_dirs\": [\"components\"], # App-level \"components\" dirs, e.g. `[app]/components/`\n \"dynamic_component_name\": \"dynamic\",\n \"libraries\": [], # [\"mysite.components.forms\", ...]\n \"multiline_tags\": True,\n \"reload_on_template_change\": False,\n \"static_files_allowed\": [\n \".css\",\n \".js\",\n # Images\n \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n \".jpeg\", \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n # Fonts\n \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n ],\n \"static_files_forbidden\": [\n \".html\", \".django\", \".dj\", \".tpl\",\n # Python files\n \".py\", \".pyc\",\n ],\n \"tag_formatter\": \"django_components.component_formatter\",\n \"template_cache_size\": 128,\n}\n
libraries
- Load component modules","text":"Configure the locations where components are loaded. To do this, add a
COMPONENTS
variable to yousettings.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:
"},{"location":"#autodiscover-toggle-autodiscovery","title":"from django_components import import_libraries\n\nimport_libraries()\n
autodiscover
- Toggle autodiscovery","text":"If you specify all the component locations with the setting above and have a lot of apps, you can (very) slightly speed things up by disabling autodiscovery.
"},{"location":"#dirs","title":"COMPONENTS = {\n \"autodiscover\": False,\n}\n
dirs
","text":"Specify the directories that contain your components.
Directories must be full paths, same as with STATICFILES_DIRS.
These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as a separate file.
"},{"location":"#app_dirs","title":"COMPONENTS = {\n \"dirs\": [BASE_DIR / \"components\"],\n}\n
app_dirs
","text":"Specify the app-level directories that contain your components.
Directories must be relative to app, e.g.:
COMPONENTS = {\n \"app_dirs\": [\"my_comps\"], # To search for [app]/my_comps\n}\n
These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as a separate file.
Each app will be searched for these directories.
Set to empty list to disable app-level components:
"},{"location":"#dynamic_component_name","title":"COMPONENTS = {\n \"app_dirs\": [],\n}\n
dynamic_component_name
","text":"By default, the dynamic component is registered under the name
\"dynamic\"
. In case of a conflict, use this setting to change the name used for the dynamic components.
"},{"location":"#multiline_tags-enabledisable-multiline-support","title":"COMPONENTS = {\n \"dynamic_component_name\": \"new_dynamic\",\n}\n
multiline_tags
- Enable/Disable multiline support","text":"If
True
, template tags can span multiple lines. Default:True
"},{"location":"#static_files_allowed","title":"COMPONENTS = {\n \"multiline_tags\": True,\n}\n
static_files_allowed
","text":"A list of regex patterns (as strings) that define which files within
COMPONENTS.dirs
andCOMPONENTS.app_dirs
are treated as static files.If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running
collectstatic
, and can be accessed under the static file endpoint.You can also pass in compiled regexes (
re.Pattern
) for more advanced patterns.By default, JS, CSS, and common image and font file formats are considered static files:
"},{"location":"#static_files_forbidden","title":"COMPONENTS = {\n \"static_files_allowed\": [\n \"css\",\n \"js\",\n # Images\n \".apng\", \".png\",\n \".avif\",\n \".gif\",\n \".jpg\", \".jpeg\", \".jfif\", \".pjpeg\", \".pjp\", # JPEG\n \".svg\",\n \".webp\", \".bmp\",\n \".ico\", \".cur\", # ICO\n \".tif\", \".tiff\",\n # Fonts\n \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n ],\n}\n
static_files_forbidden
","text":"A list of suffixes that define which files within
COMPONENTS.dirs
andCOMPONENTS.app_dirs
will NEVER be treated as static files.If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in
COMPONENTS.static_files_allowed
.Use this setting together with
COMPONENTS.static_files_allowed
for a fine control over what files will be exposed.You can also pass in compiled regexes (
re.Pattern
) for more advanced patterns.By default, any HTML and Python are considered NOT static files:
"},{"location":"#template_cache_size-tune-the-template-cache","title":"COMPONENTS = {\n \"static_files_forbidden\": [\n \".html\", \".django\", \".dj\", \".tpl\", \".py\", \".pyc\",\n ],\n}\n
template_cache_size
- Tune the template cache","text":"Each time a template is rendered it is cached to a global in-memory cache (using Python's
lru_cache
decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are using the
template
method of a component to render lots of dynamic templates, you can increase this number. To remove the cache limit altogether and cache everything, set template_cache_size toNone
.COMPONENTS = {\n \"template_cache_size\": 256,\n}\n
If you want add templates to the cache yourself, you can use
cached_template()
:
"},{"location":"#context_behavior-make-components-isolated-or-not","title":"from django_components import cached_template\n\ncached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n pass\n\ncached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n)\n
context_behavior
- Make components isolated (or not)","text":"NOTE:
context_behavior
andslot_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.
"},{"location":"#example-django","title":"Example \"django\"","text":"COMPONENTS = {\n \"context_behavior\": \"isolated\",\n}\n
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 }}
equals456
.And variable
"},{"location":"#example-isolated","title":"Example \"isolated\"","text":"\"cheese\"
equalsfeta
, because the fill CAN access all the data defined in the outer layers, like the{% with %}
tag.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 insideRootComponent.get_context_data()
. But since\"cheese\"
is not defined there, it's empty.Notice that the variables defined with the
"},{"location":"#reload_on_template_change-reload-dev-server-on-component-file-changes","title":"{% with %}
tag are ignored inside the{% fill %}
tag with the\"isolated\"
mode.reload_on_template_change
- Reload dev server on component file changes","text":"If
True
, configures Django to reload on component files. See Reload dev server on component file changes.NOTE: This setting should be enabled only for the dev environment!
"},{"location":"#tag_formatter-change-how-components-are-used-in-templates","title":"tag_formatter
- Change how components are used in templates","text":"Sets the
TagFormatter
instance. See the section Customizing component tags with TagFormatter.Can be set either as direct reference, or as an import string;
COMPONENTS = {\n \"tag_formatter\": \"django_components.component_formatter\"\n}\n
Or
"},{"location":"#running-with-development-server","title":"Running with development server","text":""},{"location":"#reload-dev-server-on-component-file-changes","title":"Reload dev server on component file changes","text":"from django_components import component_formatter\n\nCOMPONENTS = {\n \"tag_formatter\": component_formatter\n}\n
This is relevant if you are using the project structure as shown in our examples, where HTML, JS, CSS and Python are separate and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change comoponent files.
From relevant StackOverflow thread:
TL;DR is that the server won't reload if it thinks the changed file is in a templates directory, or in a nested sub directory of a templates directory. This is by design.
To make the dev server reload on all component files, set
reload_on_template_change
toTrue
. This configures Django to watch for component files too.NOTE: This setting should be enabled only for the dev environment!
"},{"location":"#logging-and-debugging","title":"Logging and debugging","text":"Django components supports logging with Django. This can help with troubleshooting.
To configure logging for Django components, set the
django_components
logger inLOGGING
insettings.py
(below).Also see the
settings.py
file in sampleproject for a real-life example.
"},{"location":"#management-command","title":"Management Command","text":"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
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 theBASE_DIR
setting from your Django settings. -
--js
: The name of the JavaScript file. This is an optional argument. The default value isscript.js
. -
--css
: The name of the CSS file. This is an optional argument. The default value isstyle.css
. -
--template
: The name of the template file. This is an optional argument. The default value istemplate.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 isFalse
.
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
"},{"location":"#management-command-examples","title":"Management Command Examples","text":"<name>
,<path>
,<js_filename>
,<css_filename>
, and<template_filename>
with your desired values.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
"},{"location":"#creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"my_component
in thecomponents
directory of your Django project. The JavaScript, CSS, and template files will be namedscript.js
,style.css
, andtemplate.html
, respectively.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
"},{"location":"#overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"new_component
in themy_components
directory. The JavaScript, CSS, and template files will be namedmy_script.js
,my_style.css
, andmy_template.html
, respectively.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
"},{"location":"#simulating-component-creation","title":"Simulating Component Creation","text":"my_component
if it exists.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
"},{"location":"#writing-and-sharing-component-libraries","title":"Writing and sharing component libraries","text":"my_component
without creating any files.You can publish and share your components for others to use. Here are the steps to do so:
"},{"location":"#writing-component-libraries","title":"Writing component libraries","text":"-
Create a Django project with the following structure:
project/\n |-- myapp/\n |-- __init__.py\n |-- apps.py\n |-- templates/\n |-- table/\n |-- table.py\n |-- table.js\n |-- table.css\n |-- table.html\n |-- menu.py <--- single-file component\n |-- templatetags/\n |-- __init__.py\n |-- mytags.py\n
-
Create custom
Library
andComponentRegistry
instances inmytags.py
This will be the entrypoint for using the components inside Django templates.
Remember that Django requires the
Library
instance to be accessible under theregister
variable (See Django docs):from django.template import Library\nfrom django_components import ComponentRegistry, RegistrySettings\n\nregister = library = django.template.Library()\ncomp_registry = ComponentRegistry(\n library=library,\n settings=RegistrySettings(\n context_behavior=\"isolated\",\n tag_formatter=\"django_components.component_formatter\",\n ),\n)\n
As you can see above, this is also the place where we configure how our components should behave, using the
settings
argument. If omitted, default settings are used.For library authors, we recommend setting
context_behavior
to\"isolated\"
, so that the state cannot leak into the components, and so the components' behavior is configured solely through the inputs. This means that the components will be more predictable and easier to debug.Next, you can decide how will others use your components by settingt the
tag_formatter
options.If omitted or set to
\"django_components.component_formatter\"
, your components will be used like this:{% component \"table\" items=items headers=headers %}\n{% endcomponent %}\n
Or you can use
\"django_components.component_shorthand_formatter\"
to use components like so:{% table items=items headers=headers %}\n{% endtable %}\n
Or you can define a custom TagFormatter.
Either way, these settings will be scoped only to your components. So, in the user code, there may be components side-by-side that use different formatters:
{% load mytags %}\n\n{# Component from your library \"mytags\", using the \"shorthand\" formatter #}\n{% table items=items headers=header %}\n{% endtable %}\n\n{# User-created components using the default settings #}\n{% component \"my_comp\" title=\"Abc...\" %}\n{% endcomponent %}\n
-
Write your components and register them with your instance of
ComponentRegistry
There's one difference when you are writing components that are to be shared, and that's that the components must be explicitly registered with your instance of
ComponentRegistry
from the previous step.For better user experience, you can also define the types for the args, kwargs, slots and data.
It's also a good idea to have a common prefix for your components, so they can be easily distinguished from users' components. In the example below, we use the prefix
my_
/My
.from typing import Dict, NotRequired, Optional, Tuple, TypedDict\n\nfrom django_components import Component, SlotFunc, register, types\n\nfrom myapp.templatetags.mytags import comp_registry\n\n# Define the types\nclass EmptyDict(TypedDict):\n pass\n\ntype MyMenuArgs = Tuple[int, str]\n\nclass MyMenuSlots(TypedDict):\n default: NotRequired[Optional[SlotFunc[EmptyDict]]]\n\nclass MyMenuProps(TypedDict):\n vertical: NotRequired[bool]\n klass: NotRequired[str]\n style: NotRequired[str]\n\n# Define the component\n# NOTE: Don't forget to set the `registry`!\n@register(\"my_menu\", registry=comp_registry)\nclass MyMenu(Component[MyMenuArgs, MyMenuProps, MyMenuSlots, Any, Any, Any]):\n def get_context_data(\n self,\n *args,\n attrs: Optional[Dict] = None,\n ):\n return {\n \"attrs\": attrs,\n }\n\n template: types.django_html = \"\"\"\n {# Load django_components template tags #}\n {% load component_tags %}\n\n <div {% html_attrs attrs class=\"my-menu\" %}>\n <div class=\"my-menu__content\">\n {% slot \"default\" default / %}\n </div>\n </div>\n \"\"\"\n
-
Import the components in
apps.py
Normally, users rely on autodiscovery and
COMPONENTS.dirs
to load the component files.Since you, as the library author, are not in control of the file system, it is recommended to load the components manually.
We recommend doing this in the
AppConfig.ready()
hook of yourapps.py
:from django.apps import AppConfig\n\nclass MyAppConfig(AppConfig):\n default_auto_field = \"django.db.models.BigAutoField\"\n name = \"myapp\"\n\n # This is the code that gets run when user adds myapp\n # to Django's INSTALLED_APPS\n def ready(self) -> None:\n # Import the components that you want to make available\n # inside the templates.\n from myapp.templates import (\n menu,\n table,\n )\n
Note that you can also include any other startup logic within
AppConfig.ready()
.
And that's it! The next step is to publish it.
"},{"location":"#publishing-component-libraries","title":"Publishing component libraries","text":"Once you are ready to share your library, you need to build a distribution and then publish it to PyPI.
django_components uses the
build
utility to build a distribution:python -m build --sdist --wheel --outdir dist/ .\n
And to publish to PyPI, you can use
twine
(See Python user guide)twine upload --repository pypi dist/* -u __token__ -p <PyPI_TOKEN>\n
Notes on publishing: - The user of the package NEEDS to have installed and configured
"},{"location":"#installing-and-using-component-libraries","title":"Installing and using component libraries","text":"django_components
. - If you use components where the HTML / CSS / JS files are separate, you may need to defineMANIFEST.in
to include those files with the distribution (see user guide).After the package has been published, all that remains is to install it in other django projects:
-
Install the package:
pip install myapp\n
-
Add the package to
INSTALLED_APPS
INSTALLED_APPS = [\n ...\n \"myapp\",\n]\n
-
Optionally add the template tags to the
builtins
, so you don't have to call{% load mytags %}
in every template:TEMPLATES = [\n {\n ...,\n 'OPTIONS': {\n 'context_processors': [\n ...\n ],\n 'builtins': [\n 'myapp.templatetags.mytags',\n ]\n },\n },\n]\n
-
And, at last, you can use the components in your own project!
{% my_menu title=\"Abc...\" %}\n Hello World!\n{% endmy_menu %}\n
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.
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:
"},{"location":"#running-playwright-tests","title":"Running Playwright tests","text":"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
We use Playwright for end-to-end tests. You will therefore need to install Playwright to be able to run these tests.
Luckily, Playwright makes it very easy:
pip install -r requirements-dev.txt\nplaywright install chromium --with-deps\n
After Playwright is ready, simply run the tests with
tox
:
"},{"location":"#developing-against-live-django-app","title":"Developing against live Django app","text":"tox\n
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 thesetup.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
"},{"location":"#building-js-code","title":"Building JS code","text":"urls.py
, like in the case of http://127.0.0.1:8000/greetingdjango_components uses a bit of JS code to: - Manage the loading of JS and CSS files used by the components - Allow to pass data from Python to JS
When you make changes to this JS code, you also need to compile it:
- Make sure you are inside
src/django_components_js
:
cd src/django_components_js\n
- Install the JS dependencies
npm install\n
- Compile the JS/TS code:
python build.py\n
The script will combine all JS/TS code into a single
"},{"location":"#packaging-and-publishing","title":"Packaging and publishing","text":".js
file, minify it, and copy it todjango_components/static/django_components/django_components.min.js
.To package the library into a distribution that can be published to PyPI, run:
# Install pypa/build\npython -m pip install build --user\n# Build a binary wheel and a source tarball\npython -m build --sdist --wheel --outdir dist/ .\n
To publish the package to PyPI, use
twine
(See Python user guide):twine upload --repository pypi dist/* -u __token__ -p <PyPI_TOKEN>\n
See the full workflow here.
"},{"location":"#development-guides","title":"Development guides","text":"Deep dive into how django_components' features are implemented.
- Slot rendering
- Slots and blocks
- JS and CSS dependency management
- Prevent rendering Slot tags during fill discovery stage to fix a case when a component inside a slot fill tried to access provided data too early.
- Ensure consistent order of scripts in
Component.Media.js
- Allow components to accept default fill even if no default slot was encountered during rendering
- Prevent rendering Component tags during fill discovery stage to fix a case when a component inside the default slot tried to access provided data too early.
-
Installation changes:
- If your components include JS or CSS, you now must use the middleware and add django-components' URLs to your
urlpatterns
(See \"Adding support for JS and CSS\")
- If your components include JS or CSS, you now must use the middleware and add django-components' URLs to your
-
Component typing signature changed from
Component[Args, Kwargs, Data, Slots]\n
to
Component[Args, Kwargs, Slots, Data, JsData, CssData]\n
-
If you rendered a component A with
Component.render()
and then inserted that into another component B, now you must passrender_dependencies=False
to component A:prerendered_a = CompA.render(\n args=[...],\n kwargs={...},\n render_dependencies=False,\n)\n\nhtml = CompB.render(\n kwargs={\n content=prerendered_a,\n },\n)\n
- Intellisense and mypy validation for settings:
Instead of defining the
COMPONENTS
settings as a plain dict, you can useComponentsSettings
:# settings.py\nfrom django_components import ComponentsSettings\n\nCOMPONENTS = ComponentsSettings(\n autodiscover=True,\n ...\n)\n
- Use
get_component_dirs()
andget_component_files()
to get the same list of dirs / files that would be imported byautodiscover()
, but without actually importing them.
-
For advanced use cases, use can omit the middleware and instead manage component JS and CSS dependencies yourself with
render_dependencies
-
The
ComponentRegistry
settingsRegistrySettings
were lowercased to align with the global settings: RegistrySettings.CONTEXT_BEHAVIOR
->RegistrySettings.context_behavior
RegistrySettings.TAG_FORMATTER
->RegistrySettings.tag_formatter
The old uppercase settings
CONTEXT_BEHAVIOR
andTAG_FORMATTER
are deprecated and will be removed in v1.-
The setting
reload_on_template_change
was renamed toreload_on_file_change
. And now it properly triggers server reload when any file in the component dirs change. The old namereload_on_template_change
is deprecated and will be removed in v1. -
The setting
forbidden_static_files
was renamed tostatic_files_forbidden
to align withstatic_files_allowed
The old nameforbidden_static_files
is deprecated and will be removed in v1.
-
{% component_dependencies %}
tag was removed. Instead, use{% component_js_dependencies %}
and{% component_css_dependencies %}
-
The combined tag was removed to encourage the best practice of putting JS scripts at the end of
<body>
, and CSS styles inside<head>
.On the other hand, co-locating JS script and CSS styles can lead to a flash of unstyled content, as either JS scripts will block the rendering, or CSS will load too late.
-
-
The undocumented keyword arg
preload
of{% component_js_dependencies %}
and{% component_css_dependencies %}
tags was removed. This will be replaced with HTML fragment support.
- Allow using forward slash (
/
) when defining custom TagFormatter, e.g.{% MyComp %}..{% /MyComp %}
.
{% component_dependencies %}
tags are now OPTIONAL - If your components use JS and CSS, but you don't use{% component_dependencies %}
tags, the JS and CSS will now be, by default, inserted at the end of<body>
and at the end of<head>
respectively.
- Fills can now be defined within loops (
{% for %}
) or other tags (like{% with %}
), or even other templates using{% include %}
.
Following is now possible
{% component \"table\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name %}\n {% endfill %}\n {% endfor %}\n{% endcomponent %}\n
- If you need to access the data or the default content of a default fill, you can set the
name
kwarg to\"default\"
.
Previously, a default fill would be defined simply by omitting the
{% fill %}
tags:{% component \"child\" %}\n Hello world\n{% endcomponent %}\n
But in that case you could not access the slot data or the default content, like it's possible for named fills:
{% component \"child\" %}\n {% fill name=\"header\" data=\"data\" %}\n Hello {{ data.user.name }}\n {% endfill %}\n{% endcomponent %}\n
Now, you can specify default tag by using
name=\"default\"
:{% component \"child\" %}\n {% fill name=\"default\" data=\"data\" %}\n Hello {{ data.user.name }}\n {% endfill %}\n{% endcomponent %}\n
- When inside
get_context_data()
or other component methods, the default fill can now be accessed asComponent.input.slots[\"default\"]
, e.g.:
class MyTable(Component):\n def get_context_data(self, *args, **kwargs):\n default_slot = self.input.slots[\"default\"]\n ...\n
- You can now dynamically pass all slots to a child component. This is similar to passing all slots in Vue:
"},{"location":"CHANGELOG/#fix_5","title":"Fix","text":"class MyTable(Component):\n def get_context_data(self, *args, **kwargs):\n return {\n \"slots\": self.input.slots,\n }\n\n template: \"\"\"\n <div>\n {% component \"child\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name data=\"data\" %}\n {% slot name=slot_name ...data / %}\n {% endfill %}\n {% endfor %}\n {% endcomponent %}\n </div>\n \"\"\"\n
-
Slots defined with
{% fill %}
tags are now properly accessible viaself.input.slots
inget_context_data()
-
Do not raise error if multiple slots with same name are flagged as default
-
Slots can now be defined within loops (
{% for %}
) or other tags (like{% with %}
), or even other templates using{% include %}
.
Previously, following would cause the kwarg
name
to be an empty string:
"},{"location":"CHANGELOG/#refactor_2","title":"Refactor","text":"{% for slot_name in slots %}\n {% slot name=slot_name %}\n{% endfor %}\n
- When you define multiple slots with the same name inside a template, you now have to set the
default
andrequired
flags individually.
<div class=\"calendar-component\">\n <div class=\"header\">\n {% slot \"image\" default required %}Image here{% endslot %}\n </div>\n <div class=\"body\">\n {% slot \"image\" default required %}Image here{% endslot %}\n </div>\n</div>\n
This means you can also have multiple slots with the same name but different conditions.
E.g. in this example, we have a component that renders a user avatar - a small circular image with a profile picture of name initials.
If the component is given
image_src
orname_initials
variables, theimage
slot is optional. But if neither of those are provided, you MUST fill theimage
slot.<div class=\"avatar\">\n {% if image_src %}\n {% slot \"image\" default %}\n <img src=\"{{ image_src }}\" />\n {% endslot %}\n {% elif name_initials %}\n {% slot \"image\" default required %}\n <div style=\"\n border-radius: 25px;\n width: 50px;\n height: 50px;\n background: blue;\n \">\n {{ name_initials }}\n </div>\n {% endslot %}\n {% else %}\n {% slot \"image\" default required / %}\n {% endif %}\n</div>\n
- The slot fills that were passed to a component and which can be accessed as
Component.input.slots
can now be passed through the Django template, e.g. as inputs to other tags.
Internally, django-components handles slot fills as functions.
Previously, if you tried to pass a slot fill within a template, Django would try to call it as a function.
Now, something like this is possible:
class MyTable(Component):\n def get_context_data(self, *args, **kwargs):\n return {\n \"child_slot\": self.input.slots[\"child_slot\"],\n }\n\n template: \"\"\"\n <div>\n {% component \"child\" content=child_slot / %}\n </div>\n \"\"\"\n
NOTE: Using
{% slot %}
and{% fill %}
tags is still the preferred method, but the approach above may be necessary in some complex or edge cases.- The
is_filled
variable (and the{{ component_vars.is_filled }}
context variable) now returnsFalse
when you try to access a slot name which has not been defined:
Before:
{{ component_vars.is_filled.header }} -> True\n{{ component_vars.is_filled.footer }} -> False\n{{ component_vars.is_filled.nonexist }} -> \"\" (empty string)\n
After:
{{ component_vars.is_filled.header }} -> True\n{{ component_vars.is_filled.footer }} -> False\n{{ component_vars.is_filled.nonexist }} -> False\n
-
Components no longer raise an error if there are extra slot fills
-
Components will raise error when a slot is doubly-filled.
E.g. if we have a component with a default slot:
{% slot name=\"content\" default / %}\n
Now there is two ways how we can target this slot: Either using
name=\"default\"
orname=\"content\"
.In case you specify BOTH, the component will raise an error:
"},{"location":"CHANGELOG/#v0100","title":"\ud83d\udea8\ud83d\udce2 v0.100","text":""},{"location":"CHANGELOG/#breaking-changes_2","title":"BREAKING CHANGES","text":"{% component \"child\" %}\n {% fill slot=\"default\" %}\n Hello from default slot\n {% endfill %}\n {% fill slot=\"content\" data=\"data\" %}\n Hello from content slot\n {% endfill %}\n{% endcomponent %}\n
-
django_components.safer_staticfiles
app was removed. It is no longer needed. -
Installation changes:
- Instead of defining component directories in
STATICFILES_DIRS
, set them toCOMPONENTS.dirs
. -
You now must define
STATICFILES_FINDERS
-
See here how to migrate your settings.py
- Instead of defining component directories in
- Beside the top-level
/components
directory, you can now define also app-level components dirs, e.g.[app]/components
(SeeCOMPONENTS.app_dirs
).
- When you call
as_view()
on a component instance, that instance will be passed toView.as_view()
- Fixed template caching. You can now also manually create cached templates with
cached_template()
-
The previously undocumented
get_template
was made private. -
In it's place, there's a new
get_template
, which supersedesget_template_string
(will be removed in v1). The newget_template
is the same asget_template_string
, except it allows to return either a string or a Template instance. -
You now must use only one of
template
,get_template
,template_name
, orget_template_name
.
-
Run-time type validation for Python 3.11+ - If the
Component
class is typed, e.g.Component[Args, Kwargs, ...]
, the args, kwargs, slots, and data are validated against the given types. (See Runtime input validation with types) -
Render hooks - Set
on_render_before
andon_render_after
methods onComponent
to intercept or modify the template or context before rendering, or the rendered result afterwards. (See Component hooks) -
component_vars.is_filled
context variable can be accessed from withinon_render_before
andon_render_after
hooks asself.is_filled.my_slot
- Added support for dynamic components, where the component name is passed as a variable. (See Dynamic components)
- Changed
Component.input
to raiseRuntimeError
if accessed outside of render context. Previously it returnedNone
if unset.
-
django_components now automatically configures Django to support multi-line tags. (See Multi-line tags)
-
New setting
reload_on_template_change
. Set this toTrue
to reload the dev server on changes to component template files. (See Reload dev server on component file changes)
-
Spread operator
...dict
inside template tags. (See Spread operator) -
Use template tags inside string literals in component inputs. (See Use template tags inside component inputs)
-
Dynamic slots, fills and provides - The
name
argument for these can now be a variable, a template expression, or via spread operator -
Component library authors can now configure
CONTEXT_BEHAVIOR
andTAG_FORMATTER
settings independently from user settings.
Component
class is no longer a subclass ofView
. To configure theView
class, set theComponent.View
nested class. HTTP methods likeget
orpost
can still be defined directly onComponent
class, andComponent.as_view()
internally callsComponent.View.as_view()
. (See Modifying the View class)
-
The inputs (args, kwargs, slots, context, ...) that you pass to
Component.render()
can be accessed from withinget_context_data
,get_template
andget_template_name
viaself.input
. (See Accessing data passed to the component) -
Typing:
Component
class supports generics that specify types forComponent.render
(See Adding type hints with Generics)
-
All tags (
component
,slot
,fill
, ...) now support \"self-closing\" or \"inline\" form, where you can omit the closing tag:{# Before #}\n{% component \"button\" %}{% endcomponent %}\n{# After #}\n{% component \"button\" / %}\n
-
All tags now support the \"dictionary key\" or \"aggregate\" syntax (
kwarg:key=val
):{% component \"button\" attrs:class=\"hidden\" %}\n
-
You can change how the components are written in the template with TagFormatter.
The default is
django_components.component_formatter
:{% component \"button\" href=\"...\" disabled %}\n Click me!\n{% endcomponent %}\n
While
django_components.shorthand_component_formatter
allows you to write components like so:{% button href=\"...\" disabled %}\n Click me!\n{% endbutton %}\n
-
Autodiscovery module resolution changed. Following undocumented behavior was removed:
-
Previously, autodiscovery also imported any
[app]/components.py
files, and usedSETTINGS_MODULE
to search for component dirs.To migrate from:
-
[app]/components.py
- Define each module inCOMPONENTS.libraries
setting, or import each module inside theAppConfig.ready()
hook in respectiveapps.py
files. -
SETTINGS_MODULE
- Define component dirs usingSTATICFILES_DIRS
-
-
Previously, autodiscovery handled relative files in
STATICFILES_DIRS
. To align with Django,STATICFILES_DIRS
now must be full paths (Django docs).
-
- The order of arguments to
render_to_response
has changed, to align with the (now public)render
method ofComponent
class.
-
Component.render()
is public and documented -
Slots passed
render_to_response
andrender
can now be rendered also as functions.
- Vue-like provide/inject with the
{% provide %}
tag andinject()
method.
- 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.
-
The syntax for accessing default slot content has changed from
{% fill \"my_slot\" as \"alias\" %}\n {{ alias.default }}\n{% endfill %}\n
to
{% fill \"my_slot\" default=\"alias\" %}\n {{ alias }}\n{% endfill %}\n
-
{% html_attrs %}
tag for formatting data as HTML attributes -
prefix:key=val
construct for passing dicts to components
-
{% if_filled \"my_slot\" %}
tags were replaced with{{ component_vars.is_filled.my_slot }}
variables. -
Simplified settings -
slot_context_behavior
andcontext_behavior
were merged. See the documentation for more details.
- Changed the default way how context variables are resolved in slots. See the documentation for more details.
-
{% 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.
- Components as views, which allows you to handle requests and render responses from within a component. See the documentation for more details.
- 'implicit' slot filling and the
default
option forslot
tags.
- A second installable app
django_components.safer_staticfiles
. It provides the same behavior asdjango.contrib.staticfiles
but with extra security guarantees (more info below in Security Notes).
-
Changed the syntax for
{% slot %}
tags. From now on, we separate defining a slot ({% slot %}
) from filling a slot with content ({% fill %}
). This means you will likely need to change a lot of slot tags to fill.We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice feature to have access to. Hoping that this will feel worth it!
-
All files inside components subdirectores are autoimported to simplify setup.
An existing project might start to get
AlreadyRegistered
errors because of this. To solve this, either remove your custom loading of components, or set\"autodiscover\": False
insettings.COMPONENTS
.
-
Renamed
Component.context
andComponent.template
toget_context_data
andget_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
andComponent.template
will be removed when version 1.0 is released.
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
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
MIT License
Copyright (c) 2019 Emil Stenstr\u00f6m
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"},{"location":"migrating_from_safer_staticfiles/","title":"Migrating from safer_staticfiles","text":"This guide is for you if you're upgrating django_components to v0.100 or later from older versions.
In version 0.100, we changed how components' static JS and CSS files are handled. See more in the \"Static files\" section.
Migration steps:
- Remove
django_components.safer_staticfiles
fromINSTALLED_APPS
in yoursettings.py
, and replace it withdjango.contrib.staticfiles
.
Before:
INSTALLED_APPS = [\n \"django.contrib.admin\",\n ...\n # \"django.contrib.staticfiles\", # <-- ADD\n \"django_components\",\n \"django_components.safer_staticfiles\", # <-- REMOVE\n]\n
After:
INSTALLED_APPS = [\n \"django.contrib.admin\",\n ...\n \"django.contrib.staticfiles\",\n \"django_components\",\n]\n
- Add
STATICFILES_FINDERS
tosettings.py
, and adddjango_components.finders.ComponentsFileSystemFinder
:
STATICFILES_FINDERS = [\n # Default finders\n \"django.contrib.staticfiles.finders.FileSystemFinder\",\n \"django.contrib.staticfiles.finders.AppDirectoriesFinder\",\n # Django components\n \"django_components.finders.ComponentsFileSystemFinder\", # <-- ADDED\n]\n
- Add
COMPONENTS.dirs
tosettings.py
.
If you previously defined
STATICFILES_DIRS
, move only those directories fromSTATICFILES_DIRS
that point to components directories, and keep the rest.E.g. if you have
STATICFILES_DIRS
like this:STATICFILES_DIRS = [\n BASE_DIR / \"components\", # <-- MOVE\n BASE_DIR / \"myapp\" / \"components\", # <-- MOVE\n BASE_DIR / \"assets\",\n]\n
Then first two entries point to components dirs, whereas
/assets
points to non-component static files. In this case move only the first two paths:COMPONENTS = {\n \"dirs\": [\n BASE_DIR / \"components\", # <-- MOVED\n BASE_DIR / \"myapp\" / \"components\", # <-- MOVED\n ],\n}\n\nSTATICFILES_DIRS = [\n BASE_DIR / \"assets\",\n]\n
Moreover, if you defined app-level component directories in
STATICFILES_DIRS
before, you can now define as a RELATIVE path inapp_dirs
:
"},{"location":"devguides/dependency_mgmt/","title":"JS and CSS rendering","text":"COMPONENTS = {\n \"dirs\": [\n # Search top-level \"/components/\" dir\n BASE_DIR / \"components\",\n ],\n \"app_dirs\": [\n # Search \"/[app]/components/\" dirs\n \"components\",\n ],\n}\n\nSTATICFILES_DIRS = [\n BASE_DIR / \"assets\",\n]\n
Aim of this doc is to share the intuition on how we manage the JS and CSS (\"dependencies\") associated with components, and how we render them.
"},{"location":"devguides/dependency_mgmt/#starting-conditions","title":"Starting conditions","text":"- First of all, when we consider a component, it has two kind of dependencies - the \"inlined\" JS and CSS, and additional linked JS and CSS via
Media.js/css
:
from django_components import Component, types\n\nclass MyTable(Component):\n # Inlined JS\n js: types.js = \"\"\"\n console.log(123);\n \"\"\"\n\n # Inlined CSS\n css: types.css = \"\"\"\n .my-table {\n color: red;\n }\n \"\"\"\n\n # Linked JS / CSS\n class Media:\n js = [\n \"script-one.js\", # STATIC file relative to component file\n \"/script-two.js\", # URL path\n \"https://example.com/script-three.js\", # URL\n ]\n\n css = [\n \"style-one.css\", # STATIC file relative to component file\n \"/style-two.css\", # URL path\n \"https://example.com/style-three.css\", # URL\n ]\n
- Second thing to keep in mind is that all component's are eventually rendered into a string. And so, if we want to associate extra info with a rendered component, it has to be serialized to a string.
This is because a component may be embedded in a Django Template with the
{% component %}
tag, which, when rendered, is turned into a string:template = Template(\"\"\"\n {% load component_tags %}\n <div>\n {% component \"my_table\" / %}\n </div>\n\"\"\")\n\nhtml_str = template.render(Context({}))\n
And for this reason, we take the same approach also when we render a component with
Component.render()
- It returns a string.- Thirdly, we also want to add support for JS / CSS variables. That is, that a variable defined on the component would be somehow accessible from within the JS script / CSS style.
A simple approach to this would be to modify the inlined JS / CSS directly, and insert them for each component. But if you had extremely large JS / CSS, and e.g. only a single JS / CSS variable that you want to insert, it would be extremely wasteful to copy-paste the JS / CSS for each component instance.
So instead, a preferred approach here is to defined and insert the inlined JS / CSS only once, and have some kind of mechanism on how we make correct the JS / CSS variables available only to the correct components.
- Last important thing is that we want the JS / CSS dependencies to work also with HTML fragments.
So normally, e.g. when a user hits URL of a web page, the server renders full HTML document, with
<!doctype>
,<html>
,<head>
, and<body>
. In such case, we know about ALL JS and CSS dependencies at render time, so we can e.g. insert them into<head>
and<body>
ourselves.However this renders only the initial state. HTML fragments is a common pattern where interactivity is added to the web page by fetching and replacing bits of HTML on the main HTML document after some user action.
In the case of HTML fragments, the HTML is NOT a proper document, but only the HTML that will be inserted somewhere into the DOM.
The challenge here is that Django template for the HTML fragment MAY contain components, and these components MAY have inlined or linked JS and CSS.
def fragment_view(request):\n template = Template(\"\"\"\n {% load component_tags %}\n <div>\n {% component \"my_table\" / %}\n </div>\n \"\"\")\n\n fragment_str = template.render(Context({}))\n return HttpResponse(fragment_str, status=200)\n
User may use different libraries to fetch and insert the HTML fragments (e.g. HTMX, AlpineJS, ...). From our perspective, the only thing that we can reliably say is that we expect that the HTML fragment WILL be eventually inserted into the DOM.
So to include the corresponding JS and CSS, a simple approach could be to append them to the HTML as
<style>
and<script>
, e.g.:<!-- Original content -->\n<div>...</div>\n<!-- Associated CSS files -->\n<link href=\"http://...\" />\n<style>\n .my-class {\n color: red;\n }\n</style>\n<!-- Associated JS files -->\n<script src=\"http://...\"></script>\n<script>\n console.log(123);\n</script>\n
But this has a number of issues:
- The JS scripts would run for each instance of the component.
- Bloating of the HTML file, as each inlined JS or CSS would be included fully for each component.
- While this sound OK, this could really bloat the HTML files if we used a UI component library for the basic building blocks like buttons, lists, cards, etc.
So the solution should address all the points above. To achieve that, we manage the JS / CSS dependencies ourselves in the browser. So when a full HTML document is loaded, we keep track of which JS and CSS have been loaded. And when an HTML fragment is inserted, we check which JS / CSS dependencies it has, and load only those that have NOT been loaded yet.
This is how we achieve that:
- When a component is rendered, it inserts an HTML comment containing metadata about the rendered component.
So a template like this
{% load component_tags %}\n<div>\n {% component \"my_table\" / %}\n</div>\n{% component \"button\" %}\n Click me!\n{% endcomponent %}\n
May actually render:
<div>\n <!-- _RENDERED \"my_table_10bc2c,c020ad\" -->\n <table>\n ...\n </table>\n</div>\n<!-- _RENDERED \"button_309dcf,31c0da\" -->\n<button>Click me!</button>\n
Each
<!-- _RENDERED -->
comment includes comma-separated data - a unique hash for the component class, e.g.my_table_10bc2c
, and the component ID, e.g.c020ad
.This way, we or the user can freely pass the rendered around or transform it, treating it as a string to add / remove / replace bits. As long as the
<!-- _RENDERED -->
comments remain in the rendered string, we will be able to deduce which JS and CSS dependencies the component needs.- Post-process the rendered HTML, extracting the
<!-- _RENDERED -->
comments, and instead inserting the corresponding JS and CSS dependencies.
If we dealt only with JS, then we could get away with processing the
<!-- _RENDERED -->
comments on the client (browser). However, the CSS needs to be processed still on the server, so the browser receives CSS styles already inserted as<style>
or<link>
HTML tags. Because if we do not do that, we get a flash of unstyled content, as there will be a delay between when the HTML page loaded and when the CSS was fetched and loaded.So, assuming that a user has already rendered their template, which still contains
<!-- _RENDERED -->
comments, we need to extract and process these comments.There's multiple ways to achieve this:
-
The approach recommended to the users is to use the
ComponentDependencyMiddleware
middleware, which scans all outgoing HTML, and post-processes the<!-- _RENDERED -->
comments. -
If users are using
Component.render()
orComponent.render_to_response()
, these post-process the<!-- _RENDERED -->
comments by default.- NOTE: Users are able to opt out of the post-processing by setting
render_dependencies=False
.
- NOTE: Users are able to opt out of the post-processing by setting
-
For advanced use cases, users may use
render_dependencies()
directly. This is the function that bothComponentDependencyMiddleware
andComponent.render()
call internally.
render_dependencies()
, whether called directly, via middleware or other way, does the following:-
Find all
<!-- _RENDERED -->
comments, and for each comment: -
Look up the corresponding component class.
-
Get the component's inlined JS / CSS from
Component.js/css
, and linked JS / CSS fromComponent.Media.js/css
. -
Generate JS script that loads the JS / CSS dependencies.
-
Insert the JS scripts either at the end of
<body>
, or in place of{% component_dependencies %}
/{% component_js_dependencies %}
tags. -
To avoid the flash of unstyled content, we need place the styles into the HTML instead of dynamically loading them from within a JS script. The CSS is placed either at the end of
<head>
, or in place of{% component_dependencies %}
/{% component_css_dependencies %}
-
We cache the component's inlined JS and CSS, so they can be fetched via an URL, so the inlined JS / CSS an be treated the same way as the JS / CSS dependencies set in
Component.Media.js/css
.- NOTE: While this is currently not entirely necessary, it opens up the doors for allowing plugins to post-process the inlined JS and CSS. Because after it has been post-processed, we need to store it somewhere.
-
Server returns the post-processed HTML.
-
In the browser, the generated JS script from step 2.4 is executed. It goes through all JS and CSS dependencies it was given. If some JS / CSS was already loaded, it is NOT fetched again. Otherwise it generates the corresponding
<script>
or<link>
HTML tags to load the JS / CSS dependencies.
In the browser, the \"dependency manager JS\" may look like this:
// Load JS or CSS script if not loaded already\nComponents.loadScript(\"js\", '<script src=\"/abc/xyz/script.js\">');\nComponents.loadScript(\"css\", '<link href=\"/abc/xyz/style.css\">');\n\n// Or mark one as already-loaded, so it is ignored when\n// we call `loadScript`\nComponents.markScriptLoaded(\"js\", \"/abc/def\");\n
Note that
loadScript()
receives a whole<script>
and<link>
tags, not just the URL. This is because when Django'sMedia
class renders JS and CSS, it formats it as<script>
and<link>
tags. And we allow users to modify how the JS and CSS should be rendered into the<script>
and<link>
tags.So, if users decided to add an extra attribute to their
<script>
tags, e.g.<script defer src=\"http://...\"></script>
, then this way we make sure that thedefer
attribute will be present on the<script>
tag when it is inserted into the DOM at the time of loading the JS script.- To be able to fetch component's inlined JS and CSS, django-components adds a URL path under:
/components/cache/<str:comp_cls_hash>.<str:script_type>/
E.g.
/components/cache/my_table_10bc2c.js/
This endpoint takes the component's unique hash, e.g.
my_table_10bc2c
, and looks up the component's inlined JS or CSS.Thus, with this approach, we ensure that:
- All JS / CSS dependencies are loaded / executed only once.
- The approach is compatible with HTML fragments
- The approach is compatible with JS / CSS variables.
- Inlined JS / CSS may be post-processed by plugins
This doc serves as a primer on how component slots and fills are resolved.
"},{"location":"devguides/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
-
The names of the slots and fills may be defined using variables
| -- {% slot slot_name %} ---\n| ---- STU {{ my_var }}\n| -- {% endslot %} ---\n| -------\n
-
The slot and fill names may be defined using for loops or other variables defined within the template (e.g.
{% with %}
tag or{% ... as var %}
syntax)| -- {% for slot_name in slots %} ---\n| ---- {% slot slot_name %} ---\n| ------ STU {{ slot_name }}\n| ---- {% endslot %} ---\n| -- {% endfor %} ---\n| -------\n
-
Variables for names and for loops allow us implement \"passthrough slots\" - that is, taking all slots that our component received, and passing them to a child component, dynamically.
| -- {% component \"mycomp\" %} ---\n| ---- {% for slot_name in slots %} ---\n| ------ {% fill slot_name %} ---\n| -------- {% slot slot_name %} ---\n| ---------- XYZ {{ slot_name }}\n| --------- {% endslot %}\n| ------- {% endfill %}\n| ---- {% endfor %} ---\n| -- {% endcomponent %} ---\n| ----\n
-
Putting that all together, a document may look like this:
| -- {{ my_var }} --\n| -- ABC\n| -- {% slot \"myslot\" %}---\n| ----- DEF {{ my_var }}\n| ----- {% slot \"myslot_inner\" %}\n| -------- GHI {{ my_var }}\n| ----- {% endslot %}\n| -- {% endslot %} ---\n| ------\n| -- {% component \"mycomp\" %} ---\n| ---- {% slot \"myslot\" %} ---\n| ------- JKL {{ my_var }}\n| ------- {% slot \"myslot_inner\" %}\n| ---------- MNO {{ my_var }}\n| ------- {% endslot %}\n| ---- {% endslot %} ---\n| -- {% endcomponent %} ---\n| ----\n| -- {% slot \"myslot2\" %} ---\n| ---- PQR {{ my_var }}\n| -- {% endslot %} ---\n| -------\n| -- {% for slot_name in slots %} ---\n| ---- {% component \"mycomp\" %} ---\n| ------- {% slot slot_name %}\n| ---------- STU {{ slot_name }}\n| ------- {% endslot %}\n| ---- {% endcomponent %} ---\n| -- {% endfor %} ---\n| ----\n| -- {% component \"mycomp\" %} ---\n| ---- {% for slot_name in slots %} ---\n| ------ {% fill slot_name %} ---\n| -------- {% slot slot_name %} ---\n| ---------- XYZ {{ slot_name }}\n| --------- {% endslot %}\n| ------- {% endfill %}\n| ---- {% endfor %} ---\n| -- {% endcomponent %} ---\n| -------\n
-
Given the above, we want to render the slots with
{% fill %}
tag that were defined OUTSIDE of this template. How do I do that?NOTE: Before v0.110, slots were resolved statically, by walking down the Django Template and Nodes. However, this did not allow for using for loops or other variables defined in the template.
Currently, this consists of 2 steps:
-
If a component is rendered within a template using
{% component %}
tag, determine the given{% fill %}
tags in the component's body (the content in between{% component %}
and{% endcomponent %}
).After this step, we know about all the fills that were passed to the component.
-
Then we simply render the template as usual. And then we reach the
{% slot %}
tag, we search the context for the available fills.- If there IS a fill with the same name as the slot, we render the fill.
- If the slot is marked
default
, and there is a fill nameddefault
, then we render that. - Otherwise, we render the slot's default content.
-
-
Obtaining the fills from
{% fill %}
.When a component is rendered with
{% component %}
tag, and it has some content in between{% component %}
and{% endcomponent %}
, we want to figure out if that content is a default slot (no{% fill %}
used), or if there is a collection of named{% fill %}
tags:Default slot:
| -- {% component \"mycomp\" %} ---\n| ---- STU {{ slot_name }}\n| -- {% endcomponent %} ---\n
Named slots:
| -- {% component \"mycomp\" %} ---\n| ---- {% fill \"slot_a\" %}\n| ------ STU\n| ---- {% endslot %}\n| ---- {% fill \"slot_b\" %}\n| ------ XYZ\n| ---- {% endslot %}\n| -- {% endcomponent %} ---\n
To respect any forloops or other variables defined within the template to which the fills may have access, we:
- Render the content between
{% component %}
and{% endcomponent %}
using the context outside of the component. - When we reach a
{% fill %}
tag, we capture any variables that were created between the{% component %}
and{% fill %}
tags. - When we reach
{% fill %}
tag, we do not continue rendering deeper. Instead we make a record that we found the fill tag with given name, kwargs, etc. - After the rendering is done, we check if we've encountered any fills. If yes, we expect only named fills. If no, we assume that the the component's body is a default slot.
- Lastly we process the found fills, and make them available to the context, so any slots inside the component may access these fills.
- Render the content between
-
Rendering slots
Slot rendering works similarly to collecting fills, in a sense that we do not search for the slots ahead of the time, but instead let Django handle the rendering of the template, and we step in only when Django come across as
{% slot %}
tag.When we reach a slot tag, we search the context for the available fills.
- If there IS a fill with the same name as the slot, we render the fill.
- If the slot is marked
default
, and there is a fill nameddefault
, then we render that. - Otherwise, we render the slot's default content.
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
"},{"location":"devguides/slots_and_blocks/","title":"Using{% slot %}
node, in it'srender()
method, we access the data above, and, depending on thecontext_behavior
setting, include the current context or not. For more info, seeSlotNode.render()
.slot
andblock
tags","text":"-
First let's clarify how
include
andextends
tags work inside components. So when component template includesinclude
orextends
tags, it's as if the \"included\" template was inlined. So if the \"included\" template containsslot
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 thebody
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 thecomponent
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 ofabc.html
if my component template usesextends
. In that case, just as you would expect, theblock inner
insideabc.html
will renderOVERRIDEN
:@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
andbody
slots, and you will not get an error for an invalid/unknown slot name. But sincebody
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
-
- django_components
- app_settings
- apps
- attributes
- autodiscovery
- component
- component_media
- component_registry
- components
- dynamic
- context
- dependencies
- expression
- finders
- library
- management
- commands
- startcomponent
- upgradecomponent
- middleware
- node
- provide
- slots
- tag_formatter
- template
- template_loader
- template_parser
- templatetags
- component_tags
- types
- urls
- util
- cache
- html
- loader
- logger
- misc
- nanoid
- tag_parser
- types
- validation
- django_components_js
- build
- docs
- scripts
- reference
Main package for Django Components.
Modules:
-
app_settings
\u2013 -
attributes
\u2013 -
autodiscovery
\u2013 -
component
\u2013 -
component_media
\u2013 -
component_registry
\u2013 -
components
\u2013 -
context
\u2013This file centralizes various ways we use Django's Context class
-
dependencies
\u2013All code related to management of component dependencies (JS and CSS scripts)
-
expression
\u2013 -
finders
\u2013 -
library
\u2013Module for interfacing with Django's Library (
django.template.library
) -
management
\u2013 -
middleware
\u2013 -
node
\u2013 -
provide
\u2013 -
slots
\u2013 -
tag_formatter
\u2013 -
template
\u2013 -
template_loader
\u2013Template loader that loads templates from each Django app's \"components\" directory.
-
template_parser
\u2013Overrides for the Django Template system to allow finer control over template parsing.
-
templatetags
\u2013 -
types
\u2013Helper types for IDEs.
-
util
\u2013
Classes:
-
AlreadyRegistered
\u2013Raised when you try to register a Component,
-
Component
\u2013 -
ComponentFileEntry
\u2013Result returned by
get_component_files()
. -
ComponentFormatter
\u2013The original django_component's component tag formatter, it uses the
{% component %}
-
ComponentRegistry
\u2013Manages components and makes them available
-
ComponentVars
\u2013Type for the variables available inside the component templates.
-
ComponentView
\u2013Subclass of
django.views.View
where theComponent
instance is available -
ComponentsSettings
\u2013Settings available for django_components.
-
ContextBehavior
\u2013Configure how (and whether) the context is passed to the component fills
-
DynamicComponent
\u2013This component is given a registered name or a reference to another component,
-
EmptyDict
\u2013TypedDict with no members.
-
NotRegistered
\u2013Raised when you try to access a Component,
-
RegistrySettings
\u2013Configuration for a
ComponentRegistry
. -
ShorthandComponentFormatter
\u2013The component tag formatter that uses
{% <name> %}
/{% end<name> %}
tags. -
Slot
\u2013This class holds the slot content function along with related metadata.
-
SlotRef
\u2013SlotRef allows to treat a slot as a variable. The slot is rendered only once
-
TagFormatterABC
\u2013Abstract base class for defining custom tag formatters.
-
TagProtectedError
\u2013The way the
TagFormatter
works is that, -
TagResult
\u2013The return value from
TagFormatter.parse()
.
Functions:
-
autodiscover
\u2013Search for all python files in
-
cached_template
\u2013Create a Template instance that will be cached as per the
-
get_component_dirs
\u2013Get directories that may contain component files.
-
get_component_files
\u2013Search for files within the component directories (as defined in
-
import_libraries
\u2013Import modules set in
-
register
\u2013Class decorator for registering a component
-
render_dependencies
\u2013Given a string that contains parts that were rendered by components,
Attributes:
-
EmptyTuple
\u2013Tuple with no members.
-
registry
(ComponentRegistry
) \u2013The default and global component registry.
module-attribute
","text":"EmptyTuple = Tuple[]\n
Tuple with no members.
You can use this to define a Component that accepts NO positional arguments:
from django_components import Component, EmptyTuple\n\nclass Table(Component(EmptyTuple, Any, Any, Any, Any, Any))\n ...\n
After that, when you call
Component.render()
orComponent.render_to_response()
, theargs
parameter will raise type error ifargs
is anything else than an empty tuple.Table.render(\n args: (),\n)\n
Omitting
args
is also fine:Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
"},{"location":"reference/django_components/#django_components.registry","title":"registryTable.render(\n args: (\"one\", 2, \"three\"),\n)\n
module-attribute
","text":"registry: ComponentRegistry = ComponentRegistry()\n
The default and global component registry. Use this instance to directly register or remove components:
See Registering components.
"},{"location":"reference/django_components/#django_components.AlreadyRegistered","title":"AlreadyRegistered","text":"# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get single\nregistry.get(\"button\")\n\n# Get all\nregistry.all()\n\n# Unregister single\nregistry.unregister(\"button\")\n\n# Unregister all\nregistry.clear()\n
Bases:
Exception
Raised when you try to register a Component, but it's already registered with given ComponentRegistry.
"},{"location":"reference/django_components/#django_components.Component","title":"Component","text":"Component(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Generic[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template
(Optional[Union[str, Template]]
) \u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.Component.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
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.css","title":"cssclass-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/#django_components.Component.input","title":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/#django_components.Component.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/#django_components.Component.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/#django_components.Component.media","title":"mediainstance-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.response_class","title":"response_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/#django_components.Component.template","title":"templaterender_to_response
class-attribute
instance-attribute
","text":"template: Optional[Union[str, Template]] = None\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
"},{"location":"reference/django_components/#django_components.Component.template_name","title":"template_nametemplate_name
,get_template_name
,template
orget_template
must be defined.class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/#django_components.Component.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.Component.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.Component.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.Component.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/#django_components.Component.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.Component.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.Component.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.Component.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.ComponentFileEntry","title":"ComponentFileEntry","text":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
Bases:
NamedTuple
Result returned by
get_component_files()
.Attributes:
-
dot_path
(str
) \u2013The python import path for the module. E.g.
app.components.mycomp
-
filepath
(Path
) \u2013The filesystem path to the module. E.g.
/path/to/project/app/components/mycomp.py
instance-attribute
","text":"dot_path: str\n
The python import path for the module. E.g.
"},{"location":"reference/django_components/#django_components.ComponentFileEntry.filepath","title":"filepathapp.components.mycomp
instance-attribute
","text":"filepath: Path\n
The filesystem path to the module. E.g.
"},{"location":"reference/django_components/#django_components.ComponentFormatter","title":"ComponentFormatter","text":"/path/to/project/app/components/mycomp.py
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 given as the first positional arg.Example as block:
{% component \"mycomp\" abc=123 %}\n {% fill \"myfill\" %}\n ...\n {% endfill %}\n{% endcomponent %}\n
Example as inlined tag:
Source code in{% component \"mycomp\" abc=123 / %}\n
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.ComponentRegistry","title":"ComponentRegistry","text":"def __init__(self, tag: str):\n self.tag = tag\n
ComponentRegistry(\n library: Optional[Library] = None, settings: Optional[Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]] = None\n)\n
Manages components and makes them available in the template, by default as
{% component %}
tags.{% component \"my_comp\" key=value %}\n{% endcomponent %}\n
To enable a component to be used in a template, the component must be registered with a component registry.
When you register a component to a registry, behind the scenes the registry automatically adds the component's template tag (e.g.
{% component %}
to theLibrary
. And the opposite happens when you unregister a component - the tag is removed.See Registering components.
Parameters:
-
library
(Library
, default:None
) \u2013Django
Library
associated with this registry. If omitted, the default Library instance from django_components is used. -
settings
(Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]
, default:None
) \u2013Configure how the components registered with this registry will behave when rendered. See
RegistrySettings
. Can be either a static value or a callable that returns the settings. If omitted, the settings fromCOMPONENTS
are used.
Notes:
- The default registry is available as
django_components.registry
. - The default registry is used when registering components with
@register
decorator.
Example:
"},{"location":"reference/django_components/#django_components.ComponentRegistry--using-registry-to-share-components","title":"Using registry to share components","text":"# 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
You can use component registry for isolating or \"packaging\" components:
-
Create new instance of
ComponentRegistry
and Library:my_comps = Library()\nmy_comps_reg = ComponentRegistry(library=my_comps)\n
-
Register components to the registry:
my_comps_reg.register(\"my_button\", ButtonComponent)\nmy_comps_reg.register(\"my_card\", CardComponent)\n
-
In your target project, load the Library associated with the registry:
{% load my_comps %}\n
-
Use the registered components in your templates:
{% component \"button\" %}\n{% endcomponent %}\n
Methods:
-
all
\u2013Retrieve all registered
Component
classes. -
clear
\u2013Clears the registry, unregistering all components.
-
get
\u2013Retrieve a
Component
-
register
\u2013Register a
Component
class -
unregister
\u2013Unregister the
Component
class
Attributes:
-
library
(Library
) \u2013The template tag
Library
-
settings
(InternalRegistrySettings
) \u2013Registry settings configured for this registry.
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.ComponentRegistry.library","title":"librarydef __init__(\n self,\n library: Optional[Library] = None,\n settings: Optional[Union[RegistrySettings, Callable[[\"ComponentRegistry\"], RegistrySettings]]] = None,\n) -> None:\n self._registry: Dict[str, ComponentRegistryEntry] = {} # component name -> component_entry mapping\n self._tags: Dict[str, Set[str]] = {} # tag -> list[component names]\n self._library = library\n self._settings_input = settings\n self._settings: Optional[Callable[[], InternalRegistrySettings]] = None\n\n all_registries.append(self)\n
property
","text":"library: Library\n
The template tag
"},{"location":"reference/django_components/#django_components.ComponentRegistry.settings","title":"settingsLibrary
that is associated with the registry.property
","text":"settings: InternalRegistrySettings\n
Registry settings configured for this registry.
"},{"location":"reference/django_components/#django_components.ComponentRegistry.all","title":"all","text":"all() -> Dict[str, Type[Component]]\n
Retrieve all registered
Component
classes.Returns:
-
Dict[str, Type[Component]]
\u2013Dict[str, Type[Component]]: A dictionary of component names to component classes
Example:
Source code in# 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
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.ComponentRegistry.clear","title":"clear","text":"def all(self) -> Dict[str, Type[\"Component\"]]:\n \"\"\"\n Retrieve all registered [`Component`](../api#django_components.Component) classes.\n\n Returns:\n Dict[str, Type[Component]]: A dictionary of component names to component classes\n\n **Example:**\n\n ```python\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
clear() -> None\n
Clears the registry, unregistering all components.
Example:
Source code in# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then clear\nregistry.clear()\n# Then get all\nregistry.all()\n# > {}\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.ComponentRegistry.get","title":"get","text":"def clear(self) -> None:\n \"\"\"\n Clears the registry, unregistering all components.\n\n Example:\n\n ```python\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
get(name: str) -> Type[Component]\n
Retrieve a
Component
class registered under the given name.Parameters:
-
name
(str
) \u2013The name under which the component was registered. Required.
Returns:
-
Type[Component]
\u2013Type[Component]: The component class registered under the given name.
Raises:
NotRegistered
if the given name is not registered.
Example:
Source code in# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then get\nregistry.get(\"button\")\n# > ButtonComponent\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.ComponentRegistry.register","title":"register","text":"def get(self, name: str) -> Type[\"Component\"]:\n \"\"\"\n Retrieve a [`Component`](../api#django_components.Component)\n class registered under the given name.\n\n Args:\n name (str): The name under which the component was registered. Required.\n\n Returns:\n Type[Component]: The component class registered under the given name.\n\n **Raises:**\n\n - [`NotRegistered`](../exceptions#django_components.NotRegistered)\n if the given name is not registered.\n\n **Example:**\n\n ```python\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
register(name: str, component: Type[Component]) -> None\n
Register a
Component
class with this registry under the given name.A component MUST be registered before it can be used in a template such as:
{% component \"my_comp\" %}\n{% endcomponent %}\n
Parameters:
-
name
(str
) \u2013The name under which the component will be registered. Required.
-
component
(Type[Component]
) \u2013The component class to register. Required.
Raises:
AlreadyRegistered
if a different component was already registered under the same name.
Example:
Source code inregistry.register(\"button\", ButtonComponent)\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.ComponentRegistry.unregister","title":"unregister","text":"def register(self, name: str, component: Type[\"Component\"]) -> None:\n \"\"\"\n Register a [`Component`](../api#django_components.Component) class\n 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\" %}\n {% endcomponent %}\n ```\n\n Args:\n name (str): The name under which the component will be registered. Required.\n component (Type[Component]): The component class to register. Required.\n\n **Raises:**\n\n - [`AlreadyRegistered`](../exceptions#django_components.AlreadyRegistered)\n if a different component was already registered under the same name.\n\n **Example:**\n\n ```python\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
unregister(name: str) -> None\n
Unregister the
Component
class that was registered under the given name.Once a component is unregistered, it is no longer available in the templates.
Parameters:
-
name
(str
) \u2013The name under which the component is registered. Required.
Raises:
NotRegistered
if the given name is not registered.
Example:
Source code in# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.ComponentVars","title":"ComponentVars","text":"def unregister(self, name: str) -> None:\n \"\"\"\n Unregister the [`Component`](../api#django_components.Component) class\n that was registered under the given name.\n\n Once a component is unregistered, it is no longer available in the templates.\n\n Args:\n name (str): The name under which the component is registered. Required.\n\n **Raises:**\n\n - [`NotRegistered`](../exceptions#django_components.NotRegistered)\n if the given name is not registered.\n\n **Example:**\n\n ```python\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
Bases:
NamedTuple
Type for the variables available inside the component templates.
All variables here are scoped under
component_vars.
, so e.g. attributeis_filled
on this class is accessible inside the template as:{{ component_vars.is_filled }}\n
Attributes:
-
is_filled
(Dict[str, bool]
) \u2013Dictonary describing which component slots are filled (
True
) or are not (False
).
instance-attribute
","text":"is_filled: Dict[str, bool]\n
Dictonary describing which component slots are filled (
True
) or are not (False
).New in version 0.70
Use as
{{ component_vars.is_filled }}
Example:
"},{"location":"reference/django_components/#django_components.ComponentView","title":"ComponentView","text":"{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n <div class=\"slot-wrapper\">\n {% slot \"my_slot\" / %}\n </div>\n{% endif %}\n
ComponentView(component: Component, **kwargs: Any)\n
Bases:
View
Subclass of
Source code indjango.views.View
where theComponent
instance is available viaself.component
.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.ComponentsSettings","title":"ComponentsSettings","text":"def __init__(self, component: \"Component\", **kwargs: Any) -> None:\n super().__init__(**kwargs)\n self.component = component\n
Bases:
NamedTuple
Settings available for django_components.
Example:
COMPONENTS = ComponentsSettings(\n autodiscover=False,\n dirs = [BASE_DIR / \"components\"],\n)\n
Attributes:
-
app_dirs
(Optional[Sequence[str]]
) \u2013Specify the app-level directories that contain your components.
-
autodiscover
(Optional[bool]
) \u2013Toggle whether to run autodiscovery at the Django server startup.
-
context_behavior
(Optional[ContextBehaviorType]
) \u2013Configure whether, inside a component template, you can use variables from the outside
-
dirs
(Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]]
) \u2013Specify the directories that contain your components.
-
dynamic_component_name
(Optional[str]
) \u2013By default, the dynamic component
-
forbidden_static_files
(Optional[List[Union[str, Pattern]]]
) \u2013Deprecated. Use
-
libraries
(Optional[List[str]]
) \u2013Configure extra python modules that should be loaded.
-
multiline_tags
(Optional[bool]
) \u2013Enable / disable
-
reload_on_file_change
(Optional[bool]
) \u2013This is relevant if you are using the project structure where
-
reload_on_template_change
(Optional[bool]
) \u2013Deprecated. Use
-
static_files_allowed
(Optional[List[Union[str, Pattern]]]
) \u2013A list of file extensions (including the leading dot) that define which files within
-
static_files_forbidden
(Optional[List[Union[str, Pattern]]]
) \u2013A list of file extensions (including the leading dot) that define which files within
-
tag_formatter
(Optional[Union[TagFormatterABC, str]]
) \u2013Configure what syntax is used inside Django templates to render components.
-
template_cache_size
(Optional[int]
) \u2013Configure the maximum amount of Django templates to be cached.
class-attribute
instance-attribute
","text":"app_dirs: Optional[Sequence[str]] = None\n
Specify the app-level directories that contain your components.
Defaults to
[\"components\"]
. That is, for each Django app, we search<app>/components/
for components.The paths must be relative to app, e.g.:
COMPONENTS = ComponentsSettings(\n app_dirs=[\"my_comps\"],\n)\n
To search for
<app>/my_comps/
.These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.
Set to empty list to disable app-level components:
"},{"location":"reference/django_components/#django_components.ComponentsSettings.autodiscover","title":"autodiscoverCOMPONENTS = ComponentsSettings(\n app_dirs=[],\n)\n
class-attribute
instance-attribute
","text":"autodiscover: Optional[bool] = None\n
Toggle whether to run autodiscovery at the Django server startup.
Defaults to
True
"},{"location":"reference/django_components/#django_components.ComponentsSettings.context_behavior","title":"context_behaviorCOMPONENTS = ComponentsSettings(\n autodiscover=False,\n)\n
class-attribute
instance-attribute
","text":"context_behavior: Optional[ContextBehaviorType] = None\n
Configure whether, inside a component template, you can use variables from the outside (
\"django\"
) or not (\"isolated\"
). This also affects what variables are available inside the{% fill %}
tags.Also see Component context and scope.
Defaults to
\"django\"
.COMPONENTS = ComponentsSettings(\n context_behavior=\"isolated\",\n)\n
NOTE:
context_behavior
andslot_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
"},{"location":"reference/django_components/#django_components.ComponentsSettings.dirs","title":"dirs\"django\"
. See the rationale for change here.class-attribute
instance-attribute
","text":"dirs: Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]] = None\n
Specify the directories that contain your components.
Defaults to
[Path(settings.BASE_DIR) / \"components\"]
. That is, the rootcomponents/
app.Directories must be full paths, same as with STATICFILES_DIRS.
These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.
COMPONENTS = ComponentsSettings(\n dirs=[BASE_DIR / \"components\"],\n)\n
Set to empty list to disable global components directories:
"},{"location":"reference/django_components/#django_components.ComponentsSettings.dynamic_component_name","title":"dynamic_component_nameCOMPONENTS = ComponentsSettings(\n dirs=[],\n)\n
class-attribute
instance-attribute
","text":"dynamic_component_name: Optional[str] = None\n
By default, the dynamic component is registered under the name
\"dynamic\"
.In case of a conflict, you can use this setting to change the component name used for the dynamic components.
# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
"},{"location":"reference/django_components/#django_components.ComponentsSettings.forbidden_static_files","title":"forbidden_static_files{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
class-attribute
instance-attribute
","text":"forbidden_static_files: Optional[List[Union[str, Pattern]]] = None\n
Deprecated. Use
"},{"location":"reference/django_components/#django_components.ComponentsSettings.libraries","title":"librariesCOMPONENTS.static_files_forbidden
instead.class-attribute
instance-attribute
","text":"libraries: Optional[List[str]] = None\n
Configure extra python modules that should be loaded.
This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.
Expects a list of python module paths. Defaults to empty list.
Example:
COMPONENTS = ComponentsSettings(\n libraries=[\n \"mysite.components.forms\",\n \"mysite.components.buttons\",\n \"mysite.components.cards\",\n ],\n)\n
This would be the equivalent of importing these modules from within Django's
AppConfig.ready()
:
"},{"location":"reference/django_components/#django_components.ComponentsSettings.libraries--manually-loading-libraries","title":"Manually loading libraries","text":"class MyAppConfig(AppConfig):\n def ready(self):\n import \"mysite.components.forms\"\n import \"mysite.components.buttons\"\n import \"mysite.components.cards\"\n
In the rare case that you need to manually trigger the import of libraries, you can use the
import_libraries()
function:
"},{"location":"reference/django_components/#django_components.ComponentsSettings.multiline_tags","title":"multiline_tagsfrom django_components import import_libraries\n\nimport_libraries()\n
class-attribute
instance-attribute
","text":"multiline_tags: Optional[bool] = None\n
Enable / disable multiline support for template tags. If
True
, template tags like{% component %}
or{{ my_var }}
can span multiple lines.Defaults to
True
.Disable this setting if you are making custom modifications to Django's regular expression for parsing templates at
django.template.base.tag_re
.
"},{"location":"reference/django_components/#django_components.ComponentsSettings.reload_on_file_change","title":"reload_on_file_changeCOMPONENTS = ComponentsSettings(\n multiline_tags=False,\n)\n
class-attribute
instance-attribute
","text":"reload_on_file_change: Optional[bool] = None\n
This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.
Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.
The setting
reload_on_file_change
fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.If
True
, django_components configures Django to reload when files insideCOMPONENTS.dirs
orCOMPONENTS.app_dirs
change.See Reload dev server on component file changes.
Defaults to
False
.Warning
This setting should be enabled only for the dev environment!
"},{"location":"reference/django_components/#django_components.ComponentsSettings.reload_on_template_change","title":"reload_on_template_changeclass-attribute
instance-attribute
","text":"reload_on_template_change: Optional[bool] = None\n
Deprecated. Use
"},{"location":"reference/django_components/#django_components.ComponentsSettings.static_files_allowed","title":"static_files_allowedCOMPONENTS.reload_on_file_change
instead.class-attribute
instance-attribute
","text":"static_files_allowed: Optional[List[Union[str, Pattern]]] = None\n
A list of file extensions (including the leading dot) that define which files within
COMPONENTS.dirs
orCOMPONENTS.app_dirs
are treated as static files.If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running
collectstatic
, and can be accessed under the static file endpoint.You can also pass in compiled regexes (
re.Pattern
) for more advanced patterns.By default, JS, CSS, and common image and font file formats are considered static files:
COMPONENTS = ComponentsSettings(\n static_files_allowed=[\n \".css\",\n \".js\", \".jsx\", \".ts\", \".tsx\",\n # Images\n \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n \".jpeg\", \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n # Fonts\n \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n ],\n)\n
Warning
Exposing your Python files can be a security vulnerability. See Security notes.
"},{"location":"reference/django_components/#django_components.ComponentsSettings.static_files_forbidden","title":"static_files_forbiddenclass-attribute
instance-attribute
","text":"static_files_forbidden: Optional[List[Union[str, Pattern]]] = None\n
A list of file extensions (including the leading dot) that define which files within
COMPONENTS.dirs
orCOMPONENTS.app_dirs
will NEVER be treated as static files.If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in
static_files_allowed
.Use this setting together with
static_files_allowed
for a fine control over what file types will be exposed.You can also pass in compiled regexes (
re.Pattern
) for more advanced patterns.By default, any HTML and Python are considered NOT static files:
COMPONENTS = ComponentsSettings(\n static_files_forbidden=[\n \".html\", \".django\", \".dj\", \".tpl\",\n # Python files\n \".py\", \".pyc\",\n ],\n)\n
Warning
Exposing your Python files can be a security vulnerability. See Security notes.
"},{"location":"reference/django_components/#django_components.ComponentsSettings.tag_formatter","title":"tag_formatterclass-attribute
instance-attribute
","text":"tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n
Configure what syntax is used inside Django templates to render components. See the available tag formatters.
Defaults to
\"django_components.component_formatter\"
.Learn more about Customizing component tags with TagFormatter.
Can be set either as direct reference:
from django_components import component_formatter\n\nCOMPONENTS = ComponentsSettings(\n \"tag_formatter\": component_formatter\n)\n
Or as an import string;
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_formatter\"\n)\n
Examples:
-
\"django_components.component_formatter\"
Set
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_formatter\"\n)\n
To write components like this:
{% component \"button\" href=\"...\" %}\n Click me!\n{% endcomponent %}\n
-
django_components.component_shorthand_formatter
Set
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_shorthand_formatter\"\n)\n
To write components like this:
{% button href=\"...\" %}\n Click me!\n{% endbutton %}\n
class-attribute
instance-attribute
","text":"template_cache_size: Optional[int] = None\n
Configure the maximum amount of Django templates to be cached.
Defaults to
128
.Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's
lru_cache
decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding
Component.get_template()
to render many dynamic templates, you can increase this number.COMPONENTS = ComponentsSettings(\n template_cache_size=256,\n)\n
To remove the cache limit altogether and cache everything, set
template_cache_size
toNone
.COMPONENTS = ComponentsSettings(\n template_cache_size=None,\n)\n
If you want to add templates to the cache yourself, you can use
cached_template()
:
"},{"location":"reference/django_components/#django_components.ContextBehavior","title":"ContextBehavior","text":"from django_components import cached_template\n\ncached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n pass\n\ncached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n)\n
Bases:
str
,Enum
Configure how (and whether) the context is passed to the component fills and what variables are available inside the
{% fill %}
tags.Also see Component context and scope.
Options:
django
: With this setting, component fills behave as usual Django tags.isolated
: This setting makes the component fills behave similar to Vue or React.
Attributes:
-
DJANGO
\u2013With this setting, component fills behave as usual Django tags.
-
ISOLATED
\u2013This setting makes the component fills behave similar to Vue or React, where
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
Component.get_context_data()
are available to the component fill.
Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the
Component.get_context_data()
method{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
456 # my_var\nfeta # cheese\n
Because \"my_comp\" overrides the variable \"my_var\", so
{{ my_var }}
equals456
.And variable \"cheese\" will equal
"},{"location":"reference/django_components/#django_components.ContextBehavior.ISOLATED","title":"ISOLATEDfeta
, because the fill CAN access the current context.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
Component.get_context_data()
.Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the
get_context_data()
method{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
123 # my_var\n # cheese\n
Because both variables \"my_var\" and \"cheese\" are taken from the root context. Since \"cheese\" is not defined in root context, it's empty.
"},{"location":"reference/django_components/#django_components.DynamicComponent","title":"DynamicComponent","text":"DynamicComponent(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Component
This component is given a registered name or a reference to another component, and behaves as if the other component was in its place.
The args, kwargs, and slot fills are all passed down to the underlying component.
Parameters:
-
is
(str | Type[Component]
) \u2013Component that should be rendered. Either a registered name of a component, or a Component class directly. Required.
-
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to search for the registered name. If omitted, all registries are searched until the first match.
-
*args
\u2013Additional data passed to the component.
-
**kwargs
\u2013Additional data passed to the component.
Slots:
- Any slots, depending on the actual component.
Examples:
Django
{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Python
"},{"location":"reference/django_components/#django_components.DynamicComponent--use-cases","title":"Use cases","text":"from django_components import DynamicComponent\n\nDynamicComponent.render(\n kwargs={\n \"is\": table_comp,\n \"data\": table_data,\n \"headers\": table_headers,\n },\n slots={\n \"pagination\": PaginationComponent.render(\n render_dependencies=False,\n ),\n },\n)\n
Dynamic components are suitable if you are writing something like a form component. You may design it such that users give you a list of input types, and you render components depending on the input types.
While you could handle this with a series of if / else statements, that's not an extensible approach. Instead, you can use the dynamic component in place of normal components.
"},{"location":"reference/django_components/#django_components.DynamicComponent--component-name","title":"Component name","text":"By default, the dynamic component is registered under the name
\"dynamic\"
. In case of a conflict, you can set theCOMPONENTS.dynamic_component_name
setting to change the name used for the dynamic components.# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.DynamicComponent.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
class-attribute
instance-attribute
","text":"Media = ComponentMediaInput\n
Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/#django_components.DynamicComponent.css","title":"cssclass-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/#django_components.DynamicComponent.input","title":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/#django_components.DynamicComponent.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/#django_components.DynamicComponent.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/#django_components.DynamicComponent.media","title":"mediainstance-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.DynamicComponent.response_class","title":"response_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/#django_components.DynamicComponent.template_name","title":"template_namerender_to_response
class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/#django_components.DynamicComponent.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.DynamicComponent.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.DynamicComponent.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.DynamicComponent.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/#django_components.DynamicComponent.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.DynamicComponent.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.DynamicComponent.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.DynamicComponent.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.EmptyDict","title":"EmptyDict","text":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
Bases:
TypedDict
TypedDict with no members.
You can use this to define a Component that accepts NO kwargs, or NO slots, or returns NO data from
Component.get_context_data()
/Component.get_js_data()
/Component.get_css_data()
:Accepts NO kwargs:
from django_components import Component, EmptyDict\n\nclass Table(Component(Any, EmptyDict, Any, Any, Any, Any))\n ...\n
Accepts NO slots:
from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, EmptyDict, Any, Any, Any))\n ...\n
Returns NO data from
get_context_data()
:from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, Any, EmptyDict, Any, Any))\n ...\n
Going back to the example with NO kwargs, when you then call
Component.render()
orComponent.render_to_response()
, thekwargs
parameter will raise type error ifkwargs
is anything else than an empty dict.Table.render(\n kwargs: {},\n)\n
Omitting
kwargs
is also fine:Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
"},{"location":"reference/django_components/#django_components.NotRegistered","title":"NotRegistered","text":"Table.render(\n kwargs: {\n \"one\": 2,\n \"three\": 4,\n },\n)\n
Bases:
Exception
Raised when you try to access a Component, but it's NOT registered with given ComponentRegistry.
"},{"location":"reference/django_components/#django_components.RegistrySettings","title":"RegistrySettings","text":"Bases:
NamedTuple
Configuration for a
ComponentRegistry
.These settings define how the components registered with this registry will behave when rendered.
from django_components import ComponentRegistry, RegistrySettings\n\nregistry_settings = RegistrySettings(\n context_behavior=\"django\",\n tag_formatter=\"django_components.component_shorthand_formatter\",\n)\n\nregistry = ComponentRegistry(settings=registry_settings)\n
Attributes:
-
CONTEXT_BEHAVIOR
(Optional[ContextBehaviorType]
) \u2013Deprecated. Use
context_behavior
instead. Will be removed in v1. -
TAG_FORMATTER
(Optional[Union[TagFormatterABC, str]]
) \u2013Deprecated. Use
tag_formatter
instead. Will be removed in v1. -
context_behavior
(Optional[ContextBehaviorType]
) \u2013Same as the global
-
tag_formatter
(Optional[Union[TagFormatterABC, str]]
) \u2013Same as the global
class-attribute
instance-attribute
","text":"CONTEXT_BEHAVIOR: Optional[ContextBehaviorType] = None\n
Deprecated. Use
context_behavior
instead. Will be removed in v1.Same as the global
COMPONENTS.context_behavior
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/#django_components.RegistrySettings.TAG_FORMATTER","title":"TAG_FORMATTERCOMPONENTS.context_behavior
setting.class-attribute
instance-attribute
","text":"TAG_FORMATTER: Optional[Union[TagFormatterABC, str]] = None\n
Deprecated. Use
tag_formatter
instead. Will be removed in v1.Same as the global
COMPONENTS.tag_formatter
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/#django_components.RegistrySettings.context_behavior","title":"context_behaviorCOMPONENTS.tag_formatter
setting.class-attribute
instance-attribute
","text":"context_behavior: Optional[ContextBehaviorType] = None\n
Same as the global
COMPONENTS.context_behavior
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/#django_components.RegistrySettings.tag_formatter","title":"tag_formatterCOMPONENTS.context_behavior
setting.class-attribute
instance-attribute
","text":"tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n
Same as the global
COMPONENTS.tag_formatter
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/#django_components.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":"COMPONENTS.tag_formatter
setting.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:
"},{"location":"reference/django_components/#django_components.Slot","title":"Slot{% mycomp abc=123 / %}\n
dataclass
","text":"Slot(content_func: SlotFunc[TSlotData])\n
Bases:
Generic[TSlotData]
This class holds the slot content function along with related metadata.
"},{"location":"reference/django_components/#django_components.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
Source code in{{ my_lazy_slot }}
, it will output the contents of the slot.src/django_components/slots.py
"},{"location":"reference/django_components/#django_components.TagFormatterABC","title":"TagFormatterABC","text":"def __init__(self, slot: \"SlotNode\", context: Context):\n self._slot = slot\n self._context = context\n
Bases:
ABC
Abstract base class for defining custom tag formatters.
Tag formatters define how the component tags are used in the template.
Read more about Tag formatter.
For example, with the default tag formatter (
ComponentFormatter
), components are written as:{% component \"comp_name\" %}\n{% endcomponent %}\n
While with the shorthand tag formatter (
ShorthandComponentFormatter
), components are written as:{% comp_name %}\n{% endcomp_name %}\n
Example:
Implementation for
ShorthandComponentFormatter
:from djagno_components import TagFormatterABC, TagResult\n\nclass ShorthandComponentFormatter(TagFormatterABC):\n def start_tag(self, name: str) -> str:\n return name\n\n def end_tag(self, name: str) -> str:\n return f\"end{name}\"\n\n def parse(self, tokens: List[str]) -> TagResult:\n tokens = [*tokens]\n name = tokens.pop(0)\n return TagResult(name, tokens)\n
Methods:
-
end_tag
\u2013Formats the end tag of a block component.
-
parse
\u2013Given the tokens (words) passed to a component start tag, this function extracts
-
start_tag
\u2013Formats the start tag of a component.
abstractmethod
","text":"end_tag(name: str) -> str\n
Formats the end tag of a block component.
Parameters:
-
name
(str
) \u2013Component's registered name. Required.
Returns:
-
str
(str
) \u2013The formatted end tag.
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.TagFormatterABC.parse","title":"parse@abc.abstractmethod\ndef end_tag(self, name: str) -> str:\n \"\"\"\n Formats the end tag of a block component.\n\n Args:\n name (str): Component's registered name. Required.\n\n Returns:\n str: The formatted end tag.\n \"\"\"\n ...\n
abstractmethod
","text":"parse(tokens: List[str]) -> TagResult\n
Given the tokens (words) passed to a component start tag, this function extracts the component name from the tokens list, and returns
TagResult
, which is a tuple of(component_name, remaining_tokens)
.Parameters:
-
tokens
([List(str]
) \u2013List of tokens passed to the component tag.
Returns:
-
TagResult
(TagResult
) \u2013Parsed component name and remaining tokens.
Example:
Assuming we used a component in a template like this:
{% component \"my_comp\" key=val key2=val2 %}\n{% endcomponent %}\n
This function receives a list of tokens:
['component', '\"my_comp\"', 'key=val', 'key2=val2']\n
component
is the tag name, which we drop.\"my_comp\"
is the component name, but we must remove the extra quotes.- The remaining tokens we pass unmodified, as that's the input to the component.
So in the end, we return:
Source code inTagResult('my_comp', ['key=val', 'key2=val2'])\n
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.TagFormatterABC.start_tag","title":"start_tag@abc.abstractmethod\ndef parse(self, tokens: List[str]) -> TagResult:\n \"\"\"\n Given the tokens (words) passed to a component start tag, this function extracts\n the component name from the tokens list, and returns\n [`TagResult`](../api#django_components.TagResult),\n which is a tuple of `(component_name, remaining_tokens)`.\n\n Args:\n tokens [List(str]): List of tokens passed to the component tag.\n\n Returns:\n TagResult: Parsed component name and remaining tokens.\n\n **Example:**\n\n Assuming we used a component in a template like this:\n\n ```django\n {% component \"my_comp\" key=val key2=val2 %}\n {% endcomponent %}\n ```\n\n This function receives a list of tokens:\n\n ```python\n ['component', '\"my_comp\"', 'key=val', 'key2=val2']\n ```\n\n - `component` is the tag name, which we drop.\n - `\"my_comp\"` is the component name, but we must remove the extra quotes.\n - The remaining tokens we pass unmodified, as that's the input to the component.\n\n So in the end, we return:\n\n ```python\n TagResult('my_comp', ['key=val', 'key2=val2'])\n ```\n \"\"\"\n ...\n
abstractmethod
","text":"start_tag(name: str) -> str\n
Formats the start tag of a component.
Parameters:
-
name
(str
) \u2013Component's registered name. Required.
Returns:
-
str
(str
) \u2013The formatted start tag.
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.TagProtectedError","title":"TagProtectedError","text":"@abc.abstractmethod\ndef start_tag(self, name: str) -> str:\n \"\"\"\n Formats the start tag of a component.\n\n Args:\n name (str): Component's registered name. Required.\n\n Returns:\n str: The formatted start tag.\n \"\"\"\n ...\n
Bases:
Exception
The way the
TagFormatter
works is that, based on which start and end tags are used for rendering components, theComponentRegistry
behind the scenes un-/registers the template tags with the associated instance of Django'sLibrary
.In other words, if I have registered a component
\"table\"
, and I use the shorthand syntax:{% table ... %}\n{% endtable %}\n
Then
ComponentRegistry
registers the tagtable
onto the Django's Library instance.However, that means that if we registered a component
\"slot\"
, then we would overwrite the{% slot %}
tag from django_components.Thus, this exception is raised when a component is attempted to be registered under a forbidden name, such that it would overwrite one of django_component's own template tags.
"},{"location":"reference/django_components/#django_components.TagResult","title":"TagResult","text":"Bases:
NamedTuple
The return value from
TagFormatter.parse()
.Read more about Tag formatter.
Attributes:
-
component_name
(str
) \u2013Component name extracted from the template tag
-
tokens
(List[str]
) \u2013Remaining tokens (words) that were passed to the tag, with component name removed
instance-attribute
","text":"component_name: str\n
Component name extracted from the template tag
For example, if we had tag
{% component \"my_comp\" key=val key2=val2 %}\n
Then
"},{"location":"reference/django_components/#django_components.TagResult.tokens","title":"tokenscomponent_name
would bemy_comp
.instance-attribute
","text":"tokens: List[str]\n
Remaining tokens (words) that were passed to the tag, with component name removed
For example, if we had tag
{% component \"my_comp\" key=val key2=val2 %}\n
Then
"},{"location":"reference/django_components/#django_components.autodiscover","title":"autodiscover","text":"tokens
would be['key=val', 'key2=val2']
.autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Search for all python files in
COMPONENTS.dirs
andCOMPONENTS.app_dirs
and import them.See Autodiscovery.
Parameters:
-
map_module
(Callable[[str], str]
, default:None
) \u2013Map the module paths with
map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Returns:
-
List[str]
\u2013List[str]: A list of module paths of imported files.
To get the same list of modules that
autodiscover()
would return, but without importing them, useget_component_files()
:
Source code infrom django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
src/django_components/autodiscovery.py
"},{"location":"reference/django_components/#django_components.cached_template","title":"cached_template","text":"def autodiscover(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Search for all python files in\n [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n and\n [`COMPONENTS.app_dirs`](../settings#django_components.app_settings.ComponentsSettings.app_dirs)\n and import them.\n\n See [Autodiscovery](../../concepts/fundamentals/autodiscovery).\n\n Args:\n map_module (Callable[[str], str], optional): Map the module paths with `map_module` function.\\\n This serves as an escape hatch for when you need to use this function in tests.\n\n Returns:\n List[str]: A list of module paths of imported files.\n\n To get the same list of modules that `autodiscover()` would return, but without importing them, use\n [`get_component_files()`](../api#django_components.get_component_files):\n\n ```python\n from django_components import get_component_files\n\n modules = get_component_files(\".py\")\n ```\n \"\"\"\n modules = get_component_files(\".py\")\n logger.debug(f\"Autodiscover found {len(modules)} files in component directories.\")\n return _import_modules([entry.dot_path for entry in modules], map_module)\n
cached_template(\n template_string: str,\n template_cls: Optional[Type[Template]] = None,\n origin: Optional[Origin] = None,\n name: Optional[str] = None,\n engine: Optional[Any] = None,\n) -> Template\n
Create a Template instance that will be cached as per the
COMPONENTS.template_cache_size
setting.Parameters:
-
template_string
(str
) \u2013Template as a string, same as the first argument to Django's
Template
. Required. -
template_cls
(Type[Template]
, default:None
) \u2013Specify the Template class that should be instantiated. Defaults to Django's
Template
class. -
origin
(Type[Origin]
, default:None
) \u2013Sets
Template.Origin
. -
name
(Type[str]
, default:None
) \u2013Sets
Template.name
-
engine
(Type[Any]
, default:None
) \u2013Sets
Template.engine
Source code infrom django_components import cached_template\n\ntemplate = cached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n pass\n\ntemplate = cached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n)\n
src/django_components/template.py
"},{"location":"reference/django_components/#django_components.get_component_dirs","title":"get_component_dirs","text":"def cached_template(\n template_string: str,\n template_cls: Optional[Type[Template]] = None,\n origin: Optional[Origin] = None,\n name: Optional[str] = None,\n engine: Optional[Any] = None,\n) -> Template:\n \"\"\"\n Create a Template instance that will be cached as per the\n [`COMPONENTS.template_cache_size`](../settings#django_components.app_settings.ComponentsSettings.template_cache_size)\n setting.\n\n Args:\n template_string (str): Template as a string, same as the first argument to Django's\\\n [`Template`](https://docs.djangoproject.com/en/5.1/topics/templates/#template). Required.\n template_cls (Type[Template], optional): Specify the Template class that should be instantiated.\\\n Defaults to Django's [`Template`](https://docs.djangoproject.com/en/5.1/topics/templates/#template) class.\n origin (Type[Origin], optional): Sets \\\n [`Template.Origin`](https://docs.djangoproject.com/en/5.1/howto/custom-template-backend/#origin-api-and-3rd-party-integration).\n name (Type[str], optional): Sets `Template.name`\n engine (Type[Any], optional): Sets `Template.engine`\n\n ```python\n from django_components import cached_template\n\n template = cached_template(\"Variable: {{ variable }}\")\n\n # You can optionally specify Template class, and other Template inputs:\n class MyTemplate(Template):\n pass\n\n template = cached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n )\n ```\n \"\"\" # noqa: E501\n template = _create_template(template_cls or Template, template_string, engine)\n\n # Assign the origin and name separately, so the caching doesn't depend on them\n # Since we might be accessing a template from cache, we want to define these only once\n if not getattr(template, \"_dc_cached\", False):\n template.origin = origin or Origin(UNKNOWN_SOURCE)\n template.name = name\n template._dc_cached = True\n\n return template\n
get_component_dirs(include_apps: bool = True) -> List[Path]\n
Get directories that may contain component files.
This is the heart of all features that deal with filesystem and file lookup. Autodiscovery, Django template resolution, static file resolution - They all use this.
Parameters:
-
include_apps
(bool
, default:True
) \u2013Include directories from installed Django apps. Defaults to
True
.
Returns:
-
List[Path]
\u2013List[Path]: A list of directories that may contain component files.
get_component_dirs()
searches for dirs set inCOMPONENTS.dirs
settings. If none set, defaults to searching for a\"components\"
app.In addition to that, also all installed Django apps are checked whether they contain directories as set in
COMPONENTS.app_dirs
(e.g.[app]/components
).Notes:
-
Paths that do not point to directories are ignored.
-
BASE_DIR
setting is required. -
The paths in
COMPONENTS.dirs
must be absolute paths.
src/django_components/util/loader.py
"},{"location":"reference/django_components/#django_components.get_component_files","title":"get_component_files","text":"def get_component_dirs(include_apps: bool = True) -> List[Path]:\n \"\"\"\n Get directories that may contain component files.\n\n This is the heart of all features that deal with filesystem and file lookup.\n Autodiscovery, Django template resolution, static file resolution - They all use this.\n\n Args:\n include_apps (bool, optional): Include directories from installed Django apps.\\\n Defaults to `True`.\n\n Returns:\n List[Path]: A list of directories that may contain component files.\n\n `get_component_dirs()` searches for dirs set in\n [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n settings. If none set, defaults to searching for a `\"components\"` app.\n\n In addition to that, also all installed Django apps are checked whether they contain\n directories as set in\n [`COMPONENTS.app_dirs`](../settings#django_components.app_settings.ComponentsSettings.app_dirs)\n (e.g. `[app]/components`).\n\n **Notes:**\n\n - Paths that do not point to directories are ignored.\n\n - `BASE_DIR` setting is required.\n\n - The paths in [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n must be absolute paths.\n \"\"\"\n # Allow to configure from settings which dirs should be checked for components\n component_dirs = app_settings.DIRS\n\n # TODO_REMOVE_IN_V1\n raw_component_settings = getattr(settings, \"COMPONENTS\", {})\n if isinstance(raw_component_settings, dict):\n raw_dirs_value = raw_component_settings.get(\"dirs\", None)\n elif isinstance(raw_component_settings, ComponentsSettings):\n raw_dirs_value = raw_component_settings.dirs\n else:\n raw_dirs_value = None\n is_component_dirs_set = raw_dirs_value is not None\n is_legacy_paths = (\n # Use value of `STATICFILES_DIRS` ONLY if `COMPONENT.dirs` not set\n not is_component_dirs_set\n and hasattr(settings, \"STATICFILES_DIRS\")\n and settings.STATICFILES_DIRS\n )\n if is_legacy_paths:\n # NOTE: For STATICFILES_DIRS, we use the defaults even for empty list.\n # We don't do this for COMPONENTS.dirs, so user can explicitly specify \"NO dirs\".\n component_dirs = settings.STATICFILES_DIRS or [settings.BASE_DIR / \"components\"]\n # END TODO_REMOVE_IN_V1\n\n source = \"STATICFILES_DIRS\" if is_legacy_paths else \"COMPONENTS.dirs\"\n\n logger.debug(\n \"get_component_dirs will search for valid dirs from following options:\\n\"\n + \"\\n\".join([f\" - {str(d)}\" for d in component_dirs])\n )\n\n # Add `[app]/[APP_DIR]` to the directories. This is, by default `[app]/components`\n app_paths: List[Path] = []\n if include_apps:\n for conf in apps.get_app_configs():\n for app_dir in app_settings.APP_DIRS:\n comps_path = Path(conf.path).joinpath(app_dir)\n if comps_path.exists():\n app_paths.append(comps_path)\n\n directories: Set[Path] = set(app_paths)\n\n # Validate and add other values from the config\n for component_dir in component_dirs:\n # Consider tuples for STATICFILES_DIRS (See #489)\n # See https://docs.djangoproject.com/en/5.0/ref/settings/#prefixes-optional\n if isinstance(component_dir, (tuple, list)):\n component_dir = component_dir[1]\n try:\n Path(component_dir)\n except TypeError:\n logger.warning(\n f\"{source} expected str, bytes or os.PathLike object, or tuple/list of length 2. \"\n f\"See Django documentation for STATICFILES_DIRS. Got {type(component_dir)} : {component_dir}\"\n )\n continue\n\n if not Path(component_dir).is_absolute():\n raise ValueError(f\"{source} must contain absolute paths, got '{component_dir}'\")\n else:\n directories.add(Path(component_dir).resolve())\n\n logger.debug(\n \"get_component_dirs matched following template dirs:\\n\" + \"\\n\".join([f\" - {str(d)}\" for d in directories])\n )\n return list(directories)\n
get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]\n
Search for files within the component directories (as defined in
get_component_dirs()
).Requires
BASE_DIR
setting to be set.Parameters:
-
suffix
(Optional[str]
, default:None
) \u2013The suffix to search for. E.g.
.py
,.js
,.css
. Defaults toNone
, which will search for all files.
Returns:
-
List[ComponentFileEntry]
\u2013List[ComponentFileEntry] A list of entries that contain both the filesystem path and the python import path (dot path).
Example:
Source code infrom django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
src/django_components/util/loader.py
"},{"location":"reference/django_components/#django_components.import_libraries","title":"import_libraries","text":"def get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]:\n \"\"\"\n Search for files within the component directories (as defined in\n [`get_component_dirs()`](../api#django_components.get_component_dirs)).\n\n Requires `BASE_DIR` setting to be set.\n\n Args:\n suffix (Optional[str], optional): The suffix to search for. E.g. `.py`, `.js`, `.css`.\\\n Defaults to `None`, which will search for all files.\n\n Returns:\n List[ComponentFileEntry] A list of entries that contain both the filesystem path and \\\n the python import path (dot path).\n\n **Example:**\n\n ```python\n from django_components import get_component_files\n\n modules = get_component_files(\".py\")\n ```\n \"\"\"\n search_glob = f\"**/*{suffix}\" if suffix else \"**/*\"\n\n dirs = get_component_dirs(include_apps=False)\n component_filepaths = _search_dirs(dirs, search_glob)\n\n if hasattr(settings, \"BASE_DIR\") and settings.BASE_DIR:\n project_root = str(settings.BASE_DIR)\n else:\n # Fallback for getting the root dir, see https://stackoverflow.com/a/16413955/9788634\n project_root = os.path.abspath(os.path.dirname(__name__))\n\n # NOTE: We handle dirs from `COMPONENTS.dirs` and from individual apps separately.\n modules: List[ComponentFileEntry] = []\n\n # First let's handle the dirs from `COMPONENTS.dirs`\n #\n # Because for dirs in `COMPONENTS.dirs`, we assume they will be nested under `BASE_DIR`,\n # and that `BASE_DIR` is the current working dir (CWD). So the path relatively to `BASE_DIR`\n # is ALSO the python import path.\n for filepath in component_filepaths:\n module_path = _filepath_to_python_module(filepath, project_root, None)\n # Ignore files starting with dot `.` or files in dirs that start with dot.\n #\n # If any of the parts of the path start with a dot, e.g. the filesystem path\n # is `./abc/.def`, then this gets converted to python module as `abc..def`\n #\n # NOTE: This approach also ignores files:\n # - with two dots in the middle (ab..cd.py)\n # - an extra dot at the end (abcd..py)\n # - files outside of the parent component (../abcd.py).\n # But all these are NOT valid python modules so that's fine.\n if \"..\" in module_path:\n continue\n\n entry = ComponentFileEntry(dot_path=module_path, filepath=filepath)\n modules.append(entry)\n\n # For for apps, the directories may be outside of the project, e.g. in case of third party\n # apps. So we have to resolve the python import path relative to the package name / the root\n # import path for the app.\n # See https://github.com/EmilStenstrom/django-components/issues/669\n for conf in apps.get_app_configs():\n for app_dir in app_settings.APP_DIRS:\n comps_path = Path(conf.path).joinpath(app_dir)\n if not comps_path.exists():\n continue\n app_component_filepaths = _search_dirs([comps_path], search_glob)\n for filepath in app_component_filepaths:\n app_component_module = _filepath_to_python_module(filepath, conf.path, conf.name)\n entry = ComponentFileEntry(dot_path=app_component_module, filepath=filepath)\n modules.append(entry)\n\n return modules\n
import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Import modules set in
COMPONENTS.libraries
setting.See Autodiscovery.
Parameters:
-
map_module
(Callable[[str], str]
, default:None
) \u2013Map the module paths with
map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Returns:
-
List[str]
\u2013List[str]: A list of module paths of imported files.
Examples:
Normal usage - load libraries after Django has loaded
from django_components import import_libraries\n\nclass MyAppConfig(AppConfig):\n def ready(self):\n import_libraries()\n
Potential usage in tests
Source code infrom django_components import import_libraries\n\nimport_libraries(lambda path: path.replace(\"tests.\", \"myapp.\"))\n
src/django_components/autodiscovery.py
"},{"location":"reference/django_components/#django_components.register","title":"register","text":"def import_libraries(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Import modules set in\n [`COMPONENTS.libraries`](../settings#django_components.app_settings.ComponentsSettings.libraries)\n setting.\n\n See [Autodiscovery](../../concepts/fundamentals/autodiscovery).\n\n Args:\n map_module (Callable[[str], str], optional): Map the module paths with `map_module` function.\\\n This serves as an escape hatch for when you need to use this function in tests.\n\n Returns:\n List[str]: A list of module paths of imported files.\n\n **Examples:**\n\n Normal usage - load libraries after Django has loaded\n ```python\n from django_components import import_libraries\n\n class MyAppConfig(AppConfig):\n def ready(self):\n import_libraries()\n ```\n\n Potential usage in tests\n ```python\n from django_components import import_libraries\n\n import_libraries(lambda path: path.replace(\"tests.\", \"myapp.\"))\n ```\n \"\"\"\n from django_components.app_settings import app_settings\n\n return _import_modules(app_settings.LIBRARIES, map_module)\n
register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[\n [Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]]],\n Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]],\n]\n
Class decorator for registering a component to a component registry.
See Registering components.
Parameters:
-
name
(str
) \u2013Registered name. This is the name by which the component will be accessed from within a template when using the
{% component %}
tag. Required. -
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to which to register this component. If omitted, component is registered to the default registry.
Raises:
-
AlreadyRegistered
\u2013If there is already a component registered under the same name.
Examples:
from django_components import Component, register\n\n@register(\"my_component\")\nclass MyComponent(Component):\n ...\n
Specifing
ComponentRegistry
the component should be registered to by setting theregistry
kwarg:
Source code infrom django.template import Library\nfrom django_components import Component, ComponentRegistry, register\n\nmy_lib = Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n ...\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.render_dependencies","title":"render_dependencies","text":"def register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[\n [Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"]],\n Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"],\n]:\n \"\"\"\n Class decorator for registering a [component](./#django_components.Component)\n to a [component registry](./#django_components.ComponentRegistry).\n\n See [Registering components](../../concepts/advanced/component_registry).\n\n Args:\n name (str): Registered name. This is the name by which the component will be accessed\\\n from within a template when using the [`{% component %}`](../template_tags#component) tag. Required.\n registry (ComponentRegistry, optional): Specify the [registry](./#django_components.ComponentRegistry)\\\n to which to register this component. If omitted, component is registered to the default registry.\n\n Raises:\n AlreadyRegistered: If there is already a component registered under the same name.\n\n **Examples**:\n\n ```python\n from django_components import Component, register\n\n @register(\"my_component\")\n class MyComponent(Component):\n ...\n ```\n\n Specifing [`ComponentRegistry`](./#django_components.ComponentRegistry) the component\n should be registered to by setting the `registry` kwarg:\n\n ```python\n from django.template import Library\n from django_components import Component, ComponentRegistry, register\n\n my_lib = 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(\n component: Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"],\n ) -> Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"]:\n registry.register(name=name, component=component)\n return component\n\n return decorator\n
render_dependencies(content: TContent, type: RenderType = 'document') -> TContent\n
Given a string that contains parts that were rendered by components, this function inserts all used JS and CSS.
By default, the string is parsed as an HTML and: - CSS is inserted at the end of
<head>
(if present) - JS is inserted at the end of<body>
(if present)If you used
{% component_js_dependencies %}
or{% component_css_dependencies %}
, then the JS and CSS will be inserted only at these locations.Example:
Source code indef my_view(request):\n template = Template('''\n {% load components %}\n <!doctype html>\n <html>\n <head></head>\n <body>\n <h1>{{ table_name }}</h1>\n {% component \"table\" name=table_name / %}\n </body>\n </html>\n ''')\n\n html = template.render(\n Context({\n \"table_name\": request.GET[\"name\"],\n })\n )\n\n # This inserts components' JS and CSS\n processed_html = render_dependencies(html)\n\n return HttpResponse(processed_html)\n
src/django_components/dependencies.py
"},{"location":"reference/django_components/#django_components.app_settings","title":"app_settings","text":"def render_dependencies(content: TContent, type: RenderType = \"document\") -> TContent:\n \"\"\"\n Given a string that contains parts that were rendered by components,\n this function inserts all used JS and CSS.\n\n By default, the string is parsed as an HTML and:\n - CSS is inserted at the end of `<head>` (if present)\n - JS is inserted at the end of `<body>` (if present)\n\n If you used `{% component_js_dependencies %}` or `{% component_css_dependencies %}`,\n then the JS and CSS will be inserted only at these locations.\n\n Example:\n ```python\n def my_view(request):\n template = Template('''\n {% load components %}\n <!doctype html>\n <html>\n <head></head>\n <body>\n <h1>{{ table_name }}</h1>\n {% component \"table\" name=table_name / %}\n </body>\n </html>\n ''')\n\n html = template.render(\n Context({\n \"table_name\": request.GET[\"name\"],\n })\n )\n\n # This inserts components' JS and CSS\n processed_html = render_dependencies(html)\n\n return HttpResponse(processed_html)\n ```\n \"\"\"\n is_safestring = isinstance(content, SafeString)\n\n if isinstance(content, str):\n content_ = content.encode()\n else:\n content_ = cast(bytes, content)\n\n content_, js_dependencies, css_dependencies = _process_dep_declarations(content_, type)\n\n # Replace the placeholders with the actual content\n did_find_js_placeholder = False\n did_find_css_placeholder = False\n\n def on_replace_match(match: \"re.Match[bytes]\") -> bytes:\n nonlocal did_find_css_placeholder\n nonlocal did_find_js_placeholder\n\n if match[0] == CSS_PLACEHOLDER_BYTES:\n replacement = css_dependencies\n did_find_css_placeholder = True\n elif match[0] == JS_PLACEHOLDER_BYTES:\n replacement = js_dependencies\n did_find_js_placeholder = True\n else:\n raise RuntimeError(\n \"Unexpected error: Regex for component dependencies processing\"\n f\" matched unknown string '{match[0].decode()}'\"\n )\n return replacement\n\n content_ = PLACEHOLDER_REGEX.sub(on_replace_match, content_)\n\n # By default, if user didn't specify any `{% component_dependencies %}`,\n # then try to insert the JS scripts at the end of <body> and CSS sheets at the end\n # of <head>\n if type == \"document\" and (not did_find_js_placeholder or not did_find_css_placeholder):\n tree = parse_document_or_nodes(content_.decode())\n\n if isinstance(tree, LexborHTMLParser):\n did_modify_html = False\n\n if not did_find_css_placeholder and tree.head:\n css_elems = parse_multiroot_html(css_dependencies.decode())\n for css_elem in css_elems:\n tree.head.insert_child(css_elem) # type: ignore # TODO: Update to selectolax 0.3.25\n did_modify_html = True\n\n if not did_find_js_placeholder and tree.body:\n js_elems = parse_multiroot_html(js_dependencies.decode())\n for js_elem in js_elems:\n tree.body.insert_child(js_elem) # type: ignore # TODO: Update to selectolax 0.3.25\n did_modify_html = True\n\n transformed = cast(str, tree.html)\n if did_modify_html:\n content_ = transformed.encode()\n\n # Return the same type as we were given\n output = content_.decode() if isinstance(content, str) else content_\n output = mark_safe(output) if is_safestring else output\n return cast(TContent, output)\n
Classes:
-
ComponentsSettings
\u2013Settings available for django_components.
-
ContextBehavior
\u2013Configure how (and whether) the context is passed to the component fills
Bases:
NamedTuple
Settings available for django_components.
Example:
COMPONENTS = ComponentsSettings(\n autodiscover=False,\n dirs = [BASE_DIR / \"components\"],\n)\n
Attributes:
-
app_dirs
(Optional[Sequence[str]]
) \u2013Specify the app-level directories that contain your components.
-
autodiscover
(Optional[bool]
) \u2013Toggle whether to run autodiscovery at the Django server startup.
-
context_behavior
(Optional[ContextBehaviorType]
) \u2013Configure whether, inside a component template, you can use variables from the outside
-
dirs
(Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]]
) \u2013Specify the directories that contain your components.
-
dynamic_component_name
(Optional[str]
) \u2013By default, the dynamic component
-
forbidden_static_files
(Optional[List[Union[str, Pattern]]]
) \u2013Deprecated. Use
-
libraries
(Optional[List[str]]
) \u2013Configure extra python modules that should be loaded.
-
multiline_tags
(Optional[bool]
) \u2013Enable / disable
-
reload_on_file_change
(Optional[bool]
) \u2013This is relevant if you are using the project structure where
-
reload_on_template_change
(Optional[bool]
) \u2013Deprecated. Use
-
static_files_allowed
(Optional[List[Union[str, Pattern]]]
) \u2013A list of file extensions (including the leading dot) that define which files within
-
static_files_forbidden
(Optional[List[Union[str, Pattern]]]
) \u2013A list of file extensions (including the leading dot) that define which files within
-
tag_formatter
(Optional[Union[TagFormatterABC, str]]
) \u2013Configure what syntax is used inside Django templates to render components.
-
template_cache_size
(Optional[int]
) \u2013Configure the maximum amount of Django templates to be cached.
class-attribute
instance-attribute
","text":"app_dirs: Optional[Sequence[str]] = None\n
Specify the app-level directories that contain your components.
Defaults to
[\"components\"]
. That is, for each Django app, we search<app>/components/
for components.The paths must be relative to app, e.g.:
COMPONENTS = ComponentsSettings(\n app_dirs=[\"my_comps\"],\n)\n
To search for
<app>/my_comps/
.These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.
Set to empty list to disable app-level components:
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.autodiscover","title":"autodiscoverCOMPONENTS = ComponentsSettings(\n app_dirs=[],\n)\n
class-attribute
instance-attribute
","text":"autodiscover: Optional[bool] = None\n
Toggle whether to run autodiscovery at the Django server startup.
Defaults to
True
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.context_behavior","title":"context_behaviorCOMPONENTS = ComponentsSettings(\n autodiscover=False,\n)\n
class-attribute
instance-attribute
","text":"context_behavior: Optional[ContextBehaviorType] = None\n
Configure whether, inside a component template, you can use variables from the outside (
\"django\"
) or not (\"isolated\"
). This also affects what variables are available inside the{% fill %}
tags.Also see Component context and scope.
Defaults to
\"django\"
.COMPONENTS = ComponentsSettings(\n context_behavior=\"isolated\",\n)\n
NOTE:
context_behavior
andslot_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
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.dirs","title":"dirs\"django\"
. See the rationale for change here.class-attribute
instance-attribute
","text":"dirs: Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]] = None\n
Specify the directories that contain your components.
Defaults to
[Path(settings.BASE_DIR) / \"components\"]
. That is, the rootcomponents/
app.Directories must be full paths, same as with STATICFILES_DIRS.
These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.
COMPONENTS = ComponentsSettings(\n dirs=[BASE_DIR / \"components\"],\n)\n
Set to empty list to disable global components directories:
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.dynamic_component_name","title":"dynamic_component_nameCOMPONENTS = ComponentsSettings(\n dirs=[],\n)\n
class-attribute
instance-attribute
","text":"dynamic_component_name: Optional[str] = None\n
By default, the dynamic component is registered under the name
\"dynamic\"
.In case of a conflict, you can use this setting to change the component name used for the dynamic components.
# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.forbidden_static_files","title":"forbidden_static_files{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
class-attribute
instance-attribute
","text":"forbidden_static_files: Optional[List[Union[str, Pattern]]] = None\n
Deprecated. Use
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.libraries","title":"librariesCOMPONENTS.static_files_forbidden
instead.class-attribute
instance-attribute
","text":"libraries: Optional[List[str]] = None\n
Configure extra python modules that should be loaded.
This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.
Expects a list of python module paths. Defaults to empty list.
Example:
COMPONENTS = ComponentsSettings(\n libraries=[\n \"mysite.components.forms\",\n \"mysite.components.buttons\",\n \"mysite.components.cards\",\n ],\n)\n
This would be the equivalent of importing these modules from within Django's
AppConfig.ready()
:
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.libraries--manually-loading-libraries","title":"Manually loading libraries","text":"class MyAppConfig(AppConfig):\n def ready(self):\n import \"mysite.components.forms\"\n import \"mysite.components.buttons\"\n import \"mysite.components.cards\"\n
In the rare case that you need to manually trigger the import of libraries, you can use the
import_libraries()
function:
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.multiline_tags","title":"multiline_tagsfrom django_components import import_libraries\n\nimport_libraries()\n
class-attribute
instance-attribute
","text":"multiline_tags: Optional[bool] = None\n
Enable / disable multiline support for template tags. If
True
, template tags like{% component %}
or{{ my_var }}
can span multiple lines.Defaults to
True
.Disable this setting if you are making custom modifications to Django's regular expression for parsing templates at
django.template.base.tag_re
.
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.reload_on_file_change","title":"reload_on_file_changeCOMPONENTS = ComponentsSettings(\n multiline_tags=False,\n)\n
class-attribute
instance-attribute
","text":"reload_on_file_change: Optional[bool] = None\n
This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.
Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.
The setting
reload_on_file_change
fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.If
True
, django_components configures Django to reload when files insideCOMPONENTS.dirs
orCOMPONENTS.app_dirs
change.See Reload dev server on component file changes.
Defaults to
False
.Warning
This setting should be enabled only for the dev environment!
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.reload_on_template_change","title":"reload_on_template_changeclass-attribute
instance-attribute
","text":"reload_on_template_change: Optional[bool] = None\n
Deprecated. Use
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.static_files_allowed","title":"static_files_allowedCOMPONENTS.reload_on_file_change
instead.class-attribute
instance-attribute
","text":"static_files_allowed: Optional[List[Union[str, Pattern]]] = None\n
A list of file extensions (including the leading dot) that define which files within
COMPONENTS.dirs
orCOMPONENTS.app_dirs
are treated as static files.If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running
collectstatic
, and can be accessed under the static file endpoint.You can also pass in compiled regexes (
re.Pattern
) for more advanced patterns.By default, JS, CSS, and common image and font file formats are considered static files:
COMPONENTS = ComponentsSettings(\n static_files_allowed=[\n \".css\",\n \".js\", \".jsx\", \".ts\", \".tsx\",\n # Images\n \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n \".jpeg\", \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n # Fonts\n \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n ],\n)\n
Warning
Exposing your Python files can be a security vulnerability. See Security notes.
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.static_files_forbidden","title":"static_files_forbiddenclass-attribute
instance-attribute
","text":"static_files_forbidden: Optional[List[Union[str, Pattern]]] = None\n
A list of file extensions (including the leading dot) that define which files within
COMPONENTS.dirs
orCOMPONENTS.app_dirs
will NEVER be treated as static files.If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in
static_files_allowed
.Use this setting together with
static_files_allowed
for a fine control over what file types will be exposed.You can also pass in compiled regexes (
re.Pattern
) for more advanced patterns.By default, any HTML and Python are considered NOT static files:
COMPONENTS = ComponentsSettings(\n static_files_forbidden=[\n \".html\", \".django\", \".dj\", \".tpl\",\n # Python files\n \".py\", \".pyc\",\n ],\n)\n
Warning
Exposing your Python files can be a security vulnerability. See Security notes.
"},{"location":"reference/django_components/#django_components.app_settings.ComponentsSettings.tag_formatter","title":"tag_formatterclass-attribute
instance-attribute
","text":"tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n
Configure what syntax is used inside Django templates to render components. See the available tag formatters.
Defaults to
\"django_components.component_formatter\"
.Learn more about Customizing component tags with TagFormatter.
Can be set either as direct reference:
from django_components import component_formatter\n\nCOMPONENTS = ComponentsSettings(\n \"tag_formatter\": component_formatter\n)\n
Or as an import string;
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_formatter\"\n)\n
Examples:
-
\"django_components.component_formatter\"
Set
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_formatter\"\n)\n
To write components like this:
{% component \"button\" href=\"...\" %}\n Click me!\n{% endcomponent %}\n
-
django_components.component_shorthand_formatter
Set
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_shorthand_formatter\"\n)\n
To write components like this:
{% button href=\"...\" %}\n Click me!\n{% endbutton %}\n
class-attribute
instance-attribute
","text":"template_cache_size: Optional[int] = None\n
Configure the maximum amount of Django templates to be cached.
Defaults to
128
.Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's
lru_cache
decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding
Component.get_template()
to render many dynamic templates, you can increase this number.COMPONENTS = ComponentsSettings(\n template_cache_size=256,\n)\n
To remove the cache limit altogether and cache everything, set
template_cache_size
toNone
.COMPONENTS = ComponentsSettings(\n template_cache_size=None,\n)\n
If you want to add templates to the cache yourself, you can use
cached_template()
:
"},{"location":"reference/django_components/#django_components.app_settings.ContextBehavior","title":"ContextBehavior","text":"from django_components import cached_template\n\ncached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n pass\n\ncached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n)\n
Bases:
str
,Enum
Configure how (and whether) the context is passed to the component fills and what variables are available inside the
{% fill %}
tags.Also see Component context and scope.
Options:
django
: With this setting, component fills behave as usual Django tags.isolated
: This setting makes the component fills behave similar to Vue or React.
Attributes:
-
DJANGO
\u2013With this setting, component fills behave as usual Django tags.
-
ISOLATED
\u2013This setting makes the component fills behave similar to Vue or React, where
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
Component.get_context_data()
are available to the component fill.
Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the
Component.get_context_data()
method{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
456 # my_var\nfeta # cheese\n
Because \"my_comp\" overrides the variable \"my_var\", so
{{ my_var }}
equals456
.And variable \"cheese\" will equal
"},{"location":"reference/django_components/#django_components.app_settings.ContextBehavior.ISOLATED","title":"ISOLATEDfeta
, because the fill CAN access the current context.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
Component.get_context_data()
.Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the
get_context_data()
method{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
123 # my_var\n # cheese\n
Because both variables \"my_var\" and \"cheese\" are taken from the root context. Since \"cheese\" is not defined in root context, it's empty.
"},{"location":"reference/django_components/#django_components.attributes","title":"attributes","text":"Functions:
-
append_attributes
\u2013Merges the key-value pairs and returns a new dictionary.
-
attributes_to_string
\u2013Convert a dict of attributes to a string.
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 insrc/django_components/attributes.py
"},{"location":"reference/django_components/#django_components.attributes.attributes_to_string","title":"attributes_to_string","text":"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
attributes_to_string(attributes: Mapping[str, Any]) -> str\n
Convert a dict of attributes to a string.
Source code insrc/django_components/attributes.py
"},{"location":"reference/django_components/#django_components.autodiscovery","title":"autodiscovery","text":"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
Functions:
-
autodiscover
\u2013Search for all python files in
-
import_libraries
\u2013Import modules set in
autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Search for all python files in
COMPONENTS.dirs
andCOMPONENTS.app_dirs
and import them.See Autodiscovery.
Parameters:
-
map_module
(Callable[[str], str]
, default:None
) \u2013Map the module paths with
map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Returns:
-
List[str]
\u2013List[str]: A list of module paths of imported files.
To get the same list of modules that
autodiscover()
would return, but without importing them, useget_component_files()
:
Source code infrom django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
src/django_components/autodiscovery.py
"},{"location":"reference/django_components/#django_components.autodiscovery.import_libraries","title":"import_libraries","text":"def autodiscover(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Search for all python files in\n [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n and\n [`COMPONENTS.app_dirs`](../settings#django_components.app_settings.ComponentsSettings.app_dirs)\n and import them.\n\n See [Autodiscovery](../../concepts/fundamentals/autodiscovery).\n\n Args:\n map_module (Callable[[str], str], optional): Map the module paths with `map_module` function.\\\n This serves as an escape hatch for when you need to use this function in tests.\n\n Returns:\n List[str]: A list of module paths of imported files.\n\n To get the same list of modules that `autodiscover()` would return, but without importing them, use\n [`get_component_files()`](../api#django_components.get_component_files):\n\n ```python\n from django_components import get_component_files\n\n modules = get_component_files(\".py\")\n ```\n \"\"\"\n modules = get_component_files(\".py\")\n logger.debug(f\"Autodiscover found {len(modules)} files in component directories.\")\n return _import_modules([entry.dot_path for entry in modules], map_module)\n
import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Import modules set in
COMPONENTS.libraries
setting.See Autodiscovery.
Parameters:
-
map_module
(Callable[[str], str]
, default:None
) \u2013Map the module paths with
map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Returns:
-
List[str]
\u2013List[str]: A list of module paths of imported files.
Examples:
Normal usage - load libraries after Django has loaded
from django_components import import_libraries\n\nclass MyAppConfig(AppConfig):\n def ready(self):\n import_libraries()\n
Potential usage in tests
Source code infrom django_components import import_libraries\n\nimport_libraries(lambda path: path.replace(\"tests.\", \"myapp.\"))\n
src/django_components/autodiscovery.py
"},{"location":"reference/django_components/#django_components.component","title":"component","text":"def import_libraries(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Import modules set in\n [`COMPONENTS.libraries`](../settings#django_components.app_settings.ComponentsSettings.libraries)\n setting.\n\n See [Autodiscovery](../../concepts/fundamentals/autodiscovery).\n\n Args:\n map_module (Callable[[str], str], optional): Map the module paths with `map_module` function.\\\n This serves as an escape hatch for when you need to use this function in tests.\n\n Returns:\n List[str]: A list of module paths of imported files.\n\n **Examples:**\n\n Normal usage - load libraries after Django has loaded\n ```python\n from django_components import import_libraries\n\n class MyAppConfig(AppConfig):\n def ready(self):\n import_libraries()\n ```\n\n Potential usage in tests\n ```python\n from django_components import import_libraries\n\n import_libraries(lambda path: path.replace(\"tests.\", \"myapp.\"))\n ```\n \"\"\"\n from django_components.app_settings import app_settings\n\n return _import_modules(app_settings.LIBRARIES, map_module)\n
Classes:
-
Component
\u2013 -
ComponentNode
\u2013Django.template.Node subclass that renders a django-components component
-
ComponentVars
\u2013Type for the variables available inside the component templates.
-
ComponentView
\u2013Subclass of
django.views.View
where theComponent
instance is available
Component(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Generic[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template
(Optional[Union[str, Template]]
) \u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.Component.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
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":"cssclass-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":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/#django_components.component.Component.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/#django_components.component.Component.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.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":"mediainstance-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_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/#django_components.component.Component.template","title":"templaterender_to_response
class-attribute
instance-attribute
","text":"template: Optional[Union[str, Template]] = None\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
"},{"location":"reference/django_components/#django_components.component.Component.template_name","title":"template_nametemplate_name
,get_template_name
,template
orget_template
must be defined.class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/#django_components.component.Component.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.Component.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.Component.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.Component.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.Component.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.Component.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.Component.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.Component.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.ComponentNode","title":"ComponentNode","text":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
ComponentNode(\n name: str,\n args: List[Expression],\n kwargs: RuntimeKwargs,\n registry: ComponentRegistry,\n isolated_context: bool = False,\n nodelist: Optional[NodeList] = None,\n node_id: Optional[str] = None,\n)\n
Bases:
BaseNode
Django.template.Node subclass that renders a django-components component
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.component.ComponentVars","title":"ComponentVars","text":"def __init__(\n self,\n name: str,\n args: List[Expression],\n kwargs: RuntimeKwargs,\n registry: ComponentRegistry, # noqa F811\n isolated_context: bool = False,\n nodelist: Optional[NodeList] = None,\n node_id: Optional[str] = None,\n) -> None:\n super().__init__(nodelist=nodelist or NodeList(), args=args, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.isolated_context = isolated_context\n self.registry = registry\n
Bases:
NamedTuple
Type for the variables available inside the component templates.
All variables here are scoped under
component_vars.
, so e.g. attributeis_filled
on this class is accessible inside the template as:{{ component_vars.is_filled }}\n
Attributes:
-
is_filled
(Dict[str, bool]
) \u2013Dictonary describing which component slots are filled (
True
) or are not (False
).
instance-attribute
","text":"is_filled: Dict[str, bool]\n
Dictonary describing which component slots are filled (
True
) or are not (False
).New in version 0.70
Use as
{{ component_vars.is_filled }}
Example:
"},{"location":"reference/django_components/#django_components.component.ComponentView","title":"ComponentView","text":"{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n <div class=\"slot-wrapper\">\n {% slot \"my_slot\" / %}\n </div>\n{% endif %}\n
ComponentView(component: Component, **kwargs: Any)\n
Bases:
View
Subclass of
Source code indjango.views.View
where theComponent
instance is available viaself.component
.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.component_media","title":"component_media","text":"def __init__(self, component: \"Component\", **kwargs: Any) -> None:\n super().__init__(**kwargs)\n self.component = component\n
Classes:
-
ComponentMediaInput
\u2013Defines JS and CSS media files associated with this component.
-
MediaMeta
\u2013Metaclass for handling media files for components.
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 ofMedia
attribute to define associated JS/CSS files, which are then available undermedia
attribute as a instance ofMedia
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
E.g. if in a directory
my_comp
you havescript.js
andmy_comp.py
, andmy_comp.py
looks like this:class MyComponent(Component):\n class Media:\n js = \"script.js\"\n
Then
"},{"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":"script.js
will be resolved asmy_comp/script.js
.E.g.:
"},{"location":"reference/django_components/#django_components.component_media.MediaMeta--4-subclass-media-class-with-media_class","title":"4. Subclassdef 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
Media
class withmedia_class
","text":"Normal
MediaDefiningClass
creates an instance ofMedia
class under themedia
attribute. This class allows to override which class will be instantiated withmedia_class
attribute:
"},{"location":"reference/django_components/#django_components.component_registry","title":"component_registry","text":"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
Classes:
-
AlreadyRegistered
\u2013Raised when you try to register a Component,
-
ComponentRegistry
\u2013Manages components and makes them available
-
NotRegistered
\u2013Raised when you try to access a Component,
-
RegistrySettings
\u2013Configuration for a
ComponentRegistry
.
Functions:
-
register
\u2013Class decorator for registering a component
Attributes:
-
registry
(ComponentRegistry
) \u2013The default and global component registry.
module-attribute
","text":"registry: ComponentRegistry = ComponentRegistry()\n
The default and global component registry. Use this instance to directly register or remove components:
See Registering components.
"},{"location":"reference/django_components/#django_components.component_registry.AlreadyRegistered","title":"AlreadyRegistered","text":"# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get single\nregistry.get(\"button\")\n\n# Get all\nregistry.all()\n\n# Unregister single\nregistry.unregister(\"button\")\n\n# Unregister all\nregistry.clear()\n
Bases:
Exception
Raised when you try to register a Component, but it's already registered with given ComponentRegistry.
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry","title":"ComponentRegistry","text":"ComponentRegistry(\n library: Optional[Library] = None, settings: Optional[Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]] = None\n)\n
Manages components and makes them available in the template, by default as
{% component %}
tags.{% component \"my_comp\" key=value %}\n{% endcomponent %}\n
To enable a component to be used in a template, the component must be registered with a component registry.
When you register a component to a registry, behind the scenes the registry automatically adds the component's template tag (e.g.
{% component %}
to theLibrary
. And the opposite happens when you unregister a component - the tag is removed.See Registering components.
Parameters:
-
library
(Library
, default:None
) \u2013Django
Library
associated with this registry. If omitted, the default Library instance from django_components is used. -
settings
(Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]
, default:None
) \u2013Configure how the components registered with this registry will behave when rendered. See
RegistrySettings
. Can be either a static value or a callable that returns the settings. If omitted, the settings fromCOMPONENTS
are used.
Notes:
- The default registry is available as
django_components.registry
. - The default registry is used when registering components with
@register
decorator.
Example:
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry--using-registry-to-share-components","title":"Using registry to share components","text":"# 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
You can use component registry for isolating or \"packaging\" components:
-
Create new instance of
ComponentRegistry
and Library:my_comps = Library()\nmy_comps_reg = ComponentRegistry(library=my_comps)\n
-
Register components to the registry:
my_comps_reg.register(\"my_button\", ButtonComponent)\nmy_comps_reg.register(\"my_card\", CardComponent)\n
-
In your target project, load the Library associated with the registry:
{% load my_comps %}\n
-
Use the registered components in your templates:
{% component \"button\" %}\n{% endcomponent %}\n
Methods:
-
all
\u2013Retrieve all registered
Component
classes. -
clear
\u2013Clears the registry, unregistering all components.
-
get
\u2013Retrieve a
Component
-
register
\u2013Register a
Component
class -
unregister
\u2013Unregister the
Component
class
Attributes:
-
library
(Library
) \u2013The template tag
Library
-
settings
(InternalRegistrySettings
) \u2013Registry settings configured for this registry.
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.library","title":"librarydef __init__(\n self,\n library: Optional[Library] = None,\n settings: Optional[Union[RegistrySettings, Callable[[\"ComponentRegistry\"], RegistrySettings]]] = None,\n) -> None:\n self._registry: Dict[str, ComponentRegistryEntry] = {} # component name -> component_entry mapping\n self._tags: Dict[str, Set[str]] = {} # tag -> list[component names]\n self._library = library\n self._settings_input = settings\n self._settings: Optional[Callable[[], InternalRegistrySettings]] = None\n\n all_registries.append(self)\n
property
","text":"library: Library\n
The template tag
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.settings","title":"settingsLibrary
that is associated with the registry.property
","text":"settings: InternalRegistrySettings\n
Registry settings configured for this registry.
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.all","title":"all","text":"all() -> Dict[str, Type[Component]]\n
Retrieve all registered
Component
classes.Returns:
-
Dict[str, Type[Component]]
\u2013Dict[str, Type[Component]]: A dictionary of component names to component classes
Example:
Source code in# 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
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.clear","title":"clear","text":"def all(self) -> Dict[str, Type[\"Component\"]]:\n \"\"\"\n Retrieve all registered [`Component`](../api#django_components.Component) classes.\n\n Returns:\n Dict[str, Type[Component]]: A dictionary of component names to component classes\n\n **Example:**\n\n ```python\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
clear() -> None\n
Clears the registry, unregistering all components.
Example:
Source code in# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then clear\nregistry.clear()\n# Then get all\nregistry.all()\n# > {}\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.get","title":"get","text":"def clear(self) -> None:\n \"\"\"\n Clears the registry, unregistering all components.\n\n Example:\n\n ```python\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
get(name: str) -> Type[Component]\n
Retrieve a
Component
class registered under the given name.Parameters:
-
name
(str
) \u2013The name under which the component was registered. Required.
Returns:
-
Type[Component]
\u2013Type[Component]: The component class registered under the given name.
Raises:
NotRegistered
if the given name is not registered.
Example:
Source code in# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then get\nregistry.get(\"button\")\n# > ButtonComponent\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.register","title":"register","text":"def get(self, name: str) -> Type[\"Component\"]:\n \"\"\"\n Retrieve a [`Component`](../api#django_components.Component)\n class registered under the given name.\n\n Args:\n name (str): The name under which the component was registered. Required.\n\n Returns:\n Type[Component]: The component class registered under the given name.\n\n **Raises:**\n\n - [`NotRegistered`](../exceptions#django_components.NotRegistered)\n if the given name is not registered.\n\n **Example:**\n\n ```python\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
register(name: str, component: Type[Component]) -> None\n
Register a
Component
class with this registry under the given name.A component MUST be registered before it can be used in a template such as:
{% component \"my_comp\" %}\n{% endcomponent %}\n
Parameters:
-
name
(str
) \u2013The name under which the component will be registered. Required.
-
component
(Type[Component]
) \u2013The component class to register. Required.
Raises:
AlreadyRegistered
if a different component was already registered under the same name.
Example:
Source code inregistry.register(\"button\", ButtonComponent)\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.component_registry.ComponentRegistry.unregister","title":"unregister","text":"def register(self, name: str, component: Type[\"Component\"]) -> None:\n \"\"\"\n Register a [`Component`](../api#django_components.Component) class\n 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\" %}\n {% endcomponent %}\n ```\n\n Args:\n name (str): The name under which the component will be registered. Required.\n component (Type[Component]): The component class to register. Required.\n\n **Raises:**\n\n - [`AlreadyRegistered`](../exceptions#django_components.AlreadyRegistered)\n if a different component was already registered under the same name.\n\n **Example:**\n\n ```python\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
unregister(name: str) -> None\n
Unregister the
Component
class that was registered under the given name.Once a component is unregistered, it is no longer available in the templates.
Parameters:
-
name
(str
) \u2013The name under which the component is registered. Required.
Raises:
NotRegistered
if the given name is not registered.
Example:
Source code in# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.component_registry.NotRegistered","title":"NotRegistered","text":"def unregister(self, name: str) -> None:\n \"\"\"\n Unregister the [`Component`](../api#django_components.Component) class\n that was registered under the given name.\n\n Once a component is unregistered, it is no longer available in the templates.\n\n Args:\n name (str): The name under which the component is registered. Required.\n\n **Raises:**\n\n - [`NotRegistered`](../exceptions#django_components.NotRegistered)\n if the given name is not registered.\n\n **Example:**\n\n ```python\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
Bases:
Exception
Raised when you try to access a Component, but it's NOT registered with given ComponentRegistry.
"},{"location":"reference/django_components/#django_components.component_registry.RegistrySettings","title":"RegistrySettings","text":"Bases:
NamedTuple
Configuration for a
ComponentRegistry
.These settings define how the components registered with this registry will behave when rendered.
from django_components import ComponentRegistry, RegistrySettings\n\nregistry_settings = RegistrySettings(\n context_behavior=\"django\",\n tag_formatter=\"django_components.component_shorthand_formatter\",\n)\n\nregistry = ComponentRegistry(settings=registry_settings)\n
Attributes:
-
CONTEXT_BEHAVIOR
(Optional[ContextBehaviorType]
) \u2013Deprecated. Use
context_behavior
instead. Will be removed in v1. -
TAG_FORMATTER
(Optional[Union[TagFormatterABC, str]]
) \u2013Deprecated. Use
tag_formatter
instead. Will be removed in v1. -
context_behavior
(Optional[ContextBehaviorType]
) \u2013Same as the global
-
tag_formatter
(Optional[Union[TagFormatterABC, str]]
) \u2013Same as the global
class-attribute
instance-attribute
","text":"CONTEXT_BEHAVIOR: Optional[ContextBehaviorType] = None\n
Deprecated. Use
context_behavior
instead. Will be removed in v1.Same as the global
COMPONENTS.context_behavior
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/#django_components.component_registry.RegistrySettings.TAG_FORMATTER","title":"TAG_FORMATTERCOMPONENTS.context_behavior
setting.class-attribute
instance-attribute
","text":"TAG_FORMATTER: Optional[Union[TagFormatterABC, str]] = None\n
Deprecated. Use
tag_formatter
instead. Will be removed in v1.Same as the global
COMPONENTS.tag_formatter
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/#django_components.component_registry.RegistrySettings.context_behavior","title":"context_behaviorCOMPONENTS.tag_formatter
setting.class-attribute
instance-attribute
","text":"context_behavior: Optional[ContextBehaviorType] = None\n
Same as the global
COMPONENTS.context_behavior
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/#django_components.component_registry.RegistrySettings.tag_formatter","title":"tag_formatterCOMPONENTS.context_behavior
setting.class-attribute
instance-attribute
","text":"tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n
Same as the global
COMPONENTS.tag_formatter
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/#django_components.component_registry.register","title":"register","text":"COMPONENTS.tag_formatter
setting.register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[\n [Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]]],\n Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]],\n]\n
Class decorator for registering a component to a component registry.
See Registering components.
Parameters:
-
name
(str
) \u2013Registered name. This is the name by which the component will be accessed from within a template when using the
{% component %}
tag. Required. -
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to which to register this component. If omitted, component is registered to the default registry.
Raises:
-
AlreadyRegistered
\u2013If there is already a component registered under the same name.
Examples:
from django_components import Component, register\n\n@register(\"my_component\")\nclass MyComponent(Component):\n ...\n
Specifing
ComponentRegistry
the component should be registered to by setting theregistry
kwarg:
Source code infrom django.template import Library\nfrom django_components import Component, ComponentRegistry, register\n\nmy_lib = Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n ...\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/#django_components.components","title":"components","text":"def register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[\n [Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"]],\n Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"],\n]:\n \"\"\"\n Class decorator for registering a [component](./#django_components.Component)\n to a [component registry](./#django_components.ComponentRegistry).\n\n See [Registering components](../../concepts/advanced/component_registry).\n\n Args:\n name (str): Registered name. This is the name by which the component will be accessed\\\n from within a template when using the [`{% component %}`](../template_tags#component) tag. Required.\n registry (ComponentRegistry, optional): Specify the [registry](./#django_components.ComponentRegistry)\\\n to which to register this component. If omitted, component is registered to the default registry.\n\n Raises:\n AlreadyRegistered: If there is already a component registered under the same name.\n\n **Examples**:\n\n ```python\n from django_components import Component, register\n\n @register(\"my_component\")\n class MyComponent(Component):\n ...\n ```\n\n Specifing [`ComponentRegistry`](./#django_components.ComponentRegistry) the component\n should be registered to by setting the `registry` kwarg:\n\n ```python\n from django.template import Library\n from django_components import Component, ComponentRegistry, register\n\n my_lib = 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(\n component: Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"],\n ) -> Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"]:\n registry.register(name=name, component=component)\n return component\n\n return decorator\n
Modules:
-
dynamic
\u2013
Classes:
-
DynamicComponent
\u2013This component is given a registered name or a reference to another component,
DynamicComponent(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Component
This component is given a registered name or a reference to another component, and behaves as if the other component was in its place.
The args, kwargs, and slot fills are all passed down to the underlying component.
Parameters:
-
is
(str | Type[Component]
) \u2013Component that should be rendered. Either a registered name of a component, or a Component class directly. Required.
-
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to search for the registered name. If omitted, all registries are searched until the first match.
-
*args
\u2013Additional data passed to the component.
-
**kwargs
\u2013Additional data passed to the component.
Slots:
- Any slots, depending on the actual component.
Examples:
Django
{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Python
"},{"location":"reference/django_components/#django_components.components.DynamicComponent--use-cases","title":"Use cases","text":"from django_components import DynamicComponent\n\nDynamicComponent.render(\n kwargs={\n \"is\": table_comp,\n \"data\": table_data,\n \"headers\": table_headers,\n },\n slots={\n \"pagination\": PaginationComponent.render(\n render_dependencies=False,\n ),\n },\n)\n
Dynamic components are suitable if you are writing something like a form component. You may design it such that users give you a list of input types, and you render components depending on the input types.
While you could handle this with a series of if / else statements, that's not an extensible approach. Instead, you can use the dynamic component in place of normal components.
"},{"location":"reference/django_components/#django_components.components.DynamicComponent--component-name","title":"Component name","text":"By default, the dynamic component is registered under the name
\"dynamic\"
. In case of a conflict, you can set theCOMPONENTS.dynamic_component_name
setting to change the name used for the dynamic components.# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
class-attribute
instance-attribute
","text":"Media = ComponentMediaInput\n
Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.css","title":"cssclass-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.input","title":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.media","title":"mediainstance-attribute
","text":"media: Media\n
Normalized definition of JS and CSS media files associated with this component.
NOTE: This field is generated from Component.Media class.
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.response_class","title":"response_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.template_name","title":"template_namerender_to_response
class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.DynamicComponent.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic","title":"dynamic","text":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
Modules:
-
types
\u2013Helper types for IDEs.
Classes:
-
DynamicComponent
\u2013This component is given a registered name or a reference to another component,
DynamicComponent(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Component
This component is given a registered name or a reference to another component, and behaves as if the other component was in its place.
The args, kwargs, and slot fills are all passed down to the underlying component.
Parameters:
-
is
(str | Type[Component]
) \u2013Component that should be rendered. Either a registered name of a component, or a Component class directly. Required.
-
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to search for the registered name. If omitted, all registries are searched until the first match.
-
*args
\u2013Additional data passed to the component.
-
**kwargs
\u2013Additional data passed to the component.
Slots:
- Any slots, depending on the actual component.
Examples:
Django
{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Python
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent--use-cases","title":"Use cases","text":"from django_components import DynamicComponent\n\nDynamicComponent.render(\n kwargs={\n \"is\": table_comp,\n \"data\": table_data,\n \"headers\": table_headers,\n },\n slots={\n \"pagination\": PaginationComponent.render(\n render_dependencies=False,\n ),\n },\n)\n
Dynamic components are suitable if you are writing something like a form component. You may design it such that users give you a list of input types, and you render components depending on the input types.
While you could handle this with a series of if / else statements, that's not an extensible approach. Instead, you can use the dynamic component in place of normal components.
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent--component-name","title":"Component name","text":"By default, the dynamic component is registered under the name
\"dynamic\"
. In case of a conflict, you can set theCOMPONENTS.dynamic_component_name
setting to change the name used for the dynamic components.# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
class-attribute
instance-attribute
","text":"Media = ComponentMediaInput\n
Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.css","title":"cssclass-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.input","title":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.media","title":"mediainstance-attribute
","text":"media: Media\n
Normalized definition of JS and CSS media files associated with this component.
NOTE: This field is generated from Component.Media class.
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.response_class","title":"response_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.template_name","title":"template_namerender_to_response
class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.components.dynamic.DynamicComponent.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/#django_components.context","title":"context","text":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
This file centralizes various ways we use Django's Context class pass data across components, nodes, slots, and contexts.
You can think of the Context as our storage system.
Functions:
-
copy_forloop_context
\u2013Forward the info about the current loop
-
get_injected_context_var
\u2013Retrieve a 'provided' field. The field MUST have been previously 'provided'
-
set_provided_context_var
\u2013'Provide' given data under given key. In other words, this data can be retrieved
copy_forloop_context(from_context: Context, to_context: Context) -> None\n
Forward the info about the current loop
Source code insrc/django_components/context.py
"},{"location":"reference/django_components/#django_components.context.get_injected_context_var","title":"get_injected_context_var","text":"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
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
Source code in{% provide %}
template tag.src/django_components/context.py
"},{"location":"reference/django_components/#django_components.context.set_provided_context_var","title":"set_provided_context_var","text":"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
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
Source code inself.inject(key)
inside ofget_context_data()
method of components that are nested inside the{% provide %}
tag.src/django_components/context.py
"},{"location":"reference/django_components/#django_components.dependencies","title":"dependencies","text":"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
All code related to management of component dependencies (JS and CSS scripts)
Modules:
-
types
\u2013Helper types for IDEs.
Classes:
-
ComponentDependencyMiddleware
\u2013Middleware that inserts CSS/JS dependencies for all rendered
Functions:
-
render_dependencies
\u2013Given a string that contains parts that were rendered by components,
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 insrc/django_components/dependencies.py
"},{"location":"reference/django_components/#django_components.dependencies.render_dependencies","title":"render_dependencies","text":"def __init__(self, get_response: \"Callable[[HttpRequest], HttpResponse]\") -> None:\n self.get_response = get_response\n\n # NOTE: Required to work with async\n if iscoroutinefunction(self.get_response):\n markcoroutinefunction(self)\n
render_dependencies(content: TContent, type: RenderType = 'document') -> TContent\n
Given a string that contains parts that were rendered by components, this function inserts all used JS and CSS.
By default, the string is parsed as an HTML and: - CSS is inserted at the end of
<head>
(if present) - JS is inserted at the end of<body>
(if present)If you used
{% component_js_dependencies %}
or{% component_css_dependencies %}
, then the JS and CSS will be inserted only at these locations.Example:
Source code indef my_view(request):\n template = Template('''\n {% load components %}\n <!doctype html>\n <html>\n <head></head>\n <body>\n <h1>{{ table_name }}</h1>\n {% component \"table\" name=table_name / %}\n </body>\n </html>\n ''')\n\n html = template.render(\n Context({\n \"table_name\": request.GET[\"name\"],\n })\n )\n\n # This inserts components' JS and CSS\n processed_html = render_dependencies(html)\n\n return HttpResponse(processed_html)\n
src/django_components/dependencies.py
"},{"location":"reference/django_components/#django_components.expression","title":"expression","text":"def render_dependencies(content: TContent, type: RenderType = \"document\") -> TContent:\n \"\"\"\n Given a string that contains parts that were rendered by components,\n this function inserts all used JS and CSS.\n\n By default, the string is parsed as an HTML and:\n - CSS is inserted at the end of `<head>` (if present)\n - JS is inserted at the end of `<body>` (if present)\n\n If you used `{% component_js_dependencies %}` or `{% component_css_dependencies %}`,\n then the JS and CSS will be inserted only at these locations.\n\n Example:\n ```python\n def my_view(request):\n template = Template('''\n {% load components %}\n <!doctype html>\n <html>\n <head></head>\n <body>\n <h1>{{ table_name }}</h1>\n {% component \"table\" name=table_name / %}\n </body>\n </html>\n ''')\n\n html = template.render(\n Context({\n \"table_name\": request.GET[\"name\"],\n })\n )\n\n # This inserts components' JS and CSS\n processed_html = render_dependencies(html)\n\n return HttpResponse(processed_html)\n ```\n \"\"\"\n is_safestring = isinstance(content, SafeString)\n\n if isinstance(content, str):\n content_ = content.encode()\n else:\n content_ = cast(bytes, content)\n\n content_, js_dependencies, css_dependencies = _process_dep_declarations(content_, type)\n\n # Replace the placeholders with the actual content\n did_find_js_placeholder = False\n did_find_css_placeholder = False\n\n def on_replace_match(match: \"re.Match[bytes]\") -> bytes:\n nonlocal did_find_css_placeholder\n nonlocal did_find_js_placeholder\n\n if match[0] == CSS_PLACEHOLDER_BYTES:\n replacement = css_dependencies\n did_find_css_placeholder = True\n elif match[0] == JS_PLACEHOLDER_BYTES:\n replacement = js_dependencies\n did_find_js_placeholder = True\n else:\n raise RuntimeError(\n \"Unexpected error: Regex for component dependencies processing\"\n f\" matched unknown string '{match[0].decode()}'\"\n )\n return replacement\n\n content_ = PLACEHOLDER_REGEX.sub(on_replace_match, content_)\n\n # By default, if user didn't specify any `{% component_dependencies %}`,\n # then try to insert the JS scripts at the end of <body> and CSS sheets at the end\n # of <head>\n if type == \"document\" and (not did_find_js_placeholder or not did_find_css_placeholder):\n tree = parse_document_or_nodes(content_.decode())\n\n if isinstance(tree, LexborHTMLParser):\n did_modify_html = False\n\n if not did_find_css_placeholder and tree.head:\n css_elems = parse_multiroot_html(css_dependencies.decode())\n for css_elem in css_elems:\n tree.head.insert_child(css_elem) # type: ignore # TODO: Update to selectolax 0.3.25\n did_modify_html = True\n\n if not did_find_js_placeholder and tree.body:\n js_elems = parse_multiroot_html(js_dependencies.decode())\n for js_elem in js_elems:\n tree.body.insert_child(js_elem) # type: ignore # TODO: Update to selectolax 0.3.25\n did_modify_html = True\n\n transformed = cast(str, tree.html)\n if did_modify_html:\n content_ = transformed.encode()\n\n # Return the same type as we were given\n output = content_.decode() if isinstance(content, str) else content_\n output = mark_safe(output) if is_safestring else output\n return cast(TContent, output)\n
Classes:
-
Operator
\u2013Operator describes something that somehow changes the inputs
-
SpreadOperator
\u2013Operator that inserts one or more kwargs at the specified location.
Functions:
-
process_aggregate_kwargs
\u2013This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs
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 insrc/django_components/expression.py
"},{"location":"reference/django_components/#django_components.expression.process_aggregate_kwargs","title":"process_aggregate_kwargs","text":"def __init__(self, expr: Expression) -> None:\n self.expr = expr\n
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 theattrs
dict.So, instead, we allow to \"aggregate\" props into a dict. So all props that start with
attrs:
, likeattrs:class=\"text-red\"
, will be collected into a dict at keyattrs
.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 insrc/django_components/expression.py
"},{"location":"reference/django_components/#django_components.finders","title":"finders","text":"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
Classes:
-
ComponentsFileSystemFinder
\u2013A static files finder based on
FileSystemFinder
.
ComponentsFileSystemFinder(app_names: Any = None, *args: Any, **kwargs: Any)\n
Bases:
BaseFinder
A static files finder based on
FileSystemFinder
.Differences: - This finder uses
COMPONENTS.dirs
setting to locate files instead ofSTATICFILES_DIRS
. - Whether a file withinCOMPONENTS.dirs
is considered a STATIC file is configured byCOMPONENTS.static_files_allowed
andCOMPONENTS.static_files_forbidden
. - IfCOMPONENTS.dirs
is not set, defaults tosettings.BASE_DIR / \"components\"
Methods:
-
find
\u2013Look for files in the extra locations as defined in COMPONENTS.dirs.
-
find_location
\u2013Find a requested static file in a location and return the found
-
list
\u2013List all files in all locations.
src/django_components/finders.py
"},{"location":"reference/django_components/#django_components.finders.ComponentsFileSystemFinder.find","title":"find","text":"def __init__(self, app_names: Any = None, *args: Any, **kwargs: Any) -> None:\n component_dirs = [str(p) for p in get_component_dirs()]\n\n # NOTE: The rest of the __init__ is the same as `django.contrib.staticfiles.finders.FileSystemFinder`,\n # but using our locations instead of STATICFILES_DIRS.\n\n # List of locations with static files\n self.locations: List[Tuple[str, str]] = []\n\n # Maps dir paths to an appropriate storage instance\n self.storages: Dict[str, FileSystemStorage] = {}\n for root in component_dirs:\n if isinstance(root, (list, tuple)):\n prefix, root = root\n else:\n prefix = \"\"\n if (prefix, root) not in self.locations:\n self.locations.append((prefix, root))\n for prefix, root in self.locations:\n filesystem_storage = FileSystemStorage(location=root)\n filesystem_storage.prefix = prefix\n self.storages[root] = filesystem_storage\n\n super().__init__(*args, **kwargs)\n
find(path: str, all: bool = False) -> Union[List[str], str]\n
Look for files in the extra locations as defined in COMPONENTS.dirs.
Source code insrc/django_components/finders.py
"},{"location":"reference/django_components/#django_components.finders.ComponentsFileSystemFinder.find_location","title":"find_location","text":"def find(self, path: str, all: bool = False) -> Union[List[str], str]:\n \"\"\"\n Look for files in the extra locations as defined in COMPONENTS.dirs.\n \"\"\"\n matches: List[str] = []\n for prefix, root in self.locations:\n if root not in searched_locations:\n searched_locations.append(root)\n matched_path = self.find_location(root, path, prefix)\n if matched_path:\n if not all:\n return matched_path\n matches.append(matched_path)\n return matches\n
find_location(root: str, path: str, prefix: Optional[str] = None) -> Optional[str]\n
Find a requested static file in a location and return the found absolute path (or
Source code inNone
if no match).src/django_components/finders.py
"},{"location":"reference/django_components/#django_components.finders.ComponentsFileSystemFinder.list","title":"list","text":"def find_location(self, root: str, path: str, prefix: Optional[str] = None) -> Optional[str]:\n \"\"\"\n Find a requested static file in a location and return the found\n absolute path (or ``None`` if no match).\n \"\"\"\n if prefix:\n prefix = \"%s%s\" % (prefix, os.sep)\n if not path.startswith(prefix):\n return None\n path = path.removeprefix(prefix)\n path = safe_join(root, path)\n\n if os.path.exists(path) and self._is_path_valid(path):\n return path\n return None\n
list(ignore_patterns: List[str]) -> Iterable[Tuple[str, FileSystemStorage]]\n
List all files in all locations.
Source code insrc/django_components/finders.py
"},{"location":"reference/django_components/#django_components.library","title":"library","text":"def list(self, ignore_patterns: List[str]) -> Iterable[Tuple[str, FileSystemStorage]]:\n \"\"\"\n List all files in all locations.\n \"\"\"\n for prefix, root in self.locations:\n # Skip nonexistent directories.\n if os.path.isdir(root):\n storage = self.storages[root]\n for path in get_files(storage, ignore_patterns):\n if self._is_path_valid(path):\n yield path, storage\n
Module for interfacing with Django's Library (
django.template.library
)Classes:
-
TagProtectedError
\u2013The way the
TagFormatter
works is that,
Attributes:
-
PROTECTED_TAGS
\u2013These are the names that users cannot choose for their components,
module-attribute
","text":"PROTECTED_TAGS = ['component_css_dependencies', 'component_js_dependencies', 'fill', 'html_attrs', 'provide', 'slot']\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.library.TagProtectedError","title":"TagProtectedError","text":"Bases:
Exception
The way the
TagFormatter
works is that, based on which start and end tags are used for rendering components, theComponentRegistry
behind the scenes un-/registers the template tags with the associated instance of Django'sLibrary
.In other words, if I have registered a component
\"table\"
, and I use the shorthand syntax:{% table ... %}\n{% endtable %}\n
Then
ComponentRegistry
registers the tagtable
onto the Django's Library instance.However, that means that if we registered a component
\"slot\"
, then we would overwrite the{% slot %}
tag from django_components.Thus, this exception is raised when a component is attempted to be registered under a forbidden name, such that it would overwrite one of django_component's own template tags.
"},{"location":"reference/django_components/#django_components.management","title":"management","text":"Modules:
-
commands
\u2013
Modules:
-
startcomponent
\u2013
Classes:
-
Command
\u2013
Bases:
"},{"location":"reference/django_components/#django_components.management.commands.startcomponent.Command--management-command-usage","title":"Management Command Usage","text":"BaseCommand
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
"},{"location":"reference/django_components/#django_components.management.commands.startcomponent.Command--management-command-examples","title":"Management Command Examples","text":"<name>
,<path>
,<js_filename>
,<css_filename>
, and<template_filename>
with your desired values.Here are some examples of how you can use the command:
"},{"location":"reference/django_components/#django_components.management.commands.startcomponent.Command--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
"},{"location":"reference/django_components/#django_components.management.commands.startcomponent.Command--creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"my_component
in thecomponents
directory of your Django project. The JavaScript, CSS, and template files will be namedscript.js
,style.css
, andtemplate.html
, respectively.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
"},{"location":"reference/django_components/#django_components.management.commands.startcomponent.Command--overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"new_component
in themy_components
directory. The JavaScript, CSS, and template files will be namedmy_script.js
,my_style.css
, andmy_template.html
, respectively.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
"},{"location":"reference/django_components/#django_components.management.commands.startcomponent.Command--simulating-component-creation","title":"Simulating Component Creation","text":"my_component
if it exists.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
"},{"location":"reference/django_components/#django_components.middleware","title":"middleware","text":"my_component
without creating any files.Classes:
-
ComponentDependencyMiddleware
\u2013Middleware that inserts CSS/JS dependencies for all rendered
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 insrc/django_components/dependencies.py
"},{"location":"reference/django_components/#django_components.node","title":"node","text":"def __init__(self, get_response: \"Callable[[HttpRequest], HttpResponse]\") -> None:\n self.get_response = get_response\n\n # NOTE: Required to work with async\n if iscoroutinefunction(self.get_response):\n markcoroutinefunction(self)\n
Classes:
-
BaseNode
\u2013Shared behavior for our subclasses of Django's
Node
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
Source code inNode
src/django_components/node.py
"},{"location":"reference/django_components/#django_components.provide","title":"provide","text":"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
Classes:
-
ProvideNode
\u2013Implementation of the
{% provide %}
tag.
ProvideNode(nodelist: NodeList, trace_id: str, node_id: Optional[str] = None, kwargs: Optional[RuntimeKwargs] = None)\n
Bases:
BaseNode
Implementation of the
Source code in{% provide %}
tag. For more info seeComponent.inject
.src/django_components/provide.py
"},{"location":"reference/django_components/#django_components.slots","title":"slots","text":"def __init__(\n self,\n nodelist: NodeList,\n trace_id: str,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.nodelist = nodelist\n self.node_id = node_id or gen_id()\n self.trace_id = trace_id\n self.kwargs = kwargs or RuntimeKwargs({})\n
Classes:
-
FillNode
\u2013Node corresponding to
{% fill %}
-
Slot
\u2013This class holds the slot content function along with related metadata.
-
SlotFill
\u2013SlotFill describes what WILL be rendered.
-
SlotIsFilled
\u2013Dictionary that returns
True
if the slot is filled (key is found),False
otherwise. -
SlotNode
\u2013Node corresponding to
{% slot %}
-
SlotRef
\u2013SlotRef allows to treat a slot as a variable. The slot is rendered only once
Functions:
-
resolve_fills
\u2013Given a component body (
django.template.NodeList
), find all slot fills,
FillNode(nodelist: NodeList, kwargs: RuntimeKwargs, trace_id: str, node_id: Optional[str] = None)\n
Bases:
BaseNode
Node corresponding to
Source code in{% fill %}
src/django_components/slots.py
"},{"location":"reference/django_components/#django_components.slots.Slot","title":"Slotdef __init__(\n self,\n nodelist: NodeList,\n kwargs: RuntimeKwargs,\n trace_id: str,\n node_id: Optional[str] = None,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.trace_id = trace_id\n
dataclass
","text":"Slot(content_func: SlotFunc[TSlotData])\n
Bases:
Generic[TSlotData]
This class holds the slot content function along with related metadata.
"},{"location":"reference/django_components/#django_components.slots.SlotFill","title":"SlotFilldataclass
","text":"SlotFill(name: str, is_filled: bool, slot: Slot[TSlotData])\n
Bases:
Generic[TSlotData]
SlotFill describes what WILL be rendered.
The fill may be provided by the user from the outside (
is_filled=True
), or it may be the default content of the slot (is_filled=False
).Attributes:
-
name
(str
) \u2013Name of the slot.
instance-attribute
","text":"name: str\n
Name of the slot.
"},{"location":"reference/django_components/#django_components.slots.SlotIsFilled","title":"SlotIsFilled","text":"SlotIsFilled(fills: Dict, *args: Any, **kwargs: Any)\n
Bases:
dict
Dictionary that returns
Source code inTrue
if the slot is filled (key is found),False
otherwise.src/django_components/slots.py
"},{"location":"reference/django_components/#django_components.slots.SlotNode","title":"SlotNode","text":"def __init__(self, fills: Dict, *args: Any, **kwargs: Any) -> None:\n escaped_fill_names = {_escape_slot_name(fill_name): True for fill_name in fills.keys()}\n super().__init__(escaped_fill_names, *args, **kwargs)\n
SlotNode(\n nodelist: NodeList,\n trace_id: str,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n is_required: bool = False,\n is_default: bool = False,\n)\n
Bases:
BaseNode
Node corresponding to
Source code in{% slot %}
src/django_components/slots.py
"},{"location":"reference/django_components/#django_components.slots.SlotRef","title":"SlotRef","text":"def __init__(\n self,\n nodelist: NodeList,\n trace_id: str,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n is_required: bool = False,\n is_default: bool = False,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.is_required = is_required\n self.is_default = is_default\n self.trace_id = trace_id\n
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
Source code in{{ my_lazy_slot }}
, it will output the contents of the slot.src/django_components/slots.py
"},{"location":"reference/django_components/#django_components.slots.resolve_fills","title":"resolve_fills","text":"def __init__(self, slot: \"SlotNode\", context: Context):\n self._slot = slot\n self._context = context\n
resolve_fills(context: Context, nodelist: NodeList, component_name: str) -> Dict[SlotName, Slot]\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 finds 2 fill nodes: \"first_fill\" and \"second_fill\", and formats them as slot functions, returning:
{\n \"first_fill\": SlotFunc(...),\n \"second_fill\": SlotFunc(...),\n}\n
If no fill nodes are found, then the content is treated as default slot content.
{\n DEFAULT_SLOT_KEY: SlotFunc(...),\n}\n
This function also handles for-loops, if/else statements, or include tags to generate fill tags:
Source code in{% component \"mycomponent\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name %}\n {% slot name=slot_name / %}\n {% endfill %}\n {% endfor %}\n{% endcomponent %}\n
src/django_components/slots.py
"},{"location":"reference/django_components/#django_components.tag_formatter","title":"tag_formatter","text":"def resolve_fills(\n context: Context,\n nodelist: NodeList,\n component_name: str,\n) -> Dict[SlotName, Slot]:\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\n Then this function finds 2 fill nodes: \"first_fill\" and \"second_fill\",\n and formats them as slot functions, returning:\n\n ```python\n {\n \"first_fill\": SlotFunc(...),\n \"second_fill\": SlotFunc(...),\n }\n ```\n\n If no fill nodes are found, then the content is treated as default slot content.\n\n ```python\n {\n DEFAULT_SLOT_KEY: SlotFunc(...),\n }\n ```\n\n This function also handles for-loops, if/else statements, or include tags to generate fill tags:\n\n ```django\n {% component \"mycomponent\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name %}\n {% slot name=slot_name / %}\n {% endfill %}\n {% endfor %}\n {% endcomponent %}\n ```\n \"\"\"\n slots: Dict[SlotName, Slot] = {}\n\n if not nodelist:\n return slots\n\n maybe_fills = _extract_fill_content(nodelist, context, component_name)\n\n # The content has no fills, so treat it as default slot, e.g.:\n # {% component \"mycomponent\" %}\n # Hello!\n # {% if True %} 123 {% endif %}\n # {% endcomponent %}\n if maybe_fills is False:\n # Ignore empty content between `{% component %} ... {% endcomponent %}` tags\n nodelist_is_empty = not len(nodelist) or all(\n isinstance(node, TextNode) and not node.s.strip() for node in nodelist\n )\n\n if not nodelist_is_empty:\n slots[DEFAULT_SLOT_KEY] = _nodelist_to_slot_render_func(\n DEFAULT_SLOT_KEY,\n nodelist,\n data_var=None,\n default_var=None,\n )\n\n # The content has fills\n else:\n # NOTE: If slot fills are explicitly defined, we use them even if they are empty (or only whitespace).\n # This is different from the default slot, where we ignore empty content.\n for fill in maybe_fills:\n slots[fill.name] = _nodelist_to_slot_render_func(\n slot_name=fill.name,\n nodelist=fill.fill.nodelist,\n data_var=fill.data_var,\n default_var=fill.default_var,\n extra_context=fill.extra_context,\n )\n\n return slots\n
Classes:
-
ComponentFormatter
\u2013The original django_component's component tag formatter, it uses the
{% component %}
-
InternalTagFormatter
\u2013Internal wrapper around user-provided TagFormatters, so that we validate the outputs.
-
ShorthandComponentFormatter
\u2013The component tag formatter that uses
{% <name> %}
/{% end<name> %}
tags. -
TagFormatterABC
\u2013Abstract base class for defining custom tag formatters.
-
TagResult
\u2013The return value from
TagFormatter.parse()
.
Functions:
-
get_tag_formatter
\u2013Returns an instance of the currently configured component tag formatter.
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 given as the first positional arg.Example as block:
{% component \"mycomp\" abc=123 %}\n {% fill \"myfill\" %}\n ...\n {% endfill %}\n{% endcomponent %}\n
Example as inlined tag:
Source code in{% component \"mycomp\" abc=123 / %}\n
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.tag_formatter.InternalTagFormatter","title":"InternalTagFormatter","text":"def __init__(self, tag: str):\n self.tag = tag\n
InternalTagFormatter(tag_formatter: TagFormatterABC)\n
Internal wrapper around user-provided TagFormatters, so that we validate the outputs.
Source code insrc/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.tag_formatter.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":"def __init__(self, tag_formatter: TagFormatterABC):\n self.tag_formatter = tag_formatter\n
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:
"},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC","title":"TagFormatterABC","text":"{% mycomp abc=123 / %}\n
Bases:
ABC
Abstract base class for defining custom tag formatters.
Tag formatters define how the component tags are used in the template.
Read more about Tag formatter.
For example, with the default tag formatter (
ComponentFormatter
), components are written as:{% component \"comp_name\" %}\n{% endcomponent %}\n
While with the shorthand tag formatter (
ShorthandComponentFormatter
), components are written as:{% comp_name %}\n{% endcomp_name %}\n
Example:
Implementation for
ShorthandComponentFormatter
:from djagno_components import TagFormatterABC, TagResult\n\nclass ShorthandComponentFormatter(TagFormatterABC):\n def start_tag(self, name: str) -> str:\n return name\n\n def end_tag(self, name: str) -> str:\n return f\"end{name}\"\n\n def parse(self, tokens: List[str]) -> TagResult:\n tokens = [*tokens]\n name = tokens.pop(0)\n return TagResult(name, tokens)\n
Methods:
-
end_tag
\u2013Formats the end tag of a block component.
-
parse
\u2013Given the tokens (words) passed to a component start tag, this function extracts
-
start_tag
\u2013Formats the start tag of a component.
abstractmethod
","text":"end_tag(name: str) -> str\n
Formats the end tag of a block component.
Parameters:
-
name
(str
) \u2013Component's registered name. Required.
Returns:
-
str
(str
) \u2013The formatted end tag.
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC.parse","title":"parse@abc.abstractmethod\ndef end_tag(self, name: str) -> str:\n \"\"\"\n Formats the end tag of a block component.\n\n Args:\n name (str): Component's registered name. Required.\n\n Returns:\n str: The formatted end tag.\n \"\"\"\n ...\n
abstractmethod
","text":"parse(tokens: List[str]) -> TagResult\n
Given the tokens (words) passed to a component start tag, this function extracts the component name from the tokens list, and returns
TagResult
, which is a tuple of(component_name, remaining_tokens)
.Parameters:
-
tokens
([List(str]
) \u2013List of tokens passed to the component tag.
Returns:
-
TagResult
(TagResult
) \u2013Parsed component name and remaining tokens.
Example:
Assuming we used a component in a template like this:
{% component \"my_comp\" key=val key2=val2 %}\n{% endcomponent %}\n
This function receives a list of tokens:
['component', '\"my_comp\"', 'key=val', 'key2=val2']\n
component
is the tag name, which we drop.\"my_comp\"
is the component name, but we must remove the extra quotes.- The remaining tokens we pass unmodified, as that's the input to the component.
So in the end, we return:
Source code inTagResult('my_comp', ['key=val', 'key2=val2'])\n
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.tag_formatter.TagFormatterABC.start_tag","title":"start_tag@abc.abstractmethod\ndef parse(self, tokens: List[str]) -> TagResult:\n \"\"\"\n Given the tokens (words) passed to a component start tag, this function extracts\n the component name from the tokens list, and returns\n [`TagResult`](../api#django_components.TagResult),\n which is a tuple of `(component_name, remaining_tokens)`.\n\n Args:\n tokens [List(str]): List of tokens passed to the component tag.\n\n Returns:\n TagResult: Parsed component name and remaining tokens.\n\n **Example:**\n\n Assuming we used a component in a template like this:\n\n ```django\n {% component \"my_comp\" key=val key2=val2 %}\n {% endcomponent %}\n ```\n\n This function receives a list of tokens:\n\n ```python\n ['component', '\"my_comp\"', 'key=val', 'key2=val2']\n ```\n\n - `component` is the tag name, which we drop.\n - `\"my_comp\"` is the component name, but we must remove the extra quotes.\n - The remaining tokens we pass unmodified, as that's the input to the component.\n\n So in the end, we return:\n\n ```python\n TagResult('my_comp', ['key=val', 'key2=val2'])\n ```\n \"\"\"\n ...\n
abstractmethod
","text":"start_tag(name: str) -> str\n
Formats the start tag of a component.
Parameters:
-
name
(str
) \u2013Component's registered name. Required.
Returns:
-
str
(str
) \u2013The formatted start tag.
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.tag_formatter.TagResult","title":"TagResult","text":"@abc.abstractmethod\ndef start_tag(self, name: str) -> str:\n \"\"\"\n Formats the start tag of a component.\n\n Args:\n name (str): Component's registered name. Required.\n\n Returns:\n str: The formatted start tag.\n \"\"\"\n ...\n
Bases:
NamedTuple
The return value from
TagFormatter.parse()
.Read more about Tag formatter.
Attributes:
-
component_name
(str
) \u2013Component name extracted from the template tag
-
tokens
(List[str]
) \u2013Remaining tokens (words) that were passed to the tag, with component name removed
instance-attribute
","text":"component_name: str\n
Component name extracted from the template tag
For example, if we had tag
{% component \"my_comp\" key=val key2=val2 %}\n
Then
"},{"location":"reference/django_components/#django_components.tag_formatter.TagResult.tokens","title":"tokenscomponent_name
would bemy_comp
.instance-attribute
","text":"tokens: List[str]\n
Remaining tokens (words) that were passed to the tag, with component name removed
For example, if we had tag
{% component \"my_comp\" key=val key2=val2 %}\n
Then
"},{"location":"reference/django_components/#django_components.tag_formatter.get_tag_formatter","title":"get_tag_formatter","text":"tokens
would be['key=val', 'key2=val2']
.get_tag_formatter(registry: ComponentRegistry) -> InternalTagFormatter\n
Returns an instance of the currently configured component tag formatter.
Source code insrc/django_components/tag_formatter.py
"},{"location":"reference/django_components/#django_components.template","title":"template","text":"def get_tag_formatter(registry: \"ComponentRegistry\") -> InternalTagFormatter:\n \"\"\"Returns an instance of the currently configured component tag formatter.\"\"\"\n # Allow users to configure the component TagFormatter\n formatter_cls_or_str = registry.settings.tag_formatter\n\n if isinstance(formatter_cls_or_str, str):\n tag_formatter: TagFormatterABC = import_string(formatter_cls_or_str)\n else:\n tag_formatter = formatter_cls_or_str\n\n return InternalTagFormatter(tag_formatter)\n
Functions:
-
cached_template
\u2013Create a Template instance that will be cached as per the
cached_template(\n template_string: str,\n template_cls: Optional[Type[Template]] = None,\n origin: Optional[Origin] = None,\n name: Optional[str] = None,\n engine: Optional[Any] = None,\n) -> Template\n
Create a Template instance that will be cached as per the
COMPONENTS.template_cache_size
setting.Parameters:
-
template_string
(str
) \u2013Template as a string, same as the first argument to Django's
Template
. Required. -
template_cls
(Type[Template]
, default:None
) \u2013Specify the Template class that should be instantiated. Defaults to Django's
Template
class. -
origin
(Type[Origin]
, default:None
) \u2013Sets
Template.Origin
. -
name
(Type[str]
, default:None
) \u2013Sets
Template.name
-
engine
(Type[Any]
, default:None
) \u2013Sets
Template.engine
Source code infrom django_components import cached_template\n\ntemplate = cached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n pass\n\ntemplate = cached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n)\n
src/django_components/template.py
"},{"location":"reference/django_components/#django_components.template_loader","title":"template_loader","text":"def cached_template(\n template_string: str,\n template_cls: Optional[Type[Template]] = None,\n origin: Optional[Origin] = None,\n name: Optional[str] = None,\n engine: Optional[Any] = None,\n) -> Template:\n \"\"\"\n Create a Template instance that will be cached as per the\n [`COMPONENTS.template_cache_size`](../settings#django_components.app_settings.ComponentsSettings.template_cache_size)\n setting.\n\n Args:\n template_string (str): Template as a string, same as the first argument to Django's\\\n [`Template`](https://docs.djangoproject.com/en/5.1/topics/templates/#template). Required.\n template_cls (Type[Template], optional): Specify the Template class that should be instantiated.\\\n Defaults to Django's [`Template`](https://docs.djangoproject.com/en/5.1/topics/templates/#template) class.\n origin (Type[Origin], optional): Sets \\\n [`Template.Origin`](https://docs.djangoproject.com/en/5.1/howto/custom-template-backend/#origin-api-and-3rd-party-integration).\n name (Type[str], optional): Sets `Template.name`\n engine (Type[Any], optional): Sets `Template.engine`\n\n ```python\n from django_components import cached_template\n\n template = cached_template(\"Variable: {{ variable }}\")\n\n # You can optionally specify Template class, and other Template inputs:\n class MyTemplate(Template):\n pass\n\n template = cached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n )\n ```\n \"\"\" # noqa: E501\n template = _create_template(template_cls or Template, template_string, engine)\n\n # Assign the origin and name separately, so the caching doesn't depend on them\n # Since we might be accessing a template from cache, we want to define these only once\n if not getattr(template, \"_dc_cached\", False):\n template.origin = origin or Origin(UNKNOWN_SOURCE)\n template.name = name\n template._dc_cached = True\n\n return template\n
Template loader that loads templates from each Django app's \"components\" directory.
Classes:
-
Loader
\u2013
Bases:
Loader
Methods:
-
get_dirs
\u2013Prepare directories that may contain component files:
get_dirs(include_apps: bool = True) -> List[Path]\n
Prepare directories that may contain component files:
Searches for dirs set in
COMPONENTS.dirs
settings. If none set, defaults to searching for a \"components\" app. The dirs inCOMPONENTS.dirs
must be absolute paths.In addition to that, also all apps are checked for
[app]/components
dirs.Paths are accepted only if they resolve to a directory. E.g.
/path/to/django_project/my_app/components/
.
Source code inBASE_DIR
setting is required.src/django_components/template_loader.py
"},{"location":"reference/django_components/#django_components.template_parser","title":"template_parser","text":"def get_dirs(self, include_apps: bool = True) -> List[Path]:\n \"\"\"\n Prepare directories that may contain component files:\n\n Searches for dirs set in `COMPONENTS.dirs` settings. If none set, defaults to searching\n for a \"components\" app. The dirs in `COMPONENTS.dirs` must be absolute paths.\n\n In addition to that, also all apps are checked for `[app]/components` dirs.\n\n Paths are accepted only if they resolve to a directory.\n E.g. `/path/to/django_project/my_app/components/`.\n\n `BASE_DIR` setting is required.\n \"\"\"\n return get_component_dirs(include_apps)\n
Overrides for the Django Template system to allow finer control over template parsing.
Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py
Functions:
-
parse_bits
\u2013Parse bits for template tag helpers simple_tag and inclusion_tag, in
-
token_kwargs
\u2013Parse token keyword arguments and return a dictionary of the arguments
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 insrc/django_components/template_parser.py
"},{"location":"reference/django_components/#django_components.template_parser.token_kwargs","title":"token_kwargs","text":"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
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
Source code inbits
to be keyword arguments, so return the dictionary as soon as an invalid argument format is reached.src/django_components/template_parser.py
"},{"location":"reference/django_components/#django_components.templatetags","title":"templatetags","text":"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
Modules:
-
component_tags
\u2013
Functions:
-
component
\u2013Renders one of the components that was previously registered with
-
component_css_dependencies
\u2013Marks location where CSS link tags should be rendered after the whole HTML has been generated.
-
component_js_dependencies
\u2013Marks location where JS link tags should be rendered after the whole HTML has been generated.
-
fill
\u2013Use this tag to insert content into component's slots.
-
html_attrs
\u2013Generate HTML attributes (
key=\"value\"
), combining data from multiple sources, -
provide
\u2013The \"provider\" part of the provide / inject feature.
-
slot
\u2013Slot tag marks a place inside a component where content can be inserted
Bases:
NamedTuple
Definition of args, kwargs, flags, etc, for a template tag.
Attributes:
-
end_tag
(Optional[str]
) \u2013End tag.
-
flags
(Optional[List[str]]
) \u2013List of allowed flags.
-
keywordonly_args
(Optional[Union[bool, List[str]]]
) \u2013Parameters that MUST be given only as kwargs (not accounting for
pos_or_keyword_args
). -
optional_kwargs
(Optional[List[str]]
) \u2013Specify which kwargs can be optional.
-
pos_or_keyword_args
(Optional[List[str]]
) \u2013Like regular Python kwargs, these can be given EITHER as positional OR as keyword arguments.
-
positional_args_allow_extra
(bool
) \u2013If
True
, allows variable number of positional args, e.g.{% mytag val1 1234 val2 890 ... %}
-
positional_only_args
(Optional[List[str]]
) \u2013Arguments that MUST be given as positional args.
-
repeatable_kwargs
(Optional[Union[bool, List[str]]]
) \u2013Whether this tag allows all or certain kwargs to be repeated.
-
tag
(str
) \u2013Tag name. E.g.
\"slot\"
means the tag is written like so{% slot ... %}
class-attribute
instance-attribute
","text":"end_tag: Optional[str] = None\n
End tag.
E.g.
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.TagSpec.flags","title":"flags\"endslot\"
means anything between the start tag and{% endslot %}
is considered the slot's body.class-attribute
instance-attribute
","text":"flags: Optional[List[str]] = None\n
List of allowed flags.
Flags are like kwargs, but without the value part. E.g. in
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.TagSpec.keywordonly_args","title":"keywordonly_args{% mytag only required %}
: -only
andrequired
are treated asonly=True
andrequired=True
if present - and treated asonly=False
andrequired=False
if omittedclass-attribute
instance-attribute
","text":"keywordonly_args: Optional[Union[bool, List[str]]] = False\n
Parameters that MUST be given only as kwargs (not accounting for
pos_or_keyword_args
).- If
False
, NO extra kwargs allowed. - If
True
, ANY number of extra kwargs allowed. - If a list of strings, e.g.
[\"class\", \"style\"]
, then only those kwargs are allowed.
class-attribute
instance-attribute
","text":"optional_kwargs: Optional[List[str]] = None\n
Specify which kwargs can be optional.
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.TagSpec.pos_or_keyword_args","title":"pos_or_keyword_argsclass-attribute
instance-attribute
","text":"pos_or_keyword_args: Optional[List[str]] = None\n
Like regular Python kwargs, these can be given EITHER as positional OR as keyword arguments.
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.TagSpec.positional_args_allow_extra","title":"positional_args_allow_extraclass-attribute
instance-attribute
","text":"positional_args_allow_extra: bool = False\n
If
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.TagSpec.positional_only_args","title":"positional_only_argsTrue
, allows variable number of positional args, e.g.{% mytag val1 1234 val2 890 ... %}
class-attribute
instance-attribute
","text":"positional_only_args: Optional[List[str]] = None\n
Arguments that MUST be given as positional args.
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.TagSpec.repeatable_kwargs","title":"repeatable_kwargsclass-attribute
instance-attribute
","text":"repeatable_kwargs: Optional[Union[bool, List[str]]] = False\n
Whether this tag allows all or certain kwargs to be repeated.
- If
False
, NO kwargs can repeat. - If
True
, ALL kwargs can repeat. - If a list of strings, e.g.
[\"class\", \"style\"]
, then only those kwargs can repeat.
E.g.
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.TagSpec.tag","title":"tag[\"class\"]
means one can write{% mytag class=\"one\" class=\"two\" %}
instance-attribute
","text":"tag: str\n
Tag name. E.g.
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.component","title":"component","text":"\"slot\"
means the tag is written like so{% slot ... %}
component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str, tag_spec: TagSpec) -> ComponentNode\n
Renders one of the components that was previously registered with
@register()
decorator.Args:
name
(str, required): Registered name of the component to render- All other args and kwargs are defined based on the component itself.
If you defined a component
\"my_table\"
from django_component import Component, register\n\n@register(\"my_table\")\nclass MyTable(Component):\n template = \"\"\"\n <table>\n <thead>\n {% for header in headers %}\n <th>{{ header }}</th>\n {% endfor %}\n </thead>\n <tbody>\n {% for row in rows %}\n <tr>\n {% for cell in row %}\n <td>{{ cell }}</td>\n {% endfor %}\n </tr>\n {% endfor %}\n <tbody>\n </table>\n \"\"\"\n\n def get_context_data(self, rows: List, headers: List):\n return {\n \"rows\": rows,\n \"headers\": headers,\n }\n
Then you can render this component by referring to
MyTable
via its registered name\"my_table\"
:
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.component--component-input","title":"Component input","text":"{% component \"my_table\" rows=rows headers=headers ... / %}\n
Positional and keyword arguments can be literals or template variables.
The component name must be a single- or double-quotes string and must be either:
-
The first positional argument after
component
:{% component \"my_table\" rows=rows headers=headers ... / %}\n
-
Passed as kwarg
name
:{% component rows=rows headers=headers name=\"my_table\" ... / %}\n
If the component defined any slots, you can pass in the content to be placed inside those slots by inserting
{% fill %}
tags, directly within the{% component %}
tag:
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.component--isolating-components","title":"Isolating components","text":"{% component \"my_table\" rows=rows headers=headers ... / %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n{% endcomponent %}\n
By default, components behave similarly to Django's
{% include %}
, and the template inside the component has access to the variables defined in the outer template.You can selectively isolate a component, using the
only
flag, so that the inner template can access only the data that was explicitly passed to it:
Source code in{% component \"name\" positional_arg keyword_arg=value ... only %}\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"@with_tag_spec(\n TagSpec(\n tag=\"component\",\n end_tag=\"endcomponent\",\n positional_only_args=[],\n positional_args_allow_extra=True, # Allow many args\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[COMP_ONLY_FLAG],\n )\n)\ndef component(\n parser: Parser,\n token: Token,\n registry: ComponentRegistry,\n tag_name: str,\n tag_spec: TagSpec,\n) -> ComponentNode:\n \"\"\"\n Renders one of the components that was previously registered with\n [`@register()`](./api.md#django_components.register)\n decorator.\n\n **Args:**\n\n - `name` (str, required): Registered name of the component to render\n - All other args and kwargs are defined based on the component itself.\n\n If you defined a component `\"my_table\"`\n\n ```python\n from django_component import Component, register\n\n @register(\"my_table\")\n class MyTable(Component):\n template = \\\"\\\"\\\"\n <table>\n <thead>\n {% for header in headers %}\n <th>{{ header }}</th>\n {% endfor %}\n </thead>\n <tbody>\n {% for row in rows %}\n <tr>\n {% for cell in row %}\n <td>{{ cell }}</td>\n {% endfor %}\n </tr>\n {% endfor %}\n <tbody>\n </table>\n \\\"\\\"\\\"\n\n def get_context_data(self, rows: List, headers: List):\n return {\n \"rows\": rows,\n \"headers\": headers,\n }\n ```\n\n Then you can render this component by referring to `MyTable` via its\n registered name `\"my_table\"`:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n ```\n\n ### Component input\n\n Positional and keyword arguments can be literals or template variables.\n\n The component name must be a single- or double-quotes string and must\n be either:\n\n - The first positional argument after `component`:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n ```\n\n - Passed as kwarg `name`:\n\n ```django\n {% component rows=rows headers=headers name=\"my_table\" ... / %}\n ```\n\n ### Inserting into slots\n\n If the component defined any [slots](../concepts/fundamentals/slots.md), you can\n pass in the content to be placed inside those slots by inserting [`{% fill %}`](#fill) tags,\n directly within the `{% component %}` tag:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Isolating components\n\n By default, components behave similarly to Django's\n [`{% include %}`](https://docs.djangoproject.com/en/5.1/ref/templates/builtins/#include),\n and the template inside the component has access to the variables defined in the outer template.\n\n You can selectively isolate a component, using the `only` flag, so that the inner template\n can access only the data that was explicitly passed to it:\n\n ```django\n {% component \"name\" positional_arg keyword_arg=value ... only %}\n ```\n \"\"\"\n _fix_nested_tags(parser, token)\n bits = token.split_contents()\n\n # Let the TagFormatter pre-process the tokens\n formatter = get_tag_formatter(registry)\n result = formatter.parse([*bits])\n end_tag = formatter.end_tag(result.component_name)\n\n # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n bits = [bits[0], *result.tokens]\n token.contents = \" \".join(bits)\n\n tag = _parse_tag(\n parser,\n token,\n TagSpec(\n **{\n **tag_spec._asdict(),\n \"tag\": tag_name,\n \"end_tag\": end_tag,\n }\n ),\n )\n\n # Check for isolated context keyword\n isolated_context = tag.flags[COMP_ONLY_FLAG]\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n body = tag.parse_body()\n\n component_node = ComponentNode(\n name=result.component_name,\n args=tag.args,\n kwargs=tag.kwargs,\n isolated_context=isolated_context,\n nodelist=body,\n node_id=tag.id,\n registry=registry,\n )\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n return component_node\n
component_css_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode\n
Marks location where CSS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted into the
<head>
tag of the HTML.If the generated HTML does NOT contain any
{% component_css_dependencies %}
tags, CSS links are by default inserted into the<head>
tag of the HTML. (See JS and CSS output locations)Note that there should be only one
Source code in{% component_css_dependencies %}
for the whole HTML document. If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"@register.tag(\"component_css_dependencies\")\n@with_tag_spec(\n TagSpec(\n tag=\"component_css_dependencies\",\n end_tag=None, # inline-only\n )\n)\ndef component_css_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode:\n \"\"\"\n Marks location where CSS link tags should be rendered after the whole HTML has been generated.\n\n Generally, this should be inserted into the `<head>` tag of the HTML.\n\n If the generated HTML does NOT contain any `{% component_css_dependencies %}` tags, CSS links\n are by default inserted into the `<head>` tag of the HTML. (See\n [JS and CSS output locations](../../concepts/advanced/rendering_js_css/#js-and-css-output-locations))\n\n Note that there should be only one `{% component_css_dependencies %}` for the whole HTML document.\n If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.\n \"\"\"\n # Parse to check that the syntax is valid\n _parse_tag(parser, token, tag_spec)\n return _component_dependencies(\"css\")\n
component_js_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode\n
Marks location where JS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted at the end of the
<body>
tag of the HTML.If the generated HTML does NOT contain any
{% component_js_dependencies %}
tags, JS scripts are by default inserted at the end of the<body>
tag of the HTML. (See JS and CSS output locations)Note that there should be only one
Source code in{% component_js_dependencies %}
for the whole HTML document. If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.fill","title":"fill","text":"@register.tag(name=\"component_js_dependencies\")\n@with_tag_spec(\n TagSpec(\n tag=\"component_js_dependencies\",\n end_tag=None, # inline-only\n )\n)\ndef component_js_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode:\n \"\"\"\n Marks location where JS link tags should be rendered after the whole HTML has been generated.\n\n Generally, this should be inserted at the end of the `<body>` tag of the HTML.\n\n If the generated HTML does NOT contain any `{% component_js_dependencies %}` tags, JS scripts\n are by default inserted at the end of the `<body>` tag of the HTML. (See\n [JS and CSS output locations](../../concepts/advanced/rendering_js_css/#js-and-css-output-locations))\n\n Note that there should be only one `{% component_js_dependencies %}` for the whole HTML document.\n If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.\n \"\"\"\n # Parse to check that the syntax is valid\n _parse_tag(parser, token, tag_spec)\n return _component_dependencies(\"js\")\n
fill(parser: Parser, token: Token, tag_spec: TagSpec) -> FillNode\n
Use this tag to insert content into component's slots.
{% fill %}
tag may be used only within a{% component %}..{% endcomponent %}
block. Runtime checks should prohibit other usages.Args:
name
(str, required): Name of the slot to insert this content into. Use\"default\"
for the default slot.default
(str, optional): This argument allows you to access the original content of the slot under the specified variable name. See Accessing original content of slotsdata
(str, optional): This argument allows you to access the data passed to the slot under the specified variable name. See Scoped slots
Examples:
Basic usage:
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.fill--accessing-slots-default-content-with-the-default-kwarg","title":"Accessing slot's default content with the{% component \"my_table\" %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n{% endcomponent %}\n
default
kwarg","text":"{# my_table.html #}\n<table>\n ...\n {% slot \"pagination\" %}\n < 1 | 2 | 3 >\n {% endslot %}\n</table>\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.fill--accessing-slots-data-with-the-data-kwarg","title":"Accessing slot's data with the{% component \"my_table\" %}\n {% fill \"pagination\" default=\"default_pag\" %}\n <div class=\"my-class\">\n {{ default_pag }}\n </div>\n {% endfill %}\n{% endcomponent %}\n
data
kwarg","text":"{# my_table.html #}\n<table>\n ...\n {% slot \"pagination\" pages=pages %}\n < 1 | 2 | 3 >\n {% endslot %}\n</table>\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.fill--accessing-slot-data-and-default-content-on-the-default-slot","title":"Accessing slot data and default content on the default slot","text":"{% component \"my_table\" %}\n {% fill \"pagination\" data=\"slot_data\" %}\n {% for page in slot_data.pages %}\n <a href=\"{{ page.link }}\">\n {{ page.index }}\n </a>\n {% endfor %}\n {% endfill %}\n{% endcomponent %}\n
To access slot data and the default slot content on the default slot, use
{% fill %}
withname
set to\"default\"
:
Source code in{% component \"button\" %}\n {% fill name=\"default\" data=\"slot_data\" default=\"default_slot\" %}\n You clicked me {{ slot_data.count }} times!\n {{ default_slot }}\n {% endfill %}\n{% endcomponent %}\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"@register.tag(\"fill\")\n@with_tag_spec(\n TagSpec(\n tag=\"fill\",\n end_tag=\"endfill\",\n positional_only_args=[],\n pos_or_keyword_args=[SLOT_NAME_KWARG],\n keywordonly_args=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n optional_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n repeatable_kwargs=False,\n )\n)\ndef fill(parser: Parser, token: Token, tag_spec: TagSpec) -> FillNode:\n \"\"\"\n Use this tag to insert content into component's slots.\n\n `{% fill %}` tag may be used only within a `{% component %}..{% endcomponent %}` block.\n Runtime checks should prohibit other usages.\n\n **Args:**\n\n - `name` (str, required): Name of the slot to insert this content into. Use `\"default\"` for\n the default slot.\n - `default` (str, optional): This argument allows you to access the original content of the slot\n under the specified variable name. See\n [Accessing original content of slots](../../concepts/fundamentals/slots#accessing-original-content-of-slots)\n - `data` (str, optional): This argument allows you to access the data passed to the slot\n under the specified variable name. See [Scoped slots](../../concepts/fundamentals/slots#scoped-slots)\n\n **Examples:**\n\n Basic usage:\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot's default content with the `default` kwarg\n\n ```django\n {# my_table.html #}\n <table>\n ...\n {% slot \"pagination\" %}\n < 1 | 2 | 3 >\n {% endslot %}\n </table>\n ```\n\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" default=\"default_pag\" %}\n <div class=\"my-class\">\n {{ default_pag }}\n </div>\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot's data with the `data` kwarg\n\n ```django\n {# my_table.html #}\n <table>\n ...\n {% slot \"pagination\" pages=pages %}\n < 1 | 2 | 3 >\n {% endslot %}\n </table>\n ```\n\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" data=\"slot_data\" %}\n {% for page in slot_data.pages %}\n <a href=\"{{ page.link }}\">\n {{ page.index }}\n </a>\n {% endfor %}\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot data and default content on the default slot\n\n To access slot data and the default slot content on the default slot,\n use `{% fill %}` with `name` set to `\"default\"`:\n\n ```django\n {% component \"button\" %}\n {% fill name=\"default\" data=\"slot_data\" default=\"default_slot\" %}\n You clicked me {{ slot_data.count }} times!\n {{ default_slot }}\n {% endfill %}\n {% endcomponent %}\n ```\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n fill_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n trace_id = f\"fill-id-{tag.id} ({fill_name_kwarg})\" if fill_name_kwarg else f\"fill-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id)\n\n body = tag.parse_body()\n fill_node = FillNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id, \"...Done!\")\n return fill_node\n
html_attrs(parser: Parser, token: Token, tag_spec: TagSpec) -> HtmlAttrsNode\n
Generate HTML attributes (
key=\"value\"
), combining data from multiple sources, whether its template variables or static text.It is designed to easily merge HTML attributes passed from outside with the internal. See how to in Passing HTML attributes to components.
Args:
attrs
(dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides values in thedefault
dictionary.default
(str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden with values in theattrs
dictionary.- Any extra kwargs will be appended to the corresponding keys
The attributes in
attrs
anddefaults
are merged and resulting dict is rendered as HTML attributes (key=\"value\"
).Extra kwargs (
key=value
) are concatenated to existing keys. So if we haveattrs = {\"class\": \"my-class\"}\n
Then
{% html_attrs attrs class=\"extra-class\" %}\n
will result in
class=\"my-class extra-class\"
.Example:
<div {% html_attrs\n attrs\n defaults:class=\"default-class\"\n class=\"extra-class\"\n data-id=\"123\"\n%}>\n
renders
<div class=\"my-class extra-class\" data-id=\"123\">\n
See more usage examples in HTML attributes.
Source code insrc/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.provide","title":"provide","text":"@register.tag(\"html_attrs\")\n@with_tag_spec(\n TagSpec(\n tag=\"html_attrs\",\n end_tag=None, # inline-only\n positional_only_args=[],\n pos_or_keyword_args=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n optional_kwargs=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n keywordonly_args=True,\n repeatable_kwargs=True,\n flags=[],\n )\n)\ndef html_attrs(parser: Parser, token: Token, tag_spec: TagSpec) -> HtmlAttrsNode:\n \"\"\"\n Generate HTML attributes (`key=\"value\"`), combining data from multiple sources,\n whether its template variables or static text.\n\n It is designed to easily merge HTML attributes passed from outside with the internal.\n See how to in [Passing HTML attributes to components](../../guides/howto/passing_html_attrs/).\n\n **Args:**\n\n - `attrs` (dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides\n values in the `default` dictionary.\n - `default` (str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden\n with values in the `attrs` dictionary.\n - Any extra kwargs will be appended to the corresponding keys\n\n The attributes in `attrs` and `defaults` are merged and resulting dict is rendered as HTML attributes\n (`key=\"value\"`).\n\n Extra kwargs (`key=value`) are concatenated to existing keys. So if we have\n\n ```python\n attrs = {\"class\": \"my-class\"}\n ```\n\n Then\n\n ```django\n {% html_attrs attrs class=\"extra-class\" %}\n ```\n\n will result in `class=\"my-class extra-class\"`.\n\n **Example:**\n ```django\n <div {% html_attrs\n attrs\n defaults:class=\"default-class\"\n class=\"extra-class\"\n data-id=\"123\"\n %}>\n ```\n\n renders\n\n ```html\n <div class=\"my-class extra-class\" data-id=\"123\">\n ```\n\n **See more usage examples in\n [HTML attributes](../../concepts/fundamentals/html_attributes#examples-for-html_attrs).**\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n return HtmlAttrsNode(\n kwargs=tag.kwargs,\n kwarg_pairs=tag.kwarg_pairs,\n )\n
provide(parser: Parser, token: Token, tag_spec: TagSpec) -> ProvideNode\n
The \"provider\" part of the provide / inject feature. Pass kwargs to this tag to define the provider's data. Any components defined within the
{% provide %}..{% endprovide %}
tags will be able to access this data withComponent.inject()
.This is similar to React's
ContextProvider
, or Vue'sprovide()
.Args:
name
(str, required): Provider name. This is the name you will then use inComponent.inject()
.**kwargs
: Any extra kwargs will be passed as the provided data.
Example:
Provide the \"user_data\" in parent component:
@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n <div>\n {% provide \"user_data\" user=user %}\n {% component \"child\" / %}\n {% endprovide %}\n </div>\n \"\"\"\n\n def get_context_data(self, user: User):\n return {\n \"user\": user,\n }\n
Since the \"child\" component is used within the
{% provide %} / {% endprovide %}
tags, we can request the \"user_data\" usingComponent.inject(\"user_data\")
:@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n User is: {{ user }}\n </div>\n \"\"\"\n\n def get_context_data(self):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n
Notice that the keys defined on the
{% provide %}
tag are then accessed as attributes when accessing them withComponent.inject()
.\u2705 Do this
user = self.inject(\"user_data\").user\n
\u274c Don't do this
Source code inuser = self.inject(\"user_data\")[\"user\"]\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.slot","title":"slot","text":"@register.tag(\"provide\")\n@with_tag_spec(\n TagSpec(\n tag=\"provide\",\n end_tag=\"endprovide\",\n positional_only_args=[],\n pos_or_keyword_args=[PROVIDE_NAME_KWARG],\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[],\n )\n)\ndef provide(parser: Parser, token: Token, tag_spec: TagSpec) -> ProvideNode:\n \"\"\"\n The \"provider\" part of the [provide / inject feature](../../concepts/advanced/provide_inject).\n Pass kwargs to this tag to define the provider's data.\n Any components defined within the `{% provide %}..{% endprovide %}` tags will be able to access this data\n with [`Component.inject()`](../api#django_components.Component.inject).\n\n This is similar to React's [`ContextProvider`](https://react.dev/learn/passing-data-deeply-with-context),\n or Vue's [`provide()`](https://vuejs.org/guide/components/provide-inject).\n\n **Args:**\n\n - `name` (str, required): Provider name. This is the name you will then use in\n [`Component.inject()`](../api#django_components.Component.inject).\n - `**kwargs`: Any extra kwargs will be passed as the provided data.\n\n **Example:**\n\n Provide the \"user_data\" in parent component:\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n <div>\n {% provide \"user_data\" user=user %}\n {% component \"child\" / %}\n {% endprovide %}\n </div>\n \\\"\\\"\\\"\n\n def get_context_data(self, user: User):\n return {\n \"user\": user,\n }\n ```\n\n Since the \"child\" component is used within the `{% provide %} / {% endprovide %}` tags,\n we can request the \"user_data\" using `Component.inject(\"user_data\")`:\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n User is: {{ user }}\n </div>\n \\\"\\\"\\\"\n\n def get_context_data(self):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n ```\n\n Notice that the keys defined on the `{% provide %}` tag are then accessed as attributes\n when accessing them with [`Component.inject()`](../api#django_components.Component.inject).\n\n \u2705 Do this\n ```python\n user = self.inject(\"user_data\").user\n ```\n\n \u274c Don't do this\n ```python\n user = self.inject(\"user_data\")[\"user\"]\n ```\n \"\"\"\n # e.g. {% provide <name> key=val key2=val2 %}\n tag = _parse_tag(parser, token, tag_spec)\n\n name_kwarg = tag.kwargs.kwargs.get(PROVIDE_NAME_KWARG, None)\n trace_id = f\"provide-id-{tag.id} ({name_kwarg})\" if name_kwarg else f\"fill-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"PROVIDE\", trace_id, tag.id)\n\n body = tag.parse_body()\n provide_node = ProvideNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"PROVIDE\", trace_id, tag.id, \"...Done!\")\n return provide_node\n
slot(parser: Parser, token: Token, tag_spec: TagSpec) -> SlotNode\n
Slot tag marks a place inside a component where content can be inserted from outside.
Learn more about using slots.
This is similar to slots as seen in Web components, Vue or React's
children
.Args:
name
(str, required): Registered name of the component to renderdefault
: Optional flag. If there is a default slot, you can pass the component slot content without using the{% fill %}
tag. See Default slotrequired
: Optional flag. Will raise an error if a slot is required but not given.**kwargs
: Any extra kwargs will be passed as the slot data.
Example:
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" default %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n <aside>\n {% slot \"sidebar\" required / %}\n </aside>\n \"\"\"\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.slot--passing-data-to-slots","title":"Passing data to slots","text":"@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n <div>\n {% component \"child\" %}\n {% fill \"content\" %}\n \ud83d\uddde\ufe0f\ud83d\udcf0\n {% endfill %}\n\n {% fill \"sidebar\" %}\n \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n {% endfill %}\n {% endcomponent %}\n </div>\n \"\"\"\n
Any extra kwargs will be considered as slot data, and will be accessible in the
{% fill %}
tag via fill'sdata
kwarg:@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \"\"\"\n
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.slot--accessing-default-slot-content","title":"Accessing default slot content","text":"@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
The content between the
{% slot %}..{% endslot %}
tags is the default content that will be rendered if no fill is given for the slot.This default content can then be accessed from within the
{% fill %}
tag using the fill'sdefault
kwarg. This is useful if you need to wrap / prepend / append the original slot's content.@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" %}\n This is default content!\n {% endslot %}\n </div>\n \"\"\"\n
Source code in@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot's default content #}\n {% component \"child\" %}\n {% fill \"content\" default=\"default\" %}\n {{ default }}\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/#django_components.templatetags.component_tags.with_tag_spec","title":"with_tag_spec","text":"@register.tag(\"slot\")\n@with_tag_spec(\n TagSpec(\n tag=\"slot\",\n end_tag=\"endslot\",\n positional_only_args=[],\n pos_or_keyword_args=[SLOT_NAME_KWARG],\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[SLOT_DEFAULT_KEYWORD, SLOT_REQUIRED_KEYWORD],\n )\n)\ndef slot(parser: Parser, token: Token, tag_spec: TagSpec) -> SlotNode:\n \"\"\"\n Slot tag marks a place inside a component where content can be inserted\n from outside.\n\n [Learn more](../../concepts/fundamentals/slots) about using slots.\n\n This is similar to slots as seen in\n [Web components](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot),\n [Vue](https://vuejs.org/guide/components/slots.html)\n or [React's `children`](https://react.dev/learn/passing-props-to-a-component#passing-jsx-as-children).\n\n **Args:**\n\n - `name` (str, required): Registered name of the component to render\n - `default`: Optional flag. If there is a default slot, you can pass the component slot content\n without using the [`{% fill %}`](#fill) tag. See\n [Default slot](../../concepts/fundamentals/slots#default-slot)\n - `required`: Optional flag. Will raise an error if a slot is required but not given.\n - `**kwargs`: Any extra kwargs will be passed as the slot data.\n\n **Example:**\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {% slot \"content\" default %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n <aside>\n {% slot \"sidebar\" required / %}\n </aside>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n <div>\n {% component \"child\" %}\n {% fill \"content\" %}\n \ud83d\uddde\ufe0f\ud83d\udcf0\n {% endfill %}\n\n {% fill \"sidebar\" %}\n \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n {% endfill %}\n {% endcomponent %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ### Passing data to slots\n\n Any extra kwargs will be considered as slot data, and will be accessible in the [`{% fill %}`](#fill)\n tag via fill's `data` kwarg:\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \\\"\\\"\\\"\n ```\n\n ### Accessing default slot content\n\n The content between the `{% slot %}..{% endslot %}` tags is the default content that\n will be rendered if no fill is given for the slot.\n\n This default content can then be accessed from within the [`{% fill %}`](#fill) tag using\n the fill's `default` kwarg.\n This is useful if you need to wrap / prepend / append the original slot's content.\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {% slot \"content\" %}\n This is default content!\n {% endslot %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n {# Parent can access the slot's default content #}\n {% component \"child\" %}\n {% fill \"content\" default=\"default\" %}\n {{ default }}\n {% endfill %}\n {% endcomponent %}\n \\\"\\\"\\\"\n ```\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n slot_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n trace_id = f\"slot-id-{tag.id} ({slot_name_kwarg})\" if slot_name_kwarg else f\"slot-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"SLOT\", trace_id, tag.id)\n\n body = tag.parse_body()\n slot_node = SlotNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n is_required=tag.flags[SLOT_REQUIRED_KEYWORD],\n is_default=tag.flags[SLOT_DEFAULT_KEYWORD],\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"SLOT\", trace_id, tag.id, \"...Done!\")\n return slot_node\n
Source code inwith_tag_spec(tag_spec: TagSpec) -> Callable\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/#django_components.types","title":"types","text":"def with_tag_spec(tag_spec: TagSpec) -> Callable:\n \"\"\"\"\"\"\n\n def decorator(fn: Callable) -> Any:\n fn._tag_spec = tag_spec # type: ignore[attr-defined]\n\n @functools.wraps(fn)\n def wrapper(*args: Any, **kwargs: Any) -> Any:\n return fn(*args, **kwargs, tag_spec=tag_spec)\n\n return wrapper\n\n return decorator\n
Helper types for IDEs.
"},{"location":"reference/django_components/#django_components.util","title":"util","text":"Modules:
-
cache
\u2013 -
html
\u2013 -
loader
\u2013 -
logger
\u2013 -
misc
\u2013 -
tag_parser
\u2013 -
types
\u2013
Functions:
-
lazy_cache
\u2013Decorator that caches the given function similarly to
functools.lru_cache
.
lazy_cache(make_cache: Callable[[], Callable[[Callable], Callable]]) -> Callable[[TFunc], TFunc]\n
Decorator that caches the given function similarly to
functools.lru_cache
. But the cache is instantiated only at first invocation.
Source code incache
argument is a function that generates the cache function, e.g.functools.lru_cache()
.src/django_components/util/cache.py
"},{"location":"reference/django_components/#django_components.util.html","title":"html","text":"def lazy_cache(\n make_cache: Callable[[], Callable[[Callable], Callable]],\n) -> Callable[[TFunc], TFunc]:\n \"\"\"\n Decorator that caches the given function similarly to `functools.lru_cache`.\n But the cache is instantiated only at first invocation.\n\n `cache` argument is a function that generates the cache function,\n e.g. `functools.lru_cache()`.\n \"\"\"\n _cached_fn = None\n\n def decorator(fn: TFunc) -> TFunc:\n @functools.wraps(fn)\n def wrapper(*args: Any, **kwargs: Any) -> Any:\n # Lazily initialize the cache\n nonlocal _cached_fn\n if not _cached_fn:\n # E.g. `lambda: functools.lru_cache(maxsize=app_settings.TEMPLATE_CACHE_SIZE)`\n cache = make_cache()\n _cached_fn = cache(fn)\n\n return _cached_fn(*args, **kwargs)\n\n # Allow to access the LRU cache methods\n # See https://stackoverflow.com/a/37654201/9788634\n wrapper.cache_info = lambda: _cached_fn.cache_info() # type: ignore\n wrapper.cache_clear = lambda: _cached_fn.cache_clear() # type: ignore\n\n # And allow to remove the cache instance (mostly for tests)\n def cache_remove() -> None:\n nonlocal _cached_fn\n _cached_fn = None\n\n wrapper.cache_remove = cache_remove # type: ignore\n\n return cast(TFunc, wrapper)\n\n return decorator\n
Functions:
-
parse_document_or_nodes
\u2013Use this if you do NOT know whether the given HTML is a full document
-
parse_multiroot_html
\u2013Use this when you know the given HTML is a multiple nodes like
-
parse_node
\u2013Use this when you know the given HTML is a single node like
parse_document_or_nodes(html: str) -> Union[List[LexborNode], LexborHTMLParser]\n
Use this if you do NOT know whether the given HTML is a full document with
Source code in<html>
,<head>
, and<body>
tags, or an HTML fragment.src/django_components/util/html.py
"},{"location":"reference/django_components/#django_components.util.html.parse_multiroot_html","title":"parse_multiroot_html","text":"def parse_document_or_nodes(html: str) -> Union[List[LexborNode], LexborHTMLParser]:\n \"\"\"\n Use this if you do NOT know whether the given HTML is a full document\n with `<html>`, `<head>`, and `<body>` tags, or an HTML fragment.\n \"\"\"\n html = html.strip()\n tree = LexborHTMLParser(html)\n is_fragment = is_html_parser_fragment(html, tree)\n\n if is_fragment:\n nodes = parse_multiroot_html(html)\n return nodes\n else:\n return tree\n
parse_multiroot_html(html: str) -> List[LexborNode]\n
Use this when you know the given HTML is a multiple nodes like
Source code in<div> Hi </div> <span> Hello </span>
src/django_components/util/html.py
"},{"location":"reference/django_components/#django_components.util.html.parse_node","title":"parse_node","text":"def parse_multiroot_html(html: str) -> List[LexborNode]:\n \"\"\"\n Use this when you know the given HTML is a multiple nodes like\n\n `<div> Hi </div> <span> Hello </span>`\n \"\"\"\n # NOTE: HTML / XML MUST have a single root. So, to support multiple\n # top-level elements, we wrap them in a dummy singular root.\n parser = LexborHTMLParser(f\"<root>{html}</root>\")\n\n # Get all contents of the root\n root_elem = parser.css_first(\"root\")\n elems = [*root_elem.iter()] if root_elem else []\n return elems\n
parse_node(html: str) -> LexborNode\n
Use this when you know the given HTML is a single node like
Source code in<div> Hi </div>
src/django_components/util/html.py
"},{"location":"reference/django_components/#django_components.util.loader","title":"loader","text":"def parse_node(html: str) -> LexborNode:\n \"\"\"\n Use this when you know the given HTML is a single node like\n\n `<div> Hi </div>`\n \"\"\"\n tree = LexborHTMLParser(html)\n # NOTE: The parser automatically places <style> tags inside <head>\n # while <script> tags are inside <body>.\n return tree.body.child or tree.head.child # type: ignore[union-attr, return-value]\n
Classes:
-
ComponentFileEntry
\u2013Result returned by
get_component_files()
.
Functions:
-
get_component_dirs
\u2013Get directories that may contain component files.
-
get_component_files
\u2013Search for files within the component directories (as defined in
Bases:
NamedTuple
Result returned by
get_component_files()
.Attributes:
-
dot_path
(str
) \u2013The python import path for the module. E.g.
app.components.mycomp
-
filepath
(Path
) \u2013The filesystem path to the module. E.g.
/path/to/project/app/components/mycomp.py
instance-attribute
","text":"dot_path: str\n
The python import path for the module. E.g.
"},{"location":"reference/django_components/#django_components.util.loader.ComponentFileEntry.filepath","title":"filepathapp.components.mycomp
instance-attribute
","text":"filepath: Path\n
The filesystem path to the module. E.g.
"},{"location":"reference/django_components/#django_components.util.loader.get_component_dirs","title":"get_component_dirs","text":"/path/to/project/app/components/mycomp.py
get_component_dirs(include_apps: bool = True) -> List[Path]\n
Get directories that may contain component files.
This is the heart of all features that deal with filesystem and file lookup. Autodiscovery, Django template resolution, static file resolution - They all use this.
Parameters:
-
include_apps
(bool
, default:True
) \u2013Include directories from installed Django apps. Defaults to
True
.
Returns:
-
List[Path]
\u2013List[Path]: A list of directories that may contain component files.
get_component_dirs()
searches for dirs set inCOMPONENTS.dirs
settings. If none set, defaults to searching for a\"components\"
app.In addition to that, also all installed Django apps are checked whether they contain directories as set in
COMPONENTS.app_dirs
(e.g.[app]/components
).Notes:
-
Paths that do not point to directories are ignored.
-
BASE_DIR
setting is required. -
The paths in
COMPONENTS.dirs
must be absolute paths.
src/django_components/util/loader.py
"},{"location":"reference/django_components/#django_components.util.loader.get_component_files","title":"get_component_files","text":"def get_component_dirs(include_apps: bool = True) -> List[Path]:\n \"\"\"\n Get directories that may contain component files.\n\n This is the heart of all features that deal with filesystem and file lookup.\n Autodiscovery, Django template resolution, static file resolution - They all use this.\n\n Args:\n include_apps (bool, optional): Include directories from installed Django apps.\\\n Defaults to `True`.\n\n Returns:\n List[Path]: A list of directories that may contain component files.\n\n `get_component_dirs()` searches for dirs set in\n [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n settings. If none set, defaults to searching for a `\"components\"` app.\n\n In addition to that, also all installed Django apps are checked whether they contain\n directories as set in\n [`COMPONENTS.app_dirs`](../settings#django_components.app_settings.ComponentsSettings.app_dirs)\n (e.g. `[app]/components`).\n\n **Notes:**\n\n - Paths that do not point to directories are ignored.\n\n - `BASE_DIR` setting is required.\n\n - The paths in [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n must be absolute paths.\n \"\"\"\n # Allow to configure from settings which dirs should be checked for components\n component_dirs = app_settings.DIRS\n\n # TODO_REMOVE_IN_V1\n raw_component_settings = getattr(settings, \"COMPONENTS\", {})\n if isinstance(raw_component_settings, dict):\n raw_dirs_value = raw_component_settings.get(\"dirs\", None)\n elif isinstance(raw_component_settings, ComponentsSettings):\n raw_dirs_value = raw_component_settings.dirs\n else:\n raw_dirs_value = None\n is_component_dirs_set = raw_dirs_value is not None\n is_legacy_paths = (\n # Use value of `STATICFILES_DIRS` ONLY if `COMPONENT.dirs` not set\n not is_component_dirs_set\n and hasattr(settings, \"STATICFILES_DIRS\")\n and settings.STATICFILES_DIRS\n )\n if is_legacy_paths:\n # NOTE: For STATICFILES_DIRS, we use the defaults even for empty list.\n # We don't do this for COMPONENTS.dirs, so user can explicitly specify \"NO dirs\".\n component_dirs = settings.STATICFILES_DIRS or [settings.BASE_DIR / \"components\"]\n # END TODO_REMOVE_IN_V1\n\n source = \"STATICFILES_DIRS\" if is_legacy_paths else \"COMPONENTS.dirs\"\n\n logger.debug(\n \"get_component_dirs will search for valid dirs from following options:\\n\"\n + \"\\n\".join([f\" - {str(d)}\" for d in component_dirs])\n )\n\n # Add `[app]/[APP_DIR]` to the directories. This is, by default `[app]/components`\n app_paths: List[Path] = []\n if include_apps:\n for conf in apps.get_app_configs():\n for app_dir in app_settings.APP_DIRS:\n comps_path = Path(conf.path).joinpath(app_dir)\n if comps_path.exists():\n app_paths.append(comps_path)\n\n directories: Set[Path] = set(app_paths)\n\n # Validate and add other values from the config\n for component_dir in component_dirs:\n # Consider tuples for STATICFILES_DIRS (See #489)\n # See https://docs.djangoproject.com/en/5.0/ref/settings/#prefixes-optional\n if isinstance(component_dir, (tuple, list)):\n component_dir = component_dir[1]\n try:\n Path(component_dir)\n except TypeError:\n logger.warning(\n f\"{source} expected str, bytes or os.PathLike object, or tuple/list of length 2. \"\n f\"See Django documentation for STATICFILES_DIRS. Got {type(component_dir)} : {component_dir}\"\n )\n continue\n\n if not Path(component_dir).is_absolute():\n raise ValueError(f\"{source} must contain absolute paths, got '{component_dir}'\")\n else:\n directories.add(Path(component_dir).resolve())\n\n logger.debug(\n \"get_component_dirs matched following template dirs:\\n\" + \"\\n\".join([f\" - {str(d)}\" for d in directories])\n )\n return list(directories)\n
get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]\n
Search for files within the component directories (as defined in
get_component_dirs()
).Requires
BASE_DIR
setting to be set.Parameters:
-
suffix
(Optional[str]
, default:None
) \u2013The suffix to search for. E.g.
.py
,.js
,.css
. Defaults toNone
, which will search for all files.
Returns:
-
List[ComponentFileEntry]
\u2013List[ComponentFileEntry] A list of entries that contain both the filesystem path and the python import path (dot path).
Example:
Source code infrom django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
src/django_components/util/loader.py
"},{"location":"reference/django_components/#django_components.util.logger","title":"logger","text":"def get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]:\n \"\"\"\n Search for files within the component directories (as defined in\n [`get_component_dirs()`](../api#django_components.get_component_dirs)).\n\n Requires `BASE_DIR` setting to be set.\n\n Args:\n suffix (Optional[str], optional): The suffix to search for. E.g. `.py`, `.js`, `.css`.\\\n Defaults to `None`, which will search for all files.\n\n Returns:\n List[ComponentFileEntry] A list of entries that contain both the filesystem path and \\\n the python import path (dot path).\n\n **Example:**\n\n ```python\n from django_components import get_component_files\n\n modules = get_component_files(\".py\")\n ```\n \"\"\"\n search_glob = f\"**/*{suffix}\" if suffix else \"**/*\"\n\n dirs = get_component_dirs(include_apps=False)\n component_filepaths = _search_dirs(dirs, search_glob)\n\n if hasattr(settings, \"BASE_DIR\") and settings.BASE_DIR:\n project_root = str(settings.BASE_DIR)\n else:\n # Fallback for getting the root dir, see https://stackoverflow.com/a/16413955/9788634\n project_root = os.path.abspath(os.path.dirname(__name__))\n\n # NOTE: We handle dirs from `COMPONENTS.dirs` and from individual apps separately.\n modules: List[ComponentFileEntry] = []\n\n # First let's handle the dirs from `COMPONENTS.dirs`\n #\n # Because for dirs in `COMPONENTS.dirs`, we assume they will be nested under `BASE_DIR`,\n # and that `BASE_DIR` is the current working dir (CWD). So the path relatively to `BASE_DIR`\n # is ALSO the python import path.\n for filepath in component_filepaths:\n module_path = _filepath_to_python_module(filepath, project_root, None)\n # Ignore files starting with dot `.` or files in dirs that start with dot.\n #\n # If any of the parts of the path start with a dot, e.g. the filesystem path\n # is `./abc/.def`, then this gets converted to python module as `abc..def`\n #\n # NOTE: This approach also ignores files:\n # - with two dots in the middle (ab..cd.py)\n # - an extra dot at the end (abcd..py)\n # - files outside of the parent component (../abcd.py).\n # But all these are NOT valid python modules so that's fine.\n if \"..\" in module_path:\n continue\n\n entry = ComponentFileEntry(dot_path=module_path, filepath=filepath)\n modules.append(entry)\n\n # For for apps, the directories may be outside of the project, e.g. in case of third party\n # apps. So we have to resolve the python import path relative to the package name / the root\n # import path for the app.\n # See https://github.com/EmilStenstrom/django-components/issues/669\n for conf in apps.get_app_configs():\n for app_dir in app_settings.APP_DIRS:\n comps_path = Path(conf.path).joinpath(app_dir)\n if not comps_path.exists():\n continue\n app_component_filepaths = _search_dirs([comps_path], search_glob)\n for filepath in app_component_filepaths:\n app_component_module = _filepath_to_python_module(filepath, conf.path, conf.name)\n entry = ComponentFileEntry(dot_path=app_component_module, filepath=filepath)\n modules.append(entry)\n\n return modules\n
Functions:
-
trace
\u2013TRACE level logger.
-
trace_msg
\u2013TRACE level logger with opinionated format for tracing interaction of components,
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:
Source code inLOGGING = {\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
src/django_components/util/logger.py
"},{"location":"reference/django_components/#django_components.util.logger.trace_msg","title":"trace_msg","text":"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
trace_msg(\n action: Literal[\"PARSE\", \"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:
Source code in\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"
src/django_components/util/logger.py
"},{"location":"reference/django_components/#django_components.util.misc","title":"misc","text":"def trace_msg(\n action: Literal[\"PARSE\", \"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 == \"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
Functions:
-
gen_id
\u2013Generate a unique ID that can be associated with a Node
-
get_import_path
\u2013Get the full import path for a class or a function, e.g.
\"path.to.MyClass\"
gen_id() -> str\n
Generate a unique ID that can be associated with a Node
Source code insrc/django_components/util/misc.py
"},{"location":"reference/django_components/#django_components.util.misc.get_import_path","title":"get_import_path","text":"def gen_id() -> str:\n \"\"\"Generate a unique ID that can be associated with a Node\"\"\"\n # Alphabet is only alphanumeric. Compared to the default alphabet used by nanoid,\n # we've omitted `-` and `_`.\n # With this alphabet, at 6 chars, the chance of collision is 1 in 3.3M.\n # See https://zelark.github.io/nano-id-cc/\n return generate(\n \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\",\n size=6,\n )\n
get_import_path(cls_or_fn: Type[Any]) -> str\n
Get the full import path for a class or a function, e.g.
Source code in\"path.to.MyClass\"
src/django_components/util/misc.py
"},{"location":"reference/django_components/#django_components.util.tag_parser","title":"tag_parser","text":"def get_import_path(cls_or_fn: Type[Any]) -> str:\n \"\"\"\n Get the full import path for a class or a function, e.g. `\"path.to.MyClass\"`\n \"\"\"\n module = cls_or_fn.__module__\n if module == \"builtins\":\n return cls_or_fn.__qualname__ # avoid outputs like 'builtins.str'\n return module + \".\" + cls_or_fn.__qualname__\n
Classes:
-
TagAttr
\u2013
dataclass
","text":"TagAttr(key: Optional[str], value: str, start_index: int, quoted: bool)\n
Attributes:
-
quoted
(bool
) \u2013Whether the value is quoted (either with single or double quotes)
-
start_index
(int
) \u2013Start index of the attribute (include both key and value),
instance-attribute
","text":"quoted: bool\n
Whether the value is quoted (either with single or double quotes)
"},{"location":"reference/django_components/#django_components.util.tag_parser.TagAttr.start_index","title":"start_indexinstance-attribute
","text":"start_index: int\n
Start index of the attribute (include both key and value), relative to the start of the owner Tag.
"},{"location":"reference/django_components/#django_components.util.types","title":"types","text":"Classes:
-
EmptyDict
\u2013TypedDict with no members.
Attributes:
-
EmptyTuple
\u2013Tuple with no members.
module-attribute
","text":"EmptyTuple = Tuple[]\n
Tuple with no members.
You can use this to define a Component that accepts NO positional arguments:
from django_components import Component, EmptyTuple\n\nclass Table(Component(EmptyTuple, Any, Any, Any, Any, Any))\n ...\n
After that, when you call
Component.render()
orComponent.render_to_response()
, theargs
parameter will raise type error ifargs
is anything else than an empty tuple.Table.render(\n args: (),\n)\n
Omitting
args
is also fine:Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
"},{"location":"reference/django_components/#django_components.util.types.EmptyDict","title":"EmptyDict","text":"Table.render(\n args: (\"one\", 2, \"three\"),\n)\n
Bases:
TypedDict
TypedDict with no members.
You can use this to define a Component that accepts NO kwargs, or NO slots, or returns NO data from
Component.get_context_data()
/Component.get_js_data()
/Component.get_css_data()
:Accepts NO kwargs:
from django_components import Component, EmptyDict\n\nclass Table(Component(Any, EmptyDict, Any, Any, Any, Any))\n ...\n
Accepts NO slots:
from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, EmptyDict, Any, Any, Any))\n ...\n
Returns NO data from
get_context_data()
:from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, Any, EmptyDict, Any, Any))\n ...\n
Going back to the example with NO kwargs, when you then call
Component.render()
orComponent.render_to_response()
, thekwargs
parameter will raise type error ifkwargs
is anything else than an empty dict.Table.render(\n kwargs: {},\n)\n
Omitting
kwargs
is also fine:Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
"},{"location":"reference/django_components/app_settings/","title":"Table.render(\n kwargs: {\n \"one\": 2,\n \"three\": 4,\n },\n)\n
app_settings","text":""},{"location":"reference/django_components/app_settings/#django_components.app_settings","title":"app_settings","text":"
Classes:
-
ComponentsSettings
\u2013Settings available for django_components.
-
ContextBehavior
\u2013Configure how (and whether) the context is passed to the component fills
Bases:
NamedTuple
Settings available for django_components.
Example:
COMPONENTS = ComponentsSettings(\n autodiscover=False,\n dirs = [BASE_DIR / \"components\"],\n)\n
Attributes:
-
app_dirs
(Optional[Sequence[str]]
) \u2013Specify the app-level directories that contain your components.
-
autodiscover
(Optional[bool]
) \u2013Toggle whether to run autodiscovery at the Django server startup.
-
context_behavior
(Optional[ContextBehaviorType]
) \u2013Configure whether, inside a component template, you can use variables from the outside
-
dirs
(Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]]
) \u2013Specify the directories that contain your components.
-
dynamic_component_name
(Optional[str]
) \u2013By default, the dynamic component
-
forbidden_static_files
(Optional[List[Union[str, Pattern]]]
) \u2013Deprecated. Use
-
libraries
(Optional[List[str]]
) \u2013Configure extra python modules that should be loaded.
-
multiline_tags
(Optional[bool]
) \u2013Enable / disable
-
reload_on_file_change
(Optional[bool]
) \u2013This is relevant if you are using the project structure where
-
reload_on_template_change
(Optional[bool]
) \u2013Deprecated. Use
-
static_files_allowed
(Optional[List[Union[str, Pattern]]]
) \u2013A list of file extensions (including the leading dot) that define which files within
-
static_files_forbidden
(Optional[List[Union[str, Pattern]]]
) \u2013A list of file extensions (including the leading dot) that define which files within
-
tag_formatter
(Optional[Union[TagFormatterABC, str]]
) \u2013Configure what syntax is used inside Django templates to render components.
-
template_cache_size
(Optional[int]
) \u2013Configure the maximum amount of Django templates to be cached.
class-attribute
instance-attribute
","text":"app_dirs: Optional[Sequence[str]] = None\n
Specify the app-level directories that contain your components.
Defaults to
[\"components\"]
. That is, for each Django app, we search<app>/components/
for components.The paths must be relative to app, e.g.:
COMPONENTS = ComponentsSettings(\n app_dirs=[\"my_comps\"],\n)\n
To search for
<app>/my_comps/
.These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.
Set to empty list to disable app-level components:
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.autodiscover","title":"autodiscoverCOMPONENTS = ComponentsSettings(\n app_dirs=[],\n)\n
class-attribute
instance-attribute
","text":"autodiscover: Optional[bool] = None\n
Toggle whether to run autodiscovery at the Django server startup.
Defaults to
True
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.context_behavior","title":"context_behaviorCOMPONENTS = ComponentsSettings(\n autodiscover=False,\n)\n
class-attribute
instance-attribute
","text":"context_behavior: Optional[ContextBehaviorType] = None\n
Configure whether, inside a component template, you can use variables from the outside (
\"django\"
) or not (\"isolated\"
). This also affects what variables are available inside the{% fill %}
tags.Also see Component context and scope.
Defaults to
\"django\"
.COMPONENTS = ComponentsSettings(\n context_behavior=\"isolated\",\n)\n
NOTE:
context_behavior
andslot_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
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.dirs","title":"dirs\"django\"
. See the rationale for change here.class-attribute
instance-attribute
","text":"dirs: Optional[Sequence[Union[str, PathLike, Tuple[str, str], Tuple[str, PathLike]]]] = None\n
Specify the directories that contain your components.
Defaults to
[Path(settings.BASE_DIR) / \"components\"]
. That is, the rootcomponents/
app.Directories must be full paths, same as with STATICFILES_DIRS.
These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.
COMPONENTS = ComponentsSettings(\n dirs=[BASE_DIR / \"components\"],\n)\n
Set to empty list to disable global components directories:
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.dynamic_component_name","title":"dynamic_component_nameCOMPONENTS = ComponentsSettings(\n dirs=[],\n)\n
class-attribute
instance-attribute
","text":"dynamic_component_name: Optional[str] = None\n
By default, the dynamic component is registered under the name
\"dynamic\"
.In case of a conflict, you can use this setting to change the component name used for the dynamic components.
# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.forbidden_static_files","title":"forbidden_static_files{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
class-attribute
instance-attribute
","text":"forbidden_static_files: Optional[List[Union[str, Pattern]]] = None\n
Deprecated. Use
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.libraries","title":"librariesCOMPONENTS.static_files_forbidden
instead.class-attribute
instance-attribute
","text":"libraries: Optional[List[str]] = None\n
Configure extra python modules that should be loaded.
This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.
Expects a list of python module paths. Defaults to empty list.
Example:
COMPONENTS = ComponentsSettings(\n libraries=[\n \"mysite.components.forms\",\n \"mysite.components.buttons\",\n \"mysite.components.cards\",\n ],\n)\n
This would be the equivalent of importing these modules from within Django's
AppConfig.ready()
:
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.libraries--manually-loading-libraries","title":"Manually loading libraries","text":"class MyAppConfig(AppConfig):\n def ready(self):\n import \"mysite.components.forms\"\n import \"mysite.components.buttons\"\n import \"mysite.components.cards\"\n
In the rare case that you need to manually trigger the import of libraries, you can use the
import_libraries()
function:
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.multiline_tags","title":"multiline_tagsfrom django_components import import_libraries\n\nimport_libraries()\n
class-attribute
instance-attribute
","text":"multiline_tags: Optional[bool] = None\n
Enable / disable multiline support for template tags. If
True
, template tags like{% component %}
or{{ my_var }}
can span multiple lines.Defaults to
True
.Disable this setting if you are making custom modifications to Django's regular expression for parsing templates at
django.template.base.tag_re
.
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.reload_on_file_change","title":"reload_on_file_changeCOMPONENTS = ComponentsSettings(\n multiline_tags=False,\n)\n
class-attribute
instance-attribute
","text":"reload_on_file_change: Optional[bool] = None\n
This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.
In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.
Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.
The setting
reload_on_file_change
fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.If
True
, django_components configures Django to reload when files insideCOMPONENTS.dirs
orCOMPONENTS.app_dirs
change.See Reload dev server on component file changes.
Defaults to
False
.Warning
This setting should be enabled only for the dev environment!
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.reload_on_template_change","title":"reload_on_template_changeclass-attribute
instance-attribute
","text":"reload_on_template_change: Optional[bool] = None\n
Deprecated. Use
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.static_files_allowed","title":"static_files_allowedCOMPONENTS.reload_on_file_change
instead.class-attribute
instance-attribute
","text":"static_files_allowed: Optional[List[Union[str, Pattern]]] = None\n
A list of file extensions (including the leading dot) that define which files within
COMPONENTS.dirs
orCOMPONENTS.app_dirs
are treated as static files.If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running
collectstatic
, and can be accessed under the static file endpoint.You can also pass in compiled regexes (
re.Pattern
) for more advanced patterns.By default, JS, CSS, and common image and font file formats are considered static files:
COMPONENTS = ComponentsSettings(\n static_files_allowed=[\n \".css\",\n \".js\", \".jsx\", \".ts\", \".tsx\",\n # Images\n \".apng\", \".png\", \".avif\", \".gif\", \".jpg\",\n \".jpeg\", \".jfif\", \".pjpeg\", \".pjp\", \".svg\",\n \".webp\", \".bmp\", \".ico\", \".cur\", \".tif\", \".tiff\",\n # Fonts\n \".eot\", \".ttf\", \".woff\", \".otf\", \".svg\",\n ],\n)\n
Warning
Exposing your Python files can be a security vulnerability. See Security notes.
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.static_files_forbidden","title":"static_files_forbiddenclass-attribute
instance-attribute
","text":"static_files_forbidden: Optional[List[Union[str, Pattern]]] = None\n
A list of file extensions (including the leading dot) that define which files within
COMPONENTS.dirs
orCOMPONENTS.app_dirs
will NEVER be treated as static files.If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in
static_files_allowed
.Use this setting together with
static_files_allowed
for a fine control over what file types will be exposed.You can also pass in compiled regexes (
re.Pattern
) for more advanced patterns.By default, any HTML and Python are considered NOT static files:
COMPONENTS = ComponentsSettings(\n static_files_forbidden=[\n \".html\", \".django\", \".dj\", \".tpl\",\n # Python files\n \".py\", \".pyc\",\n ],\n)\n
Warning
Exposing your Python files can be a security vulnerability. See Security notes.
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ComponentsSettings.tag_formatter","title":"tag_formatterclass-attribute
instance-attribute
","text":"tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n
Configure what syntax is used inside Django templates to render components. See the available tag formatters.
Defaults to
\"django_components.component_formatter\"
.Learn more about Customizing component tags with TagFormatter.
Can be set either as direct reference:
from django_components import component_formatter\n\nCOMPONENTS = ComponentsSettings(\n \"tag_formatter\": component_formatter\n)\n
Or as an import string;
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_formatter\"\n)\n
Examples:
-
\"django_components.component_formatter\"
Set
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_formatter\"\n)\n
To write components like this:
{% component \"button\" href=\"...\" %}\n Click me!\n{% endcomponent %}\n
-
django_components.component_shorthand_formatter
Set
COMPONENTS = ComponentsSettings(\n \"tag_formatter\": \"django_components.component_shorthand_formatter\"\n)\n
To write components like this:
{% button href=\"...\" %}\n Click me!\n{% endbutton %}\n
class-attribute
instance-attribute
","text":"template_cache_size: Optional[int] = None\n
Configure the maximum amount of Django templates to be cached.
Defaults to
128
.Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's
lru_cache
decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding
Component.get_template()
to render many dynamic templates, you can increase this number.COMPONENTS = ComponentsSettings(\n template_cache_size=256,\n)\n
To remove the cache limit altogether and cache everything, set
template_cache_size
toNone
.COMPONENTS = ComponentsSettings(\n template_cache_size=None,\n)\n
If you want to add templates to the cache yourself, you can use
cached_template()
:
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ContextBehavior","title":"ContextBehavior","text":"from django_components import cached_template\n\ncached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n pass\n\ncached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n)\n
Bases:
str
,Enum
Configure how (and whether) the context is passed to the component fills and what variables are available inside the
{% fill %}
tags.Also see Component context and scope.
Options:
django
: With this setting, component fills behave as usual Django tags.isolated
: This setting makes the component fills behave similar to Vue or React.
Attributes:
-
DJANGO
\u2013With this setting, component fills behave as usual Django tags.
-
ISOLATED
\u2013This setting makes the component fills behave similar to Vue or React, where
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
Component.get_context_data()
are available to the component fill.
Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the
Component.get_context_data()
method{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
456 # my_var\nfeta # cheese\n
Because \"my_comp\" overrides the variable \"my_var\", so
{{ my_var }}
equals456
.And variable \"cheese\" will equal
"},{"location":"reference/django_components/app_settings/#django_components.app_settings.ContextBehavior.ISOLATED","title":"ISOLATEDfeta
, because the fill CAN access the current context.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
Component.get_context_data()
.Example:
Given this template
{% with cheese=\"feta\" %}\n {% component 'my_comp' %}\n {{ my_var }} # my_var\n {{ cheese }} # cheese\n {% endcomponent %}\n{% endwith %}\n
and this context returned from the
get_context_data()
method{ \"my_var\": 123 }\n
Then if component \"my_comp\" defines context
{ \"my_var\": 456 }\n
Then this will render:
123 # my_var\n # cheese\n
Because both variables \"my_var\" and \"cheese\" are taken from the root context. Since \"cheese\" is not defined in root context, it's empty.
"},{"location":"reference/django_components/apps/","title":"apps","text":""},{"location":"reference/django_components/apps/#django_components.apps","title":"apps","text":""},{"location":"reference/django_components/attributes/","title":"
attributes","text":""},{"location":"reference/django_components/attributes/#django_components.attributes","title":"attributes","text":"
Functions:
-
append_attributes
\u2013Merges the key-value pairs and returns a new dictionary.
-
attributes_to_string
\u2013Convert a dict of attributes to a string.
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 insrc/django_components/attributes.py
"},{"location":"reference/django_components/attributes/#django_components.attributes.attributes_to_string","title":"attributes_to_string","text":"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
attributes_to_string(attributes: Mapping[str, Any]) -> str\n
Convert a dict of attributes to a string.
Source code insrc/django_components/attributes.py
"},{"location":"reference/django_components/autodiscovery/","title":"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
autodiscovery","text":""},{"location":"reference/django_components/autodiscovery/#django_components.autodiscovery","title":"autodiscovery","text":"
Functions:
-
autodiscover
\u2013Search for all python files in
-
import_libraries
\u2013Import modules set in
autodiscover(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Search for all python files in
COMPONENTS.dirs
andCOMPONENTS.app_dirs
and import them.See Autodiscovery.
Parameters:
-
map_module
(Callable[[str], str]
, default:None
) \u2013Map the module paths with
map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Returns:
-
List[str]
\u2013List[str]: A list of module paths of imported files.
To get the same list of modules that
autodiscover()
would return, but without importing them, useget_component_files()
:
Source code infrom django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
src/django_components/autodiscovery.py
"},{"location":"reference/django_components/autodiscovery/#django_components.autodiscovery.import_libraries","title":"import_libraries","text":"def autodiscover(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Search for all python files in\n [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n and\n [`COMPONENTS.app_dirs`](../settings#django_components.app_settings.ComponentsSettings.app_dirs)\n and import them.\n\n See [Autodiscovery](../../concepts/fundamentals/autodiscovery).\n\n Args:\n map_module (Callable[[str], str], optional): Map the module paths with `map_module` function.\\\n This serves as an escape hatch for when you need to use this function in tests.\n\n Returns:\n List[str]: A list of module paths of imported files.\n\n To get the same list of modules that `autodiscover()` would return, but without importing them, use\n [`get_component_files()`](../api#django_components.get_component_files):\n\n ```python\n from django_components import get_component_files\n\n modules = get_component_files(\".py\")\n ```\n \"\"\"\n modules = get_component_files(\".py\")\n logger.debug(f\"Autodiscover found {len(modules)} files in component directories.\")\n return _import_modules([entry.dot_path for entry in modules], map_module)\n
import_libraries(map_module: Optional[Callable[[str], str]] = None) -> List[str]\n
Import modules set in
COMPONENTS.libraries
setting.See Autodiscovery.
Parameters:
-
map_module
(Callable[[str], str]
, default:None
) \u2013Map the module paths with
map_module
function. This serves as an escape hatch for when you need to use this function in tests.
Returns:
-
List[str]
\u2013List[str]: A list of module paths of imported files.
Examples:
Normal usage - load libraries after Django has loaded
from django_components import import_libraries\n\nclass MyAppConfig(AppConfig):\n def ready(self):\n import_libraries()\n
Potential usage in tests
Source code infrom django_components import import_libraries\n\nimport_libraries(lambda path: path.replace(\"tests.\", \"myapp.\"))\n
src/django_components/autodiscovery.py
"},{"location":"reference/django_components/component/","title":"def import_libraries(\n map_module: Optional[Callable[[str], str]] = None,\n) -> List[str]:\n \"\"\"\n Import modules set in\n [`COMPONENTS.libraries`](../settings#django_components.app_settings.ComponentsSettings.libraries)\n setting.\n\n See [Autodiscovery](../../concepts/fundamentals/autodiscovery).\n\n Args:\n map_module (Callable[[str], str], optional): Map the module paths with `map_module` function.\\\n This serves as an escape hatch for when you need to use this function in tests.\n\n Returns:\n List[str]: A list of module paths of imported files.\n\n **Examples:**\n\n Normal usage - load libraries after Django has loaded\n ```python\n from django_components import import_libraries\n\n class MyAppConfig(AppConfig):\n def ready(self):\n import_libraries()\n ```\n\n Potential usage in tests\n ```python\n from django_components import import_libraries\n\n import_libraries(lambda path: path.replace(\"tests.\", \"myapp.\"))\n ```\n \"\"\"\n from django_components.app_settings import app_settings\n\n return _import_modules(app_settings.LIBRARIES, map_module)\n
component","text":""},{"location":"reference/django_components/component/#django_components.component","title":"component","text":"
Classes:
-
Component
\u2013 -
ComponentNode
\u2013Django.template.Node subclass that renders a django-components component
-
ComponentVars
\u2013Type for the variables available inside the component templates.
-
ComponentView
\u2013Subclass of
django.views.View
where theComponent
instance is available
Component(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Generic[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template
(Optional[Union[str, Template]]
) \u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.Component.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
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":"cssclass-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":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/component/#django_components.component.Component.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/component/#django_components.component.Component.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.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":"mediainstance-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_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/component/#django_components.component.Component.template","title":"templaterender_to_response
class-attribute
instance-attribute
","text":"template: Optional[Union[str, Template]] = None\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
"},{"location":"reference/django_components/component/#django_components.component.Component.template_name","title":"template_nametemplate_name
,get_template_name
,template
orget_template
must be defined.class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/component/#django_components.component.Component.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.Component.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.Component.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.Component.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.Component.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.Component.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.Component.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.Component.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.ComponentNode","title":"ComponentNode","text":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
ComponentNode(\n name: str,\n args: List[Expression],\n kwargs: RuntimeKwargs,\n registry: ComponentRegistry,\n isolated_context: bool = False,\n nodelist: Optional[NodeList] = None,\n node_id: Optional[str] = None,\n)\n
Bases:
BaseNode
Django.template.Node subclass that renders a django-components component
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/component/#django_components.component.ComponentVars","title":"ComponentVars","text":"def __init__(\n self,\n name: str,\n args: List[Expression],\n kwargs: RuntimeKwargs,\n registry: ComponentRegistry, # noqa F811\n isolated_context: bool = False,\n nodelist: Optional[NodeList] = None,\n node_id: Optional[str] = None,\n) -> None:\n super().__init__(nodelist=nodelist or NodeList(), args=args, kwargs=kwargs, node_id=node_id)\n\n self.name = name\n self.isolated_context = isolated_context\n self.registry = registry\n
Bases:
NamedTuple
Type for the variables available inside the component templates.
All variables here are scoped under
component_vars.
, so e.g. attributeis_filled
on this class is accessible inside the template as:{{ component_vars.is_filled }}\n
Attributes:
-
is_filled
(Dict[str, bool]
) \u2013Dictonary describing which component slots are filled (
True
) or are not (False
).
instance-attribute
","text":"is_filled: Dict[str, bool]\n
Dictonary describing which component slots are filled (
True
) or are not (False
).New in version 0.70
Use as
{{ component_vars.is_filled }}
Example:
"},{"location":"reference/django_components/component/#django_components.component.ComponentView","title":"ComponentView","text":"{# Render wrapping HTML only if the slot is defined #}\n{% if component_vars.is_filled.my_slot %}\n <div class=\"slot-wrapper\">\n {% slot \"my_slot\" / %}\n </div>\n{% endif %}\n
ComponentView(component: Component, **kwargs: Any)\n
Bases:
View
Subclass of
Source code indjango.views.View
where theComponent
instance is available viaself.component
.src/django_components/component.py
"},{"location":"reference/django_components/component_media/","title":"def __init__(self, component: \"Component\", **kwargs: Any) -> None:\n super().__init__(**kwargs)\n self.component = component\n
component_media","text":""},{"location":"reference/django_components/component_media/#django_components.component_media","title":"component_media","text":"
Classes:
-
ComponentMediaInput
\u2013Defines JS and CSS media files associated with this component.
-
MediaMeta
\u2013Metaclass for handling media files for components.
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 ofMedia
attribute to define associated JS/CSS files, which are then available undermedia
attribute as a instance ofMedia
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
E.g. if in a directory
my_comp
you havescript.js
andmy_comp.py
, andmy_comp.py
looks like this:class MyComponent(Component):\n class Media:\n js = \"script.js\"\n
Then
"},{"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":"script.js
will be resolved asmy_comp/script.js
.E.g.:
"},{"location":"reference/django_components/component_media/#django_components.component_media.MediaMeta--4-subclass-media-class-with-media_class","title":"4. Subclassdef 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
Media
class withmedia_class
","text":"Normal
MediaDefiningClass
creates an instance ofMedia
class under themedia
attribute. This class allows to override which class will be instantiated withmedia_class
attribute:
"},{"location":"reference/django_components/component_registry/","title":"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
component_registry","text":""},{"location":"reference/django_components/component_registry/#django_components.component_registry","title":"component_registry","text":"
Classes:
-
AlreadyRegistered
\u2013Raised when you try to register a Component,
-
ComponentRegistry
\u2013Manages components and makes them available
-
NotRegistered
\u2013Raised when you try to access a Component,
-
RegistrySettings
\u2013Configuration for a
ComponentRegistry
.
Functions:
-
register
\u2013Class decorator for registering a component
Attributes:
-
registry
(ComponentRegistry
) \u2013The default and global component registry.
module-attribute
","text":"registry: ComponentRegistry = ComponentRegistry()\n
The default and global component registry. Use this instance to directly register or remove components:
See Registering components.
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.AlreadyRegistered","title":"AlreadyRegistered","text":"# Register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n\n# Get single\nregistry.get(\"button\")\n\n# Get all\nregistry.all()\n\n# Unregister single\nregistry.unregister(\"button\")\n\n# Unregister all\nregistry.clear()\n
Bases:
Exception
Raised when you try to register a Component, but it's already registered with given ComponentRegistry.
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry","title":"ComponentRegistry","text":"ComponentRegistry(\n library: Optional[Library] = None, settings: Optional[Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]] = None\n)\n
Manages components and makes them available in the template, by default as
{% component %}
tags.{% component \"my_comp\" key=value %}\n{% endcomponent %}\n
To enable a component to be used in a template, the component must be registered with a component registry.
When you register a component to a registry, behind the scenes the registry automatically adds the component's template tag (e.g.
{% component %}
to theLibrary
. And the opposite happens when you unregister a component - the tag is removed.See Registering components.
Parameters:
-
library
(Library
, default:None
) \u2013Django
Library
associated with this registry. If omitted, the default Library instance from django_components is used. -
settings
(Union[RegistrySettings, Callable[[ComponentRegistry], RegistrySettings]]
, default:None
) \u2013Configure how the components registered with this registry will behave when rendered. See
RegistrySettings
. Can be either a static value or a callable that returns the settings. If omitted, the settings fromCOMPONENTS
are used.
Notes:
- The default registry is available as
django_components.registry
. - The default registry is used when registering components with
@register
decorator.
Example:
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry--using-registry-to-share-components","title":"Using registry to share components","text":"# 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
You can use component registry for isolating or \"packaging\" components:
-
Create new instance of
ComponentRegistry
and Library:my_comps = Library()\nmy_comps_reg = ComponentRegistry(library=my_comps)\n
-
Register components to the registry:
my_comps_reg.register(\"my_button\", ButtonComponent)\nmy_comps_reg.register(\"my_card\", CardComponent)\n
-
In your target project, load the Library associated with the registry:
{% load my_comps %}\n
-
Use the registered components in your templates:
{% component \"button\" %}\n{% endcomponent %}\n
Methods:
-
all
\u2013Retrieve all registered
Component
classes. -
clear
\u2013Clears the registry, unregistering all components.
-
get
\u2013Retrieve a
Component
-
register
\u2013Register a
Component
class -
unregister
\u2013Unregister the
Component
class
Attributes:
-
library
(Library
) \u2013The template tag
Library
-
settings
(InternalRegistrySettings
) \u2013Registry settings configured for this registry.
src/django_components/component_registry.py
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.library","title":"librarydef __init__(\n self,\n library: Optional[Library] = None,\n settings: Optional[Union[RegistrySettings, Callable[[\"ComponentRegistry\"], RegistrySettings]]] = None,\n) -> None:\n self._registry: Dict[str, ComponentRegistryEntry] = {} # component name -> component_entry mapping\n self._tags: Dict[str, Set[str]] = {} # tag -> list[component names]\n self._library = library\n self._settings_input = settings\n self._settings: Optional[Callable[[], InternalRegistrySettings]] = None\n\n all_registries.append(self)\n
property
","text":"library: Library\n
The template tag
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.settings","title":"settingsLibrary
that is associated with the registry.property
","text":"settings: InternalRegistrySettings\n
Registry settings configured for this registry.
"},{"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.Returns:
-
Dict[str, Type[Component]]
\u2013Dict[str, Type[Component]]: A dictionary of component names to component classes
Example:
Source code in# 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
src/django_components/component_registry.py
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.clear","title":"clear","text":"def all(self) -> Dict[str, Type[\"Component\"]]:\n \"\"\"\n Retrieve all registered [`Component`](../api#django_components.Component) classes.\n\n Returns:\n Dict[str, Type[Component]]: A dictionary of component names to component classes\n\n **Example:**\n\n ```python\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
clear() -> None\n
Clears the registry, unregistering all components.
Example:
Source code in# First register components\nregistry.register(\"button\", ButtonComponent)\nregistry.register(\"card\", CardComponent)\n# Then clear\nregistry.clear()\n# Then get all\nregistry.all()\n# > {}\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.get","title":"get","text":"def clear(self) -> None:\n \"\"\"\n Clears the registry, unregistering all components.\n\n Example:\n\n ```python\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
get(name: str) -> Type[Component]\n
Retrieve a
Component
class registered under the given name.Parameters:
-
name
(str
) \u2013The name under which the component was registered. Required.
Returns:
-
Type[Component]
\u2013Type[Component]: The component class registered under the given name.
Raises:
NotRegistered
if the given name is not registered.
Example:
Source code in# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then get\nregistry.get(\"button\")\n# > ButtonComponent\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.register","title":"register","text":"def get(self, name: str) -> Type[\"Component\"]:\n \"\"\"\n Retrieve a [`Component`](../api#django_components.Component)\n class registered under the given name.\n\n Args:\n name (str): The name under which the component was registered. Required.\n\n Returns:\n Type[Component]: The component class registered under the given name.\n\n **Raises:**\n\n - [`NotRegistered`](../exceptions#django_components.NotRegistered)\n if the given name is not registered.\n\n **Example:**\n\n ```python\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
register(name: str, component: Type[Component]) -> None\n
Register a
Component
class with this registry under the given name.A component MUST be registered before it can be used in a template such as:
{% component \"my_comp\" %}\n{% endcomponent %}\n
Parameters:
-
name
(str
) \u2013The name under which the component will be registered. Required.
-
component
(Type[Component]
) \u2013The component class to register. Required.
Raises:
AlreadyRegistered
if a different component was already registered under the same name.
Example:
Source code inregistry.register(\"button\", ButtonComponent)\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.ComponentRegistry.unregister","title":"unregister","text":"def register(self, name: str, component: Type[\"Component\"]) -> None:\n \"\"\"\n Register a [`Component`](../api#django_components.Component) class\n 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\" %}\n {% endcomponent %}\n ```\n\n Args:\n name (str): The name under which the component will be registered. Required.\n component (Type[Component]): The component class to register. Required.\n\n **Raises:**\n\n - [`AlreadyRegistered`](../exceptions#django_components.AlreadyRegistered)\n if a different component was already registered under the same name.\n\n **Example:**\n\n ```python\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
unregister(name: str) -> None\n
Unregister the
Component
class that was registered under the given name.Once a component is unregistered, it is no longer available in the templates.
Parameters:
-
name
(str
) \u2013The name under which the component is registered. Required.
Raises:
NotRegistered
if the given name is not registered.
Example:
Source code in# First register component\nregistry.register(\"button\", ButtonComponent)\n# Then unregister\nregistry.unregister(\"button\")\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.NotRegistered","title":"NotRegistered","text":"def unregister(self, name: str) -> None:\n \"\"\"\n Unregister the [`Component`](../api#django_components.Component) class\n that was registered under the given name.\n\n Once a component is unregistered, it is no longer available in the templates.\n\n Args:\n name (str): The name under which the component is registered. Required.\n\n **Raises:**\n\n - [`NotRegistered`](../exceptions#django_components.NotRegistered)\n if the given name is not registered.\n\n **Example:**\n\n ```python\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
Bases:
Exception
Raised when you try to access a Component, but it's NOT registered with given ComponentRegistry.
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.RegistrySettings","title":"RegistrySettings","text":"Bases:
NamedTuple
Configuration for a
ComponentRegistry
.These settings define how the components registered with this registry will behave when rendered.
from django_components import ComponentRegistry, RegistrySettings\n\nregistry_settings = RegistrySettings(\n context_behavior=\"django\",\n tag_formatter=\"django_components.component_shorthand_formatter\",\n)\n\nregistry = ComponentRegistry(settings=registry_settings)\n
Attributes:
-
CONTEXT_BEHAVIOR
(Optional[ContextBehaviorType]
) \u2013Deprecated. Use
context_behavior
instead. Will be removed in v1. -
TAG_FORMATTER
(Optional[Union[TagFormatterABC, str]]
) \u2013Deprecated. Use
tag_formatter
instead. Will be removed in v1. -
context_behavior
(Optional[ContextBehaviorType]
) \u2013Same as the global
-
tag_formatter
(Optional[Union[TagFormatterABC, str]]
) \u2013Same as the global
class-attribute
instance-attribute
","text":"CONTEXT_BEHAVIOR: Optional[ContextBehaviorType] = None\n
Deprecated. Use
context_behavior
instead. Will be removed in v1.Same as the global
COMPONENTS.context_behavior
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.RegistrySettings.TAG_FORMATTER","title":"TAG_FORMATTERCOMPONENTS.context_behavior
setting.class-attribute
instance-attribute
","text":"TAG_FORMATTER: Optional[Union[TagFormatterABC, str]] = None\n
Deprecated. Use
tag_formatter
instead. Will be removed in v1.Same as the global
COMPONENTS.tag_formatter
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.RegistrySettings.context_behavior","title":"context_behaviorCOMPONENTS.tag_formatter
setting.class-attribute
instance-attribute
","text":"context_behavior: Optional[ContextBehaviorType] = None\n
Same as the global
COMPONENTS.context_behavior
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.RegistrySettings.tag_formatter","title":"tag_formatterCOMPONENTS.context_behavior
setting.class-attribute
instance-attribute
","text":"tag_formatter: Optional[Union[TagFormatterABC, str]] = None\n
Same as the global
COMPONENTS.tag_formatter
setting, but for this registry.If omitted, defaults to the global
"},{"location":"reference/django_components/component_registry/#django_components.component_registry.register","title":"register","text":"COMPONENTS.tag_formatter
setting.register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[\n [Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]]],\n Type[Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]],\n]\n
Class decorator for registering a component to a component registry.
See Registering components.
Parameters:
-
name
(str
) \u2013Registered name. This is the name by which the component will be accessed from within a template when using the
{% component %}
tag. Required. -
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to which to register this component. If omitted, component is registered to the default registry.
Raises:
-
AlreadyRegistered
\u2013If there is already a component registered under the same name.
Examples:
from django_components import Component, register\n\n@register(\"my_component\")\nclass MyComponent(Component):\n ...\n
Specifing
ComponentRegistry
the component should be registered to by setting theregistry
kwarg:
Source code infrom django.template import Library\nfrom django_components import Component, ComponentRegistry, register\n\nmy_lib = Library()\nmy_reg = ComponentRegistry(library=my_lib)\n\n@register(\"my_component\", registry=my_reg)\nclass MyComponent(Component):\n ...\n
src/django_components/component_registry.py
"},{"location":"reference/django_components/components/","title":"Index","text":""},{"location":"reference/django_components/components/#django_components.components","title":"components","text":"def register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[\n [Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"]],\n Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"],\n]:\n \"\"\"\n Class decorator for registering a [component](./#django_components.Component)\n to a [component registry](./#django_components.ComponentRegistry).\n\n See [Registering components](../../concepts/advanced/component_registry).\n\n Args:\n name (str): Registered name. This is the name by which the component will be accessed\\\n from within a template when using the [`{% component %}`](../template_tags#component) tag. Required.\n registry (ComponentRegistry, optional): Specify the [registry](./#django_components.ComponentRegistry)\\\n to which to register this component. If omitted, component is registered to the default registry.\n\n Raises:\n AlreadyRegistered: If there is already a component registered under the same name.\n\n **Examples**:\n\n ```python\n from django_components import Component, register\n\n @register(\"my_component\")\n class MyComponent(Component):\n ...\n ```\n\n Specifing [`ComponentRegistry`](./#django_components.ComponentRegistry) the component\n should be registered to by setting the `registry` kwarg:\n\n ```python\n from django.template import Library\n from django_components import Component, ComponentRegistry, register\n\n my_lib = 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(\n component: Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"],\n ) -> Type[\"Component[ArgsType, KwargsType, SlotsType, DataType, JsDataType, CssDataType]\"]:\n registry.register(name=name, component=component)\n return component\n\n return decorator\n
Modules:
-
dynamic
\u2013
Classes:
-
DynamicComponent
\u2013This component is given a registered name or a reference to another component,
DynamicComponent(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Component
This component is given a registered name or a reference to another component, and behaves as if the other component was in its place.
The args, kwargs, and slot fills are all passed down to the underlying component.
Parameters:
-
is
(str | Type[Component]
) \u2013Component that should be rendered. Either a registered name of a component, or a Component class directly. Required.
-
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to search for the registered name. If omitted, all registries are searched until the first match.
-
*args
\u2013Additional data passed to the component.
-
**kwargs
\u2013Additional data passed to the component.
Slots:
- Any slots, depending on the actual component.
Examples:
Django
{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Python
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent--use-cases","title":"Use cases","text":"from django_components import DynamicComponent\n\nDynamicComponent.render(\n kwargs={\n \"is\": table_comp,\n \"data\": table_data,\n \"headers\": table_headers,\n },\n slots={\n \"pagination\": PaginationComponent.render(\n render_dependencies=False,\n ),\n },\n)\n
Dynamic components are suitable if you are writing something like a form component. You may design it such that users give you a list of input types, and you render components depending on the input types.
While you could handle this with a series of if / else statements, that's not an extensible approach. Instead, you can use the dynamic component in place of normal components.
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent--component-name","title":"Component name","text":"By default, the dynamic component is registered under the name
\"dynamic\"
. In case of a conflict, you can set theCOMPONENTS.dynamic_component_name
setting to change the name used for the dynamic components.# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
class-attribute
instance-attribute
","text":"Media = ComponentMediaInput\n
Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.css","title":"cssclass-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.input","title":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.media","title":"mediainstance-attribute
","text":"media: Media\n
Normalized definition of JS and CSS media files associated with this component.
NOTE: This field is generated from Component.Media class.
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.response_class","title":"response_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.template_name","title":"template_namerender_to_response
class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.DynamicComponent.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic","title":"dynamic","text":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
Modules:
-
types
\u2013Helper types for IDEs.
Classes:
-
DynamicComponent
\u2013This component is given a registered name or a reference to another component,
DynamicComponent(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Component
This component is given a registered name or a reference to another component, and behaves as if the other component was in its place.
The args, kwargs, and slot fills are all passed down to the underlying component.
Parameters:
-
is
(str | Type[Component]
) \u2013Component that should be rendered. Either a registered name of a component, or a Component class directly. Required.
-
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to search for the registered name. If omitted, all registries are searched until the first match.
-
*args
\u2013Additional data passed to the component.
-
**kwargs
\u2013Additional data passed to the component.
Slots:
- Any slots, depending on the actual component.
Examples:
Django
{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Python
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent--use-cases","title":"Use cases","text":"from django_components import DynamicComponent\n\nDynamicComponent.render(\n kwargs={\n \"is\": table_comp,\n \"data\": table_data,\n \"headers\": table_headers,\n },\n slots={\n \"pagination\": PaginationComponent.render(\n render_dependencies=False,\n ),\n },\n)\n
Dynamic components are suitable if you are writing something like a form component. You may design it such that users give you a list of input types, and you render components depending on the input types.
While you could handle this with a series of if / else statements, that's not an extensible approach. Instead, you can use the dynamic component in place of normal components.
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent--component-name","title":"Component name","text":"By default, the dynamic component is registered under the name
\"dynamic\"
. In case of a conflict, you can set theCOMPONENTS.dynamic_component_name
setting to change the name used for the dynamic components.# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
class-attribute
instance-attribute
","text":"Media = ComponentMediaInput\n
Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.css","title":"cssclass-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.input","title":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.media","title":"mediainstance-attribute
","text":"media: Media\n
Normalized definition of JS and CSS media files associated with this component.
NOTE: This field is generated from Component.Media class.
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.response_class","title":"response_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.template_name","title":"template_namerender_to_response
class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/components/#django_components.components.dynamic.DynamicComponent.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/","title":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
dynamic","text":""},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic","title":"dynamic","text":"
Modules:
-
types
\u2013Helper types for IDEs.
Classes:
-
DynamicComponent
\u2013This component is given a registered name or a reference to another component,
DynamicComponent(\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None,\n)\n
Bases:
Component
This component is given a registered name or a reference to another component, and behaves as if the other component was in its place.
The args, kwargs, and slot fills are all passed down to the underlying component.
Parameters:
-
is
(str | Type[Component]
) \u2013Component that should be rendered. Either a registered name of a component, or a Component class directly. Required.
-
registry
(ComponentRegistry
, default:None
) \u2013Specify the registry to search for the registered name. If omitted, all registries are searched until the first match.
-
*args
\u2013Additional data passed to the component.
-
**kwargs
\u2013Additional data passed to the component.
Slots:
- Any slots, depending on the actual component.
Examples:
Django
{% component \"dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Python
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent--use-cases","title":"Use cases","text":"from django_components import DynamicComponent\n\nDynamicComponent.render(\n kwargs={\n \"is\": table_comp,\n \"data\": table_data,\n \"headers\": table_headers,\n },\n slots={\n \"pagination\": PaginationComponent.render(\n render_dependencies=False,\n ),\n },\n)\n
Dynamic components are suitable if you are writing something like a form component. You may design it such that users give you a list of input types, and you render components depending on the input types.
While you could handle this with a series of if / else statements, that's not an extensible approach. Instead, you can use the dynamic component in place of normal components.
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent--component-name","title":"Component name","text":"By default, the dynamic component is registered under the name
\"dynamic\"
. In case of a conflict, you can set theCOMPONENTS.dynamic_component_name
setting to change the name used for the dynamic components.# settings.py\nCOMPONENTS = ComponentsSettings(\n dynamic_component_name=\"my_dynamic\",\n)\n
After which you will be able to use the dynamic component with the new name:
{% component \"my_dynamic\" is=table_comp data=table_data headers=table_headers %}\n {% fill \"pagination\" %}\n {% component \"pagination\" / %}\n {% endfill %}\n{% endcomponent %}\n
Methods:
-
as_view
\u2013Shortcut for calling
Component.View.as_view
and passing component instance to it. -
get_template
\u2013Inlined Django template associated with this component. Can be a plain string or a Template instance.
-
get_template_name
\u2013Filepath to the Django template associated with this component.
-
inject
\u2013Use this method to retrieve the data that was passed to a
{% provide %}
tag -
on_render_after
\u2013Hook that runs just after the component's template was rendered.
-
on_render_before
\u2013Hook that runs just before the component's template is rendered.
-
render
\u2013Render the component into a string.
-
render_to_response
\u2013Render the component and wrap the content in the response class.
Attributes:
-
Media
\u2013Defines JS and CSS media files associated with this component.
-
css
(Optional[str]
) \u2013Inlined CSS associated with this component.
-
input
(RenderInput[ArgsType, KwargsType, SlotsType]
) \u2013Input holds the data (like arg, kwargs, slots) that were passsed to
-
is_filled
(SlotIsFilled
) \u2013Dictionary describing which slots have or have not been filled.
-
js
(Optional[str]
) \u2013Inlined JS associated with this component.
-
media
(Media
) \u2013Normalized definition of JS and CSS media files associated with this component.
-
response_class
\u2013This allows to configure what class is used to generate response from
render_to_response
-
template_name
(Optional[str]
) \u2013Filepath to the Django template associated with this component.
src/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.Media","title":"Mediadef __init__(\n self,\n registered_name: Optional[str] = None,\n component_id: Optional[str] = None,\n outer_context: Optional[Context] = None,\n registry: Optional[ComponentRegistry] = None, # noqa F811\n):\n # When user first instantiates the component class before calling\n # `render` or `render_to_response`, then we want to allow the render\n # function to make use of the instantiated object.\n #\n # So while `MyComp.render()` creates a new instance of MyComp internally,\n # if we do `MyComp(registered_name=\"abc\").render()`, then we use the\n # already-instantiated object.\n #\n # To achieve that, we want to re-assign the class methods as instance methods.\n # For that we have to \"unwrap\" the class methods via __func__.\n # See https://stackoverflow.com/a/76706399/9788634\n self.render_to_response = types.MethodType(self.__class__.render_to_response.__func__, self) # type: ignore\n self.render = types.MethodType(self.__class__.render.__func__, self) # type: ignore\n self.as_view = types.MethodType(self.__class__.as_view.__func__, self) # type: ignore\n\n self.registered_name: Optional[str] = registered_name\n self.outer_context: Context = outer_context or Context()\n self.component_id = component_id or gen_id()\n self.registry = registry or registry_\n self._render_stack: Deque[RenderStackItem[ArgsType, KwargsType, SlotsType]] = deque()\n # None == uninitialized, False == No types, Tuple == types\n self._types: Optional[Union[Tuple[Any, Any, Any, Any, Any, Any], Literal[False]]] = None\n
class-attribute
instance-attribute
","text":"Media = ComponentMediaInput\n
Defines JS and CSS media files associated with this component.
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.css","title":"cssclass-attribute
instance-attribute
","text":"css: Optional[str] = None\n
Inlined CSS associated with this component.
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.input","title":"inputproperty
","text":"input: RenderInput[ArgsType, KwargsType, SlotsType]\n
Input holds the data (like arg, kwargs, slots) that were passsed to the current execution of the
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.is_filled","title":"is_filledrender
method.property
","text":"is_filled: SlotIsFilled\n
Dictionary describing which slots have or have not been filled.
This attribute is available for use only within the template as
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.js","title":"js{{ component_vars.is_filled.slot_name }}
, and withinon_render_before
andon_render_after
hooks.class-attribute
instance-attribute
","text":"js: Optional[str] = None\n
Inlined JS associated with this component.
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.media","title":"mediainstance-attribute
","text":"media: Media\n
Normalized definition of JS and CSS media files associated with this component.
NOTE: This field is generated from Component.Media class.
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.response_class","title":"response_classclass-attribute
instance-attribute
","text":"response_class = HttpResponse\n
This allows to configure what class is used to generate response from
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.template_name","title":"template_namerender_to_response
class-attribute
instance-attribute
","text":"template_name: Optional[str] = None\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.as_view","title":"as_viewtemplate_name
,get_template_name
,template
orget_template
must be defined.classmethod
","text":"as_view(**initkwargs: Any) -> ViewFn\n
Shortcut for calling
Source code inComponent.View.as_view
and passing component instance to it.src/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.get_template","title":"get_template","text":"@classmethod\ndef as_view(cls, **initkwargs: Any) -> ViewFn:\n \"\"\"\n Shortcut for calling `Component.View.as_view` and passing component instance to it.\n \"\"\"\n # This method may be called as class method or as instance method.\n # If called as class method, create a new instance.\n if isinstance(cls, Component):\n comp: Component = cls\n else:\n comp = cls()\n\n # Allow the View class to access this component via `self.component`\n return comp.View.as_view(**initkwargs, component=comp)\n
get_template(context: Context) -> Optional[Union[str, Template]]\n
Inlined Django template associated with this component. Can be a plain string or a Template instance.
Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.get_template_name","title":"get_template_name","text":"def get_template(self, context: Context) -> Optional[Union[str, Template]]:\n \"\"\"\n Inlined Django template associated with this component. Can be a plain string or a Template instance.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
get_template_name(context: Context) -> Optional[str]\n
Filepath to the Django template associated with this component.
The filepath must be relative to either the file where the component class was defined, or one of the roots of
STATIFILES_DIRS
.Only one of
Source code intemplate_name
,get_template_name
,template
orget_template
must be defined.src/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.inject","title":"inject","text":"def get_template_name(self, context: Context) -> Optional[str]:\n \"\"\"\n Filepath to the Django template associated with this component.\n\n The filepath must be relative to either the file where the component class was defined,\n or one of the roots of `STATIFILES_DIRS`.\n\n Only one of `template_name`, `get_template_name`, `template` or `get_template` must be defined.\n \"\"\"\n return None\n
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
Source code in{{ data.hello }}
is taken from the \"provider\".src/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.on_render_after","title":"on_render_after","text":"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
on_render_after(context: Context, template: Template, content: str) -> Optional[SlotResult]\n
Hook that runs just after the component's template was rendered. It receives the rendered output as the last argument.
You can use this hook to access the context or the template, but modifying them won't have any effect.
To override the content that gets rendered, you can return a string or SafeString from this hook.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.on_render_before","title":"on_render_before","text":"def on_render_after(self, context: Context, template: Template, content: str) -> Optional[SlotResult]:\n \"\"\"\n Hook that runs just after the component's template was rendered.\n It receives the rendered output as the last argument.\n\n You can use this hook to access the context or the template, but modifying\n them won't have any effect.\n\n To override the content that gets rendered, you can return a string or SafeString\n from this hook.\n \"\"\"\n pass\n
on_render_before(context: Context, template: Template) -> None\n
Hook that runs just before the component's template is rendered.
You can use this hook to access or modify the context or the template.
Source code insrc/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.render","title":"renderdef on_render_before(self, context: Context, template: Template) -> None:\n \"\"\"\n Hook that runs just before the component's template is rendered.\n\n You can use this hook to access or modify the context or the template.\n \"\"\"\n pass\n
classmethod
","text":"render(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n type: RenderType = \"document\",\n render_dependencies: bool = True,\n) -> 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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag. -render_dependencies
- Set this toFalse
if you want to insert the resulting HTML into another component.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/components/dynamic/#django_components.components.dynamic.DynamicComponent.render_to_response","title":"render_to_response@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 type: RenderType = \"document\",\n render_dependencies: 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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\n - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.\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, type, render_dependencies)\n
classmethod
","text":"render_to_response(\n context: Optional[Union[Dict[str, Any], Context]] = None,\n slots: Optional[SlotsType] = None,\n escape_slots_content: bool = True,\n args: Optional[ArgsType] = None,\n kwargs: Optional[KwargsType] = None,\n type: RenderType = \"document\",\n *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 todjango.http.HttpResponse
.This is the interface for the
django.views.View
class which allows us to use components as Django views withcomponent.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 }
whereslot_content
can be a string or render function. -escape_slots_content
- Whether the content fromslots
should be escaped. -context
- A context (dictionary or Django's Context) within which the component is rendered. The keys on the context can be accessed from within the template. - NOTE: In \"isolated\" mode, context is NOT accessible, and data MUST be passed via component's args and kwargs. -type
- Configure how to handle JS and CSS dependencies. -\"document\"
(default) - JS dependencies are inserted into{% component_js_dependencies %}
, or to the end of the<body>
tag. CSS dependencies are inserted into{% component_css_dependencies %}
, or the end of the<head>
tag.Any additional args and kwargs are passed to the
response_class
.Example:
Source code inMyComponent.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
src/django_components/component.py
"},{"location":"reference/django_components/context/","title":"@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 type: RenderType = \"document\",\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 - `type` - Configure how to handle JS and CSS dependencies.\n - `\"document\"` (default) - JS dependencies are inserted into `{% component_js_dependencies %}`,\n or to the end of the `<body>` tag. CSS dependencies are inserted into\n `{% component_css_dependencies %}`, or the end of the `<head>` tag.\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 type=type,\n render_dependencies=True,\n )\n return cls.response_class(content, *response_args, **response_kwargs)\n
context","text":""},{"location":"reference/django_components/context/#django_components.context","title":"context","text":"
This file centralizes various ways we use Django's Context class pass data across components, nodes, slots, and contexts.
You can think of the Context as our storage system.
Functions:
-
copy_forloop_context
\u2013Forward the info about the current loop
-
get_injected_context_var
\u2013Retrieve a 'provided' field. The field MUST have been previously 'provided'
-
set_provided_context_var
\u2013'Provide' given data under given key. In other words, this data can be retrieved
copy_forloop_context(from_context: Context, to_context: Context) -> None\n
Forward the info about the current loop
Source code insrc/django_components/context.py
"},{"location":"reference/django_components/context/#django_components.context.get_injected_context_var","title":"get_injected_context_var","text":"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
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
Source code in{% provide %}
template tag.src/django_components/context.py
"},{"location":"reference/django_components/context/#django_components.context.set_provided_context_var","title":"set_provided_context_var","text":"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
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
Source code inself.inject(key)
inside ofget_context_data()
method of components that are nested inside the{% provide %}
tag.src/django_components/context.py
"},{"location":"reference/django_components/dependencies/","title":"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
dependencies","text":""},{"location":"reference/django_components/dependencies/#django_components.dependencies","title":"dependencies","text":"
All code related to management of component dependencies (JS and CSS scripts)
Modules:
-
types
\u2013Helper types for IDEs.
Classes:
-
ComponentDependencyMiddleware
\u2013Middleware that inserts CSS/JS dependencies for all rendered
Functions:
-
render_dependencies
\u2013Given a string that contains parts that were rendered by components,
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 insrc/django_components/dependencies.py
"},{"location":"reference/django_components/dependencies/#django_components.dependencies.render_dependencies","title":"render_dependencies","text":"def __init__(self, get_response: \"Callable[[HttpRequest], HttpResponse]\") -> None:\n self.get_response = get_response\n\n # NOTE: Required to work with async\n if iscoroutinefunction(self.get_response):\n markcoroutinefunction(self)\n
render_dependencies(content: TContent, type: RenderType = 'document') -> TContent\n
Given a string that contains parts that were rendered by components, this function inserts all used JS and CSS.
By default, the string is parsed as an HTML and: - CSS is inserted at the end of
<head>
(if present) - JS is inserted at the end of<body>
(if present)If you used
{% component_js_dependencies %}
or{% component_css_dependencies %}
, then the JS and CSS will be inserted only at these locations.Example:
Source code indef my_view(request):\n template = Template('''\n {% load components %}\n <!doctype html>\n <html>\n <head></head>\n <body>\n <h1>{{ table_name }}</h1>\n {% component \"table\" name=table_name / %}\n </body>\n </html>\n ''')\n\n html = template.render(\n Context({\n \"table_name\": request.GET[\"name\"],\n })\n )\n\n # This inserts components' JS and CSS\n processed_html = render_dependencies(html)\n\n return HttpResponse(processed_html)\n
src/django_components/dependencies.py
"},{"location":"reference/django_components/expression/","title":"def render_dependencies(content: TContent, type: RenderType = \"document\") -> TContent:\n \"\"\"\n Given a string that contains parts that were rendered by components,\n this function inserts all used JS and CSS.\n\n By default, the string is parsed as an HTML and:\n - CSS is inserted at the end of `<head>` (if present)\n - JS is inserted at the end of `<body>` (if present)\n\n If you used `{% component_js_dependencies %}` or `{% component_css_dependencies %}`,\n then the JS and CSS will be inserted only at these locations.\n\n Example:\n ```python\n def my_view(request):\n template = Template('''\n {% load components %}\n <!doctype html>\n <html>\n <head></head>\n <body>\n <h1>{{ table_name }}</h1>\n {% component \"table\" name=table_name / %}\n </body>\n </html>\n ''')\n\n html = template.render(\n Context({\n \"table_name\": request.GET[\"name\"],\n })\n )\n\n # This inserts components' JS and CSS\n processed_html = render_dependencies(html)\n\n return HttpResponse(processed_html)\n ```\n \"\"\"\n is_safestring = isinstance(content, SafeString)\n\n if isinstance(content, str):\n content_ = content.encode()\n else:\n content_ = cast(bytes, content)\n\n content_, js_dependencies, css_dependencies = _process_dep_declarations(content_, type)\n\n # Replace the placeholders with the actual content\n did_find_js_placeholder = False\n did_find_css_placeholder = False\n\n def on_replace_match(match: \"re.Match[bytes]\") -> bytes:\n nonlocal did_find_css_placeholder\n nonlocal did_find_js_placeholder\n\n if match[0] == CSS_PLACEHOLDER_BYTES:\n replacement = css_dependencies\n did_find_css_placeholder = True\n elif match[0] == JS_PLACEHOLDER_BYTES:\n replacement = js_dependencies\n did_find_js_placeholder = True\n else:\n raise RuntimeError(\n \"Unexpected error: Regex for component dependencies processing\"\n f\" matched unknown string '{match[0].decode()}'\"\n )\n return replacement\n\n content_ = PLACEHOLDER_REGEX.sub(on_replace_match, content_)\n\n # By default, if user didn't specify any `{% component_dependencies %}`,\n # then try to insert the JS scripts at the end of <body> and CSS sheets at the end\n # of <head>\n if type == \"document\" and (not did_find_js_placeholder or not did_find_css_placeholder):\n tree = parse_document_or_nodes(content_.decode())\n\n if isinstance(tree, LexborHTMLParser):\n did_modify_html = False\n\n if not did_find_css_placeholder and tree.head:\n css_elems = parse_multiroot_html(css_dependencies.decode())\n for css_elem in css_elems:\n tree.head.insert_child(css_elem) # type: ignore # TODO: Update to selectolax 0.3.25\n did_modify_html = True\n\n if not did_find_js_placeholder and tree.body:\n js_elems = parse_multiroot_html(js_dependencies.decode())\n for js_elem in js_elems:\n tree.body.insert_child(js_elem) # type: ignore # TODO: Update to selectolax 0.3.25\n did_modify_html = True\n\n transformed = cast(str, tree.html)\n if did_modify_html:\n content_ = transformed.encode()\n\n # Return the same type as we were given\n output = content_.decode() if isinstance(content, str) else content_\n output = mark_safe(output) if is_safestring else output\n return cast(TContent, output)\n
expression","text":""},{"location":"reference/django_components/expression/#django_components.expression","title":"expression","text":"
Classes:
-
Operator
\u2013Operator describes something that somehow changes the inputs
-
SpreadOperator
\u2013Operator that inserts one or more kwargs at the specified location.
Functions:
-
process_aggregate_kwargs
\u2013This function aggregates \"prefixed\" kwargs into dicts. \"Prefixed\" kwargs
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 insrc/django_components/expression.py
"},{"location":"reference/django_components/expression/#django_components.expression.process_aggregate_kwargs","title":"process_aggregate_kwargs","text":"def __init__(self, expr: Expression) -> None:\n self.expr = expr\n
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 theattrs
dict.So, instead, we allow to \"aggregate\" props into a dict. So all props that start with
attrs:
, likeattrs:class=\"text-red\"
, will be collected into a dict at keyattrs
.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 insrc/django_components/expression.py
"},{"location":"reference/django_components/finders/","title":"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
finders","text":""},{"location":"reference/django_components/finders/#django_components.finders","title":"finders","text":"
Classes:
-
ComponentsFileSystemFinder
\u2013A static files finder based on
FileSystemFinder
.
ComponentsFileSystemFinder(app_names: Any = None, *args: Any, **kwargs: Any)\n
Bases:
BaseFinder
A static files finder based on
FileSystemFinder
.Differences: - This finder uses
COMPONENTS.dirs
setting to locate files instead ofSTATICFILES_DIRS
. - Whether a file withinCOMPONENTS.dirs
is considered a STATIC file is configured byCOMPONENTS.static_files_allowed
andCOMPONENTS.static_files_forbidden
. - IfCOMPONENTS.dirs
is not set, defaults tosettings.BASE_DIR / \"components\"
Methods:
-
find
\u2013Look for files in the extra locations as defined in COMPONENTS.dirs.
-
find_location
\u2013Find a requested static file in a location and return the found
-
list
\u2013List all files in all locations.
src/django_components/finders.py
"},{"location":"reference/django_components/finders/#django_components.finders.ComponentsFileSystemFinder.find","title":"find","text":"def __init__(self, app_names: Any = None, *args: Any, **kwargs: Any) -> None:\n component_dirs = [str(p) for p in get_component_dirs()]\n\n # NOTE: The rest of the __init__ is the same as `django.contrib.staticfiles.finders.FileSystemFinder`,\n # but using our locations instead of STATICFILES_DIRS.\n\n # List of locations with static files\n self.locations: List[Tuple[str, str]] = []\n\n # Maps dir paths to an appropriate storage instance\n self.storages: Dict[str, FileSystemStorage] = {}\n for root in component_dirs:\n if isinstance(root, (list, tuple)):\n prefix, root = root\n else:\n prefix = \"\"\n if (prefix, root) not in self.locations:\n self.locations.append((prefix, root))\n for prefix, root in self.locations:\n filesystem_storage = FileSystemStorage(location=root)\n filesystem_storage.prefix = prefix\n self.storages[root] = filesystem_storage\n\n super().__init__(*args, **kwargs)\n
find(path: str, all: bool = False) -> Union[List[str], str]\n
Look for files in the extra locations as defined in COMPONENTS.dirs.
Source code insrc/django_components/finders.py
"},{"location":"reference/django_components/finders/#django_components.finders.ComponentsFileSystemFinder.find_location","title":"find_location","text":"def find(self, path: str, all: bool = False) -> Union[List[str], str]:\n \"\"\"\n Look for files in the extra locations as defined in COMPONENTS.dirs.\n \"\"\"\n matches: List[str] = []\n for prefix, root in self.locations:\n if root not in searched_locations:\n searched_locations.append(root)\n matched_path = self.find_location(root, path, prefix)\n if matched_path:\n if not all:\n return matched_path\n matches.append(matched_path)\n return matches\n
find_location(root: str, path: str, prefix: Optional[str] = None) -> Optional[str]\n
Find a requested static file in a location and return the found absolute path (or
Source code inNone
if no match).src/django_components/finders.py
"},{"location":"reference/django_components/finders/#django_components.finders.ComponentsFileSystemFinder.list","title":"list","text":"def find_location(self, root: str, path: str, prefix: Optional[str] = None) -> Optional[str]:\n \"\"\"\n Find a requested static file in a location and return the found\n absolute path (or ``None`` if no match).\n \"\"\"\n if prefix:\n prefix = \"%s%s\" % (prefix, os.sep)\n if not path.startswith(prefix):\n return None\n path = path.removeprefix(prefix)\n path = safe_join(root, path)\n\n if os.path.exists(path) and self._is_path_valid(path):\n return path\n return None\n
list(ignore_patterns: List[str]) -> Iterable[Tuple[str, FileSystemStorage]]\n
List all files in all locations.
Source code insrc/django_components/finders.py
"},{"location":"reference/django_components/library/","title":"def list(self, ignore_patterns: List[str]) -> Iterable[Tuple[str, FileSystemStorage]]:\n \"\"\"\n List all files in all locations.\n \"\"\"\n for prefix, root in self.locations:\n # Skip nonexistent directories.\n if os.path.isdir(root):\n storage = self.storages[root]\n for path in get_files(storage, ignore_patterns):\n if self._is_path_valid(path):\n yield path, storage\n
library","text":""},{"location":"reference/django_components/library/#django_components.library","title":"library","text":"
Module for interfacing with Django's Library (
django.template.library
)Classes:
-
TagProtectedError
\u2013The way the
TagFormatter
works is that,
Attributes:
-
PROTECTED_TAGS
\u2013These are the names that users cannot choose for their components,
module-attribute
","text":"PROTECTED_TAGS = ['component_css_dependencies', 'component_js_dependencies', 'fill', 'html_attrs', 'provide', 'slot']\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/library/#django_components.library.TagProtectedError","title":"TagProtectedError","text":"Bases:
Exception
The way the
TagFormatter
works is that, based on which start and end tags are used for rendering components, theComponentRegistry
behind the scenes un-/registers the template tags with the associated instance of Django'sLibrary
.In other words, if I have registered a component
\"table\"
, and I use the shorthand syntax:{% table ... %}\n{% endtable %}\n
Then
ComponentRegistry
registers the tagtable
onto the Django's Library instance.However, that means that if we registered a component
\"slot\"
, then we would overwrite the{% slot %}
tag from django_components.Thus, this exception is raised when a component is attempted to be registered under a forbidden name, such that it would overwrite one of django_component's own template tags.
"},{"location":"reference/django_components/management/","title":"Index","text":""},{"location":"reference/django_components/management/#django_components.management","title":"management","text":"Modules:
-
commands
\u2013
Modules:
-
startcomponent
\u2013
Classes:
-
Command
\u2013
Bases:
"},{"location":"reference/django_components/management/#django_components.management.commands.startcomponent.Command--management-command-usage","title":"Management Command Usage","text":"BaseCommand
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
"},{"location":"reference/django_components/management/#django_components.management.commands.startcomponent.Command--management-command-examples","title":"Management Command Examples","text":"<name>
,<path>
,<js_filename>
,<css_filename>
, and<template_filename>
with your desired values.Here are some examples of how you can use the command:
"},{"location":"reference/django_components/management/#django_components.management.commands.startcomponent.Command--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
"},{"location":"reference/django_components/management/#django_components.management.commands.startcomponent.Command--creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"my_component
in thecomponents
directory of your Django project. The JavaScript, CSS, and template files will be namedscript.js
,style.css
, andtemplate.html
, respectively.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
"},{"location":"reference/django_components/management/#django_components.management.commands.startcomponent.Command--overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"new_component
in themy_components
directory. The JavaScript, CSS, and template files will be namedmy_script.js
,my_style.css
, andmy_template.html
, respectively.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
"},{"location":"reference/django_components/management/#django_components.management.commands.startcomponent.Command--simulating-component-creation","title":"Simulating Component Creation","text":"my_component
if it exists.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
"},{"location":"reference/django_components/management/commands/","title":"Index","text":""},{"location":"reference/django_components/management/commands/#django_components.management.commands","title":"commands","text":"my_component
without creating any files.Modules:
-
startcomponent
\u2013
Classes:
-
Command
\u2013
Bases:
"},{"location":"reference/django_components/management/commands/#django_components.management.commands.startcomponent.Command--management-command-usage","title":"Management Command Usage","text":"BaseCommand
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
"},{"location":"reference/django_components/management/commands/#django_components.management.commands.startcomponent.Command--management-command-examples","title":"Management Command Examples","text":"<name>
,<path>
,<js_filename>
,<css_filename>
, and<template_filename>
with your desired values.Here are some examples of how you can use the command:
"},{"location":"reference/django_components/management/commands/#django_components.management.commands.startcomponent.Command--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
"},{"location":"reference/django_components/management/commands/#django_components.management.commands.startcomponent.Command--creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"my_component
in thecomponents
directory of your Django project. The JavaScript, CSS, and template files will be namedscript.js
,style.css
, andtemplate.html
, respectively.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
"},{"location":"reference/django_components/management/commands/#django_components.management.commands.startcomponent.Command--overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"new_component
in themy_components
directory. The JavaScript, CSS, and template files will be namedmy_script.js
,my_style.css
, andmy_template.html
, respectively.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
"},{"location":"reference/django_components/management/commands/#django_components.management.commands.startcomponent.Command--simulating-component-creation","title":"Simulating Component Creation","text":"my_component
if it exists.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
"},{"location":"reference/django_components/management/commands/startcomponent/","title":"my_component
without creating any files.startcomponent","text":""},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent","title":"startcomponent","text":"
Classes:
-
Command
\u2013
Bases:
"},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent.Command--management-command-usage","title":"Management Command Usage","text":"BaseCommand
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
"},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent.Command--management-command-examples","title":"Management Command Examples","text":"<name>
,<path>
,<js_filename>
,<css_filename>
, and<template_filename>
with your desired values.Here are some examples of how you can use the command:
"},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent.Command--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
"},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent.Command--creating-a-component-with-custom-settings","title":"Creating a Component with Custom Settings","text":"my_component
in thecomponents
directory of your Django project. The JavaScript, CSS, and template files will be namedscript.js
,style.css
, andtemplate.html
, respectively.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
"},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent.Command--overwriting-an-existing-component","title":"Overwriting an Existing Component","text":"new_component
in themy_components
directory. The JavaScript, CSS, and template files will be namedmy_script.js
,my_style.css
, andmy_template.html
, respectively.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
"},{"location":"reference/django_components/management/commands/startcomponent/#django_components.management.commands.startcomponent.Command--simulating-component-creation","title":"Simulating Component Creation","text":"my_component
if it exists.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
"},{"location":"reference/django_components/management/commands/upgradecomponent/","title":"my_component
without creating any files.upgradecomponent","text":""},{"location":"reference/django_components/management/commands/upgradecomponent/#django_components.management.commands.upgradecomponent","title":"upgradecomponent","text":""},{"location":"reference/django_components/middleware/","title":"
middleware","text":""},{"location":"reference/django_components/middleware/#django_components.middleware","title":"middleware","text":"
Classes:
-
ComponentDependencyMiddleware
\u2013Middleware that inserts CSS/JS dependencies for all rendered
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 insrc/django_components/dependencies.py
"},{"location":"reference/django_components/node/","title":"def __init__(self, get_response: \"Callable[[HttpRequest], HttpResponse]\") -> None:\n self.get_response = get_response\n\n # NOTE: Required to work with async\n if iscoroutinefunction(self.get_response):\n markcoroutinefunction(self)\n
node","text":""},{"location":"reference/django_components/node/#django_components.node","title":"node","text":"
Classes:
-
BaseNode
\u2013Shared behavior for our subclasses of Django's
Node
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
Source code inNode
src/django_components/node.py
"},{"location":"reference/django_components/provide/","title":"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
provide","text":""},{"location":"reference/django_components/provide/#django_components.provide","title":"provide","text":"
Classes:
-
ProvideNode
\u2013Implementation of the
{% provide %}
tag.
ProvideNode(nodelist: NodeList, trace_id: str, node_id: Optional[str] = None, kwargs: Optional[RuntimeKwargs] = None)\n
Bases:
BaseNode
Implementation of the
Source code in{% provide %}
tag. For more info seeComponent.inject
.src/django_components/provide.py
"},{"location":"reference/django_components/slots/","title":"def __init__(\n self,\n nodelist: NodeList,\n trace_id: str,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.nodelist = nodelist\n self.node_id = node_id or gen_id()\n self.trace_id = trace_id\n self.kwargs = kwargs or RuntimeKwargs({})\n
slots","text":""},{"location":"reference/django_components/slots/#django_components.slots","title":"slots","text":"
Classes:
-
FillNode
\u2013Node corresponding to
{% fill %}
-
Slot
\u2013This class holds the slot content function along with related metadata.
-
SlotFill
\u2013SlotFill describes what WILL be rendered.
-
SlotIsFilled
\u2013Dictionary that returns
True
if the slot is filled (key is found),False
otherwise. -
SlotNode
\u2013Node corresponding to
{% slot %}
-
SlotRef
\u2013SlotRef allows to treat a slot as a variable. The slot is rendered only once
Functions:
-
resolve_fills
\u2013Given a component body (
django.template.NodeList
), find all slot fills,
FillNode(nodelist: NodeList, kwargs: RuntimeKwargs, trace_id: str, node_id: Optional[str] = None)\n
Bases:
BaseNode
Node corresponding to
Source code in{% fill %}
src/django_components/slots.py
"},{"location":"reference/django_components/slots/#django_components.slots.Slot","title":"Slotdef __init__(\n self,\n nodelist: NodeList,\n kwargs: RuntimeKwargs,\n trace_id: str,\n node_id: Optional[str] = None,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.trace_id = trace_id\n
dataclass
","text":"Slot(content_func: SlotFunc[TSlotData])\n
Bases:
Generic[TSlotData]
This class holds the slot content function along with related metadata.
"},{"location":"reference/django_components/slots/#django_components.slots.SlotFill","title":"SlotFilldataclass
","text":"SlotFill(name: str, is_filled: bool, slot: Slot[TSlotData])\n
Bases:
Generic[TSlotData]
SlotFill describes what WILL be rendered.
The fill may be provided by the user from the outside (
is_filled=True
), or it may be the default content of the slot (is_filled=False
).Attributes:
-
name
(str
) \u2013Name of the slot.
instance-attribute
","text":"name: str\n
Name of the slot.
"},{"location":"reference/django_components/slots/#django_components.slots.SlotIsFilled","title":"SlotIsFilled","text":"SlotIsFilled(fills: Dict, *args: Any, **kwargs: Any)\n
Bases:
dict
Dictionary that returns
Source code inTrue
if the slot is filled (key is found),False
otherwise.src/django_components/slots.py
"},{"location":"reference/django_components/slots/#django_components.slots.SlotNode","title":"SlotNode","text":"def __init__(self, fills: Dict, *args: Any, **kwargs: Any) -> None:\n escaped_fill_names = {_escape_slot_name(fill_name): True for fill_name in fills.keys()}\n super().__init__(escaped_fill_names, *args, **kwargs)\n
SlotNode(\n nodelist: NodeList,\n trace_id: str,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n is_required: bool = False,\n is_default: bool = False,\n)\n
Bases:
BaseNode
Node corresponding to
Source code in{% slot %}
src/django_components/slots.py
"},{"location":"reference/django_components/slots/#django_components.slots.SlotRef","title":"SlotRef","text":"def __init__(\n self,\n nodelist: NodeList,\n trace_id: str,\n node_id: Optional[str] = None,\n kwargs: Optional[RuntimeKwargs] = None,\n is_required: bool = False,\n is_default: bool = False,\n):\n super().__init__(nodelist=nodelist, args=None, kwargs=kwargs, node_id=node_id)\n\n self.is_required = is_required\n self.is_default = is_default\n self.trace_id = trace_id\n
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
Source code in{{ my_lazy_slot }}
, it will output the contents of the slot.src/django_components/slots.py
"},{"location":"reference/django_components/slots/#django_components.slots.resolve_fills","title":"resolve_fills","text":"def __init__(self, slot: \"SlotNode\", context: Context):\n self._slot = slot\n self._context = context\n
resolve_fills(context: Context, nodelist: NodeList, component_name: str) -> Dict[SlotName, Slot]\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 finds 2 fill nodes: \"first_fill\" and \"second_fill\", and formats them as slot functions, returning:
{\n \"first_fill\": SlotFunc(...),\n \"second_fill\": SlotFunc(...),\n}\n
If no fill nodes are found, then the content is treated as default slot content.
{\n DEFAULT_SLOT_KEY: SlotFunc(...),\n}\n
This function also handles for-loops, if/else statements, or include tags to generate fill tags:
Source code in{% component \"mycomponent\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name %}\n {% slot name=slot_name / %}\n {% endfill %}\n {% endfor %}\n{% endcomponent %}\n
src/django_components/slots.py
"},{"location":"reference/django_components/tag_formatter/","title":"def resolve_fills(\n context: Context,\n nodelist: NodeList,\n component_name: str,\n) -> Dict[SlotName, Slot]:\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\n Then this function finds 2 fill nodes: \"first_fill\" and \"second_fill\",\n and formats them as slot functions, returning:\n\n ```python\n {\n \"first_fill\": SlotFunc(...),\n \"second_fill\": SlotFunc(...),\n }\n ```\n\n If no fill nodes are found, then the content is treated as default slot content.\n\n ```python\n {\n DEFAULT_SLOT_KEY: SlotFunc(...),\n }\n ```\n\n This function also handles for-loops, if/else statements, or include tags to generate fill tags:\n\n ```django\n {% component \"mycomponent\" %}\n {% for slot_name in slots %}\n {% fill name=slot_name %}\n {% slot name=slot_name / %}\n {% endfill %}\n {% endfor %}\n {% endcomponent %}\n ```\n \"\"\"\n slots: Dict[SlotName, Slot] = {}\n\n if not nodelist:\n return slots\n\n maybe_fills = _extract_fill_content(nodelist, context, component_name)\n\n # The content has no fills, so treat it as default slot, e.g.:\n # {% component \"mycomponent\" %}\n # Hello!\n # {% if True %} 123 {% endif %}\n # {% endcomponent %}\n if maybe_fills is False:\n # Ignore empty content between `{% component %} ... {% endcomponent %}` tags\n nodelist_is_empty = not len(nodelist) or all(\n isinstance(node, TextNode) and not node.s.strip() for node in nodelist\n )\n\n if not nodelist_is_empty:\n slots[DEFAULT_SLOT_KEY] = _nodelist_to_slot_render_func(\n DEFAULT_SLOT_KEY,\n nodelist,\n data_var=None,\n default_var=None,\n )\n\n # The content has fills\n else:\n # NOTE: If slot fills are explicitly defined, we use them even if they are empty (or only whitespace).\n # This is different from the default slot, where we ignore empty content.\n for fill in maybe_fills:\n slots[fill.name] = _nodelist_to_slot_render_func(\n slot_name=fill.name,\n nodelist=fill.fill.nodelist,\n data_var=fill.data_var,\n default_var=fill.default_var,\n extra_context=fill.extra_context,\n )\n\n return slots\n
tag_formatter","text":""},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter","title":"tag_formatter","text":"
Classes:
-
ComponentFormatter
\u2013The original django_component's component tag formatter, it uses the
{% component %}
-
InternalTagFormatter
\u2013Internal wrapper around user-provided TagFormatters, so that we validate the outputs.
-
ShorthandComponentFormatter
\u2013The component tag formatter that uses
{% <name> %}
/{% end<name> %}
tags. -
TagFormatterABC
\u2013Abstract base class for defining custom tag formatters.
-
TagResult
\u2013The return value from
TagFormatter.parse()
.
Functions:
-
get_tag_formatter
\u2013Returns an instance of the currently configured component tag formatter.
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 given as the first positional arg.Example as block:
{% component \"mycomp\" abc=123 %}\n {% fill \"myfill\" %}\n ...\n {% endfill %}\n{% endcomponent %}\n
Example as inlined tag:
Source code in{% component \"mycomp\" abc=123 / %}\n
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.InternalTagFormatter","title":"InternalTagFormatter","text":"def __init__(self, tag: str):\n self.tag = tag\n
InternalTagFormatter(tag_formatter: TagFormatterABC)\n
Internal wrapper around user-provided TagFormatters, so that we validate the outputs.
Source code insrc/django_components/tag_formatter.py
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.ShorthandComponentFormatter","title":"ShorthandComponentFormatter","text":"def __init__(self, tag_formatter: TagFormatterABC):\n self.tag_formatter = tag_formatter\n
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:
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC","title":"TagFormatterABC","text":"{% mycomp abc=123 / %}\n
Bases:
ABC
Abstract base class for defining custom tag formatters.
Tag formatters define how the component tags are used in the template.
Read more about Tag formatter.
For example, with the default tag formatter (
ComponentFormatter
), components are written as:{% component \"comp_name\" %}\n{% endcomponent %}\n
While with the shorthand tag formatter (
ShorthandComponentFormatter
), components are written as:{% comp_name %}\n{% endcomp_name %}\n
Example:
Implementation for
ShorthandComponentFormatter
:from djagno_components import TagFormatterABC, TagResult\n\nclass ShorthandComponentFormatter(TagFormatterABC):\n def start_tag(self, name: str) -> str:\n return name\n\n def end_tag(self, name: str) -> str:\n return f\"end{name}\"\n\n def parse(self, tokens: List[str]) -> TagResult:\n tokens = [*tokens]\n name = tokens.pop(0)\n return TagResult(name, tokens)\n
Methods:
-
end_tag
\u2013Formats the end tag of a block component.
-
parse
\u2013Given the tokens (words) passed to a component start tag, this function extracts
-
start_tag
\u2013Formats the start tag of a component.
abstractmethod
","text":"end_tag(name: str) -> str\n
Formats the end tag of a block component.
Parameters:
-
name
(str
) \u2013Component's registered name. Required.
Returns:
-
str
(str
) \u2013The formatted end tag.
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC.parse","title":"parse@abc.abstractmethod\ndef end_tag(self, name: str) -> str:\n \"\"\"\n Formats the end tag of a block component.\n\n Args:\n name (str): Component's registered name. Required.\n\n Returns:\n str: The formatted end tag.\n \"\"\"\n ...\n
abstractmethod
","text":"parse(tokens: List[str]) -> TagResult\n
Given the tokens (words) passed to a component start tag, this function extracts the component name from the tokens list, and returns
TagResult
, which is a tuple of(component_name, remaining_tokens)
.Parameters:
-
tokens
([List(str]
) \u2013List of tokens passed to the component tag.
Returns:
-
TagResult
(TagResult
) \u2013Parsed component name and remaining tokens.
Example:
Assuming we used a component in a template like this:
{% component \"my_comp\" key=val key2=val2 %}\n{% endcomponent %}\n
This function receives a list of tokens:
['component', '\"my_comp\"', 'key=val', 'key2=val2']\n
component
is the tag name, which we drop.\"my_comp\"
is the component name, but we must remove the extra quotes.- The remaining tokens we pass unmodified, as that's the input to the component.
So in the end, we return:
Source code inTagResult('my_comp', ['key=val', 'key2=val2'])\n
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagFormatterABC.start_tag","title":"start_tag@abc.abstractmethod\ndef parse(self, tokens: List[str]) -> TagResult:\n \"\"\"\n Given the tokens (words) passed to a component start tag, this function extracts\n the component name from the tokens list, and returns\n [`TagResult`](../api#django_components.TagResult),\n which is a tuple of `(component_name, remaining_tokens)`.\n\n Args:\n tokens [List(str]): List of tokens passed to the component tag.\n\n Returns:\n TagResult: Parsed component name and remaining tokens.\n\n **Example:**\n\n Assuming we used a component in a template like this:\n\n ```django\n {% component \"my_comp\" key=val key2=val2 %}\n {% endcomponent %}\n ```\n\n This function receives a list of tokens:\n\n ```python\n ['component', '\"my_comp\"', 'key=val', 'key2=val2']\n ```\n\n - `component` is the tag name, which we drop.\n - `\"my_comp\"` is the component name, but we must remove the extra quotes.\n - The remaining tokens we pass unmodified, as that's the input to the component.\n\n So in the end, we return:\n\n ```python\n TagResult('my_comp', ['key=val', 'key2=val2'])\n ```\n \"\"\"\n ...\n
abstractmethod
","text":"start_tag(name: str) -> str\n
Formats the start tag of a component.
Parameters:
-
name
(str
) \u2013Component's registered name. Required.
Returns:
-
str
(str
) \u2013The formatted start tag.
src/django_components/tag_formatter.py
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagResult","title":"TagResult","text":"@abc.abstractmethod\ndef start_tag(self, name: str) -> str:\n \"\"\"\n Formats the start tag of a component.\n\n Args:\n name (str): Component's registered name. Required.\n\n Returns:\n str: The formatted start tag.\n \"\"\"\n ...\n
Bases:
NamedTuple
The return value from
TagFormatter.parse()
.Read more about Tag formatter.
Attributes:
-
component_name
(str
) \u2013Component name extracted from the template tag
-
tokens
(List[str]
) \u2013Remaining tokens (words) that were passed to the tag, with component name removed
instance-attribute
","text":"component_name: str\n
Component name extracted from the template tag
For example, if we had tag
{% component \"my_comp\" key=val key2=val2 %}\n
Then
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.TagResult.tokens","title":"tokenscomponent_name
would bemy_comp
.instance-attribute
","text":"tokens: List[str]\n
Remaining tokens (words) that were passed to the tag, with component name removed
For example, if we had tag
{% component \"my_comp\" key=val key2=val2 %}\n
Then
"},{"location":"reference/django_components/tag_formatter/#django_components.tag_formatter.get_tag_formatter","title":"get_tag_formatter","text":"tokens
would be['key=val', 'key2=val2']
.get_tag_formatter(registry: ComponentRegistry) -> InternalTagFormatter\n
Returns an instance of the currently configured component tag formatter.
Source code insrc/django_components/tag_formatter.py
"},{"location":"reference/django_components/template/","title":"def get_tag_formatter(registry: \"ComponentRegistry\") -> InternalTagFormatter:\n \"\"\"Returns an instance of the currently configured component tag formatter.\"\"\"\n # Allow users to configure the component TagFormatter\n formatter_cls_or_str = registry.settings.tag_formatter\n\n if isinstance(formatter_cls_or_str, str):\n tag_formatter: TagFormatterABC = import_string(formatter_cls_or_str)\n else:\n tag_formatter = formatter_cls_or_str\n\n return InternalTagFormatter(tag_formatter)\n
template","text":""},{"location":"reference/django_components/template/#django_components.template","title":"template","text":"
Functions:
-
cached_template
\u2013Create a Template instance that will be cached as per the
cached_template(\n template_string: str,\n template_cls: Optional[Type[Template]] = None,\n origin: Optional[Origin] = None,\n name: Optional[str] = None,\n engine: Optional[Any] = None,\n) -> Template\n
Create a Template instance that will be cached as per the
COMPONENTS.template_cache_size
setting.Parameters:
-
template_string
(str
) \u2013Template as a string, same as the first argument to Django's
Template
. Required. -
template_cls
(Type[Template]
, default:None
) \u2013Specify the Template class that should be instantiated. Defaults to Django's
Template
class. -
origin
(Type[Origin]
, default:None
) \u2013Sets
Template.Origin
. -
name
(Type[str]
, default:None
) \u2013Sets
Template.name
-
engine
(Type[Any]
, default:None
) \u2013Sets
Template.engine
Source code infrom django_components import cached_template\n\ntemplate = cached_template(\"Variable: {{ variable }}\")\n\n# You can optionally specify Template class, and other Template inputs:\nclass MyTemplate(Template):\n pass\n\ntemplate = cached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n)\n
src/django_components/template.py
"},{"location":"reference/django_components/template_loader/","title":"def cached_template(\n template_string: str,\n template_cls: Optional[Type[Template]] = None,\n origin: Optional[Origin] = None,\n name: Optional[str] = None,\n engine: Optional[Any] = None,\n) -> Template:\n \"\"\"\n Create a Template instance that will be cached as per the\n [`COMPONENTS.template_cache_size`](../settings#django_components.app_settings.ComponentsSettings.template_cache_size)\n setting.\n\n Args:\n template_string (str): Template as a string, same as the first argument to Django's\\\n [`Template`](https://docs.djangoproject.com/en/5.1/topics/templates/#template). Required.\n template_cls (Type[Template], optional): Specify the Template class that should be instantiated.\\\n Defaults to Django's [`Template`](https://docs.djangoproject.com/en/5.1/topics/templates/#template) class.\n origin (Type[Origin], optional): Sets \\\n [`Template.Origin`](https://docs.djangoproject.com/en/5.1/howto/custom-template-backend/#origin-api-and-3rd-party-integration).\n name (Type[str], optional): Sets `Template.name`\n engine (Type[Any], optional): Sets `Template.engine`\n\n ```python\n from django_components import cached_template\n\n template = cached_template(\"Variable: {{ variable }}\")\n\n # You can optionally specify Template class, and other Template inputs:\n class MyTemplate(Template):\n pass\n\n template = cached_template(\n \"Variable: {{ variable }}\",\n template_cls=MyTemplate,\n name=...\n origin=...\n engine=...\n )\n ```\n \"\"\" # noqa: E501\n template = _create_template(template_cls or Template, template_string, engine)\n\n # Assign the origin and name separately, so the caching doesn't depend on them\n # Since we might be accessing a template from cache, we want to define these only once\n if not getattr(template, \"_dc_cached\", False):\n template.origin = origin or Origin(UNKNOWN_SOURCE)\n template.name = name\n template._dc_cached = True\n\n return template\n
template_loader","text":""},{"location":"reference/django_components/template_loader/#django_components.template_loader","title":"template_loader","text":"
Template loader that loads templates from each Django app's \"components\" directory.
Classes:
-
Loader
\u2013
Bases:
Loader
Methods:
-
get_dirs
\u2013Prepare directories that may contain component files:
get_dirs(include_apps: bool = True) -> List[Path]\n
Prepare directories that may contain component files:
Searches for dirs set in
COMPONENTS.dirs
settings. If none set, defaults to searching for a \"components\" app. The dirs inCOMPONENTS.dirs
must be absolute paths.In addition to that, also all apps are checked for
[app]/components
dirs.Paths are accepted only if they resolve to a directory. E.g.
/path/to/django_project/my_app/components/
.
Source code inBASE_DIR
setting is required.src/django_components/template_loader.py
"},{"location":"reference/django_components/template_parser/","title":"def get_dirs(self, include_apps: bool = True) -> List[Path]:\n \"\"\"\n Prepare directories that may contain component files:\n\n Searches for dirs set in `COMPONENTS.dirs` settings. If none set, defaults to searching\n for a \"components\" app. The dirs in `COMPONENTS.dirs` must be absolute paths.\n\n In addition to that, also all apps are checked for `[app]/components` dirs.\n\n Paths are accepted only if they resolve to a directory.\n E.g. `/path/to/django_project/my_app/components/`.\n\n `BASE_DIR` setting is required.\n \"\"\"\n return get_component_dirs(include_apps)\n
template_parser","text":""},{"location":"reference/django_components/template_parser/#django_components.template_parser","title":"template_parser","text":"
Overrides for the Django Template system to allow finer control over template parsing.
Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py
Functions:
-
parse_bits
\u2013Parse bits for template tag helpers simple_tag and inclusion_tag, in
-
token_kwargs
\u2013Parse token keyword arguments and return a dictionary of the arguments
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 insrc/django_components/template_parser.py
"},{"location":"reference/django_components/template_parser/#django_components.template_parser.token_kwargs","title":"token_kwargs","text":"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
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
Source code inbits
to be keyword arguments, so return the dictionary as soon as an invalid argument format is reached.src/django_components/template_parser.py
"},{"location":"reference/django_components/templatetags/","title":"Index","text":""},{"location":"reference/django_components/templatetags/#django_components.templatetags","title":"templatetags","text":"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
Modules:
-
component_tags
\u2013
Functions:
-
component
\u2013Renders one of the components that was previously registered with
-
component_css_dependencies
\u2013Marks location where CSS link tags should be rendered after the whole HTML has been generated.
-
component_js_dependencies
\u2013Marks location where JS link tags should be rendered after the whole HTML has been generated.
-
fill
\u2013Use this tag to insert content into component's slots.
-
html_attrs
\u2013Generate HTML attributes (
key=\"value\"
), combining data from multiple sources, -
provide
\u2013The \"provider\" part of the provide / inject feature.
-
slot
\u2013Slot tag marks a place inside a component where content can be inserted
Bases:
NamedTuple
Definition of args, kwargs, flags, etc, for a template tag.
Attributes:
-
end_tag
(Optional[str]
) \u2013End tag.
-
flags
(Optional[List[str]]
) \u2013List of allowed flags.
-
keywordonly_args
(Optional[Union[bool, List[str]]]
) \u2013Parameters that MUST be given only as kwargs (not accounting for
pos_or_keyword_args
). -
optional_kwargs
(Optional[List[str]]
) \u2013Specify which kwargs can be optional.
-
pos_or_keyword_args
(Optional[List[str]]
) \u2013Like regular Python kwargs, these can be given EITHER as positional OR as keyword arguments.
-
positional_args_allow_extra
(bool
) \u2013If
True
, allows variable number of positional args, e.g.{% mytag val1 1234 val2 890 ... %}
-
positional_only_args
(Optional[List[str]]
) \u2013Arguments that MUST be given as positional args.
-
repeatable_kwargs
(Optional[Union[bool, List[str]]]
) \u2013Whether this tag allows all or certain kwargs to be repeated.
-
tag
(str
) \u2013Tag name. E.g.
\"slot\"
means the tag is written like so{% slot ... %}
class-attribute
instance-attribute
","text":"end_tag: Optional[str] = None\n
End tag.
E.g.
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.TagSpec.flags","title":"flags\"endslot\"
means anything between the start tag and{% endslot %}
is considered the slot's body.class-attribute
instance-attribute
","text":"flags: Optional[List[str]] = None\n
List of allowed flags.
Flags are like kwargs, but without the value part. E.g. in
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.TagSpec.keywordonly_args","title":"keywordonly_args{% mytag only required %}
: -only
andrequired
are treated asonly=True
andrequired=True
if present - and treated asonly=False
andrequired=False
if omittedclass-attribute
instance-attribute
","text":"keywordonly_args: Optional[Union[bool, List[str]]] = False\n
Parameters that MUST be given only as kwargs (not accounting for
pos_or_keyword_args
).- If
False
, NO extra kwargs allowed. - If
True
, ANY number of extra kwargs allowed. - If a list of strings, e.g.
[\"class\", \"style\"]
, then only those kwargs are allowed.
class-attribute
instance-attribute
","text":"optional_kwargs: Optional[List[str]] = None\n
Specify which kwargs can be optional.
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.TagSpec.pos_or_keyword_args","title":"pos_or_keyword_argsclass-attribute
instance-attribute
","text":"pos_or_keyword_args: Optional[List[str]] = None\n
Like regular Python kwargs, these can be given EITHER as positional OR as keyword arguments.
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.TagSpec.positional_args_allow_extra","title":"positional_args_allow_extraclass-attribute
instance-attribute
","text":"positional_args_allow_extra: bool = False\n
If
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.TagSpec.positional_only_args","title":"positional_only_argsTrue
, allows variable number of positional args, e.g.{% mytag val1 1234 val2 890 ... %}
class-attribute
instance-attribute
","text":"positional_only_args: Optional[List[str]] = None\n
Arguments that MUST be given as positional args.
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.TagSpec.repeatable_kwargs","title":"repeatable_kwargsclass-attribute
instance-attribute
","text":"repeatable_kwargs: Optional[Union[bool, List[str]]] = False\n
Whether this tag allows all or certain kwargs to be repeated.
- If
False
, NO kwargs can repeat. - If
True
, ALL kwargs can repeat. - If a list of strings, e.g.
[\"class\", \"style\"]
, then only those kwargs can repeat.
E.g.
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.TagSpec.tag","title":"tag[\"class\"]
means one can write{% mytag class=\"one\" class=\"two\" %}
instance-attribute
","text":"tag: str\n
Tag name. E.g.
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component","title":"component","text":"\"slot\"
means the tag is written like so{% slot ... %}
component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str, tag_spec: TagSpec) -> ComponentNode\n
Renders one of the components that was previously registered with
@register()
decorator.Args:
name
(str, required): Registered name of the component to render- All other args and kwargs are defined based on the component itself.
If you defined a component
\"my_table\"
from django_component import Component, register\n\n@register(\"my_table\")\nclass MyTable(Component):\n template = \"\"\"\n <table>\n <thead>\n {% for header in headers %}\n <th>{{ header }}</th>\n {% endfor %}\n </thead>\n <tbody>\n {% for row in rows %}\n <tr>\n {% for cell in row %}\n <td>{{ cell }}</td>\n {% endfor %}\n </tr>\n {% endfor %}\n <tbody>\n </table>\n \"\"\"\n\n def get_context_data(self, rows: List, headers: List):\n return {\n \"rows\": rows,\n \"headers\": headers,\n }\n
Then you can render this component by referring to
MyTable
via its registered name\"my_table\"
:
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component--component-input","title":"Component input","text":"{% component \"my_table\" rows=rows headers=headers ... / %}\n
Positional and keyword arguments can be literals or template variables.
The component name must be a single- or double-quotes string and must be either:
-
The first positional argument after
component
:{% component \"my_table\" rows=rows headers=headers ... / %}\n
-
Passed as kwarg
name
:{% component rows=rows headers=headers name=\"my_table\" ... / %}\n
If the component defined any slots, you can pass in the content to be placed inside those slots by inserting
{% fill %}
tags, directly within the{% component %}
tag:
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component--isolating-components","title":"Isolating components","text":"{% component \"my_table\" rows=rows headers=headers ... / %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n{% endcomponent %}\n
By default, components behave similarly to Django's
{% include %}
, and the template inside the component has access to the variables defined in the outer template.You can selectively isolate a component, using the
only
flag, so that the inner template can access only the data that was explicitly passed to it:
Source code in{% component \"name\" positional_arg keyword_arg=value ... only %}\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"@with_tag_spec(\n TagSpec(\n tag=\"component\",\n end_tag=\"endcomponent\",\n positional_only_args=[],\n positional_args_allow_extra=True, # Allow many args\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[COMP_ONLY_FLAG],\n )\n)\ndef component(\n parser: Parser,\n token: Token,\n registry: ComponentRegistry,\n tag_name: str,\n tag_spec: TagSpec,\n) -> ComponentNode:\n \"\"\"\n Renders one of the components that was previously registered with\n [`@register()`](./api.md#django_components.register)\n decorator.\n\n **Args:**\n\n - `name` (str, required): Registered name of the component to render\n - All other args and kwargs are defined based on the component itself.\n\n If you defined a component `\"my_table\"`\n\n ```python\n from django_component import Component, register\n\n @register(\"my_table\")\n class MyTable(Component):\n template = \\\"\\\"\\\"\n <table>\n <thead>\n {% for header in headers %}\n <th>{{ header }}</th>\n {% endfor %}\n </thead>\n <tbody>\n {% for row in rows %}\n <tr>\n {% for cell in row %}\n <td>{{ cell }}</td>\n {% endfor %}\n </tr>\n {% endfor %}\n <tbody>\n </table>\n \\\"\\\"\\\"\n\n def get_context_data(self, rows: List, headers: List):\n return {\n \"rows\": rows,\n \"headers\": headers,\n }\n ```\n\n Then you can render this component by referring to `MyTable` via its\n registered name `\"my_table\"`:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n ```\n\n ### Component input\n\n Positional and keyword arguments can be literals or template variables.\n\n The component name must be a single- or double-quotes string and must\n be either:\n\n - The first positional argument after `component`:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n ```\n\n - Passed as kwarg `name`:\n\n ```django\n {% component rows=rows headers=headers name=\"my_table\" ... / %}\n ```\n\n ### Inserting into slots\n\n If the component defined any [slots](../concepts/fundamentals/slots.md), you can\n pass in the content to be placed inside those slots by inserting [`{% fill %}`](#fill) tags,\n directly within the `{% component %}` tag:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Isolating components\n\n By default, components behave similarly to Django's\n [`{% include %}`](https://docs.djangoproject.com/en/5.1/ref/templates/builtins/#include),\n and the template inside the component has access to the variables defined in the outer template.\n\n You can selectively isolate a component, using the `only` flag, so that the inner template\n can access only the data that was explicitly passed to it:\n\n ```django\n {% component \"name\" positional_arg keyword_arg=value ... only %}\n ```\n \"\"\"\n _fix_nested_tags(parser, token)\n bits = token.split_contents()\n\n # Let the TagFormatter pre-process the tokens\n formatter = get_tag_formatter(registry)\n result = formatter.parse([*bits])\n end_tag = formatter.end_tag(result.component_name)\n\n # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n bits = [bits[0], *result.tokens]\n token.contents = \" \".join(bits)\n\n tag = _parse_tag(\n parser,\n token,\n TagSpec(\n **{\n **tag_spec._asdict(),\n \"tag\": tag_name,\n \"end_tag\": end_tag,\n }\n ),\n )\n\n # Check for isolated context keyword\n isolated_context = tag.flags[COMP_ONLY_FLAG]\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n body = tag.parse_body()\n\n component_node = ComponentNode(\n name=result.component_name,\n args=tag.args,\n kwargs=tag.kwargs,\n isolated_context=isolated_context,\n nodelist=body,\n node_id=tag.id,\n registry=registry,\n )\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n return component_node\n
component_css_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode\n
Marks location where CSS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted into the
<head>
tag of the HTML.If the generated HTML does NOT contain any
{% component_css_dependencies %}
tags, CSS links are by default inserted into the<head>
tag of the HTML. (See JS and CSS output locations)Note that there should be only one
Source code in{% component_css_dependencies %}
for the whole HTML document. If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"@register.tag(\"component_css_dependencies\")\n@with_tag_spec(\n TagSpec(\n tag=\"component_css_dependencies\",\n end_tag=None, # inline-only\n )\n)\ndef component_css_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode:\n \"\"\"\n Marks location where CSS link tags should be rendered after the whole HTML has been generated.\n\n Generally, this should be inserted into the `<head>` tag of the HTML.\n\n If the generated HTML does NOT contain any `{% component_css_dependencies %}` tags, CSS links\n are by default inserted into the `<head>` tag of the HTML. (See\n [JS and CSS output locations](../../concepts/advanced/rendering_js_css/#js-and-css-output-locations))\n\n Note that there should be only one `{% component_css_dependencies %}` for the whole HTML document.\n If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.\n \"\"\"\n # Parse to check that the syntax is valid\n _parse_tag(parser, token, tag_spec)\n return _component_dependencies(\"css\")\n
component_js_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode\n
Marks location where JS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted at the end of the
<body>
tag of the HTML.If the generated HTML does NOT contain any
{% component_js_dependencies %}
tags, JS scripts are by default inserted at the end of the<body>
tag of the HTML. (See JS and CSS output locations)Note that there should be only one
Source code in{% component_js_dependencies %}
for the whole HTML document. If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.fill","title":"fill","text":"@register.tag(name=\"component_js_dependencies\")\n@with_tag_spec(\n TagSpec(\n tag=\"component_js_dependencies\",\n end_tag=None, # inline-only\n )\n)\ndef component_js_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode:\n \"\"\"\n Marks location where JS link tags should be rendered after the whole HTML has been generated.\n\n Generally, this should be inserted at the end of the `<body>` tag of the HTML.\n\n If the generated HTML does NOT contain any `{% component_js_dependencies %}` tags, JS scripts\n are by default inserted at the end of the `<body>` tag of the HTML. (See\n [JS and CSS output locations](../../concepts/advanced/rendering_js_css/#js-and-css-output-locations))\n\n Note that there should be only one `{% component_js_dependencies %}` for the whole HTML document.\n If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.\n \"\"\"\n # Parse to check that the syntax is valid\n _parse_tag(parser, token, tag_spec)\n return _component_dependencies(\"js\")\n
fill(parser: Parser, token: Token, tag_spec: TagSpec) -> FillNode\n
Use this tag to insert content into component's slots.
{% fill %}
tag may be used only within a{% component %}..{% endcomponent %}
block. Runtime checks should prohibit other usages.Args:
name
(str, required): Name of the slot to insert this content into. Use\"default\"
for the default slot.default
(str, optional): This argument allows you to access the original content of the slot under the specified variable name. See Accessing original content of slotsdata
(str, optional): This argument allows you to access the data passed to the slot under the specified variable name. See Scoped slots
Examples:
Basic usage:
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.fill--accessing-slots-default-content-with-the-default-kwarg","title":"Accessing slot's default content with the{% component \"my_table\" %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n{% endcomponent %}\n
default
kwarg","text":"{# my_table.html #}\n<table>\n ...\n {% slot \"pagination\" %}\n < 1 | 2 | 3 >\n {% endslot %}\n</table>\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.fill--accessing-slots-data-with-the-data-kwarg","title":"Accessing slot's data with the{% component \"my_table\" %}\n {% fill \"pagination\" default=\"default_pag\" %}\n <div class=\"my-class\">\n {{ default_pag }}\n </div>\n {% endfill %}\n{% endcomponent %}\n
data
kwarg","text":"{# my_table.html #}\n<table>\n ...\n {% slot \"pagination\" pages=pages %}\n < 1 | 2 | 3 >\n {% endslot %}\n</table>\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.fill--accessing-slot-data-and-default-content-on-the-default-slot","title":"Accessing slot data and default content on the default slot","text":"{% component \"my_table\" %}\n {% fill \"pagination\" data=\"slot_data\" %}\n {% for page in slot_data.pages %}\n <a href=\"{{ page.link }}\">\n {{ page.index }}\n </a>\n {% endfor %}\n {% endfill %}\n{% endcomponent %}\n
To access slot data and the default slot content on the default slot, use
{% fill %}
withname
set to\"default\"
:
Source code in{% component \"button\" %}\n {% fill name=\"default\" data=\"slot_data\" default=\"default_slot\" %}\n You clicked me {{ slot_data.count }} times!\n {{ default_slot }}\n {% endfill %}\n{% endcomponent %}\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"@register.tag(\"fill\")\n@with_tag_spec(\n TagSpec(\n tag=\"fill\",\n end_tag=\"endfill\",\n positional_only_args=[],\n pos_or_keyword_args=[SLOT_NAME_KWARG],\n keywordonly_args=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n optional_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n repeatable_kwargs=False,\n )\n)\ndef fill(parser: Parser, token: Token, tag_spec: TagSpec) -> FillNode:\n \"\"\"\n Use this tag to insert content into component's slots.\n\n `{% fill %}` tag may be used only within a `{% component %}..{% endcomponent %}` block.\n Runtime checks should prohibit other usages.\n\n **Args:**\n\n - `name` (str, required): Name of the slot to insert this content into. Use `\"default\"` for\n the default slot.\n - `default` (str, optional): This argument allows you to access the original content of the slot\n under the specified variable name. See\n [Accessing original content of slots](../../concepts/fundamentals/slots#accessing-original-content-of-slots)\n - `data` (str, optional): This argument allows you to access the data passed to the slot\n under the specified variable name. See [Scoped slots](../../concepts/fundamentals/slots#scoped-slots)\n\n **Examples:**\n\n Basic usage:\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot's default content with the `default` kwarg\n\n ```django\n {# my_table.html #}\n <table>\n ...\n {% slot \"pagination\" %}\n < 1 | 2 | 3 >\n {% endslot %}\n </table>\n ```\n\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" default=\"default_pag\" %}\n <div class=\"my-class\">\n {{ default_pag }}\n </div>\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot's data with the `data` kwarg\n\n ```django\n {# my_table.html #}\n <table>\n ...\n {% slot \"pagination\" pages=pages %}\n < 1 | 2 | 3 >\n {% endslot %}\n </table>\n ```\n\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" data=\"slot_data\" %}\n {% for page in slot_data.pages %}\n <a href=\"{{ page.link }}\">\n {{ page.index }}\n </a>\n {% endfor %}\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot data and default content on the default slot\n\n To access slot data and the default slot content on the default slot,\n use `{% fill %}` with `name` set to `\"default\"`:\n\n ```django\n {% component \"button\" %}\n {% fill name=\"default\" data=\"slot_data\" default=\"default_slot\" %}\n You clicked me {{ slot_data.count }} times!\n {{ default_slot }}\n {% endfill %}\n {% endcomponent %}\n ```\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n fill_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n trace_id = f\"fill-id-{tag.id} ({fill_name_kwarg})\" if fill_name_kwarg else f\"fill-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id)\n\n body = tag.parse_body()\n fill_node = FillNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id, \"...Done!\")\n return fill_node\n
html_attrs(parser: Parser, token: Token, tag_spec: TagSpec) -> HtmlAttrsNode\n
Generate HTML attributes (
key=\"value\"
), combining data from multiple sources, whether its template variables or static text.It is designed to easily merge HTML attributes passed from outside with the internal. See how to in Passing HTML attributes to components.
Args:
attrs
(dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides values in thedefault
dictionary.default
(str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden with values in theattrs
dictionary.- Any extra kwargs will be appended to the corresponding keys
The attributes in
attrs
anddefaults
are merged and resulting dict is rendered as HTML attributes (key=\"value\"
).Extra kwargs (
key=value
) are concatenated to existing keys. So if we haveattrs = {\"class\": \"my-class\"}\n
Then
{% html_attrs attrs class=\"extra-class\" %}\n
will result in
class=\"my-class extra-class\"
.Example:
<div {% html_attrs\n attrs\n defaults:class=\"default-class\"\n class=\"extra-class\"\n data-id=\"123\"\n%}>\n
renders
<div class=\"my-class extra-class\" data-id=\"123\">\n
See more usage examples in HTML attributes.
Source code insrc/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.provide","title":"provide","text":"@register.tag(\"html_attrs\")\n@with_tag_spec(\n TagSpec(\n tag=\"html_attrs\",\n end_tag=None, # inline-only\n positional_only_args=[],\n pos_or_keyword_args=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n optional_kwargs=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n keywordonly_args=True,\n repeatable_kwargs=True,\n flags=[],\n )\n)\ndef html_attrs(parser: Parser, token: Token, tag_spec: TagSpec) -> HtmlAttrsNode:\n \"\"\"\n Generate HTML attributes (`key=\"value\"`), combining data from multiple sources,\n whether its template variables or static text.\n\n It is designed to easily merge HTML attributes passed from outside with the internal.\n See how to in [Passing HTML attributes to components](../../guides/howto/passing_html_attrs/).\n\n **Args:**\n\n - `attrs` (dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides\n values in the `default` dictionary.\n - `default` (str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden\n with values in the `attrs` dictionary.\n - Any extra kwargs will be appended to the corresponding keys\n\n The attributes in `attrs` and `defaults` are merged and resulting dict is rendered as HTML attributes\n (`key=\"value\"`).\n\n Extra kwargs (`key=value`) are concatenated to existing keys. So if we have\n\n ```python\n attrs = {\"class\": \"my-class\"}\n ```\n\n Then\n\n ```django\n {% html_attrs attrs class=\"extra-class\" %}\n ```\n\n will result in `class=\"my-class extra-class\"`.\n\n **Example:**\n ```django\n <div {% html_attrs\n attrs\n defaults:class=\"default-class\"\n class=\"extra-class\"\n data-id=\"123\"\n %}>\n ```\n\n renders\n\n ```html\n <div class=\"my-class extra-class\" data-id=\"123\">\n ```\n\n **See more usage examples in\n [HTML attributes](../../concepts/fundamentals/html_attributes#examples-for-html_attrs).**\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n return HtmlAttrsNode(\n kwargs=tag.kwargs,\n kwarg_pairs=tag.kwarg_pairs,\n )\n
provide(parser: Parser, token: Token, tag_spec: TagSpec) -> ProvideNode\n
The \"provider\" part of the provide / inject feature. Pass kwargs to this tag to define the provider's data. Any components defined within the
{% provide %}..{% endprovide %}
tags will be able to access this data withComponent.inject()
.This is similar to React's
ContextProvider
, or Vue'sprovide()
.Args:
name
(str, required): Provider name. This is the name you will then use inComponent.inject()
.**kwargs
: Any extra kwargs will be passed as the provided data.
Example:
Provide the \"user_data\" in parent component:
@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n <div>\n {% provide \"user_data\" user=user %}\n {% component \"child\" / %}\n {% endprovide %}\n </div>\n \"\"\"\n\n def get_context_data(self, user: User):\n return {\n \"user\": user,\n }\n
Since the \"child\" component is used within the
{% provide %} / {% endprovide %}
tags, we can request the \"user_data\" usingComponent.inject(\"user_data\")
:@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n User is: {{ user }}\n </div>\n \"\"\"\n\n def get_context_data(self):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n
Notice that the keys defined on the
{% provide %}
tag are then accessed as attributes when accessing them withComponent.inject()
.\u2705 Do this
user = self.inject(\"user_data\").user\n
\u274c Don't do this
Source code inuser = self.inject(\"user_data\")[\"user\"]\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.slot","title":"slot","text":"@register.tag(\"provide\")\n@with_tag_spec(\n TagSpec(\n tag=\"provide\",\n end_tag=\"endprovide\",\n positional_only_args=[],\n pos_or_keyword_args=[PROVIDE_NAME_KWARG],\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[],\n )\n)\ndef provide(parser: Parser, token: Token, tag_spec: TagSpec) -> ProvideNode:\n \"\"\"\n The \"provider\" part of the [provide / inject feature](../../concepts/advanced/provide_inject).\n Pass kwargs to this tag to define the provider's data.\n Any components defined within the `{% provide %}..{% endprovide %}` tags will be able to access this data\n with [`Component.inject()`](../api#django_components.Component.inject).\n\n This is similar to React's [`ContextProvider`](https://react.dev/learn/passing-data-deeply-with-context),\n or Vue's [`provide()`](https://vuejs.org/guide/components/provide-inject).\n\n **Args:**\n\n - `name` (str, required): Provider name. This is the name you will then use in\n [`Component.inject()`](../api#django_components.Component.inject).\n - `**kwargs`: Any extra kwargs will be passed as the provided data.\n\n **Example:**\n\n Provide the \"user_data\" in parent component:\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n <div>\n {% provide \"user_data\" user=user %}\n {% component \"child\" / %}\n {% endprovide %}\n </div>\n \\\"\\\"\\\"\n\n def get_context_data(self, user: User):\n return {\n \"user\": user,\n }\n ```\n\n Since the \"child\" component is used within the `{% provide %} / {% endprovide %}` tags,\n we can request the \"user_data\" using `Component.inject(\"user_data\")`:\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n User is: {{ user }}\n </div>\n \\\"\\\"\\\"\n\n def get_context_data(self):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n ```\n\n Notice that the keys defined on the `{% provide %}` tag are then accessed as attributes\n when accessing them with [`Component.inject()`](../api#django_components.Component.inject).\n\n \u2705 Do this\n ```python\n user = self.inject(\"user_data\").user\n ```\n\n \u274c Don't do this\n ```python\n user = self.inject(\"user_data\")[\"user\"]\n ```\n \"\"\"\n # e.g. {% provide <name> key=val key2=val2 %}\n tag = _parse_tag(parser, token, tag_spec)\n\n name_kwarg = tag.kwargs.kwargs.get(PROVIDE_NAME_KWARG, None)\n trace_id = f\"provide-id-{tag.id} ({name_kwarg})\" if name_kwarg else f\"fill-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"PROVIDE\", trace_id, tag.id)\n\n body = tag.parse_body()\n provide_node = ProvideNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"PROVIDE\", trace_id, tag.id, \"...Done!\")\n return provide_node\n
slot(parser: Parser, token: Token, tag_spec: TagSpec) -> SlotNode\n
Slot tag marks a place inside a component where content can be inserted from outside.
Learn more about using slots.
This is similar to slots as seen in Web components, Vue or React's
children
.Args:
name
(str, required): Registered name of the component to renderdefault
: Optional flag. If there is a default slot, you can pass the component slot content without using the{% fill %}
tag. See Default slotrequired
: Optional flag. Will raise an error if a slot is required but not given.**kwargs
: Any extra kwargs will be passed as the slot data.
Example:
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" default %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n <aside>\n {% slot \"sidebar\" required / %}\n </aside>\n \"\"\"\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.slot--passing-data-to-slots","title":"Passing data to slots","text":"@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n <div>\n {% component \"child\" %}\n {% fill \"content\" %}\n \ud83d\uddde\ufe0f\ud83d\udcf0\n {% endfill %}\n\n {% fill \"sidebar\" %}\n \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n {% endfill %}\n {% endcomponent %}\n </div>\n \"\"\"\n
Any extra kwargs will be considered as slot data, and will be accessible in the
{% fill %}
tag via fill'sdata
kwarg:@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \"\"\"\n
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.slot--accessing-default-slot-content","title":"Accessing default slot content","text":"@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
The content between the
{% slot %}..{% endslot %}
tags is the default content that will be rendered if no fill is given for the slot.This default content can then be accessed from within the
{% fill %}
tag using the fill'sdefault
kwarg. This is useful if you need to wrap / prepend / append the original slot's content.@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" %}\n This is default content!\n {% endslot %}\n </div>\n \"\"\"\n
Source code in@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot's default content #}\n {% component \"child\" %}\n {% fill \"content\" default=\"default\" %}\n {{ default }}\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/#django_components.templatetags.component_tags.with_tag_spec","title":"with_tag_spec","text":"@register.tag(\"slot\")\n@with_tag_spec(\n TagSpec(\n tag=\"slot\",\n end_tag=\"endslot\",\n positional_only_args=[],\n pos_or_keyword_args=[SLOT_NAME_KWARG],\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[SLOT_DEFAULT_KEYWORD, SLOT_REQUIRED_KEYWORD],\n )\n)\ndef slot(parser: Parser, token: Token, tag_spec: TagSpec) -> SlotNode:\n \"\"\"\n Slot tag marks a place inside a component where content can be inserted\n from outside.\n\n [Learn more](../../concepts/fundamentals/slots) about using slots.\n\n This is similar to slots as seen in\n [Web components](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot),\n [Vue](https://vuejs.org/guide/components/slots.html)\n or [React's `children`](https://react.dev/learn/passing-props-to-a-component#passing-jsx-as-children).\n\n **Args:**\n\n - `name` (str, required): Registered name of the component to render\n - `default`: Optional flag. If there is a default slot, you can pass the component slot content\n without using the [`{% fill %}`](#fill) tag. See\n [Default slot](../../concepts/fundamentals/slots#default-slot)\n - `required`: Optional flag. Will raise an error if a slot is required but not given.\n - `**kwargs`: Any extra kwargs will be passed as the slot data.\n\n **Example:**\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {% slot \"content\" default %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n <aside>\n {% slot \"sidebar\" required / %}\n </aside>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n <div>\n {% component \"child\" %}\n {% fill \"content\" %}\n \ud83d\uddde\ufe0f\ud83d\udcf0\n {% endfill %}\n\n {% fill \"sidebar\" %}\n \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n {% endfill %}\n {% endcomponent %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ### Passing data to slots\n\n Any extra kwargs will be considered as slot data, and will be accessible in the [`{% fill %}`](#fill)\n tag via fill's `data` kwarg:\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \\\"\\\"\\\"\n ```\n\n ### Accessing default slot content\n\n The content between the `{% slot %}..{% endslot %}` tags is the default content that\n will be rendered if no fill is given for the slot.\n\n This default content can then be accessed from within the [`{% fill %}`](#fill) tag using\n the fill's `default` kwarg.\n This is useful if you need to wrap / prepend / append the original slot's content.\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {% slot \"content\" %}\n This is default content!\n {% endslot %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n {# Parent can access the slot's default content #}\n {% component \"child\" %}\n {% fill \"content\" default=\"default\" %}\n {{ default }}\n {% endfill %}\n {% endcomponent %}\n \\\"\\\"\\\"\n ```\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n slot_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n trace_id = f\"slot-id-{tag.id} ({slot_name_kwarg})\" if slot_name_kwarg else f\"slot-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"SLOT\", trace_id, tag.id)\n\n body = tag.parse_body()\n slot_node = SlotNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n is_required=tag.flags[SLOT_REQUIRED_KEYWORD],\n is_default=tag.flags[SLOT_DEFAULT_KEYWORD],\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"SLOT\", trace_id, tag.id, \"...Done!\")\n return slot_node\n
Source code inwith_tag_spec(tag_spec: TagSpec) -> Callable\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/component_tags/","title":"def with_tag_spec(tag_spec: TagSpec) -> Callable:\n \"\"\"\"\"\"\n\n def decorator(fn: Callable) -> Any:\n fn._tag_spec = tag_spec # type: ignore[attr-defined]\n\n @functools.wraps(fn)\n def wrapper(*args: Any, **kwargs: Any) -> Any:\n return fn(*args, **kwargs, tag_spec=tag_spec)\n\n return wrapper\n\n return decorator\n
component_tags","text":""},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags","title":"component_tags","text":"
Functions:
-
component
\u2013Renders one of the components that was previously registered with
-
component_css_dependencies
\u2013Marks location where CSS link tags should be rendered after the whole HTML has been generated.
-
component_js_dependencies
\u2013Marks location where JS link tags should be rendered after the whole HTML has been generated.
-
fill
\u2013Use this tag to insert content into component's slots.
-
html_attrs
\u2013Generate HTML attributes (
key=\"value\"
), combining data from multiple sources, -
provide
\u2013The \"provider\" part of the provide / inject feature.
-
slot
\u2013Slot tag marks a place inside a component where content can be inserted
Bases:
NamedTuple
Definition of args, kwargs, flags, etc, for a template tag.
Attributes:
-
end_tag
(Optional[str]
) \u2013End tag.
-
flags
(Optional[List[str]]
) \u2013List of allowed flags.
-
keywordonly_args
(Optional[Union[bool, List[str]]]
) \u2013Parameters that MUST be given only as kwargs (not accounting for
pos_or_keyword_args
). -
optional_kwargs
(Optional[List[str]]
) \u2013Specify which kwargs can be optional.
-
pos_or_keyword_args
(Optional[List[str]]
) \u2013Like regular Python kwargs, these can be given EITHER as positional OR as keyword arguments.
-
positional_args_allow_extra
(bool
) \u2013If
True
, allows variable number of positional args, e.g.{% mytag val1 1234 val2 890 ... %}
-
positional_only_args
(Optional[List[str]]
) \u2013Arguments that MUST be given as positional args.
-
repeatable_kwargs
(Optional[Union[bool, List[str]]]
) \u2013Whether this tag allows all or certain kwargs to be repeated.
-
tag
(str
) \u2013Tag name. E.g.
\"slot\"
means the tag is written like so{% slot ... %}
class-attribute
instance-attribute
","text":"end_tag: Optional[str] = None\n
End tag.
E.g.
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.TagSpec.flags","title":"flags\"endslot\"
means anything between the start tag and{% endslot %}
is considered the slot's body.class-attribute
instance-attribute
","text":"flags: Optional[List[str]] = None\n
List of allowed flags.
Flags are like kwargs, but without the value part. E.g. in
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.TagSpec.keywordonly_args","title":"keywordonly_args{% mytag only required %}
: -only
andrequired
are treated asonly=True
andrequired=True
if present - and treated asonly=False
andrequired=False
if omittedclass-attribute
instance-attribute
","text":"keywordonly_args: Optional[Union[bool, List[str]]] = False\n
Parameters that MUST be given only as kwargs (not accounting for
pos_or_keyword_args
).- If
False
, NO extra kwargs allowed. - If
True
, ANY number of extra kwargs allowed. - If a list of strings, e.g.
[\"class\", \"style\"]
, then only those kwargs are allowed.
class-attribute
instance-attribute
","text":"optional_kwargs: Optional[List[str]] = None\n
Specify which kwargs can be optional.
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.TagSpec.pos_or_keyword_args","title":"pos_or_keyword_argsclass-attribute
instance-attribute
","text":"pos_or_keyword_args: Optional[List[str]] = None\n
Like regular Python kwargs, these can be given EITHER as positional OR as keyword arguments.
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.TagSpec.positional_args_allow_extra","title":"positional_args_allow_extraclass-attribute
instance-attribute
","text":"positional_args_allow_extra: bool = False\n
If
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.TagSpec.positional_only_args","title":"positional_only_argsTrue
, allows variable number of positional args, e.g.{% mytag val1 1234 val2 890 ... %}
class-attribute
instance-attribute
","text":"positional_only_args: Optional[List[str]] = None\n
Arguments that MUST be given as positional args.
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.TagSpec.repeatable_kwargs","title":"repeatable_kwargsclass-attribute
instance-attribute
","text":"repeatable_kwargs: Optional[Union[bool, List[str]]] = False\n
Whether this tag allows all or certain kwargs to be repeated.
- If
False
, NO kwargs can repeat. - If
True
, ALL kwargs can repeat. - If a list of strings, e.g.
[\"class\", \"style\"]
, then only those kwargs can repeat.
E.g.
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.TagSpec.tag","title":"tag[\"class\"]
means one can write{% mytag class=\"one\" class=\"two\" %}
instance-attribute
","text":"tag: str\n
Tag name. E.g.
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component","title":"component","text":"\"slot\"
means the tag is written like so{% slot ... %}
component(parser: Parser, token: Token, registry: ComponentRegistry, tag_name: str, tag_spec: TagSpec) -> ComponentNode\n
Renders one of the components that was previously registered with
@register()
decorator.Args:
name
(str, required): Registered name of the component to render- All other args and kwargs are defined based on the component itself.
If you defined a component
\"my_table\"
from django_component import Component, register\n\n@register(\"my_table\")\nclass MyTable(Component):\n template = \"\"\"\n <table>\n <thead>\n {% for header in headers %}\n <th>{{ header }}</th>\n {% endfor %}\n </thead>\n <tbody>\n {% for row in rows %}\n <tr>\n {% for cell in row %}\n <td>{{ cell }}</td>\n {% endfor %}\n </tr>\n {% endfor %}\n <tbody>\n </table>\n \"\"\"\n\n def get_context_data(self, rows: List, headers: List):\n return {\n \"rows\": rows,\n \"headers\": headers,\n }\n
Then you can render this component by referring to
MyTable
via its registered name\"my_table\"
:
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component--component-input","title":"Component input","text":"{% component \"my_table\" rows=rows headers=headers ... / %}\n
Positional and keyword arguments can be literals or template variables.
The component name must be a single- or double-quotes string and must be either:
-
The first positional argument after
component
:{% component \"my_table\" rows=rows headers=headers ... / %}\n
-
Passed as kwarg
name
:{% component rows=rows headers=headers name=\"my_table\" ... / %}\n
If the component defined any slots, you can pass in the content to be placed inside those slots by inserting
{% fill %}
tags, directly within the{% component %}
tag:
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component--isolating-components","title":"Isolating components","text":"{% component \"my_table\" rows=rows headers=headers ... / %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n{% endcomponent %}\n
By default, components behave similarly to Django's
{% include %}
, and the template inside the component has access to the variables defined in the outer template.You can selectively isolate a component, using the
only
flag, so that the inner template can access only the data that was explicitly passed to it:
Source code in{% component \"name\" positional_arg keyword_arg=value ... only %}\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component_css_dependencies","title":"component_css_dependencies","text":"@with_tag_spec(\n TagSpec(\n tag=\"component\",\n end_tag=\"endcomponent\",\n positional_only_args=[],\n positional_args_allow_extra=True, # Allow many args\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[COMP_ONLY_FLAG],\n )\n)\ndef component(\n parser: Parser,\n token: Token,\n registry: ComponentRegistry,\n tag_name: str,\n tag_spec: TagSpec,\n) -> ComponentNode:\n \"\"\"\n Renders one of the components that was previously registered with\n [`@register()`](./api.md#django_components.register)\n decorator.\n\n **Args:**\n\n - `name` (str, required): Registered name of the component to render\n - All other args and kwargs are defined based on the component itself.\n\n If you defined a component `\"my_table\"`\n\n ```python\n from django_component import Component, register\n\n @register(\"my_table\")\n class MyTable(Component):\n template = \\\"\\\"\\\"\n <table>\n <thead>\n {% for header in headers %}\n <th>{{ header }}</th>\n {% endfor %}\n </thead>\n <tbody>\n {% for row in rows %}\n <tr>\n {% for cell in row %}\n <td>{{ cell }}</td>\n {% endfor %}\n </tr>\n {% endfor %}\n <tbody>\n </table>\n \\\"\\\"\\\"\n\n def get_context_data(self, rows: List, headers: List):\n return {\n \"rows\": rows,\n \"headers\": headers,\n }\n ```\n\n Then you can render this component by referring to `MyTable` via its\n registered name `\"my_table\"`:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n ```\n\n ### Component input\n\n Positional and keyword arguments can be literals or template variables.\n\n The component name must be a single- or double-quotes string and must\n be either:\n\n - The first positional argument after `component`:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n ```\n\n - Passed as kwarg `name`:\n\n ```django\n {% component rows=rows headers=headers name=\"my_table\" ... / %}\n ```\n\n ### Inserting into slots\n\n If the component defined any [slots](../concepts/fundamentals/slots.md), you can\n pass in the content to be placed inside those slots by inserting [`{% fill %}`](#fill) tags,\n directly within the `{% component %}` tag:\n\n ```django\n {% component \"my_table\" rows=rows headers=headers ... / %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Isolating components\n\n By default, components behave similarly to Django's\n [`{% include %}`](https://docs.djangoproject.com/en/5.1/ref/templates/builtins/#include),\n and the template inside the component has access to the variables defined in the outer template.\n\n You can selectively isolate a component, using the `only` flag, so that the inner template\n can access only the data that was explicitly passed to it:\n\n ```django\n {% component \"name\" positional_arg keyword_arg=value ... only %}\n ```\n \"\"\"\n _fix_nested_tags(parser, token)\n bits = token.split_contents()\n\n # Let the TagFormatter pre-process the tokens\n formatter = get_tag_formatter(registry)\n result = formatter.parse([*bits])\n end_tag = formatter.end_tag(result.component_name)\n\n # NOTE: The tokens returned from TagFormatter.parse do NOT include the tag itself\n bits = [bits[0], *result.tokens]\n token.contents = \" \".join(bits)\n\n tag = _parse_tag(\n parser,\n token,\n TagSpec(\n **{\n **tag_spec._asdict(),\n \"tag\": tag_name,\n \"end_tag\": end_tag,\n }\n ),\n )\n\n # Check for isolated context keyword\n isolated_context = tag.flags[COMP_ONLY_FLAG]\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id)\n\n body = tag.parse_body()\n\n component_node = ComponentNode(\n name=result.component_name,\n args=tag.args,\n kwargs=tag.kwargs,\n isolated_context=isolated_context,\n nodelist=body,\n node_id=tag.id,\n registry=registry,\n )\n\n trace_msg(\"PARSE\", \"COMP\", result.component_name, tag.id, \"...Done!\")\n return component_node\n
component_css_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode\n
Marks location where CSS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted into the
<head>
tag of the HTML.If the generated HTML does NOT contain any
{% component_css_dependencies %}
tags, CSS links are by default inserted into the<head>
tag of the HTML. (See JS and CSS output locations)Note that there should be only one
Source code in{% component_css_dependencies %}
for the whole HTML document. If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.component_js_dependencies","title":"component_js_dependencies","text":"@register.tag(\"component_css_dependencies\")\n@with_tag_spec(\n TagSpec(\n tag=\"component_css_dependencies\",\n end_tag=None, # inline-only\n )\n)\ndef component_css_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode:\n \"\"\"\n Marks location where CSS link tags should be rendered after the whole HTML has been generated.\n\n Generally, this should be inserted into the `<head>` tag of the HTML.\n\n If the generated HTML does NOT contain any `{% component_css_dependencies %}` tags, CSS links\n are by default inserted into the `<head>` tag of the HTML. (See\n [JS and CSS output locations](../../concepts/advanced/rendering_js_css/#js-and-css-output-locations))\n\n Note that there should be only one `{% component_css_dependencies %}` for the whole HTML document.\n If you insert this tag multiple times, ALL CSS links will be duplicately inserted into ALL these places.\n \"\"\"\n # Parse to check that the syntax is valid\n _parse_tag(parser, token, tag_spec)\n return _component_dependencies(\"css\")\n
component_js_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode\n
Marks location where JS link tags should be rendered after the whole HTML has been generated.
Generally, this should be inserted at the end of the
<body>
tag of the HTML.If the generated HTML does NOT contain any
{% component_js_dependencies %}
tags, JS scripts are by default inserted at the end of the<body>
tag of the HTML. (See JS and CSS output locations)Note that there should be only one
Source code in{% component_js_dependencies %}
for the whole HTML document. If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.fill","title":"fill","text":"@register.tag(name=\"component_js_dependencies\")\n@with_tag_spec(\n TagSpec(\n tag=\"component_js_dependencies\",\n end_tag=None, # inline-only\n )\n)\ndef component_js_dependencies(parser: Parser, token: Token, tag_spec: TagSpec) -> TextNode:\n \"\"\"\n Marks location where JS link tags should be rendered after the whole HTML has been generated.\n\n Generally, this should be inserted at the end of the `<body>` tag of the HTML.\n\n If the generated HTML does NOT contain any `{% component_js_dependencies %}` tags, JS scripts\n are by default inserted at the end of the `<body>` tag of the HTML. (See\n [JS and CSS output locations](../../concepts/advanced/rendering_js_css/#js-and-css-output-locations))\n\n Note that there should be only one `{% component_js_dependencies %}` for the whole HTML document.\n If you insert this tag multiple times, ALL JS scripts will be duplicately inserted into ALL these places.\n \"\"\"\n # Parse to check that the syntax is valid\n _parse_tag(parser, token, tag_spec)\n return _component_dependencies(\"js\")\n
fill(parser: Parser, token: Token, tag_spec: TagSpec) -> FillNode\n
Use this tag to insert content into component's slots.
{% fill %}
tag may be used only within a{% component %}..{% endcomponent %}
block. Runtime checks should prohibit other usages.Args:
name
(str, required): Name of the slot to insert this content into. Use\"default\"
for the default slot.default
(str, optional): This argument allows you to access the original content of the slot under the specified variable name. See Accessing original content of slotsdata
(str, optional): This argument allows you to access the data passed to the slot under the specified variable name. See Scoped slots
Examples:
Basic usage:
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.fill--accessing-slots-default-content-with-the-default-kwarg","title":"Accessing slot's default content with the{% component \"my_table\" %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n{% endcomponent %}\n
default
kwarg","text":"{# my_table.html #}\n<table>\n ...\n {% slot \"pagination\" %}\n < 1 | 2 | 3 >\n {% endslot %}\n</table>\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.fill--accessing-slots-data-with-the-data-kwarg","title":"Accessing slot's data with the{% component \"my_table\" %}\n {% fill \"pagination\" default=\"default_pag\" %}\n <div class=\"my-class\">\n {{ default_pag }}\n </div>\n {% endfill %}\n{% endcomponent %}\n
data
kwarg","text":"{# my_table.html #}\n<table>\n ...\n {% slot \"pagination\" pages=pages %}\n < 1 | 2 | 3 >\n {% endslot %}\n</table>\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.fill--accessing-slot-data-and-default-content-on-the-default-slot","title":"Accessing slot data and default content on the default slot","text":"{% component \"my_table\" %}\n {% fill \"pagination\" data=\"slot_data\" %}\n {% for page in slot_data.pages %}\n <a href=\"{{ page.link }}\">\n {{ page.index }}\n </a>\n {% endfor %}\n {% endfill %}\n{% endcomponent %}\n
To access slot data and the default slot content on the default slot, use
{% fill %}
withname
set to\"default\"
:
Source code in{% component \"button\" %}\n {% fill name=\"default\" data=\"slot_data\" default=\"default_slot\" %}\n You clicked me {{ slot_data.count }} times!\n {{ default_slot }}\n {% endfill %}\n{% endcomponent %}\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.html_attrs","title":"html_attrs","text":"@register.tag(\"fill\")\n@with_tag_spec(\n TagSpec(\n tag=\"fill\",\n end_tag=\"endfill\",\n positional_only_args=[],\n pos_or_keyword_args=[SLOT_NAME_KWARG],\n keywordonly_args=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n optional_kwargs=[SLOT_DATA_KWARG, SLOT_DEFAULT_KWARG],\n repeatable_kwargs=False,\n )\n)\ndef fill(parser: Parser, token: Token, tag_spec: TagSpec) -> FillNode:\n \"\"\"\n Use this tag to insert content into component's slots.\n\n `{% fill %}` tag may be used only within a `{% component %}..{% endcomponent %}` block.\n Runtime checks should prohibit other usages.\n\n **Args:**\n\n - `name` (str, required): Name of the slot to insert this content into. Use `\"default\"` for\n the default slot.\n - `default` (str, optional): This argument allows you to access the original content of the slot\n under the specified variable name. See\n [Accessing original content of slots](../../concepts/fundamentals/slots#accessing-original-content-of-slots)\n - `data` (str, optional): This argument allows you to access the data passed to the slot\n under the specified variable name. See [Scoped slots](../../concepts/fundamentals/slots#scoped-slots)\n\n **Examples:**\n\n Basic usage:\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" %}\n < 1 | 2 | 3 >\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot's default content with the `default` kwarg\n\n ```django\n {# my_table.html #}\n <table>\n ...\n {% slot \"pagination\" %}\n < 1 | 2 | 3 >\n {% endslot %}\n </table>\n ```\n\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" default=\"default_pag\" %}\n <div class=\"my-class\">\n {{ default_pag }}\n </div>\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot's data with the `data` kwarg\n\n ```django\n {# my_table.html #}\n <table>\n ...\n {% slot \"pagination\" pages=pages %}\n < 1 | 2 | 3 >\n {% endslot %}\n </table>\n ```\n\n ```django\n {% component \"my_table\" %}\n {% fill \"pagination\" data=\"slot_data\" %}\n {% for page in slot_data.pages %}\n <a href=\"{{ page.link }}\">\n {{ page.index }}\n </a>\n {% endfor %}\n {% endfill %}\n {% endcomponent %}\n ```\n\n ### Accessing slot data and default content on the default slot\n\n To access slot data and the default slot content on the default slot,\n use `{% fill %}` with `name` set to `\"default\"`:\n\n ```django\n {% component \"button\" %}\n {% fill name=\"default\" data=\"slot_data\" default=\"default_slot\" %}\n You clicked me {{ slot_data.count }} times!\n {{ default_slot }}\n {% endfill %}\n {% endcomponent %}\n ```\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n fill_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n trace_id = f\"fill-id-{tag.id} ({fill_name_kwarg})\" if fill_name_kwarg else f\"fill-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id)\n\n body = tag.parse_body()\n fill_node = FillNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"FILL\", trace_id, tag.id, \"...Done!\")\n return fill_node\n
html_attrs(parser: Parser, token: Token, tag_spec: TagSpec) -> HtmlAttrsNode\n
Generate HTML attributes (
key=\"value\"
), combining data from multiple sources, whether its template variables or static text.It is designed to easily merge HTML attributes passed from outside with the internal. See how to in Passing HTML attributes to components.
Args:
attrs
(dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides values in thedefault
dictionary.default
(str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden with values in theattrs
dictionary.- Any extra kwargs will be appended to the corresponding keys
The attributes in
attrs
anddefaults
are merged and resulting dict is rendered as HTML attributes (key=\"value\"
).Extra kwargs (
key=value
) are concatenated to existing keys. So if we haveattrs = {\"class\": \"my-class\"}\n
Then
{% html_attrs attrs class=\"extra-class\" %}\n
will result in
class=\"my-class extra-class\"
.Example:
<div {% html_attrs\n attrs\n defaults:class=\"default-class\"\n class=\"extra-class\"\n data-id=\"123\"\n%}>\n
renders
<div class=\"my-class extra-class\" data-id=\"123\">\n
See more usage examples in HTML attributes.
Source code insrc/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.provide","title":"provide","text":"@register.tag(\"html_attrs\")\n@with_tag_spec(\n TagSpec(\n tag=\"html_attrs\",\n end_tag=None, # inline-only\n positional_only_args=[],\n pos_or_keyword_args=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n optional_kwargs=[HTML_ATTRS_ATTRS_KEY, HTML_ATTRS_DEFAULTS_KEY],\n keywordonly_args=True,\n repeatable_kwargs=True,\n flags=[],\n )\n)\ndef html_attrs(parser: Parser, token: Token, tag_spec: TagSpec) -> HtmlAttrsNode:\n \"\"\"\n Generate HTML attributes (`key=\"value\"`), combining data from multiple sources,\n whether its template variables or static text.\n\n It is designed to easily merge HTML attributes passed from outside with the internal.\n See how to in [Passing HTML attributes to components](../../guides/howto/passing_html_attrs/).\n\n **Args:**\n\n - `attrs` (dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides\n values in the `default` dictionary.\n - `default` (str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden\n with values in the `attrs` dictionary.\n - Any extra kwargs will be appended to the corresponding keys\n\n The attributes in `attrs` and `defaults` are merged and resulting dict is rendered as HTML attributes\n (`key=\"value\"`).\n\n Extra kwargs (`key=value`) are concatenated to existing keys. So if we have\n\n ```python\n attrs = {\"class\": \"my-class\"}\n ```\n\n Then\n\n ```django\n {% html_attrs attrs class=\"extra-class\" %}\n ```\n\n will result in `class=\"my-class extra-class\"`.\n\n **Example:**\n ```django\n <div {% html_attrs\n attrs\n defaults:class=\"default-class\"\n class=\"extra-class\"\n data-id=\"123\"\n %}>\n ```\n\n renders\n\n ```html\n <div class=\"my-class extra-class\" data-id=\"123\">\n ```\n\n **See more usage examples in\n [HTML attributes](../../concepts/fundamentals/html_attributes#examples-for-html_attrs).**\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n return HtmlAttrsNode(\n kwargs=tag.kwargs,\n kwarg_pairs=tag.kwarg_pairs,\n )\n
provide(parser: Parser, token: Token, tag_spec: TagSpec) -> ProvideNode\n
The \"provider\" part of the provide / inject feature. Pass kwargs to this tag to define the provider's data. Any components defined within the
{% provide %}..{% endprovide %}
tags will be able to access this data withComponent.inject()
.This is similar to React's
ContextProvider
, or Vue'sprovide()
.Args:
name
(str, required): Provider name. This is the name you will then use inComponent.inject()
.**kwargs
: Any extra kwargs will be passed as the provided data.
Example:
Provide the \"user_data\" in parent component:
@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n <div>\n {% provide \"user_data\" user=user %}\n {% component \"child\" / %}\n {% endprovide %}\n </div>\n \"\"\"\n\n def get_context_data(self, user: User):\n return {\n \"user\": user,\n }\n
Since the \"child\" component is used within the
{% provide %} / {% endprovide %}
tags, we can request the \"user_data\" usingComponent.inject(\"user_data\")
:@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n User is: {{ user }}\n </div>\n \"\"\"\n\n def get_context_data(self):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n
Notice that the keys defined on the
{% provide %}
tag are then accessed as attributes when accessing them withComponent.inject()
.\u2705 Do this
user = self.inject(\"user_data\").user\n
\u274c Don't do this
Source code inuser = self.inject(\"user_data\")[\"user\"]\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.slot","title":"slot","text":"@register.tag(\"provide\")\n@with_tag_spec(\n TagSpec(\n tag=\"provide\",\n end_tag=\"endprovide\",\n positional_only_args=[],\n pos_or_keyword_args=[PROVIDE_NAME_KWARG],\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[],\n )\n)\ndef provide(parser: Parser, token: Token, tag_spec: TagSpec) -> ProvideNode:\n \"\"\"\n The \"provider\" part of the [provide / inject feature](../../concepts/advanced/provide_inject).\n Pass kwargs to this tag to define the provider's data.\n Any components defined within the `{% provide %}..{% endprovide %}` tags will be able to access this data\n with [`Component.inject()`](../api#django_components.Component.inject).\n\n This is similar to React's [`ContextProvider`](https://react.dev/learn/passing-data-deeply-with-context),\n or Vue's [`provide()`](https://vuejs.org/guide/components/provide-inject).\n\n **Args:**\n\n - `name` (str, required): Provider name. This is the name you will then use in\n [`Component.inject()`](../api#django_components.Component.inject).\n - `**kwargs`: Any extra kwargs will be passed as the provided data.\n\n **Example:**\n\n Provide the \"user_data\" in parent component:\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n <div>\n {% provide \"user_data\" user=user %}\n {% component \"child\" / %}\n {% endprovide %}\n </div>\n \\\"\\\"\\\"\n\n def get_context_data(self, user: User):\n return {\n \"user\": user,\n }\n ```\n\n Since the \"child\" component is used within the `{% provide %} / {% endprovide %}` tags,\n we can request the \"user_data\" using `Component.inject(\"user_data\")`:\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n User is: {{ user }}\n </div>\n \\\"\\\"\\\"\n\n def get_context_data(self):\n user = self.inject(\"user_data\").user\n return {\n \"user\": user,\n }\n ```\n\n Notice that the keys defined on the `{% provide %}` tag are then accessed as attributes\n when accessing them with [`Component.inject()`](../api#django_components.Component.inject).\n\n \u2705 Do this\n ```python\n user = self.inject(\"user_data\").user\n ```\n\n \u274c Don't do this\n ```python\n user = self.inject(\"user_data\")[\"user\"]\n ```\n \"\"\"\n # e.g. {% provide <name> key=val key2=val2 %}\n tag = _parse_tag(parser, token, tag_spec)\n\n name_kwarg = tag.kwargs.kwargs.get(PROVIDE_NAME_KWARG, None)\n trace_id = f\"provide-id-{tag.id} ({name_kwarg})\" if name_kwarg else f\"fill-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"PROVIDE\", trace_id, tag.id)\n\n body = tag.parse_body()\n provide_node = ProvideNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"PROVIDE\", trace_id, tag.id, \"...Done!\")\n return provide_node\n
slot(parser: Parser, token: Token, tag_spec: TagSpec) -> SlotNode\n
Slot tag marks a place inside a component where content can be inserted from outside.
Learn more about using slots.
This is similar to slots as seen in Web components, Vue or React's
children
.Args:
name
(str, required): Registered name of the component to renderdefault
: Optional flag. If there is a default slot, you can pass the component slot content without using the{% fill %}
tag. See Default slotrequired
: Optional flag. Will raise an error if a slot is required but not given.**kwargs
: Any extra kwargs will be passed as the slot data.
Example:
@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" default %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n <aside>\n {% slot \"sidebar\" required / %}\n </aside>\n \"\"\"\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.slot--passing-data-to-slots","title":"Passing data to slots","text":"@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n <div>\n {% component \"child\" %}\n {% fill \"content\" %}\n \ud83d\uddde\ufe0f\ud83d\udcf0\n {% endfill %}\n\n {% fill \"sidebar\" %}\n \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n {% endfill %}\n {% endcomponent %}\n </div>\n \"\"\"\n
Any extra kwargs will be considered as slot data, and will be accessible in the
{% fill %}
tag via fill'sdata
kwarg:@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \"\"\"\n
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.slot--accessing-default-slot-content","title":"Accessing default slot content","text":"@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
The content between the
{% slot %}..{% endslot %}
tags is the default content that will be rendered if no fill is given for the slot.This default content can then be accessed from within the
{% fill %}
tag using the fill'sdefault
kwarg. This is useful if you need to wrap / prepend / append the original slot's content.@register(\"child\")\nclass Child(Component):\n template = \"\"\"\n <div>\n {% slot \"content\" %}\n This is default content!\n {% endslot %}\n </div>\n \"\"\"\n
Source code in@register(\"parent\")\nclass Parent(Component):\n template = \"\"\"\n {# Parent can access the slot's default content #}\n {% component \"child\" %}\n {% fill \"content\" default=\"default\" %}\n {{ default }}\n {% endfill %}\n {% endcomponent %}\n \"\"\"\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/templatetags/component_tags/#django_components.templatetags.component_tags.with_tag_spec","title":"with_tag_spec","text":"@register.tag(\"slot\")\n@with_tag_spec(\n TagSpec(\n tag=\"slot\",\n end_tag=\"endslot\",\n positional_only_args=[],\n pos_or_keyword_args=[SLOT_NAME_KWARG],\n keywordonly_args=True,\n repeatable_kwargs=False,\n flags=[SLOT_DEFAULT_KEYWORD, SLOT_REQUIRED_KEYWORD],\n )\n)\ndef slot(parser: Parser, token: Token, tag_spec: TagSpec) -> SlotNode:\n \"\"\"\n Slot tag marks a place inside a component where content can be inserted\n from outside.\n\n [Learn more](../../concepts/fundamentals/slots) about using slots.\n\n This is similar to slots as seen in\n [Web components](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot),\n [Vue](https://vuejs.org/guide/components/slots.html)\n or [React's `children`](https://react.dev/learn/passing-props-to-a-component#passing-jsx-as-children).\n\n **Args:**\n\n - `name` (str, required): Registered name of the component to render\n - `default`: Optional flag. If there is a default slot, you can pass the component slot content\n without using the [`{% fill %}`](#fill) tag. See\n [Default slot](../../concepts/fundamentals/slots#default-slot)\n - `required`: Optional flag. Will raise an error if a slot is required but not given.\n - `**kwargs`: Any extra kwargs will be passed as the slot data.\n\n **Example:**\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {% slot \"content\" default %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n <aside>\n {% slot \"sidebar\" required / %}\n </aside>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n <div>\n {% component \"child\" %}\n {% fill \"content\" %}\n \ud83d\uddde\ufe0f\ud83d\udcf0\n {% endfill %}\n\n {% fill \"sidebar\" %}\n \ud83c\udf77\ud83e\uddc9\ud83c\udf7e\n {% endfill %}\n {% endcomponent %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ### Passing data to slots\n\n Any extra kwargs will be considered as slot data, and will be accessible in the [`{% fill %}`](#fill)\n tag via fill's `data` kwarg:\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {# Passing data to the slot #}\n {% slot \"content\" user=user %}\n This is shown if not overriden!\n {% endslot %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n {# Parent can access the slot data #}\n {% component \"child\" %}\n {% fill \"content\" data=\"data\" %}\n <div class=\"wrapper-class\">\n {{ data.user }}\n </div>\n {% endfill %}\n {% endcomponent %}\n \\\"\\\"\\\"\n ```\n\n ### Accessing default slot content\n\n The content between the `{% slot %}..{% endslot %}` tags is the default content that\n will be rendered if no fill is given for the slot.\n\n This default content can then be accessed from within the [`{% fill %}`](#fill) tag using\n the fill's `default` kwarg.\n This is useful if you need to wrap / prepend / append the original slot's content.\n\n ```python\n @register(\"child\")\n class Child(Component):\n template = \\\"\\\"\\\"\n <div>\n {% slot \"content\" %}\n This is default content!\n {% endslot %}\n </div>\n \\\"\\\"\\\"\n ```\n\n ```python\n @register(\"parent\")\n class Parent(Component):\n template = \\\"\\\"\\\"\n {# Parent can access the slot's default content #}\n {% component \"child\" %}\n {% fill \"content\" default=\"default\" %}\n {{ default }}\n {% endfill %}\n {% endcomponent %}\n \\\"\\\"\\\"\n ```\n \"\"\"\n tag = _parse_tag(parser, token, tag_spec)\n\n slot_name_kwarg = tag.kwargs.kwargs.get(SLOT_NAME_KWARG, None)\n trace_id = f\"slot-id-{tag.id} ({slot_name_kwarg})\" if slot_name_kwarg else f\"slot-id-{tag.id}\"\n\n trace_msg(\"PARSE\", \"SLOT\", trace_id, tag.id)\n\n body = tag.parse_body()\n slot_node = SlotNode(\n nodelist=body,\n node_id=tag.id,\n kwargs=tag.kwargs,\n is_required=tag.flags[SLOT_REQUIRED_KEYWORD],\n is_default=tag.flags[SLOT_DEFAULT_KEYWORD],\n trace_id=trace_id,\n )\n\n trace_msg(\"PARSE\", \"SLOT\", trace_id, tag.id, \"...Done!\")\n return slot_node\n
Source code inwith_tag_spec(tag_spec: TagSpec) -> Callable\n
src/django_components/templatetags/component_tags.py
"},{"location":"reference/django_components/types/","title":"def with_tag_spec(tag_spec: TagSpec) -> Callable:\n \"\"\"\"\"\"\n\n def decorator(fn: Callable) -> Any:\n fn._tag_spec = tag_spec # type: ignore[attr-defined]\n\n @functools.wraps(fn)\n def wrapper(*args: Any, **kwargs: Any) -> Any:\n return fn(*args, **kwargs, tag_spec=tag_spec)\n\n return wrapper\n\n return decorator\n
types","text":""},{"location":"reference/django_components/types/#django_components.types","title":"types","text":"
Helper types for IDEs.
"},{"location":"reference/django_components/urls/","title":"urls","text":""},{"location":"reference/django_components/urls/#django_components.urls","title":"urls","text":""},{"location":"reference/django_components/util/","title":"Index","text":""},{"location":"reference/django_components/util/#django_components.util","title":"util","text":"
Modules:
-
cache
\u2013 -
html
\u2013 -
loader
\u2013 -
logger
\u2013 -
misc
\u2013 -
tag_parser
\u2013 -
types
\u2013
Functions:
-
lazy_cache
\u2013Decorator that caches the given function similarly to
functools.lru_cache
.
lazy_cache(make_cache: Callable[[], Callable[[Callable], Callable]]) -> Callable[[TFunc], TFunc]\n
Decorator that caches the given function similarly to
functools.lru_cache
. But the cache is instantiated only at first invocation.
Source code incache
argument is a function that generates the cache function, e.g.functools.lru_cache()
.src/django_components/util/cache.py
"},{"location":"reference/django_components/util/#django_components.util.html","title":"html","text":"def lazy_cache(\n make_cache: Callable[[], Callable[[Callable], Callable]],\n) -> Callable[[TFunc], TFunc]:\n \"\"\"\n Decorator that caches the given function similarly to `functools.lru_cache`.\n But the cache is instantiated only at first invocation.\n\n `cache` argument is a function that generates the cache function,\n e.g. `functools.lru_cache()`.\n \"\"\"\n _cached_fn = None\n\n def decorator(fn: TFunc) -> TFunc:\n @functools.wraps(fn)\n def wrapper(*args: Any, **kwargs: Any) -> Any:\n # Lazily initialize the cache\n nonlocal _cached_fn\n if not _cached_fn:\n # E.g. `lambda: functools.lru_cache(maxsize=app_settings.TEMPLATE_CACHE_SIZE)`\n cache = make_cache()\n _cached_fn = cache(fn)\n\n return _cached_fn(*args, **kwargs)\n\n # Allow to access the LRU cache methods\n # See https://stackoverflow.com/a/37654201/9788634\n wrapper.cache_info = lambda: _cached_fn.cache_info() # type: ignore\n wrapper.cache_clear = lambda: _cached_fn.cache_clear() # type: ignore\n\n # And allow to remove the cache instance (mostly for tests)\n def cache_remove() -> None:\n nonlocal _cached_fn\n _cached_fn = None\n\n wrapper.cache_remove = cache_remove # type: ignore\n\n return cast(TFunc, wrapper)\n\n return decorator\n
Functions:
-
parse_document_or_nodes
\u2013Use this if you do NOT know whether the given HTML is a full document
-
parse_multiroot_html
\u2013Use this when you know the given HTML is a multiple nodes like
-
parse_node
\u2013Use this when you know the given HTML is a single node like
parse_document_or_nodes(html: str) -> Union[List[LexborNode], LexborHTMLParser]\n
Use this if you do NOT know whether the given HTML is a full document with
Source code in<html>
,<head>
, and<body>
tags, or an HTML fragment.src/django_components/util/html.py
"},{"location":"reference/django_components/util/#django_components.util.html.parse_multiroot_html","title":"parse_multiroot_html","text":"def parse_document_or_nodes(html: str) -> Union[List[LexborNode], LexborHTMLParser]:\n \"\"\"\n Use this if you do NOT know whether the given HTML is a full document\n with `<html>`, `<head>`, and `<body>` tags, or an HTML fragment.\n \"\"\"\n html = html.strip()\n tree = LexborHTMLParser(html)\n is_fragment = is_html_parser_fragment(html, tree)\n\n if is_fragment:\n nodes = parse_multiroot_html(html)\n return nodes\n else:\n return tree\n
parse_multiroot_html(html: str) -> List[LexborNode]\n
Use this when you know the given HTML is a multiple nodes like
Source code in<div> Hi </div> <span> Hello </span>
src/django_components/util/html.py
"},{"location":"reference/django_components/util/#django_components.util.html.parse_node","title":"parse_node","text":"def parse_multiroot_html(html: str) -> List[LexborNode]:\n \"\"\"\n Use this when you know the given HTML is a multiple nodes like\n\n `<div> Hi </div> <span> Hello </span>`\n \"\"\"\n # NOTE: HTML / XML MUST have a single root. So, to support multiple\n # top-level elements, we wrap them in a dummy singular root.\n parser = LexborHTMLParser(f\"<root>{html}</root>\")\n\n # Get all contents of the root\n root_elem = parser.css_first(\"root\")\n elems = [*root_elem.iter()] if root_elem else []\n return elems\n
parse_node(html: str) -> LexborNode\n
Use this when you know the given HTML is a single node like
Source code in<div> Hi </div>
src/django_components/util/html.py
"},{"location":"reference/django_components/util/#django_components.util.loader","title":"loader","text":"def parse_node(html: str) -> LexborNode:\n \"\"\"\n Use this when you know the given HTML is a single node like\n\n `<div> Hi </div>`\n \"\"\"\n tree = LexborHTMLParser(html)\n # NOTE: The parser automatically places <style> tags inside <head>\n # while <script> tags are inside <body>.\n return tree.body.child or tree.head.child # type: ignore[union-attr, return-value]\n
Classes:
-
ComponentFileEntry
\u2013Result returned by
get_component_files()
.
Functions:
-
get_component_dirs
\u2013Get directories that may contain component files.
-
get_component_files
\u2013Search for files within the component directories (as defined in
Bases:
NamedTuple
Result returned by
get_component_files()
.Attributes:
-
dot_path
(str
) \u2013The python import path for the module. E.g.
app.components.mycomp
-
filepath
(Path
) \u2013The filesystem path to the module. E.g.
/path/to/project/app/components/mycomp.py
instance-attribute
","text":"dot_path: str\n
The python import path for the module. E.g.
"},{"location":"reference/django_components/util/#django_components.util.loader.ComponentFileEntry.filepath","title":"filepathapp.components.mycomp
instance-attribute
","text":"filepath: Path\n
The filesystem path to the module. E.g.
"},{"location":"reference/django_components/util/#django_components.util.loader.get_component_dirs","title":"get_component_dirs","text":"/path/to/project/app/components/mycomp.py
get_component_dirs(include_apps: bool = True) -> List[Path]\n
Get directories that may contain component files.
This is the heart of all features that deal with filesystem and file lookup. Autodiscovery, Django template resolution, static file resolution - They all use this.
Parameters:
-
include_apps
(bool
, default:True
) \u2013Include directories from installed Django apps. Defaults to
True
.
Returns:
-
List[Path]
\u2013List[Path]: A list of directories that may contain component files.
get_component_dirs()
searches for dirs set inCOMPONENTS.dirs
settings. If none set, defaults to searching for a\"components\"
app.In addition to that, also all installed Django apps are checked whether they contain directories as set in
COMPONENTS.app_dirs
(e.g.[app]/components
).Notes:
-
Paths that do not point to directories are ignored.
-
BASE_DIR
setting is required. -
The paths in
COMPONENTS.dirs
must be absolute paths.
src/django_components/util/loader.py
"},{"location":"reference/django_components/util/#django_components.util.loader.get_component_files","title":"get_component_files","text":"def get_component_dirs(include_apps: bool = True) -> List[Path]:\n \"\"\"\n Get directories that may contain component files.\n\n This is the heart of all features that deal with filesystem and file lookup.\n Autodiscovery, Django template resolution, static file resolution - They all use this.\n\n Args:\n include_apps (bool, optional): Include directories from installed Django apps.\\\n Defaults to `True`.\n\n Returns:\n List[Path]: A list of directories that may contain component files.\n\n `get_component_dirs()` searches for dirs set in\n [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n settings. If none set, defaults to searching for a `\"components\"` app.\n\n In addition to that, also all installed Django apps are checked whether they contain\n directories as set in\n [`COMPONENTS.app_dirs`](../settings#django_components.app_settings.ComponentsSettings.app_dirs)\n (e.g. `[app]/components`).\n\n **Notes:**\n\n - Paths that do not point to directories are ignored.\n\n - `BASE_DIR` setting is required.\n\n - The paths in [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n must be absolute paths.\n \"\"\"\n # Allow to configure from settings which dirs should be checked for components\n component_dirs = app_settings.DIRS\n\n # TODO_REMOVE_IN_V1\n raw_component_settings = getattr(settings, \"COMPONENTS\", {})\n if isinstance(raw_component_settings, dict):\n raw_dirs_value = raw_component_settings.get(\"dirs\", None)\n elif isinstance(raw_component_settings, ComponentsSettings):\n raw_dirs_value = raw_component_settings.dirs\n else:\n raw_dirs_value = None\n is_component_dirs_set = raw_dirs_value is not None\n is_legacy_paths = (\n # Use value of `STATICFILES_DIRS` ONLY if `COMPONENT.dirs` not set\n not is_component_dirs_set\n and hasattr(settings, \"STATICFILES_DIRS\")\n and settings.STATICFILES_DIRS\n )\n if is_legacy_paths:\n # NOTE: For STATICFILES_DIRS, we use the defaults even for empty list.\n # We don't do this for COMPONENTS.dirs, so user can explicitly specify \"NO dirs\".\n component_dirs = settings.STATICFILES_DIRS or [settings.BASE_DIR / \"components\"]\n # END TODO_REMOVE_IN_V1\n\n source = \"STATICFILES_DIRS\" if is_legacy_paths else \"COMPONENTS.dirs\"\n\n logger.debug(\n \"get_component_dirs will search for valid dirs from following options:\\n\"\n + \"\\n\".join([f\" - {str(d)}\" for d in component_dirs])\n )\n\n # Add `[app]/[APP_DIR]` to the directories. This is, by default `[app]/components`\n app_paths: List[Path] = []\n if include_apps:\n for conf in apps.get_app_configs():\n for app_dir in app_settings.APP_DIRS:\n comps_path = Path(conf.path).joinpath(app_dir)\n if comps_path.exists():\n app_paths.append(comps_path)\n\n directories: Set[Path] = set(app_paths)\n\n # Validate and add other values from the config\n for component_dir in component_dirs:\n # Consider tuples for STATICFILES_DIRS (See #489)\n # See https://docs.djangoproject.com/en/5.0/ref/settings/#prefixes-optional\n if isinstance(component_dir, (tuple, list)):\n component_dir = component_dir[1]\n try:\n Path(component_dir)\n except TypeError:\n logger.warning(\n f\"{source} expected str, bytes or os.PathLike object, or tuple/list of length 2. \"\n f\"See Django documentation for STATICFILES_DIRS. Got {type(component_dir)} : {component_dir}\"\n )\n continue\n\n if not Path(component_dir).is_absolute():\n raise ValueError(f\"{source} must contain absolute paths, got '{component_dir}'\")\n else:\n directories.add(Path(component_dir).resolve())\n\n logger.debug(\n \"get_component_dirs matched following template dirs:\\n\" + \"\\n\".join([f\" - {str(d)}\" for d in directories])\n )\n return list(directories)\n
get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]\n
Search for files within the component directories (as defined in
get_component_dirs()
).Requires
BASE_DIR
setting to be set.Parameters:
-
suffix
(Optional[str]
, default:None
) \u2013The suffix to search for. E.g.
.py
,.js
,.css
. Defaults toNone
, which will search for all files.
Returns:
-
List[ComponentFileEntry]
\u2013List[ComponentFileEntry] A list of entries that contain both the filesystem path and the python import path (dot path).
Example:
Source code infrom django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
src/django_components/util/loader.py
"},{"location":"reference/django_components/util/#django_components.util.logger","title":"logger","text":"def get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]:\n \"\"\"\n Search for files within the component directories (as defined in\n [`get_component_dirs()`](../api#django_components.get_component_dirs)).\n\n Requires `BASE_DIR` setting to be set.\n\n Args:\n suffix (Optional[str], optional): The suffix to search for. E.g. `.py`, `.js`, `.css`.\\\n Defaults to `None`, which will search for all files.\n\n Returns:\n List[ComponentFileEntry] A list of entries that contain both the filesystem path and \\\n the python import path (dot path).\n\n **Example:**\n\n ```python\n from django_components import get_component_files\n\n modules = get_component_files(\".py\")\n ```\n \"\"\"\n search_glob = f\"**/*{suffix}\" if suffix else \"**/*\"\n\n dirs = get_component_dirs(include_apps=False)\n component_filepaths = _search_dirs(dirs, search_glob)\n\n if hasattr(settings, \"BASE_DIR\") and settings.BASE_DIR:\n project_root = str(settings.BASE_DIR)\n else:\n # Fallback for getting the root dir, see https://stackoverflow.com/a/16413955/9788634\n project_root = os.path.abspath(os.path.dirname(__name__))\n\n # NOTE: We handle dirs from `COMPONENTS.dirs` and from individual apps separately.\n modules: List[ComponentFileEntry] = []\n\n # First let's handle the dirs from `COMPONENTS.dirs`\n #\n # Because for dirs in `COMPONENTS.dirs`, we assume they will be nested under `BASE_DIR`,\n # and that `BASE_DIR` is the current working dir (CWD). So the path relatively to `BASE_DIR`\n # is ALSO the python import path.\n for filepath in component_filepaths:\n module_path = _filepath_to_python_module(filepath, project_root, None)\n # Ignore files starting with dot `.` or files in dirs that start with dot.\n #\n # If any of the parts of the path start with a dot, e.g. the filesystem path\n # is `./abc/.def`, then this gets converted to python module as `abc..def`\n #\n # NOTE: This approach also ignores files:\n # - with two dots in the middle (ab..cd.py)\n # - an extra dot at the end (abcd..py)\n # - files outside of the parent component (../abcd.py).\n # But all these are NOT valid python modules so that's fine.\n if \"..\" in module_path:\n continue\n\n entry = ComponentFileEntry(dot_path=module_path, filepath=filepath)\n modules.append(entry)\n\n # For for apps, the directories may be outside of the project, e.g. in case of third party\n # apps. So we have to resolve the python import path relative to the package name / the root\n # import path for the app.\n # See https://github.com/EmilStenstrom/django-components/issues/669\n for conf in apps.get_app_configs():\n for app_dir in app_settings.APP_DIRS:\n comps_path = Path(conf.path).joinpath(app_dir)\n if not comps_path.exists():\n continue\n app_component_filepaths = _search_dirs([comps_path], search_glob)\n for filepath in app_component_filepaths:\n app_component_module = _filepath_to_python_module(filepath, conf.path, conf.name)\n entry = ComponentFileEntry(dot_path=app_component_module, filepath=filepath)\n modules.append(entry)\n\n return modules\n
Functions:
-
trace
\u2013TRACE level logger.
-
trace_msg
\u2013TRACE level logger with opinionated format for tracing interaction of components,
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:
Source code inLOGGING = {\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
src/django_components/util/logger.py
"},{"location":"reference/django_components/util/#django_components.util.logger.trace_msg","title":"trace_msg","text":"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
trace_msg(\n action: Literal[\"PARSE\", \"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:
Source code in\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"
src/django_components/util/logger.py
"},{"location":"reference/django_components/util/#django_components.util.misc","title":"misc","text":"def trace_msg(\n action: Literal[\"PARSE\", \"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 == \"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
Functions:
-
gen_id
\u2013Generate a unique ID that can be associated with a Node
-
get_import_path
\u2013Get the full import path for a class or a function, e.g.
\"path.to.MyClass\"
gen_id() -> str\n
Generate a unique ID that can be associated with a Node
Source code insrc/django_components/util/misc.py
"},{"location":"reference/django_components/util/#django_components.util.misc.get_import_path","title":"get_import_path","text":"def gen_id() -> str:\n \"\"\"Generate a unique ID that can be associated with a Node\"\"\"\n # Alphabet is only alphanumeric. Compared to the default alphabet used by nanoid,\n # we've omitted `-` and `_`.\n # With this alphabet, at 6 chars, the chance of collision is 1 in 3.3M.\n # See https://zelark.github.io/nano-id-cc/\n return generate(\n \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\",\n size=6,\n )\n
get_import_path(cls_or_fn: Type[Any]) -> str\n
Get the full import path for a class or a function, e.g.
Source code in\"path.to.MyClass\"
src/django_components/util/misc.py
"},{"location":"reference/django_components/util/#django_components.util.tag_parser","title":"tag_parser","text":"def get_import_path(cls_or_fn: Type[Any]) -> str:\n \"\"\"\n Get the full import path for a class or a function, e.g. `\"path.to.MyClass\"`\n \"\"\"\n module = cls_or_fn.__module__\n if module == \"builtins\":\n return cls_or_fn.__qualname__ # avoid outputs like 'builtins.str'\n return module + \".\" + cls_or_fn.__qualname__\n
Classes:
-
TagAttr
\u2013
dataclass
","text":"TagAttr(key: Optional[str], value: str, start_index: int, quoted: bool)\n
Attributes:
-
quoted
(bool
) \u2013Whether the value is quoted (either with single or double quotes)
-
start_index
(int
) \u2013Start index of the attribute (include both key and value),
instance-attribute
","text":"quoted: bool\n
Whether the value is quoted (either with single or double quotes)
"},{"location":"reference/django_components/util/#django_components.util.tag_parser.TagAttr.start_index","title":"start_indexinstance-attribute
","text":"start_index: int\n
Start index of the attribute (include both key and value), relative to the start of the owner Tag.
"},{"location":"reference/django_components/util/#django_components.util.types","title":"types","text":"Classes:
-
EmptyDict
\u2013TypedDict with no members.
Attributes:
-
EmptyTuple
\u2013Tuple with no members.
module-attribute
","text":"EmptyTuple = Tuple[]\n
Tuple with no members.
You can use this to define a Component that accepts NO positional arguments:
from django_components import Component, EmptyTuple\n\nclass Table(Component(EmptyTuple, Any, Any, Any, Any, Any))\n ...\n
After that, when you call
Component.render()
orComponent.render_to_response()
, theargs
parameter will raise type error ifargs
is anything else than an empty tuple.Table.render(\n args: (),\n)\n
Omitting
args
is also fine:Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
"},{"location":"reference/django_components/util/#django_components.util.types.EmptyDict","title":"EmptyDict","text":"Table.render(\n args: (\"one\", 2, \"three\"),\n)\n
Bases:
TypedDict
TypedDict with no members.
You can use this to define a Component that accepts NO kwargs, or NO slots, or returns NO data from
Component.get_context_data()
/Component.get_js_data()
/Component.get_css_data()
:Accepts NO kwargs:
from django_components import Component, EmptyDict\n\nclass Table(Component(Any, EmptyDict, Any, Any, Any, Any))\n ...\n
Accepts NO slots:
from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, EmptyDict, Any, Any, Any))\n ...\n
Returns NO data from
get_context_data()
:from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, Any, EmptyDict, Any, Any))\n ...\n
Going back to the example with NO kwargs, when you then call
Component.render()
orComponent.render_to_response()
, thekwargs
parameter will raise type error ifkwargs
is anything else than an empty dict.Table.render(\n kwargs: {},\n)\n
Omitting
kwargs
is also fine:Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
"},{"location":"reference/django_components/util/cache/","title":"Table.render(\n kwargs: {\n \"one\": 2,\n \"three\": 4,\n },\n)\n
cache","text":""},{"location":"reference/django_components/util/cache/#django_components.util.cache","title":"cache","text":"
Functions:
-
lazy_cache
\u2013Decorator that caches the given function similarly to
functools.lru_cache
.
lazy_cache(make_cache: Callable[[], Callable[[Callable], Callable]]) -> Callable[[TFunc], TFunc]\n
Decorator that caches the given function similarly to
functools.lru_cache
. But the cache is instantiated only at first invocation.
Source code incache
argument is a function that generates the cache function, e.g.functools.lru_cache()
.src/django_components/util/cache.py
"},{"location":"reference/django_components/util/html/","title":"def lazy_cache(\n make_cache: Callable[[], Callable[[Callable], Callable]],\n) -> Callable[[TFunc], TFunc]:\n \"\"\"\n Decorator that caches the given function similarly to `functools.lru_cache`.\n But the cache is instantiated only at first invocation.\n\n `cache` argument is a function that generates the cache function,\n e.g. `functools.lru_cache()`.\n \"\"\"\n _cached_fn = None\n\n def decorator(fn: TFunc) -> TFunc:\n @functools.wraps(fn)\n def wrapper(*args: Any, **kwargs: Any) -> Any:\n # Lazily initialize the cache\n nonlocal _cached_fn\n if not _cached_fn:\n # E.g. `lambda: functools.lru_cache(maxsize=app_settings.TEMPLATE_CACHE_SIZE)`\n cache = make_cache()\n _cached_fn = cache(fn)\n\n return _cached_fn(*args, **kwargs)\n\n # Allow to access the LRU cache methods\n # See https://stackoverflow.com/a/37654201/9788634\n wrapper.cache_info = lambda: _cached_fn.cache_info() # type: ignore\n wrapper.cache_clear = lambda: _cached_fn.cache_clear() # type: ignore\n\n # And allow to remove the cache instance (mostly for tests)\n def cache_remove() -> None:\n nonlocal _cached_fn\n _cached_fn = None\n\n wrapper.cache_remove = cache_remove # type: ignore\n\n return cast(TFunc, wrapper)\n\n return decorator\n
html","text":""},{"location":"reference/django_components/util/html/#django_components.util.html","title":"html","text":"
Functions:
-
parse_document_or_nodes
\u2013Use this if you do NOT know whether the given HTML is a full document
-
parse_multiroot_html
\u2013Use this when you know the given HTML is a multiple nodes like
-
parse_node
\u2013Use this when you know the given HTML is a single node like
parse_document_or_nodes(html: str) -> Union[List[LexborNode], LexborHTMLParser]\n
Use this if you do NOT know whether the given HTML is a full document with
Source code in<html>
,<head>
, and<body>
tags, or an HTML fragment.src/django_components/util/html.py
"},{"location":"reference/django_components/util/html/#django_components.util.html.parse_multiroot_html","title":"parse_multiroot_html","text":"def parse_document_or_nodes(html: str) -> Union[List[LexborNode], LexborHTMLParser]:\n \"\"\"\n Use this if you do NOT know whether the given HTML is a full document\n with `<html>`, `<head>`, and `<body>` tags, or an HTML fragment.\n \"\"\"\n html = html.strip()\n tree = LexborHTMLParser(html)\n is_fragment = is_html_parser_fragment(html, tree)\n\n if is_fragment:\n nodes = parse_multiroot_html(html)\n return nodes\n else:\n return tree\n
parse_multiroot_html(html: str) -> List[LexborNode]\n
Use this when you know the given HTML is a multiple nodes like
Source code in<div> Hi </div> <span> Hello </span>
src/django_components/util/html.py
"},{"location":"reference/django_components/util/html/#django_components.util.html.parse_node","title":"parse_node","text":"def parse_multiroot_html(html: str) -> List[LexborNode]:\n \"\"\"\n Use this when you know the given HTML is a multiple nodes like\n\n `<div> Hi </div> <span> Hello </span>`\n \"\"\"\n # NOTE: HTML / XML MUST have a single root. So, to support multiple\n # top-level elements, we wrap them in a dummy singular root.\n parser = LexborHTMLParser(f\"<root>{html}</root>\")\n\n # Get all contents of the root\n root_elem = parser.css_first(\"root\")\n elems = [*root_elem.iter()] if root_elem else []\n return elems\n
parse_node(html: str) -> LexborNode\n
Use this when you know the given HTML is a single node like
Source code in<div> Hi </div>
src/django_components/util/html.py
"},{"location":"reference/django_components/util/loader/","title":"def parse_node(html: str) -> LexborNode:\n \"\"\"\n Use this when you know the given HTML is a single node like\n\n `<div> Hi </div>`\n \"\"\"\n tree = LexborHTMLParser(html)\n # NOTE: The parser automatically places <style> tags inside <head>\n # while <script> tags are inside <body>.\n return tree.body.child or tree.head.child # type: ignore[union-attr, return-value]\n
loader","text":""},{"location":"reference/django_components/util/loader/#django_components.util.loader","title":"loader","text":"
Classes:
-
ComponentFileEntry
\u2013Result returned by
get_component_files()
.
Functions:
-
get_component_dirs
\u2013Get directories that may contain component files.
-
get_component_files
\u2013Search for files within the component directories (as defined in
Bases:
NamedTuple
Result returned by
get_component_files()
.Attributes:
-
dot_path
(str
) \u2013The python import path for the module. E.g.
app.components.mycomp
-
filepath
(Path
) \u2013The filesystem path to the module. E.g.
/path/to/project/app/components/mycomp.py
instance-attribute
","text":"dot_path: str\n
The python import path for the module. E.g.
"},{"location":"reference/django_components/util/loader/#django_components.util.loader.ComponentFileEntry.filepath","title":"filepathapp.components.mycomp
instance-attribute
","text":"filepath: Path\n
The filesystem path to the module. E.g.
"},{"location":"reference/django_components/util/loader/#django_components.util.loader.get_component_dirs","title":"get_component_dirs","text":"/path/to/project/app/components/mycomp.py
get_component_dirs(include_apps: bool = True) -> List[Path]\n
Get directories that may contain component files.
This is the heart of all features that deal with filesystem and file lookup. Autodiscovery, Django template resolution, static file resolution - They all use this.
Parameters:
-
include_apps
(bool
, default:True
) \u2013Include directories from installed Django apps. Defaults to
True
.
Returns:
-
List[Path]
\u2013List[Path]: A list of directories that may contain component files.
get_component_dirs()
searches for dirs set inCOMPONENTS.dirs
settings. If none set, defaults to searching for a\"components\"
app.In addition to that, also all installed Django apps are checked whether they contain directories as set in
COMPONENTS.app_dirs
(e.g.[app]/components
).Notes:
-
Paths that do not point to directories are ignored.
-
BASE_DIR
setting is required. -
The paths in
COMPONENTS.dirs
must be absolute paths.
src/django_components/util/loader.py
"},{"location":"reference/django_components/util/loader/#django_components.util.loader.get_component_files","title":"get_component_files","text":"def get_component_dirs(include_apps: bool = True) -> List[Path]:\n \"\"\"\n Get directories that may contain component files.\n\n This is the heart of all features that deal with filesystem and file lookup.\n Autodiscovery, Django template resolution, static file resolution - They all use this.\n\n Args:\n include_apps (bool, optional): Include directories from installed Django apps.\\\n Defaults to `True`.\n\n Returns:\n List[Path]: A list of directories that may contain component files.\n\n `get_component_dirs()` searches for dirs set in\n [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n settings. If none set, defaults to searching for a `\"components\"` app.\n\n In addition to that, also all installed Django apps are checked whether they contain\n directories as set in\n [`COMPONENTS.app_dirs`](../settings#django_components.app_settings.ComponentsSettings.app_dirs)\n (e.g. `[app]/components`).\n\n **Notes:**\n\n - Paths that do not point to directories are ignored.\n\n - `BASE_DIR` setting is required.\n\n - The paths in [`COMPONENTS.dirs`](../settings#django_components.app_settings.ComponentsSettings.dirs)\n must be absolute paths.\n \"\"\"\n # Allow to configure from settings which dirs should be checked for components\n component_dirs = app_settings.DIRS\n\n # TODO_REMOVE_IN_V1\n raw_component_settings = getattr(settings, \"COMPONENTS\", {})\n if isinstance(raw_component_settings, dict):\n raw_dirs_value = raw_component_settings.get(\"dirs\", None)\n elif isinstance(raw_component_settings, ComponentsSettings):\n raw_dirs_value = raw_component_settings.dirs\n else:\n raw_dirs_value = None\n is_component_dirs_set = raw_dirs_value is not None\n is_legacy_paths = (\n # Use value of `STATICFILES_DIRS` ONLY if `COMPONENT.dirs` not set\n not is_component_dirs_set\n and hasattr(settings, \"STATICFILES_DIRS\")\n and settings.STATICFILES_DIRS\n )\n if is_legacy_paths:\n # NOTE: For STATICFILES_DIRS, we use the defaults even for empty list.\n # We don't do this for COMPONENTS.dirs, so user can explicitly specify \"NO dirs\".\n component_dirs = settings.STATICFILES_DIRS or [settings.BASE_DIR / \"components\"]\n # END TODO_REMOVE_IN_V1\n\n source = \"STATICFILES_DIRS\" if is_legacy_paths else \"COMPONENTS.dirs\"\n\n logger.debug(\n \"get_component_dirs will search for valid dirs from following options:\\n\"\n + \"\\n\".join([f\" - {str(d)}\" for d in component_dirs])\n )\n\n # Add `[app]/[APP_DIR]` to the directories. This is, by default `[app]/components`\n app_paths: List[Path] = []\n if include_apps:\n for conf in apps.get_app_configs():\n for app_dir in app_settings.APP_DIRS:\n comps_path = Path(conf.path).joinpath(app_dir)\n if comps_path.exists():\n app_paths.append(comps_path)\n\n directories: Set[Path] = set(app_paths)\n\n # Validate and add other values from the config\n for component_dir in component_dirs:\n # Consider tuples for STATICFILES_DIRS (See #489)\n # See https://docs.djangoproject.com/en/5.0/ref/settings/#prefixes-optional\n if isinstance(component_dir, (tuple, list)):\n component_dir = component_dir[1]\n try:\n Path(component_dir)\n except TypeError:\n logger.warning(\n f\"{source} expected str, bytes or os.PathLike object, or tuple/list of length 2. \"\n f\"See Django documentation for STATICFILES_DIRS. Got {type(component_dir)} : {component_dir}\"\n )\n continue\n\n if not Path(component_dir).is_absolute():\n raise ValueError(f\"{source} must contain absolute paths, got '{component_dir}'\")\n else:\n directories.add(Path(component_dir).resolve())\n\n logger.debug(\n \"get_component_dirs matched following template dirs:\\n\" + \"\\n\".join([f\" - {str(d)}\" for d in directories])\n )\n return list(directories)\n
get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]\n
Search for files within the component directories (as defined in
get_component_dirs()
).Requires
BASE_DIR
setting to be set.Parameters:
-
suffix
(Optional[str]
, default:None
) \u2013The suffix to search for. E.g.
.py
,.js
,.css
. Defaults toNone
, which will search for all files.
Returns:
-
List[ComponentFileEntry]
\u2013List[ComponentFileEntry] A list of entries that contain both the filesystem path and the python import path (dot path).
Example:
Source code infrom django_components import get_component_files\n\nmodules = get_component_files(\".py\")\n
src/django_components/util/loader.py
"},{"location":"reference/django_components/util/logger/","title":"def get_component_files(suffix: Optional[str] = None) -> List[ComponentFileEntry]:\n \"\"\"\n Search for files within the component directories (as defined in\n [`get_component_dirs()`](../api#django_components.get_component_dirs)).\n\n Requires `BASE_DIR` setting to be set.\n\n Args:\n suffix (Optional[str], optional): The suffix to search for. E.g. `.py`, `.js`, `.css`.\\\n Defaults to `None`, which will search for all files.\n\n Returns:\n List[ComponentFileEntry] A list of entries that contain both the filesystem path and \\\n the python import path (dot path).\n\n **Example:**\n\n ```python\n from django_components import get_component_files\n\n modules = get_component_files(\".py\")\n ```\n \"\"\"\n search_glob = f\"**/*{suffix}\" if suffix else \"**/*\"\n\n dirs = get_component_dirs(include_apps=False)\n component_filepaths = _search_dirs(dirs, search_glob)\n\n if hasattr(settings, \"BASE_DIR\") and settings.BASE_DIR:\n project_root = str(settings.BASE_DIR)\n else:\n # Fallback for getting the root dir, see https://stackoverflow.com/a/16413955/9788634\n project_root = os.path.abspath(os.path.dirname(__name__))\n\n # NOTE: We handle dirs from `COMPONENTS.dirs` and from individual apps separately.\n modules: List[ComponentFileEntry] = []\n\n # First let's handle the dirs from `COMPONENTS.dirs`\n #\n # Because for dirs in `COMPONENTS.dirs`, we assume they will be nested under `BASE_DIR`,\n # and that `BASE_DIR` is the current working dir (CWD). So the path relatively to `BASE_DIR`\n # is ALSO the python import path.\n for filepath in component_filepaths:\n module_path = _filepath_to_python_module(filepath, project_root, None)\n # Ignore files starting with dot `.` or files in dirs that start with dot.\n #\n # If any of the parts of the path start with a dot, e.g. the filesystem path\n # is `./abc/.def`, then this gets converted to python module as `abc..def`\n #\n # NOTE: This approach also ignores files:\n # - with two dots in the middle (ab..cd.py)\n # - an extra dot at the end (abcd..py)\n # - files outside of the parent component (../abcd.py).\n # But all these are NOT valid python modules so that's fine.\n if \"..\" in module_path:\n continue\n\n entry = ComponentFileEntry(dot_path=module_path, filepath=filepath)\n modules.append(entry)\n\n # For for apps, the directories may be outside of the project, e.g. in case of third party\n # apps. So we have to resolve the python import path relative to the package name / the root\n # import path for the app.\n # See https://github.com/EmilStenstrom/django-components/issues/669\n for conf in apps.get_app_configs():\n for app_dir in app_settings.APP_DIRS:\n comps_path = Path(conf.path).joinpath(app_dir)\n if not comps_path.exists():\n continue\n app_component_filepaths = _search_dirs([comps_path], search_glob)\n for filepath in app_component_filepaths:\n app_component_module = _filepath_to_python_module(filepath, conf.path, conf.name)\n entry = ComponentFileEntry(dot_path=app_component_module, filepath=filepath)\n modules.append(entry)\n\n return modules\n
logger","text":""},{"location":"reference/django_components/util/logger/#django_components.util.logger","title":"logger","text":"
Functions:
-
trace
\u2013TRACE level logger.
-
trace_msg
\u2013TRACE level logger with opinionated format for tracing interaction of components,
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:
Source code inLOGGING = {\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
src/django_components/util/logger.py
"},{"location":"reference/django_components/util/logger/#django_components.util.logger.trace_msg","title":"trace_msg","text":"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
trace_msg(\n action: Literal[\"PARSE\", \"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:
Source code in\"ASSOC SLOT test_slot ID 0088 TO COMP 0087\"
src/django_components/util/logger.py
"},{"location":"reference/django_components/util/misc/","title":"def trace_msg(\n action: Literal[\"PARSE\", \"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 == \"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
misc","text":""},{"location":"reference/django_components/util/misc/#django_components.util.misc","title":"misc","text":"
Functions:
-
gen_id
\u2013Generate a unique ID that can be associated with a Node
-
get_import_path
\u2013Get the full import path for a class or a function, e.g.
\"path.to.MyClass\"
gen_id() -> str\n
Generate a unique ID that can be associated with a Node
Source code insrc/django_components/util/misc.py
"},{"location":"reference/django_components/util/misc/#django_components.util.misc.get_import_path","title":"get_import_path","text":"def gen_id() -> str:\n \"\"\"Generate a unique ID that can be associated with a Node\"\"\"\n # Alphabet is only alphanumeric. Compared to the default alphabet used by nanoid,\n # we've omitted `-` and `_`.\n # With this alphabet, at 6 chars, the chance of collision is 1 in 3.3M.\n # See https://zelark.github.io/nano-id-cc/\n return generate(\n \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\",\n size=6,\n )\n
get_import_path(cls_or_fn: Type[Any]) -> str\n
Get the full import path for a class or a function, e.g.
Source code in\"path.to.MyClass\"
src/django_components/util/misc.py
"},{"location":"reference/django_components/util/nanoid/","title":"def get_import_path(cls_or_fn: Type[Any]) -> str:\n \"\"\"\n Get the full import path for a class or a function, e.g. `\"path.to.MyClass\"`\n \"\"\"\n module = cls_or_fn.__module__\n if module == \"builtins\":\n return cls_or_fn.__qualname__ # avoid outputs like 'builtins.str'\n return module + \".\" + cls_or_fn.__qualname__\n
nanoid","text":""},{"location":"reference/django_components/util/nanoid/#django_components.util.nanoid","title":"nanoid","text":""},{"location":"reference/django_components/util/tag_parser/","title":"
tag_parser","text":""},{"location":"reference/django_components/util/tag_parser/#django_components.util.tag_parser","title":"tag_parser","text":"
Classes:
-
TagAttr
\u2013
dataclass
","text":"TagAttr(key: Optional[str], value: str, start_index: int, quoted: bool)\n
Attributes:
-
quoted
(bool
) \u2013Whether the value is quoted (either with single or double quotes)
-
start_index
(int
) \u2013Start index of the attribute (include both key and value),
instance-attribute
","text":"quoted: bool\n
Whether the value is quoted (either with single or double quotes)
"},{"location":"reference/django_components/util/tag_parser/#django_components.util.tag_parser.TagAttr.start_index","title":"start_indexinstance-attribute
","text":"start_index: int\n
Start index of the attribute (include both key and value), relative to the start of the owner Tag.
"},{"location":"reference/django_components/util/types/","title":"types","text":""},{"location":"reference/django_components/util/types/#django_components.util.types","title":"types","text":"
Classes:
-
EmptyDict
\u2013TypedDict with no members.
Attributes:
-
EmptyTuple
\u2013Tuple with no members.
module-attribute
","text":"EmptyTuple = Tuple[]\n
Tuple with no members.
You can use this to define a Component that accepts NO positional arguments:
from django_components import Component, EmptyTuple\n\nclass Table(Component(EmptyTuple, Any, Any, Any, Any, Any))\n ...\n
After that, when you call
Component.render()
orComponent.render_to_response()
, theargs
parameter will raise type error ifargs
is anything else than an empty tuple.Table.render(\n args: (),\n)\n
Omitting
args
is also fine:Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
"},{"location":"reference/django_components/util/types/#django_components.util.types.EmptyDict","title":"EmptyDict","text":"Table.render(\n args: (\"one\", 2, \"three\"),\n)\n
Bases:
TypedDict
TypedDict with no members.
You can use this to define a Component that accepts NO kwargs, or NO slots, or returns NO data from
Component.get_context_data()
/Component.get_js_data()
/Component.get_css_data()
:Accepts NO kwargs:
from django_components import Component, EmptyDict\n\nclass Table(Component(Any, EmptyDict, Any, Any, Any, Any))\n ...\n
Accepts NO slots:
from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, EmptyDict, Any, Any, Any))\n ...\n
Returns NO data from
get_context_data()
:from django_components import Component, EmptyDict\n\nclass Table(Component(Any, Any, Any, EmptyDict, Any, Any))\n ...\n
Going back to the example with NO kwargs, when you then call
Component.render()
orComponent.render_to_response()
, thekwargs
parameter will raise type error ifkwargs
is anything else than an empty dict.Table.render(\n kwargs: {},\n)\n
Omitting
kwargs
is also fine:Table.render()\n
Other values are not allowed. This will raise an error with MyPy:
"},{"location":"reference/django_components/util/validation/","title":"Table.render(\n kwargs: {\n \"one\": 2,\n \"three\": 4,\n },\n)\n
validation","text":""},{"location":"reference/django_components/util/validation/#django_components.util.validation","title":"validation","text":""},{"location":"reference/django_components_js/build/","title":"
build","text":""},{"location":"reference/django_components_js/build/#django_components_js.build","title":"build","text":""},{"location":"reference/docs/","title":"Index","text":""},{"location":"reference/docs/#docs","title":"docs","text":"
Modules:
-
scripts
\u2013
Modules:
-
reference
\u2013Generate the code reference pages and navigation.
Generate the code reference pages and navigation.
No need to run this script manually, it is called by mkdocs-material during the build process.
You can run it manually to test the output.
"},{"location":"reference/docs/scripts/","title":"Index","text":""},{"location":"reference/docs/scripts/#docs.scripts","title":"scripts","text":"Modules:
-
reference
\u2013Generate the code reference pages and navigation.
Generate the code reference pages and navigation.
No need to run this script manually, it is called by mkdocs-material during the build process.
You can run it manually to test the output.
"},{"location":"reference/docs/scripts/reference/","title":"reference","text":""},{"location":"reference/docs/scripts/reference/#docs.scripts.reference","title":"reference","text":"
Generate the code reference pages and navigation.
No need to run this script manually, it is called by mkdocs-material during the build process.
You can run it manually to test the output.
"}]} \ No newline at end of file diff --git a/dev/sitemap.xml b/dev/sitemap.xml index a2b59b2e..3b551d52 100644 --- a/dev/sitemap.xml +++ b/dev/sitemap.xml @@ -2,222 +2,222 @@https://emilstenstrom.github.io/django-components/latest/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/CHANGELOG/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/CODE_OF_CONDUCT/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/SUMMARY/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/license/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/migrating_from_safer_staticfiles/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/devguides/dependency_mgmt/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/devguides/slot_rendering/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/devguides/slots_and_blocks/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/SUMMARY/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/app_settings/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/apps/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/attributes/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/autodiscovery/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/component/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/component_media/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/component_registry/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/components/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/components/dynamic/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/context/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/dependencies/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/expression/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/finders/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/library/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/management/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/management/commands/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/management/commands/startcomponent/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/management/commands/upgradecomponent/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/middleware/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/node/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/provide/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/slots/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/tag_formatter/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/template/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/template_loader/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/template_parser/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/templatetags/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/templatetags/component_tags/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/types/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/urls/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/util/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/util/cache/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/util/html/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/util/loader/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/util/logger/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/util/misc/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/util/nanoid/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/util/tag_parser/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/util/types/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components/util/validation/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/django_components_js/build/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/docs/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/docs/scripts/ -2024-11-26 +2024-11-27 https://emilstenstrom.github.io/django-components/latest/reference/docs/scripts/reference/ -2024-11-26 +2024-11-27 -
-
- Use