diff --git a/latest/404.html b/latest/404.html deleted file mode 100644 index 656fa009..00000000 --- a/latest/404.html +++ /dev/null @@ -1 +0,0 @@ -
🚨📢 Version 0.92 - BREAKING CHANGE: Component
class is no longer a subclass of View
. To configure the View
class, set the Component.View
nested class. HTTP methods like get
or post
can still be defined directly on Component
class, and Component.as_view()
internally calls Component.View.as_view()
. (See Modifying the View class)
The inputs (args, kwargs, slots, context, ...) that you pass to Component.render()
can be accessed from within get_context_data
, get_template_string
and get_template_name
via self.input
. (See Accessing data passed to the component)
Typing: Component
class supports generics that specify types for Component.render
(See Adding type hints with Generics)
Version 0.90 - All tags (component
, slot
, fill
, ...) now support "self-closing" or "inline" form, where you can omit the closing tag:
kwarg:key=val
): - You can change how the components are written in the template with TagFormatter. The default is `django_components.component_formatter`:
-```django
-{% component "button" href="..." disabled %}
- Click me!
-{% endcomponent %}
-```
-
-While `django_components.shorthand_component_formatter` allows you to write components like so:
-
-```django
-{% button href="..." disabled %}
- Click me!
-{% endbutton %}
-
🚨📢 Version 0.85 Autodiscovery module resolution changed. Following undocumented behavior was removed:
[app]/components.py
files, and used SETTINGS_MODULE
to search for component dirs.[app]/components.py
- Define each module in COMPONENTS.libraries
setting, or import each module inside the AppConfig.ready()
hook in respective apps.py
files.SETTINGS_MODULE
- Define component dirs using STATICFILES_DIRS
STATICFILES_DIRS
. To align with Django, STATICFILES_DIRS
now must be full paths (Django docs).🚨📢 Version 0.81 Aligned the render_to_response
method with the (now public) render
method of Component
class. Moreover, slots passed to these can now be rendered also as functions.
render_to_response
has changed.Version 0.80 introduces dependency injection with the {% provide %}
tag and inject()
method.
🚨📢 Version 0.79
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.🚨📢 Version 0.77 CHANGED the syntax for accessing default slot content.
{% fill "my_slot" as "alias" %}
and {{ alias.default }}
.{% fill "my_slot" default="alias" %}
and {{ alias }}
.Version 0.74 introduces html_attrs
tag and prefix:key=val
construct for passing dicts to components.
🚨📢 Version 0.70
{% if_filled "my_slot" %}
tags were replaced with {{ component_vars.is_filled.my_slot }}
variables.slot_context_behavior
and context_behavior
were merged. See the documentation for more details.Version 0.67 CHANGED the default way how context variables are resolved in slots. See the documentation for more details.
🚨📢 Version 0.5 CHANGES THE SYNTAX for components. component_block
is now component
, and component
blocks need an ending endcomponent
tag. The new python manage.py upgradecomponent
command can be used to upgrade a directory (use --path argument to point to each dir) of templates that use components to the new syntax automatically.
This change is done to simplify the API in anticipation of a 1.0 release of django_components. After 1.0 we intend to be stricter with big changes like this in point releases.
Version 0.34 adds components as views, which allows you to handle requests and render responses from within a component. See the documentation for more details.
Version 0.28 introduces 'implicit' slot filling and the default
option for slot
tags.
Version 0.27 adds a second installable app: django_components.safer_staticfiles. It provides the same behavior as django.contrib.staticfiles but with extra security guarantees (more info below in Security Notes).
Version 0.26 changes the syntax for {% slot %}
tags. From now on, we separate defining a slot ({% slot %}
) from filling a slot with content ({% fill %}
). This means you will likely need to change a lot of slot tags to fill. We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice featuPpre to have access to. Hoping that this will feel worth it!
Version 0.22 starts autoimporting all files inside components subdirectores, to simplify setup. An existing project might start to get AlreadyRegistered-errors because of this. To solve this, either remove your custom loading of components, or set "autodiscover": False in settings.COMPONENTS.
Version 0.17 renames Component.context
and Component.template
to get_context_data
and get_template_name
. The old methods still work, but emit a deprecation warning. This change was done to sync naming with Django's class based views, and make using django-components more familiar to Django users. Component.context
and Component.template
will be removed when version 1.0 is released.
Static files
Components can be organized however you prefer. That said, our prefered way is to keep the files of a component close together by bundling them in the same directory. This means that files containing backend logic, such as Python modules and HTML templates, live in the same directory as static files, e.g. JS and CSS.
If your are using django.contrib.staticfiles to collect static files, no distinction is made between the different kinds of files. As a result, your Python code and templates may inadvertently become available on your static file server. You probably don't want this, as parts of your backend logic will be exposed, posing a potential security vulnerability.
As of v0.27, django-components ships with an additional installable app django_components.safer_staticfiles. It is a drop-in replacement for django.contrib.staticfiles. Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server. To use it, add it to INSTALLED_APPS and remove django.contrib.staticfiles.
INSTALLED_APPS = [
- # 'django.contrib.staticfiles', # <-- REMOVE
- 'django_components',
- 'django_components.safer_staticfiles' # <-- ADD
-]
-
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:
but it is ignored on the development server:
For a step-by-step guide on deploying production server with static files, see the demo project.
Optional
To avoid loading the app in each template using {% load component_tags %}
, you can add the tag as a 'builtin' in settings.py
TEMPLATES = [
- {
- ...,
- 'OPTIONS': {
- 'context_processors': [
- ...
- ],
- 'builtins': [
- 'django_components.templatetags.component_tags',
- ]
- },
- },
-]
-
Read on to find out how to build your first component!
Create your first component
A component in django-components is the combination of four things: CSS, Javascript, a Django template, and some Python code to put them all together.
sampleproject/
- ├── calendarapp/
- ├── components/ 🆕
- │ └── calendar/ 🆕
- │ ├── calendar.py 🆕
- │ ├── script.js 🆕
- │ ├── style.css 🆕
- │ └── template.html 🆕
- ├── sampleproject/
- ├── manage.py
- └── requirements.txt
-
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.
/* In a file called [project root]/components/calendar/style.css */
-.calendar-component {
- width: 200px;
- background: pink;
-}
-.calendar-component span {
- font-weight: bold;
-}
-
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.
/* In a file called [project root]/components/calendar/script.js */
-(function () {
- if (document.querySelector(".calendar-component")) {
- document.querySelector(".calendar-component").onclick = function () {
- alert("Clicked calendar!");
- };
- }
-})();
-
Now you need a Django template for your component. Feel free to define more variables like date
in this example. When creating an instance of this component we will send in the values for these variables. The template will be rendered with whatever template backend you've specified in your Django settings file.
{# In a file called [project root]/components/calendar/template.html #}
-<div class="calendar-component">Today's date is <span>{{ date }}</span></div>
-
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.
## In a file called [project root]/components/calendar/calendar.py
-from django_components import Component, register
-
-@register("calendar")
-class Calendar(Component):
- # Templates inside `[your apps]/components` dir and `[project root]/components` dir
- # will be automatically found. To customize which template to use based on context
- # you can override method `get_template_name` instead of specifying `template_name`.
- #
- # `template_name` can be relative to dir where `calendar.py` is, or relative to STATICFILES_DIRS
- template_name = "template.html"
-
- # This component takes one parameter, a date string to show in the template
- def get_context_data(self, date):
- return {
- "date": date,
- }
-
- # Both `css` and `js` can be relative to dir where `calendar.py` is, or relative to STATICFILES_DIRS
- class Media:
- css = "style.css"
- js = "script.js"
-
And voilá!! We've created our first component.
Syntax highlight and code assistance
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
-
-@register("calendar")
-class Calendar(Component):
- def get_context_data(self, date):
- return {
- "date": date,
- }
-
- # language=HTML
- template= """
- <div class="calendar-component">Today's date is <span>{{ date }}</span></div>
- """
-
- # language=CSS
- css = """
- .calendar-component { width: 200px; background: pink; }
- .calendar-component span { font-weight: bold; }
- """
-
- # language=JS
- js = """
- (function(){
- if (document.querySelector(".calendar-component")) {
- document.querySelector(".calendar-component").onclick = function(){ alert("Clicked calendar!"); };
- }
- })()
- """
-
You don't need to use types.django_html
, types.css
, types.js
since Pycharm uses language injections. You only need to write the comments # language=<lang>
above the variables.
Use components outside of templates
New in version 0.81
Components can be rendered outside of Django templates, calling them as regular functions ("React-style").
The component class defines render
and render_to_response
class methods. These methods accept positional args, kwargs, and slots, offering the same flexibility as the {% component %}
tag:
class SimpleComponent(Component):
- template = """
- {% load component_tags %}
- hello: {{ hello }}
- foo: {{ foo }}
- kwargs: {{ kwargs|safe }}
- slot_first: {% slot "first" required / %}
- """
-
- def get_context_data(self, arg1, arg2, **kwargs):
- return {
- "hello": arg1,
- "foo": arg2,
- "kwargs": kwargs,
- }
-
-rendered = SimpleComponent.render(
- args=["world", "bar"],
- kwargs={"kw1": "test", "kw2": "ooo"},
- slots={"first": "FIRST_SLOT"},
- context={"from_context": 98},
-)
-
Renders:
SlotFunc
¤When rendering components with slots in render
or render_to_response
, you can pass either a string or a function.
The function has following signature:
def render_func(
- context: Context,
- data: Dict[str, Any],
- slot_ref: SlotRef,
-) -> str | SafeString:
- return nodelist.render(ctx)
-
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.str(slot_ref)
.Example:
def footer_slot(ctx, data, slot_ref):
- return f"""
- SLOT_DATA: {data['abc']}
- ORIGINAL: {slot_ref}
- """
-
-MyComponent.render_to_response(
- slots={
- "footer": footer_slot,
- },
-)
-
render_to_response
¤While render
method returns a plain string, render_to_response
wraps the rendered content in a "Response" class. By default, this is django.http.HttpResponse
.
If you want to use a different Response class in render_to_response
, set the Component.response_class
attribute:
class MyResponse(HttpResponse):
- def __init__(self, *args, **kwargs) -> None:
- super().__init__(*args, **kwargs)
- # Configure response
- self.headers = ...
- self.status = ...
-
-class SimpleComponent(Component):
- response_class = MyResponse
- template: types.django_html = "HELLO"
-
-response = SimpleComponent.render_to_response()
-assert isinstance(response, MyResponse)
-
Component as view example
Here's an example of a calendar component defined as a view:
## In a file called [project root]/components/calendar.py
-from django_components import Component, ComponentView, register
-
-@register("calendar")
-class Calendar(Component):
-
- template = """
- <div class="calendar-component">
- <div class="header">
- {% slot "header" / %}
- </div>
- <div class="body">
- Today's date is <span>{{ date }}</span>
- </div>
- </div>
- """
-
- # Handle GET requests
- def get(self, request, *args, **kwargs):
- context = {
- "date": request.GET.get("date", "2020-06-06"),
- }
- slots = {
- "header": "Calendar header",
- }
- # Return HttpResponse with the rendered content
- return self.render_to_response(
- context=context,
- slots=slots,
- )
-
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
-from django.urls import path
-from components.calendar.calendar import Calendar
-
-urlpatterns = [
- path("calendar/", Calendar.as_view()),
-]
-
Component.as_view()
is a shorthand for calling View.as_view()
and passing the component instance as one of the arguments.
Remember to add __init__.py
to your components directory, so that Django can find the urls.py
file.
Finally, include the component's urls in your project's urls.py
file:
## In a file called [project root]/urls.py
-from django.urls import include, path
-
-urlpatterns = [
- path("components/", include("components.urls")),
-]
-
Note: Slots content are automatically escaped by default to prevent XSS attacks. To disable escaping, set escape_slots_content=False
in the render_to_response
method. If you do so, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.
If you're planning on passing an HTML string, check Django's use of format_html
and mark_safe
.
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
-
-@register("calendar")
-class Calendar(Component):
- template_name = "template.html"
-
- # This component takes one parameter, a date string to show in the template
- def get_context_data(self, date):
- return {
- "date": date,
- }
-
which we then render in the template as:
As you can see, @register
links up the component class with the {% component %}
template tag. So when the template tag comes across a component called "calendar"
, it can look up it's class and instantiate it.
The default ComponentRegistry
instance can be imported as:
You can use the registry to manually add/remove/get components:
from django_components import registry
-
-## Register components
-registry.register("button", ButtonComponent)
-registry.register("card", CardComponent)
-
-## Get all or single
-registry.all() # {"button": ButtonComponent, "card": CardComponent}
-registry.get("card") # CardComponent
-
-## Unregister single component
-registry.unregister("card")
-
-## Unregister all components
-registry.clear()
-
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
-
-@register("calendar")
-class Calendar(Component):
- ...
-
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
-
-class MyAppConfig(AppConfig):
- name = "my_app"
-
- def ready(self) -> None:
- from components.card.card import Card
- from components.list.list import List
- from components.menu.menu import Menu
- from components.button.button import Button
- ...
-
However, there's a simpler way!
By default, the Python files in the STATICFILES_DIRS
directories are auto-imported in order to auto-register the components.
Autodiscovery occurs when Django is loaded, during the ready
hook of the apps.py
file.
If you are using autodiscovery, keep a few points in mind:
components
dir, that you would not want to run anyway.@register()
.py
, and module name should follow PEP-8.Autodiscovery can be disabled in the settings.
New in version 0.26:
slot
tag now serves only to declare new slots inside the component template.fill
tag instead.required
option should be added at the end of the slot
tag.Components support something called 'slots'. When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content. This mechanism makes components more reusable and composable. This behavior is similar to slots in Vue.
In the example below we introduce two block tags that work hand in hand to make this work. These are...
{% slot <name> %}
/{% endslot %}
: Declares a new slot in the component template.{% fill <name> %}
/{% endfill %}
: (Used inside a component
tag pair.) Fills a declared slot with the specified content.Let's update our calendar component to support more customization. We'll add slot
tag pairs to its template, template.html.
<div class="calendar-component">
- <div class="header">
- {% slot "header" %}Calendar header{% endslot %}
- </div>
- <div class="body">
- {% slot "body" %}Today's date is <span>{{ date }}</span>{% endslot %}
- </div>
-</div>
-
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" %}
- {% fill "body" %}Can you believe it's already <span>{{ date }}</span>??{% endfill %}
-{% endcomponent %}
-
Since the 'header' fill is unspecified, it's taken from the base template. If you put this in a template, and pass in date=2020-06-06
, this is what gets rendered:
<div class="calendar-component">
- <div class="header">
- Calendar header
- </div>
- <div class="body">
- Can you believe it's already <span>2020-06-06</span>??
- </div>
-</div>
-
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">
- <div class="header">
- {% slot "image" %}Image here{% endslot %}
- </div>
- <div class="body">
- {% slot "image" %}Image here{% endslot %}
- </div>
-</div>
-
So if used like:
{% component "calendar" date="2020-06-06" %}
- {% fill "image" %}
- <img src="..." />
- {% endfill %}
-{% endcomponent %}
-
This renders:
<div class="calendar-component">
- <div class="header">
- <img src="..." />
- </div>
- <div class="body">
- <img src="..." />
- </div>
-</div>
-
Added in version 0.26
NOTE: In version 0.77, the syntax was changed from
to
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" %}
- {% fill "body" default="body_default" %}
- {{ body_default }}. Have a great day!
- {% endfill %}
-{% endcomponent %}
-
This produces:
<div class="calendar-component">
- <div class="header">
- Calendar header
- </div>
- <div class="body">
- Today's date is <span>2020-06-06</span>. Have a great day!
- </div>
-</div>
-
is_filled
of slot names with special characters¤To be able to access a slot name via component_vars.is_filled
, the slot name needs to be composed of only alphanumeric characters and underscores (e.g. this__isvalid_123
).
However, you can still define slots with other special characters. In such case, the slot name in component_vars.is_filled
is modified to replace all invalid characters into _
.
So a slot named "my super-slot :)"
will be available as component_vars.is_filled.my_super_slot___
.
To pass the data to the slot
tag, simply pass them as keyword attributes (key=value
):
@register("my_comp")
-class MyComp(Component):
- template = """
- <div>
- {% slot "content" default input=input %}
- input: {{ input }}
- {% endslot %}
- </div>
- """
-
- def get_context_data(self, input):
- processed_input = do_something(input)
- return {
- "input": processed_input,
- }
-
As seen above, you can pass arguments to components like so:
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:
You can simplify it with html_attrs
tag:
where attrs
is:
This feature is inspired by merge_attrs
tag of django-web-components and "fallthrough attributes" feature of Vue.
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:
HTML rendering with html_attrs
tag or attributes_to_string
works the same way, where key=True
is rendered simply as key
, and key=False
is not render at all.
So given this input:
And template:
Then this renders:
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
:
And on html_attrs
tag, we set the key class
:
Then these will be merged and rendered as:
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" #}
-<div {% html_attrs attrs class="some-class another-class" class=my_var %}>
-</div>
-
Renders:
html_attrs
¤Assuming that:
class_from_var = "from-var"
-
-attrs = {
- "class": "from-attrs",
- "type": "submit",
-}
-
-defaults = {
- "class": "from-defaults",
- "role": "button",
-}
-
Then:
{% html_attr %}
renders (empty string):
{% html_attr class="some-class" class=class_from_var data-id="123" %}
renders:
class="some-class from-var" data-id="123"
{% html_attr attrs %}
renders:
class="from-attrs" type="submit"
{% html_attr attrs=attrs %}
renders:
class="from-attrs" type="submit"
{% html_attr defaults=defaults %}
renders:
class="from-defaults" role="button"
prefix:key=value
construct {% html_attr attrs:class="from-attrs" attrs:type="submit" %}
renders:
class="from-attrs" type="submit"
prefix:key=value
construct {% html_attr defaults:class="from-defaults" %}
renders:
class="from-defaults" role="button"
{% 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
{% 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
{% html_attrs attrs defaults:class="default-class" class="added_class" class=class_from_var data-id=123 %}
renders:
class="from-attrs added_class from-var" type="submit" data-id=123
If you need to use serialize HTML attributes outside of Django template and the html_attrs
tag, you can use attributes_to_string
:
from django_components.attributes import attributes_to_string
-
-attrs = {
- "class": "my-class text-red pa-4",
- "data-id": 123,
- "required": True,
- "disabled": False,
- "ignored-attr": None,
-}
-
-attributes_to_string(attrs)
-## 'class="my-class text-red pa-4" data-id="123" required'
-
Special characters
New in version 0.71:
Keyword arguments can contain 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>
-
These can then be accessed inside 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"]
- }
-
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")
-class MyComp(Component):
- template = """
- {% component "other" attrs=attrs / %}
- """
-
- def get_context_data(self, some_id: str):
- attrs = {
- "class": "pa-4 flex",
- "data-some-id": some_id,
- "@click.stop": "onClickHandler",
- }
- return {"attrs": attrs}
-
But as you can see in the case above, the event handler @click.stop
and styling pa-4 flex
are disconnected from the template. If the component grew in size and we moved the HTML to a separate file, we would have hard time reasoning about the component's template.
Luckily, there's a better way.
When we want to pass a dictionary to a component, we can define individual key-value pairs as component kwargs, so we can keep all the relevant information in the template. For that, we prefix the key with the name of the dict and :
. So key class
of input attrs
becomes attrs:class
. And our example becomes:
@register("my_comp")
-class MyComp(Component):
- template = """
- {% component "other"
- attrs:class="pa-4 flex"
- attrs:data-some-id=some_id
- attrs:@click.stop="onClickHandler"
- / %}
- """
-
- def get_context_data(self, some_id: str):
- return {"some_id": some_id}
-
Sweet! Now all the relevant HTML is inside the template, and we can move it to a separate file with confidence:
{% component "other"
- attrs:class="pa-4 flex"
- attrs:data-some-id=some_id
- attrs:@click.stop="onClickHandler"
-/ %}
-
Note: It is NOT possible to define nested dictionaries, so
attrs:my_key:two=2
would be interpreted as:
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.
{% provide %}
tag¤First we use the {% 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"
-
Notice that the provide
tag REQUIRES a name as a first argument. This is the key by which we can then access the data passed to this tag.
provide
tag key, similarly to the name argument in component
or slot
tags, has these requirements:
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:
@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 %}
-"""
-
renders:
Customizing component tags with TagFormatter
New in version 0.89
By default, components are rendered using the pair of {% component %}
/ {% endcomponent %}
template tags:
{% component "button" href="..." disabled %}
-Click me!
-{% endcomponent %}
-
-{# or #}
-
-{% component "button" href="..." disabled / %}
-
You can change this behaviour in the settings under the COMPONENTS.tag_formatter
.
For example, if you set the tag formatter to django_components.shorthand_component_formatter
, the components will use their name as the template tags:
{% button href="..." disabled %}
- Click me!
-{% endbutton %}
-
-{# or #}
-
-{% button href="..." disabled / %}
-
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.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):
- # 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']
- )
-
That's it! And once your TagFormatter
is ready, don't forget to update the settings!
Defining file paths relative to component or static dirs
As seen in the getting started example, to associate HTML/JS/CSS files with a component, you set them as template_name
, Media.js
and Media.css
respectively:
## In a file [project root]/components/calendar/calendar.py
-from django_components import Component, register
-
-@register("calendar")
-class Calendar(Component):
- template_name = "template.html"
-
- class Media:
- css = "style.css"
- js = "script.js"
-
In the example above, the files are defined relative to the directory where component.py
is.
Alternatively, you can specify the file paths relative to the directories set in STATICFILES_DIRS
.
Assuming that STATICFILES_DIRS
contains path [project root]/components
, we can rewrite the example as:
## In a file [project root]/components/calendar/calendar.py
-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"
-
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:
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", "path/to/style2.css"],
- "print": ["path/to/style3.css", "path/to/style4.css"],
- }
-
NOTE: When you define CSS as a string or a list, the all
media type is implied.
In the example above, you could see that when we used mark_safe
to mark a string as a SafeString
, we had to define the full <script>
/<link>
tag.
This is an extension of Django's Paths as objects feature, where "safe" strings are taken as is, and accessed only at render time.
Because of that, the paths defined as "safe" strings are NEVER resolved, neither relative to component's directory, nor relative to STATICFILES_DIRS
.
"Safe" strings can be used to lazily resolve a path, or to customize the <script>
or <link>
tag for individual paths:
class LazyJsPath:
- 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"),
- ]
-
The JS and CSS files included in components are not automatically rendered. Instead, use the following tags to specify where to render the dependencies:
component_dependencies
- Renders both JS and CSScomponent_js_dependencies
- Renders only JScomponent_css_dependencies
- Reneders only CSSJS files are rendered as <script>
tags.
CSS files are rendered as <style>
tags.
All library settings are handled from a global COMPONENTS
variable that is read from settings.py
. By default you don't need it set, there are resonable defaults.
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:
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:
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){% for ... %}
) that the {% fill %}
tag is part of.Given this template:
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 }
-
Then if get_context_data()
of the component "my_comp"
returns following data:
Then the template will be rendered as:
Because variables "my_var"
and "cheese"
are searched only inside RootComponent.get_context_data()
. But since "cheese"
is not defined there, it's empty.
Notice that the variables defined with the {% with %}
tag are ignored inside the {% fill %}
tag with the "isolated"
mode.
Django components supports logging with Django. This can help with troubleshooting.
To configure logging for Django components, set the django_components
logger in LOGGING
in settings.py
(below).
Also see the settings.py
file in sampleproject for a real-life example.
import logging
-import sys
-
-LOGGING = {
- 'version': 1,
- 'disable_existing_loggers': False,
- "handlers": {
- "console": {
- 'class': 'logging.StreamHandler',
- 'stream': sys.stdout,
- },
- },
- "loggers": {
- "django_components": {
- "level": logging.DEBUG,
- "handlers": ["console"],
- },
- },
-}
-
Management Command Usage
To use the command, run the following command in your terminal:
python manage.py startcomponent <name> --path <path> --js <js_filename> --css <css_filename> --template <template_filename> --force --verbose --dry-run
-
Replace <name>
, <path>
, <js_filename>
, <css_filename>
, and <template_filename>
with your desired values.
To create a component with the default settings, you only need to provide the name of the component:
This will create a new component named my_component
in the components
directory of your Django project. The JavaScript, CSS, and template files will be named script.js
, style.css
, and template.html
, respectively.
If you want to overwrite an existing component, you can use the --force
option:
This will overwrite the existing my_component
if it exists.
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.
Install locally and run the tests
Start by forking the project by clicking the Fork button up in the right corner in the GitHub . This makes a copy of the repository in your own name. Now you can clone this repository locally and start adding features:
To quickly run the tests install the local dependencies by running:
Now you can run the tests to make sure everything works as expected:
The library is also tested across many versions of Python and Django. To run tests that way:
pyenv install -s 3.8
-pyenv install -s 3.9
-pyenv install -s 3.10
-pyenv install -s 3.11
-pyenv install -s 3.12
-pyenv local 3.8 3.9 3.10 3.11 3.12
-tox -p
-
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.
Examples of behavior that contributes to creating a positive environment include:
Examples of unacceptable behavior by participants include:
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at emil@emilstenstrom.se. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq
{"use strict";/*!
- * escape-html
- * Copyright(c) 2012-2013 TJ Holowaychuk
- * Copyright(c) 2015 Andreas Lubbe
- * Copyright(c) 2015 Tiancheng "Timothy" Gu
- * MIT Licensed
- */var Va=/["'&<>]/;qn.exports=za;function za(e){var t=""+e,r=Va.exec(t);if(!r)return t;var o,n="",i=0,s=0;for(i=r.index;i