From 0f2a55812f72361826894206ae11e1f04aff3e0e Mon Sep 17 00:00:00 2001
From: github-actions If Irrespective of NOTE: The input to Next, to make Django load component HTML files as Django templates, modify Remove If In addition to NOTE: The input to Next, to make Django load component HTML files as Django templates, modify Remove Here's our example with more complex branching. Sometimes you're not interested in whether a slot is filled, but rather that it isn't. To negate the meaning of 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: You may want to design a component so that users of your component can still access the 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: Next, we head over to where we define a fill for this slot. Here, to access the slot data we set the Sometimes you're not interested in whether a slot is filled, but rather that it isn't. To negate the meaning of 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: You may want to design a component so that users of your component can still access the 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: Next, we head over to where we define a fill for this slot. Here, to access the slot data we set the To access slot data on a default slot, you have to explictly define the So this works: To access slot data on a default slot, you have to explictly define the So this works: While this does not: Note: You cannot set the When you call This means that you can use Removing atttributes Attributes that are set to So given this input: And template: Then this renders: Sometimes you may want to specify default values for attributes. You can pass a second argument (or kwarg In the example above, if Otherwise, or as kwargs Both Both All other kwargs are appended and can be repeated. Note: For readability, we've split the tags across multiple lines. Inside So if So by default, Next, let's consider what will be rendered when we call In So all kwargs that start with And So in the end All template tags in django_component, like New in version 0.71: Keyword arguments can contain special characters These can then be accessed inside While this does not: Note: You cannot set the When you call This means that you can use Removing atttributes Attributes that are set to So given this input: And template: Then this renders: Sometimes you may want to specify default values for attributes. You can pass a second argument (or kwarg In the example above, if Otherwise, or as kwargs Both Both All other kwargs are appended and can be repeated. Note: For readability, we've split the tags across multiple lines. Inside So if So by default, Next, let's consider what will be rendered when we call In So all kwargs that start with And So in the end All template tags in django_component, like New in version 0.71: Keyword arguments can contain special characters These can then be accessed inside 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 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 Instead, template tags in django_components ( In the example above: - Component This is inspired by django-cotton. You can even go a step further and have a similar experience to Vue or React, where you can evaluate arbitrary code expressions: Similar is possible with Note: Never use this feature to mix business logic and template logic. Business logic should still be in the view! 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: Instead, when you install django_components, it automatically configures Django to suport multi-line tags. So we can rewrite the above as: Much better! To disable this behavior, set What is "dependency injection" and "prop drilling"? Prop drilling refers to a scenario in UI development where you need to pass data through many layers of a component tree to reach the nested components that actually need the data. Normally, you'd use props to send data from a parent component to its children. However, this straightforward method becomes cumbersome and inefficient if the data has to travel through many levels or if several components scattered at different depths all need the same piece of information. This results in a situation where the intermediate components, which don't need the data for their own functioning, end up having to manage and pass along these props. This clutters the component tree and makes the code verbose and harder to manage. A neat solution to avoid prop drilling is using the "provide and inject" technique, AKA dependency injection. With dependency injection, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain. This feature is inspired by Vue's Provide / Inject and React's Context / useContext. First we use the Instead, template tags in django_components ( In the example above: - Component This is inspired by django-cotton. You can even go a step further and have a similar experience to Vue or React, where you can evaluate arbitrary code expressions: Similar is possible with Note: Never use this feature to mix business logic and template logic. Business logic should still be in the view! 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: Instead, when you install django_components, it automatically configures Django to suport multi-line tags. So we can rewrite the above as: Much better! To disable this behavior, set What is "dependency injection" and "prop drilling"? Prop drilling refers to a scenario in UI development where you need to pass data through many layers of a component tree to reach the nested components that actually need the data. Normally, you'd use props to send data from a parent component to its children. However, this straightforward method becomes cumbersome and inefficient if the data has to travel through many levels or if several components scattered at different depths all need the same piece of information. This results in a situation where the intermediate components, which don't need the data for their own functioning, end up having to manage and pass along these props. This clutters the component tree and makes the code verbose and harder to manage. A neat solution to avoid prop drilling is using the "provide and inject" technique, AKA dependency injection. With dependency injection, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain. This feature is inspired by Vue's Provide / Inject and React's Context / useContext. First we use the Notice that the 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 NOTE: Kwargs passed to Notice that the 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 NOTE: Kwargs passed to Similarly to slots and fills, also provide's name argument can be set dynamically via a variable, a template expression, or a spread operator: renders: Available hooks Similarly to slots and fills, also provide's name argument can be set dynamically via a variable, a template expression, or a spread operator: renders: Available hooks 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 And just like with NOTE: If you find yourself using the Components can also access the outer context in their context methods like Customizing component tags with TagFormatter New in version 0.89 By default, components are rendered using the pair of 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 And just like with NOTE: If you find yourself using the Components can also access the outer context in their context methods like Customizing component tags with TagFormatter New in version 0.89 By default, components are rendered using the pair of You can change this behaviour in the settings under the For example, if you set the tag formatter to You can change this behaviour in the settings under the For example, if you set the tag formatter to To do so, subclass from For example, this is the implementation of That's it! And once your Defining file paths relative to component or static dirs As seen in the getting started example, to associate HTML/JS/CSS files with a component, you set them as To do so, subclass from For example, this is the implementation of That's it! And once your Defining file paths relative to component or static dirs As seen in the getting started example, to associate HTML/JS/CSS files with a component, you set them as In the example above, the files are defined relative to the directory where Alternatively, you can specify the file paths relative to the directories set in Assuming that In the example above, the files are defined relative to the directory where Alternatively, you can specify the file paths relative to the directories set in Assuming that NOTE: In case of conflict, the preference goes to resolving the files relative to the component's directory. 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: NOTE: In case of conflict, the preference goes to resolving the files relative to the component's directory. 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: NOTE: When you define CSS as a string or a list, the In the example above, you could see that when we used 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 "Safe" strings can be used to lazily resolve a path, or to customize the The JS and CSS files included in components are not automatically rendered. Instead, use the following tags to specify where to render the dependencies: JS files are rendered as All library settings are handled from a global Here's overview of all available settings and their defaults: 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. NOTE: When you define CSS as a string or a list, the In the example above, you could see that when we used 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 "Safe" strings can be used to lazily resolve a path, or to customize the The JS and CSS files included in components are not automatically rendered. Instead, use the following tags to specify where to render the dependencies: JS files are rendered as All library settings are handled from a global Here's overview of all available settings and their defaults: 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. Specify the app-level directories that contain your components. Directories must be relative to app, e.g.: Specify the app-level directories that contain your components. Directories must be relative to app, e.g.: 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: 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: If If A list of suffixes that define which files within 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 Use this setting together with You can also pass in compiled regexes ( By default, any HTML and Python are considered NOT static files: NOTE: If you are migrating from BEFORE v0.67, set For v0.79 and later, the default is again You can configure what variables are available inside the This has two modes: Inside the Data returned from Inside the Given this template: Then if Then the template will be rendered as: Because variables Notice that the variables defined with the Sets the Can be set either as direct reference, or as an import string; Or Reload dev server on component file changes 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 NOTE: This setting should be enabled only for the dev environment! Management Command You can use the built-in management command Here are some examples of how you can use the command: You can also create a component with custom settings by providing additional arguments: This will create a new component named If you want to simulate the creation of a component without actually creating any files, you can use the This will simulate the creation of Writing component libraries Create a Django project with the following structure: Create custom This will be the entrypoint for using the components inside Django templates. Remember that Django requires the As you can see above, this is also the place where we configure how our components should behave, using the For library authors, we recommend setting Next, you can decide how will others use your components by settingt the If omitted or set to Or you can use 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: A list of suffixes that define which files within 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 Use this setting together with You can also pass in compiled regexes ( By default, any HTML and Python are considered NOT static files: NOTE: If you are migrating from BEFORE v0.67, set For v0.79 and later, the default is again You can configure what variables are available inside the This has two modes: Inside the Data returned from Inside the Given this template: Then if Then the template will be rendered as: Because variables Notice that the variables defined with the Sets the Can be set either as direct reference, or as an import string; Or Reload dev server on component file changes 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 NOTE: This setting should be enabled only for the dev environment! Management Command You can use the built-in management command Here are some examples of how you can use the command: You can also create a component with custom settings by providing additional arguments: This will create a new component named If you want to simulate the creation of a component without actually creating any files, you can use the This will simulate the creation of Writing component libraries Create a Django project with the following structure: Create custom This will be the entrypoint for using the components inside Django templates. Remember that Django requires the As you can see above, this is also the place where we configure how our components should behave, using the For library authors, we recommend setting Next, you can decide how will others use your components by settingt the If omitted or set to Or you can use 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: Write your components and register them with your instance of 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 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 Write your components and register them with your instance of 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 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 Import the components in Normally, users rely on autodiscovery and 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 Import the components in Normally, users rely on autodiscovery and 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 Note that you can also include any other startup logic within And that's it! The next step is to publish it. After the package has been published, all that remains is to install it in other django projects: Install the package: Add the package to Optionally add the template tags to the And, at last, you can use the components in your own project! Contributing and development 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: After Playwright is ready, simply run the tests with COMPONENTS.dirs
is omitted, django-components will by default look for a top-level /components
directory, {BASE_DIR}/components
.COMPONENTS.dirs
, django_components will also load components from app-level directories, e.g. my-app/components/
. The directories within apps are configured with COMPONENTS.app_dirs
, and the default is [app]/components
.COMPONENTS.dirs
is the same as for STATICFILES_DIRS
, and the paths must be full paths. See Django docs.
TEMPLATES
section of settings.py as follows:'APP_DIRS': True,
django.template.loaders.app_directories.Loader
loaders
to OPTIONS
list and set it to following value:COMPONENTS.dirs
is omitted, django-components will by default look for a top-level /components
directory, {BASE_DIR}/components
.COMPONENTS.dirs
, django_components will also load components from app-level directories, such as my-app/components/
. The directories within apps are configured with COMPONENTS.app_dirs
, and the default is [app]/components
.COMPONENTS.dirs
is the same as for STATICFILES_DIRS
, and the paths must be full paths. See Django docs.
TEMPLATES
section of settings.py as follows:'APP_DIRS': True,
django.template.loaders.app_directories.Loader
loaders
to OPTIONS
list and set it to following value:TEMPLATES = [
{
...,
'OPTIONS': {
@@ -291,217 +291,221 @@ While `django_components.shorthand_component_formatter` al
</div>
{% endif %}
</div>
-
<div class="frontmatter-component">
- <div class="title">
- {% slot "title" %}Title{% endslot %}
- </div>
- {% if component_vars.is_filled.subtitle %}
- <div class="subtitle">
- {% slot "subtitle" %}{# Optional subtitle #}{% endslot %}
- </div>
- {% elif component_vars.is_filled.title %}
- ...
- {% elif component_vars.is_filled.<name> %}
- ...
- {% endif %}
-</div>
-
component_vars.is_filled
, simply treat it as boolean and negate it with not
:{% if not component_vars.is_filled.subtitle %}
-<div class="subtitle">
- {% slot "subtitle" / %}
-</div>
-{% endif %}
-
Scoped slots¤
@register("my_comp")
-class MyComp(Component):
- template = """
- <div>
- {% slot "content" default %}
- input: {{ input }}
- {% endslot %}
- </div>
- """
-
- def get_context_data(self, input):
- processed_input = do_something(input)
- return {"input": processed_input}
-
input
variable, so they don't have to recompute it.
slot
tagfill
tagAccessing slot data in fill¤
data
attribute to the name of the variable through which we want to access the slot data. In the example below, we set it to data
:{% component "my_comp" %}
+
+Here's our example with more complex branching.
+
+```htmldjango
+<div class="frontmatter-component">
+ <div class="title">
+ {% slot "title" %}Title{% endslot %}
+ </div>
+ {% if component_vars.is_filled.subtitle %}
+ <div class="subtitle">
+ {% slot "subtitle" %}{# Optional subtitle #}{% endslot %}
+ </div>
+ {% elif component_vars.is_filled.title %}
+ ...
+ {% elif component_vars.is_filled.<name> %}
+ ...
+ {% endif %}
+</div>
+
component_vars.is_filled
, simply treat it as boolean and negate it with not
:{% if not component_vars.is_filled.subtitle %}
+<div class="subtitle">
+ {% slot "subtitle" / %}
+</div>
+{% endif %}
+
Scoped slots¤
@register("my_comp")
+class MyComp(Component):
+ template = """
+ <div>
+ {% slot "content" default %}
+ input: {{ input }}
+ {% endslot %}
+ </div>
+ """
+
+ def get_context_data(self, input):
+ processed_input = do_something(input)
+ return {"input": processed_input}
+
input
variable, so they don't have to recompute it.
slot
tagfill
tagAccessing slot data in fill¤
data
attribute to the name of the variable through which we want to access the slot data. In the example below, we set it to data
:{% component "my_comp" %}
+ {% fill "content" data="data" %}
+ {{ data.input }}
+ {% endfill %}
+{% endcomponent %}
+
{% fill %}
tags.{% component "my_comp" %}
{% fill "content" data="data" %}
{{ data.input }}
{% endfill %}
{% endcomponent %}
-
{% fill %}
tags.{% component "my_comp" %}
- {% fill "content" data="data" %}
- {{ data.input }}
- {% endfill %}
-{% endcomponent %}
-
data
attribute and default
attribute) to the same name. This raises an error:{% component "my_comp" %}
- {% fill "content" data="slot_var" default="slot_var" %}
- {{ slot_var.input }}
- {% endfill %}
-{% endcomponent %}
-
Accessing data passed to the component¤
Component.render
or Component.render_to_response
, the inputs to these methods can be accessed from within the instance under self.input
.self.input
inside: - get_context_data
- get_template_name
- get_template
self.input
is defined only for the duration of Component.render
, and raises RuntimeError
when called outside of this.self.input
has the same fields as the input to Component.render
:class TestComponent(Component):
- def get_context_data(self, var1, var2, variable, another, **attrs):
- assert self.input.args == (123, "str")
- assert self.input.kwargs == {"variable": "test", "another": 1}
- assert self.input.slots == {"my_slot": "MY_SLOT"}
- assert isinstance(self.input.context, Context)
-
- return {
- "variable": variable,
- }
-
-rendered = TestComponent.render(
- kwargs={"variable": "test", "another": 1},
- args=(123, "str"),
- slots={"my_slot": "MY_SLOT"},
-)
-
None
or False
are NOT rendered.Default attributes¤
defaults
) to set the defaults.attrs
contains e.g. the class
key, html_attrs
will render:class="{{ attrs.class }}"
html_attrs
will render:class="{{ defaults.class }}"
Rules for
html_attrs
¤
attrs
and defaults
can be passed as positional args{% html_attrs attrs defaults key=val %}
{% html_attrs key=val defaults=defaults attrs=attrs %}
attrs
and defaults
are optional (can be omitted)attrs
and defaults
are dictionaries, and we can define them the same way we define dictionaries for the component
tag. So either as attrs=attrs
or attrs:key=value
.Full example for
html_attrs
¤@register("my_comp")
-class MyComp(Component):
- template: t.django_html = """
- <div
- {% html_attrs attrs
- defaults:class="pa-4 text-red"
- class="my-comp-date"
- class=class_from_var
- data-id="123"
- %}
- >
- Today's date is <span>{{ date }}</span>
- </div>
- """
-
- def get_context_data(self, date: Date, attrs: dict):
- return {
- "date": date,
- "attrs": attrs,
- "class_from_var": "extra-class"
- }
-
-@register("parent")
-class Parent(Component):
- template: t.django_html = """
- {% component "my_comp"
- date=date
- attrs:class="pa-0 border-solid border-red"
- attrs:data-json=json_data
- attrs:@click="(e) => onClick(e, 'from_parent')"
- / %}
- """
-
- def get_context_data(self, date: Date):
- return {
- "date": datetime.now(),
- "json_data": json.dumps({"value": 456})
- }
-
MyComp
, we defined a default attributedefaults:class="pa-4 text-red"
attrs
includes key class
, the default above will be ignored.MyComp
also defines class
key twice. It means that whether the class
attribute is taken from attrs
or defaults
, the two class
values will be appended to it.MyComp
renders:MyComp
from Parent
component.MyComp
accepts a attrs
dictionary, that is passed to html_attrs
, so the contents of that dictionary are rendered as the HTML attributes.Parent
, we make use of passing dictionary key-value pairs as kwargs to define individual attributes as if they were regular kwargs.attrs:
will be collected into an attrs
dict. attrs:class="pa-0 border-solid border-red"
- attrs:data-json=json_data
- attrs:@click="(e) => onClick(e, 'from_parent')"
-
get_context_data
of MyComp
will receive attrs
input with following keys:attrs = {
- "class": "pa-0 border-solid",
- "data-json": '{"value": 456}',
- "@click": "(e) => onClick(e, 'from_parent')",
-}
-
attrs["class"]
overrides the default value for class
, whereas other keys will be merged.MyComp
will render:<div
- class="pa-0 border-solid my-comp-date extra-class"
- data-id="123"
- data-json='{"value": 456}'
- @click="(e) => onClick(e, 'from_parent')"
->
- ...
-</div>
-
Template tag syntax¤
{% component %}
or {% slot %}
, and so on, support extra syntax that makes it possible to write components like in Vue or React (JSX).Special characters¤
# @ . - _
, so keywords like so are still valid:<body>
- {% component "calendar" my-date="2015-06-19" @click.native=do_something #some_id=True / %}
-</body>
-
get_context_data
so:data
attribute and default
attribute) to the same name. This raises an error:{% component "my_comp" %}
+ {% fill "content" data="slot_var" default="slot_var" %}
+ {{ slot_var.input }}
+ {% endfill %}
+{% endcomponent %}
+
Accessing data passed to the component¤
Component.render
or Component.render_to_response
, the inputs to these methods can be accessed from within the instance under self.input
.self.input
inside: - get_context_data
- get_template_name
- get_template
self.input
is only defined during the execution of Component.render
, and raises a RuntimeError
when called outside of this context.self.input
has the same fields as the input to Component.render
:class TestComponent(Component):
+ def get_context_data(self, var1, var2, variable, another, **attrs):
+ assert self.input.args == (123, "str")
+ assert self.input.kwargs == {"variable": "test", "another": 1}
+ assert self.input.slots == {"my_slot": "MY_SLOT"}
+ assert isinstance(self.input.context, Context)
+
+ return {
+ "variable": variable,
+ }
+
+rendered = TestComponent.render(
+ kwargs={"variable": "test", "another": 1},
+ args=(123, "str"),
+ slots={"my_slot": "MY_SLOT"},
+)
+
None
or False
are NOT rendered.Default attributes¤
defaults
) to set the defaults.attrs
contains e.g. the class
key, html_attrs
will render:class="{{ attrs.class }}"
html_attrs
will render:class="{{ defaults.class }}"
Rules for
html_attrs
¤
attrs
and defaults
can be passed as positional args{% html_attrs attrs defaults key=val %}
{% html_attrs key=val defaults=defaults attrs=attrs %}
attrs
and defaults
are optional (can be omitted)attrs
and defaults
are dictionaries, and we can define them the same way we define dictionaries for the component
tag. So either as attrs=attrs
or attrs:key=value
.Full example for
html_attrs
¤@register("my_comp")
+class MyComp(Component):
+ template: t.django_html = """
+ <div
+ {% html_attrs attrs
+ defaults:class="pa-4 text-red"
+ class="my-comp-date"
+ class=class_from_var
+ data-id="123"
+ %}
+ >
+ Today's date is <span>{{ date }}</span>
+ </div>
+ """
+
+ def get_context_data(self, date: Date, attrs: dict):
+ return {
+ "date": date,
+ "attrs": attrs,
+ "class_from_var": "extra-class"
+ }
+
+@register("parent")
+class Parent(Component):
+ template: t.django_html = """
+ {% component "my_comp"
+ date=date
+ attrs:class="pa-0 border-solid border-red"
+ attrs:data-json=json_data
+ attrs:@click="(e) => onClick(e, 'from_parent')"
+ / %}
+ """
+
+ def get_context_data(self, date: Date):
+ return {
+ "date": datetime.now(),
+ "json_data": json.dumps({"value": 456})
+ }
+
MyComp
, we defined a default attributedefaults:class="pa-4 text-red"
attrs
includes key class
, the default above will be ignored.MyComp
also defines class
key twice. It means that whether the class
attribute is taken from attrs
or defaults
, the two class
values will be appended to it.MyComp
renders:MyComp
from Parent
component.MyComp
accepts a attrs
dictionary, that is passed to html_attrs
, so the contents of that dictionary are rendered as the HTML attributes.Parent
, we make use of passing dictionary key-value pairs as kwargs to define individual attributes as if they were regular kwargs.attrs:
will be collected into an attrs
dict. attrs:class="pa-0 border-solid border-red"
+ attrs:data-json=json_data
+ attrs:@click="(e) => onClick(e, 'from_parent')"
+
get_context_data
of MyComp
will receive attrs
input with following keys:attrs = {
+ "class": "pa-0 border-solid",
+ "data-json": '{"value": 456}',
+ "@click": "(e) => onClick(e, 'from_parent')",
+}
+
attrs["class"]
overrides the default value for class
, whereas other keys will be merged.MyComp
will render:<div
+ class="pa-0 border-solid my-comp-date extra-class"
+ data-id="123"
+ data-json='{"value": 456}'
+ @click="(e) => onClick(e, 'from_parent')"
+>
+ ...
+</div>
+
Template tag syntax¤
{% component %}
or {% slot %}
, and so on, support extra syntax that makes it possible to write components like in Vue or React (JSX).Special characters¤
# @ . - _
, so keywords like so are still valid:<body>
+ {% component "calendar" my-date="2015-06-19" @click.native=do_something #some_id=True / %}
+</body>
+
get_context_data
so:@register("calendar")
+class Calendar(Component):
+ # Since # . @ - are not valid identifiers, we have to
+ # use `**kwargs` so the method can accept these args.
+ def get_context_data(self, **kwargs):
+ return {
+ "date": kwargs["my-date"],
+ "id": kwargs["#some_id"],
+ "on_click": kwargs["@click.native"]
+ }
+
Use template tags inside component inputs¤
get_context_data()
. But this can get messy if your components contain a lot of logic.@register("calendar")
class Calendar(Component):
- # Since # . @ - are not valid identifiers, we have to
- # use `**kwargs` so the method can accept these args.
- def get_context_data(self, **kwargs):
- return {
- "date": kwargs["my-date"],
- "id": kwargs["#some_id"],
- "on_click": kwargs["@click.native"]
+ def get_context_data(self, id: str, editable: bool):
+ return {
+ "editable": editable,
+ "readonly": not editable,
+ "input_id": f"input-{id}",
+ "icon_id": f"icon-{id}",
+ ...
}
-
Use template tags inside component inputs¤
get_context_data()
. But this can get messy if your components contain a lot of logic.@register("calendar")
-class Calendar(Component):
- def get_context_data(self, id: str, editable: bool):
- return {
- "editable": editable,
- "readonly": not editable,
- "input_id": f"input-{id}",
- "icon_id": f"icon-{id}",
- ...
- }
-
{% component %}
, {% slot %}
, {% provide %}
, etc) allow you to treat literal string values as templates:{% component 'blog_post'
- "As positional arg {# yay #}"
- title="{{ person.first_name }} {{ person.last_name }}"
- id="{% random_int 10 20 %}"
- readonly="{{ editable|not }}"
- author="John Wick {# TODO: parametrize #}"
-/ %}
-
test
receives a positional argument with value "As positional arg "
. The comment is omitted. - Kwarg title
is passed as a string, e.g. John Doe
- Kwarg id
is passed as int
, e.g. 15
- Kwarg readonly
is passed as bool
, e.g. False
- Kwarg author
is passed as a string, e.g. John Wick
(Comment omitted)Evaluating Python expressions in template¤
django-expr
, which adds an expr
tag and filter that you can use to evaluate Python expressions from within the template:
Multi-line tags¤
{% component "card" title="Joanne Arc" subtitle="Head of Kitty Relations" date_last_active="2024-09-03" ... %}
-
{% component "card"
- title="Joanne Arc"
- subtitle="Head of Kitty Relations"
- date_last_active="2024-09-03"
- ...
-%}
-
COMPONENTS.multiline_tag
to False
Using
{% provide %}
tag¤{% provide %}
tag to define the data we want to "provide" (make available).{% provide "my_data" key="hi" another=123 %}
- {% component "child" / %} <--- Can access "my_data"
+
{% component %}
, {% slot %}
, {% provide %}
, etc) allow you to treat literal string values as templates:{% component 'blog_post'
+ "As positional arg {# yay #}"
+ title="{{ person.first_name }} {{ person.last_name }}"
+ id="{% random_int 10 20 %}"
+ readonly="{{ editable|not }}"
+ author="John Wick {# TODO: parametrize #}"
+/ %}
+
test
receives a positional argument with value "As positional arg "
. The comment is omitted. - Kwarg title
is passed as a string, e.g. John Doe
- Kwarg id
is passed as int
, e.g. 15
- Kwarg readonly
is passed as bool
, e.g. False
- Kwarg author
is passed as a string, e.g. John Wick
(Comment omitted)Evaluating Python expressions in template¤
django-expr
, which adds an expr
tag and filter that you can use to evaluate Python expressions from within the template:
Multi-line tags¤
{% component "card" title="Joanne Arc" subtitle="Head of Kitty Relations" date_last_active="2024-09-03" ... %}
+
{% component "card"
+ title="Joanne Arc"
+ subtitle="Head of Kitty Relations"
+ date_last_active="2024-09-03"
+ ...
+%}
+
COMPONENTS.multiline_tag
to False
Using
{% provide %}
tag¤{% provide %}
tag to define the data we want to "provide" (make available).{% provide "my_data" key="hi" another=123 %}
+ {% component "child" / %} <--- Can access "my_data"
+{% endprovide %}
+
+{% component "child" / %} <--- Cannot access "my_data"
+
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).{% with %}
tag.
{% provide %}
are NOT added to the context. In the example below, the {{ key }}
won't render anything:{% provide "my_data" key="hi" another=123 %}
+ {{ key }}
{% endprovide %}
-
-{% component "child" / %} <--- Cannot access "my_data"
-
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).{% with %}
tag.
{% provide %}
are NOT added to the context. In the example below, the {{ key }}
won't render anything:Full example¤
@register("child")
-class ChildComponent(Component):
- template = """
- <div> {{ my_data.key }} </div>
- <div> {{ my_data.another }} </div>
- """
-
- def get_context_data(self):
- my_data = self.inject("my_data", "default")
- return {"my_data": my_data}
-
-template_str = """
- {% load component_tags %}
- {% provide "my_data" key="hi" another=123 %}
- {% component "child" / %}
- {% endprovide %}
-"""
-
on_render_before
Full example¤
@register("child")
+class ChildComponent(Component):
+ template = """
+ <div> {{ my_data.key }} </div>
+ <div> {{ my_data.another }} </div>
+ """
+
+ def get_context_data(self):
+ my_data = self.inject("my_data", "default")
+ return {"my_data": my_data}
+
+template_str = """
+ {% load component_tags %}
+ {% provide "my_data" key="hi" another=123 %}
+ {% component "child" / %}
+ {% endprovide %}
+"""
+
on_render_before
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:
@@ -514,12 +518,12 @@ While `django_components.shorthand_component_formatter` al
# Append text into the Template
template.nodelist.append(TextNode("FROM_ON_BEFORE"))
```
-
on_render_after
def on_render_after(
- self: Component,
- context: Context,
- template: Template,
- content: str
-) -> None | str | SafeString:
+
on_render_after
def on_render_after(
+ self: Component,
+ context: Context,
+ template: Template,
+ content: str
+) -> None | str | SafeString:
Hook that runs just after the component's template was rendered.
It receives the rendered output as the last argument.
@@ -533,293 +537,293 @@ def on_render_after(self, context, template, content):
# Prepend text to the rendered content
return "Chocolate cookie recipe: " + content
```
-
Component context and scope¤
{% component %}
tag behaves similarly to {% include %}
tag - inside the component tag, you can access all variables that were defined outside of it.{% include %}
, if you don't want a specific component template to have access to the parent context, add only
to the {% component %}
tag:{% csrf_token %}
tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the only
modifier.only
modifier often, you can set the context_behavior option to "isolated"
, which automatically applies the only
modifier. This is useful if you want to make sure that components don't accidentally access the outer context.get_context_data
by accessing the property self.outer_context
.{% component %}
/ {% endcomponent %}
template tags:Component context and scope¤
{% component %}
tag behaves similarly to {% include %}
tag - inside the component tag, you can access all variables that were defined outside of it.{% include %}
, if you don't want a specific component template to have access to the parent context, add only
to the {% component %}
tag:{% csrf_token %}
tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the only
modifier.only
modifier often, you can set the context_behavior option to "isolated"
, which automatically applies the only
modifier. This is useful if you want to make sure that components don't accidentally access the outer context.get_context_data
by accessing the property self.outer_context
.{% component %}
/ {% endcomponent %}
template tags:{% component "button" href="..." disabled %}
+Click me!
+{% endcomponent %}
+
+{# or #}
+
+{% component "button" href="..." disabled / %}
+
COMPONENTS.tag_formatter
.django_components.shorthand_component_formatter
, the components will use their name as the template tags:{% button href="..." disabled %}
+ Click me!
+{% endbutton %}
{# or #}
-{% component "button" href="..." disabled / %}
-
COMPONENTS.tag_formatter
.django_components.shorthand_component_formatter
, the components will use their name as the template tags:{% button href="..." disabled %}
- Click me!
-{% endbutton %}
-
-{# or #}
-
-{% button href="..." disabled / %}
-
Writing your own TagFormatter¤
TagFormatter¤
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 %}
.
{% component %}
, tag formatter pre-processes the tag contents, so it can link back the custom template tag to the right component.TagFormatterABC
and implement following method: - start_tag
- end_tag
- parse
ShorthandComponentFormatter
class ShorthandComponentFormatter(TagFormatterABC):
- # Given a component name, generate the start template tag
- def start_tag(self, name: str) -> str:
- return name # e.g. 'button'
-
- # Given a component name, generate the start template tag
- def end_tag(self, name: str) -> str:
- return f"end{name}" # e.g. 'endbutton'
-
- # Given a tag, e.g.
- # `{% button href="..." disabled %}`
- #
- # The parser receives:
- # `['button', 'href="..."', 'disabled']`
- def parse(self, tokens: List[str]) -> TagResult:
- tokens = [*tokens]
- name = tokens.pop(0)
- return TagResult(
- name, # e.g. 'button'
- tokens # e.g. ['href="..."', 'disabled']
- )
-
TagFormatter
is ready, don't forget to update the settings!template_name
, Media.js
and Media.css
respectively:Writing your own TagFormatter¤
TagFormatter¤
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 %}
.
{% component %}
, tag formatter pre-processes the tag contents, so it can link back the custom template tag to the right component.TagFormatterABC
and implement following method: - start_tag
- end_tag
- parse
ShorthandComponentFormatter
class ShorthandComponentFormatter(TagFormatterABC):
+ # Given a component name, generate the start template tag
+ def start_tag(self, name: str) -> str:
+ return name # e.g. 'button'
+
+ # Given a component name, generate the start template tag
+ def end_tag(self, name: str) -> str:
+ return f"end{name}" # e.g. 'endbutton'
+
+ # Given a tag, e.g.
+ # `{% button href="..." disabled %}`
+ #
+ # The parser receives:
+ # `['button', 'href="..."', 'disabled']`
+ def parse(self, tokens: List[str]) -> TagResult:
+ tokens = [*tokens]
+ name = tokens.pop(0)
+ return TagResult(
+ name, # e.g. 'button'
+ tokens # e.g. ['href="..."', 'disabled']
+ )
+
TagFormatter
is ready, don't forget to update the settings!template_name
, Media.js
and Media.css
respectively:# In a file [project root]/components/calendar/calendar.py
+from django_components import Component, register
+
+@register("calendar")
+class Calendar(Component):
+ template_name = "template.html"
+
+ class Media:
+ css = "style.css"
+ js = "script.js"
+
component.py
is.COMPONENTS.dirs
or COMPONENTS.app_dirs
.COMPONENTS.dirs
contains path [project root]/components
, we can rewrite the example as:# In a file [project root]/components/calendar/calendar.py
from django_components import Component, register
@register("calendar")
class Calendar(Component):
- template_name = "template.html"
+ template_name = "calendar/template.html"
class Media:
- css = "style.css"
- js = "script.js"
-
component.py
is.COMPONENTS.dirs
or COMPONENTS.app_dirs
.COMPONENTS.dirs
contains path [project root]/components
, we can rewrite the example as:## In a file [project root]/components/calendar/calendar.py
-from django_components import Component, register
-
-@register("calendar")
-class Calendar(Component):
- template_name = "calendar/template.html"
-
- class Media:
- css = "calendar/style.css"
- js = "calendar/script.js"
-
Configuring CSS Media Types¤
Configuring CSS Media Types¤
class MyComponent(Component):
+ class Media:
+ css = {
+ "all": "path/to/style1.css",
+ "print": "path/to/style2.css",
+ }
+
class MyComponent(Component):
class Media:
css = {
- "all": "path/to/style1.css",
- "print": "path/to/style2.css",
+ "all": ["path/to/style1.css", "path/to/style2.css"],
+ "print": ["path/to/style3.css", "path/to/style4.css"],
}
-
class MyComponent(Component):
- class Media:
- css = {
- "all": ["path/to/style1.css", "path/to/style2.css"],
- "print": ["path/to/style3.css", "path/to/style4.css"],
- }
-
all
media type is implied.Path as objects¤
mark_safe
to mark a string as a SafeString
, we had to define the full <script>
/<link>
tag.COMPONENTS.dirs
.<script>
or <link>
tag for individual paths:class LazyJsPath:
- def __init__(self, static_path: str) -> None:
- self.static_path = static_path
-
- def __html__(self):
- full_path = static(self.static_path)
- return format_html(
- f'<script type="module" src="{full_path}"></script>'
- )
-
-@register("calendar")
-class Calendar(Component):
- template_name = "calendar/template.html"
-
- def get_context_data(self, date):
- return {
- "date": date,
- }
-
- class Media:
- css = "calendar/style.css"
- js = [
- # <script> tag constructed by Media class
- "calendar/script1.js",
- # Custom <script> tag
- LazyJsPath("calendar/script2.js"),
- ]
-
Rendering JS/CSS dependencies¤
component_dependencies
- Renders both JS and CSScomponent_js_dependencies
- Renders only JScomponent_css_dependencies
- Reneders only CSS<script>
tags.
CSS files are rendered as <style>
tags.Available settings¤
COMPONENTS
variable that is read from settings.py
. By default you don't need it set, there are resonable defaults.COMPONENTS = {
- "autodiscover": True,
- "context_behavior": "django", # "django" | "isolated"
- "dirs": [BASE_DIR / "components"], # Root-level "components" dirs, e.g. `/path/to/proj/components/`
- "app_dirs": ["components"], # App-level "components" dirs, e.g. `[app]/components/`
- "dynamic_component_name": "dynamic",
- "libraries": [], # ["mysite.components.forms", ...]
- "multiline_tags": True,
- "reload_on_template_change": False,
- "static_files_allowed": [
- ".css",
- ".js",
- # Images
- ".apng", ".png", ".avif", ".gif", ".jpg",
- ".jpeg", ".jfif", ".pjpeg", ".pjp", ".svg",
- ".webp", ".bmp", ".ico", ".cur", ".tif", ".tiff",
- # Fonts
- ".eot", ".ttf", ".woff", ".otf", ".svg",
- ],
- "static_files_forbidden": [
- ".html", ".django", ".dj", ".tpl",
- # Python files
- ".py", ".pyc",
- ],
- "tag_formatter": "django_components.component_formatter",
- "template_cache_size": 128,
-}
-
autodiscover
- Toggle autodiscovery¤all
media type is implied.Path as objects¤
mark_safe
to mark a string as a SafeString
, we had to define the full <script>
/<link>
tag.COMPONENTS.dirs
.<script>
or <link>
tag for individual paths:class LazyJsPath:
+ def __init__(self, static_path: str) -> None:
+ self.static_path = static_path
+
+ def __html__(self):
+ full_path = static(self.static_path)
+ return format_html(
+ f'<script type="module" src="{full_path}"></script>'
+ )
+
+@register("calendar")
+class Calendar(Component):
+ template_name = "calendar/template.html"
+
+ def get_context_data(self, date):
+ return {
+ "date": date,
+ }
+
+ class Media:
+ css = "calendar/style.css"
+ js = [
+ # <script> tag constructed by Media class
+ "calendar/script1.js",
+ # Custom <script> tag
+ LazyJsPath("calendar/script2.js"),
+ ]
+
Rendering JS/CSS dependencies¤
component_dependencies
- Renders both JS and CSScomponent_js_dependencies
- Renders only JScomponent_css_dependencies
- Reneders only CSS<script>
tags.
CSS files are rendered as <style>
tags.Available settings¤
COMPONENTS
variable that is read from settings.py
. By default you don't need it set, there are resonable defaults.COMPONENTS = {
+ "autodiscover": True,
+ "context_behavior": "django", # "django" | "isolated"
+ "dirs": [BASE_DIR / "components"], # Root-level "components" dirs, e.g. `/path/to/proj/components/`
+ "app_dirs": ["components"], # App-level "components" dirs, e.g. `[app]/components/`
+ "dynamic_component_name": "dynamic",
+ "libraries": [], # ["mysite.components.forms", ...]
+ "multiline_tags": True,
+ "reload_on_template_change": False,
+ "static_files_allowed": [
+ ".css",
+ ".js",
+ # Images
+ ".apng", ".png", ".avif", ".gif", ".jpg",
+ ".jpeg", ".jfif", ".pjpeg", ".pjp", ".svg",
+ ".webp", ".bmp", ".ico", ".cur", ".tif", ".tiff",
+ # Fonts
+ ".eot", ".ttf", ".woff", ".otf", ".svg",
+ ],
+ "static_files_forbidden": [
+ ".html", ".django", ".dj", ".tpl",
+ # Python files
+ ".py", ".pyc",
+ ],
+ "tag_formatter": "django_components.component_formatter",
+ "template_cache_size": 128,
+}
+
autodiscover
- Toggle autodiscovery¤app_dirs
¤app_dirs
¤multiline_tags
- Enable/Disable multiline support¤True
, template tags can span multiple lines. Default: True
multiline_tags
- Enable/Disable multiline support¤True
, template tags can span multiple lines. Default: True
static_files_forbidden
¤COMPONENTS.dirs
and COMPONENTS.app_dirs
will NEVER be treated as static files.COMPONENTS.static_files_allowed
.COMPONENTS.static_files_allowed
for a fine control over what files will be exposed.re.Pattern
) for more advanced patterns.COMPONENTS = {
- "static_files_forbidden": [
- ".html", ".django", ".dj", ".tpl", ".py", ".pyc",
- ],
-}
-
context_behavior
- Make components isolated (or not)¤
context_behavior
and slot_context_behavior
options were merged in v0.70.context_behavior
to "django"
. From v0.67 to v0.78 (incl) the default value was "isolated"
."django"
. See the rationale for change here.{% fill %}
tags. See Component context and scope.
"django"
- Default - The default Django template behavior.{% fill %}
tag, the context variables you can access are a union of:
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.{% fill %}
tag, you can ONLY access variables from 2 places:
get_context_data()
of the component which defined the template (AKA the "root" component){% for ... %}
) that the {% fill %}
tag is part of.Example "isolated"¤
class RootComp(Component):
- template = """
- {% with cheese="feta" %}
- {% component 'my_comp' %}
- {{ my_var }} # my_var
- {{ cheese }} # cheese
- {% endcomponent %}
- {% endwith %}
- """
- def get_context_data(self):
- return { "my_var": 123 }
-
get_context_data()
of the component "my_comp"
returns following data:"my_var"
and "cheese"
are searched only inside RootComponent.get_context_data()
. But since "cheese"
is not defined there, it's empty.{% with %}
tag are ignored inside the {% fill %}
tag with the "isolated"
mode.tag_formatter
- Change how components are used in templates¤TagFormatter
instance. See the section Customizing component tags with TagFormatter.from django_components import component_formatter
-
-COMPONENTS = {
- "tag_formatter": component_formatter
-}
-
reload_on_template_change
to True
. This configures Django to watch for component files too.startcomponent
to create a django component. The command accepts the following arguments and options:
name
: The name of the component to create. This is a required argument.--path
: The path to the components directory. This is an optional argument. If not provided, the command will use the BASE_DIR
setting from your Django settings.--js
: The name of the JavaScript file. This is an optional argument. The default value is script.js
.--css
: The name of the CSS file. This is an optional argument. The default value is style.css
.--template
: The name of the template file. This is an optional argument. The default value is template.html
.--force
: This option allows you to overwrite existing files if they exist. This is an optional argument.--verbose
: This option allows the command to print additional information during component creation. This is an optional argument.--dry-run
: This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False
.Management Command Examples¤
Creating a Component with Custom Settings¤
python manage.py startcomponent new_component --path my_components --js my_script.js --css my_style.css --template my_template.html
-
new_component
in the my_components
directory. The JavaScript, CSS, and template files will be named my_script.js
, my_style.css
, and my_template.html
, respectively.Simulating Component Creation¤
--dry-run
option:my_component
without creating any files.
Library
and ComponentRegistry
instances in mytags.py
Library
instance to be accessible under the register
variable (See Django docs):from django.template import Library
-from django_components import ComponentRegistry, RegistrySettings
-
-register = library = django.template.Library()
-comp_registry = ComponentRegistry(
- library=library,
- settings=RegistrySettings(
- CONTEXT_BEHAVIOR="isolated",
- TAG_FORMATTER="django_components.component_formatter",
- ),
-)
-
settings
argument. If omitted, default settings are used.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.TAG_FORMATTER
options."django_components.component_formatter"
, your components will be used like this:"django_components.component_shorthand_formatter"
to use components like so:static_files_forbidden
¤COMPONENTS.dirs
and COMPONENTS.app_dirs
will NEVER be treated as static files.COMPONENTS.static_files_allowed
.COMPONENTS.static_files_allowed
for a fine control over what files will be exposed.re.Pattern
) for more advanced patterns.COMPONENTS = {
+ "static_files_forbidden": [
+ ".html", ".django", ".dj", ".tpl", ".py", ".pyc",
+ ],
+}
+
context_behavior
- Make components isolated (or not)¤
context_behavior
and slot_context_behavior
options were merged in v0.70.context_behavior
to "django"
. From v0.67 to v0.78 (incl) the default value was "isolated"
."django"
. See the rationale for change here.{% fill %}
tags. See Component context and scope.
"django"
- Default - The default Django template behavior.{% fill %}
tag, the context variables you can access are a union of:
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.{% fill %}
tag, you can ONLY access variables from 2 places:
get_context_data()
of the component which defined the template (AKA the "root" component){% for ... %}
) that the {% fill %}
tag is part of.Example "isolated"¤
class RootComp(Component):
+ template = """
+ {% with cheese="feta" %}
+ {% component 'my_comp' %}
+ {{ my_var }} # my_var
+ {{ cheese }} # cheese
+ {% endcomponent %}
+ {% endwith %}
+ """
+ def get_context_data(self):
+ return { "my_var": 123 }
+
get_context_data()
of the component "my_comp"
returns following data:"my_var"
and "cheese"
are searched only inside RootComponent.get_context_data()
. But since "cheese"
is not defined there, it's empty.{% with %}
tag are ignored inside the {% fill %}
tag with the "isolated"
mode.tag_formatter
- Change how components are used in templates¤TagFormatter
instance. See the section Customizing component tags with TagFormatter.from django_components import component_formatter
+
+COMPONENTS = {
+ "tag_formatter": component_formatter
+}
+
reload_on_template_change
to True
. This configures Django to watch for component files too.startcomponent
to create a django component. The command accepts the following arguments and options:
name
: The name of the component to create. This is a required argument.--path
: The path to the components directory. This is an optional argument. If not provided, the command will use the BASE_DIR
setting from your Django settings.--js
: The name of the JavaScript file. This is an optional argument. The default value is script.js
.--css
: The name of the CSS file. This is an optional argument. The default value is style.css
.--template
: The name of the template file. This is an optional argument. The default value is template.html
.--force
: This option allows you to overwrite existing files if they exist. This is an optional argument.--verbose
: This option allows the command to print additional information during component creation. This is an optional argument.--dry-run
: This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is False
.Management Command Examples¤
Creating a Component with Custom Settings¤
python manage.py startcomponent new_component --path my_components --js my_script.js --css my_style.css --template my_template.html
+
new_component
in the my_components
directory. The JavaScript, CSS, and template files will be named my_script.js
, my_style.css
, and my_template.html
, respectively.Simulating Component Creation¤
--dry-run
option:my_component
without creating any files.
Library
and ComponentRegistry
instances in mytags.py
Library
instance to be accessible under the register
variable (See Django docs):from django.template import Library
+from django_components import ComponentRegistry, RegistrySettings
+
+register = library = django.template.Library()
+comp_registry = ComponentRegistry(
+ library=library,
+ settings=RegistrySettings(
+ CONTEXT_BEHAVIOR="isolated",
+ TAG_FORMATTER="django_components.component_formatter",
+ ),
+)
+
settings
argument. If omitted, default settings are used.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.TAG_FORMATTER
options."django_components.component_formatter"
, your components will be used like this:"django_components.component_shorthand_formatter"
to use components like so:ComponentRegistry
ComponentRegistry
from the previous step.my_
/ My
.from typing import Dict, NotRequired, Optional, Tuple, TypedDict
-{# Component from your library "mytags", using the "shorthand" formatter #}
-{% table items=items headers=header %}
-{% endtable %}
+from django_components import Component, SlotFunc, register, types
+
+from myapp.templatetags.mytags import comp_registry
-{# User-created components using the default settings #}
-{% component "my_comp" title="Abc..." %}
-{% endcomponent %}
-
ComponentRegistry
ComponentRegistry
from the previous step.my_
/ My
.from typing import Dict, NotRequired, Optional, Tuple, TypedDict
+# Define the types
+class EmptyDict(TypedDict):
+ pass
+
+type MyMenuArgs = Tuple[int, str]
+
+class MyMenuSlots(TypedDict):
+ default: NotRequired[Optional[SlotFunc[EmptyDict]]]
+
+class MyMenuProps(TypedDict):
+ vertical: NotRequired[bool]
+ klass: NotRequired[str]
+ style: NotRequired[str]
+
+# Define the component
+# NOTE: Don't forget to set the `registry`!
+@register("my_menu", registry=comp_registry)
+class MyMenu(Component[MyMenuArgs, MyMenuProps, MyMenuSlots, Any]):
+ def get_context_data(
+ self,
+ *args,
+ attrs: Optional[Dict] = None,
+ ):
+ return {
+ "attrs": attrs,
+ }
+
+ template: types.django_html = """
+ {# Load django_components template tags #}
+ {% load component_tags %}
+
+ <div {% html_attrs attrs class="my-menu" %}>
+ <div class="my-menu__content">
+ {% slot "default" default / %}
+ </div>
+ </div>
+ """
+
apps.py
COMPONENTS.dirs
to load the component files.AppConfig.ready()
hook of your apps.py
:from django.apps import AppConfig
-from django_components import Component, SlotFunc, register, types
-
-from myapp.templatetags.mytags import comp_registry
+class MyAppConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "myapp"
-# Define the types
-class EmptyDict(TypedDict):
- pass
-
-type MyMenuArgs = Tuple[int, str]
-
-class MyMenuSlots(TypedDict):
- default: NotRequired[Optional[SlotFunc[EmptyDict]]]
-
-class MyMenuProps(TypedDict):
- vertical: NotRequired[bool]
- klass: NotRequired[str]
- style: NotRequired[str]
-
-# Define the component
-# NOTE: Don't forget to set the `registry`!
-@register("my_menu", registry=comp_registry)
-class MyMenu(Component[MyMenuArgs, MyMenuProps, MyMenuSlots, Any]):
- def get_context_data(
- self,
- *args,
- attrs: Optional[Dict] = None,
- ):
- return {
- "attrs": attrs,
- }
-
- template: types.django_html = """
- {# Load django_components template tags #}
- {% load component_tags %}
-
- <div {% html_attrs attrs class="my-menu" %}>
- <div class="my-menu__content">
- {% slot "default" default / %}
- </div>
- </div>
- """
-
apps.py
COMPONENTS.dirs
to load the component files.AppConfig.ready()
hook of your apps.py
:from django.apps import AppConfig
-
-class MyAppConfig(AppConfig):
- default_auto_field = "django.db.models.BigAutoField"
- name = "myapp"
-
- # This is the code that gets run when user adds myapp
- # to Django's INSTALLED_APPS
- def ready(self) -> None:
- # Import the components that you want to make available
- # inside the templates.
- from myapp.templates import (
- menu,
- table,
- )
-
AppConfig.ready()
.Installing and using component libraries¤
INSTALLED_APPS
builtins
, so you don't have to call {% load mytags %}
in every template:Running Playwright tests¤
tox
:
django_components uses a bit of JS code to: - Manage the loading of JS and CSS files used by the components - Allow to pass data from Python to JS
When you make changes to this JS code, you also need to compile it:
src/django_components_js
:The script will combine all JS/TS code into a single .js
file, minify it, and copy it to django_components/static/django_components/django_components.min.js
.