django-components 0.92__tar.gz → 0.94__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {django_components-0.92/src/django_components.egg-info → django_components-0.94}/PKG-INFO +734 -129
- {django_components-0.92 → django_components-0.94}/README.md +734 -129
- {django_components-0.92 → django_components-0.94}/pyproject.toml +35 -1
- {django_components-0.92 → django_components-0.94}/src/django_components/__init__.py +8 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/app_settings.py +8 -0
- django_components-0.94/src/django_components/apps.py +45 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/attributes.py +23 -14
- {django_components-0.92 → django_components-0.94}/src/django_components/component.py +38 -43
- {django_components-0.92 → django_components-0.94}/src/django_components/component_registry.py +53 -5
- {django_components-0.92 → django_components-0.94}/src/django_components/context.py +2 -0
- django_components-0.94/src/django_components/expression.py +311 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/library.py +11 -8
- {django_components-0.92 → django_components-0.94}/src/django_components/node.py +19 -0
- django_components-0.94/src/django_components/provide.py +63 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/slots.py +175 -74
- {django_components-0.92 → django_components-0.94}/src/django_components/tag_formatter.py +7 -4
- {django_components-0.92 → django_components-0.94}/src/django_components/template_parser.py +1 -86
- {django_components-0.92 → django_components-0.94}/src/django_components/templatetags/component_tags.py +282 -211
- {django_components-0.92 → django_components-0.94}/src/django_components/types.py +4 -2
- {django_components-0.92 → django_components-0.94}/src/django_components/utils.py +14 -1
- {django_components-0.92 → django_components-0.94/src/django_components.egg-info}/PKG-INFO +734 -129
- {django_components-0.92 → django_components-0.94}/src/django_components.egg-info/SOURCES.txt +1 -0
- {django_components-0.92 → django_components-0.94}/tests/test_attributes.py +32 -0
- django_components-0.94/tests/test_expression.py +846 -0
- {django_components-0.92 → django_components-0.94}/tests/test_registry.py +82 -1
- {django_components-0.92 → django_components-0.94}/tests/test_template_parser.py +20 -19
- {django_components-0.92 → django_components-0.94}/tests/test_templatetags.py +32 -1
- {django_components-0.92 → django_components-0.94}/tests/test_templatetags_provide.py +88 -8
- {django_components-0.92 → django_components-0.94}/tests/test_templatetags_slot_fill.py +164 -2
- django_components-0.92/src/django_components/apps.py +0 -17
- django_components-0.92/src/django_components/expression.py +0 -63
- django_components-0.92/src/django_components/provide.py +0 -52
- {django_components-0.92 → django_components-0.94}/LICENSE +0 -0
- {django_components-0.92 → django_components-0.94}/setup.cfg +0 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/autodiscover.py +0 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/component_media.py +0 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/logger.py +0 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/management/__init__.py +0 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/management/commands/__init__.py +0 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/management/commands/startcomponent.py +0 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/management/commands/upgradecomponent.py +0 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/middleware.py +0 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/py.typed +0 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/safer_staticfiles/__init__.py +0 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/safer_staticfiles/apps.py +0 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/template_loader.py +0 -0
- {django_components-0.92 → django_components-0.94}/src/django_components/templatetags/__init__.py +0 -0
- {django_components-0.92 → django_components-0.94}/src/django_components.egg-info/dependency_links.txt +0 -0
- {django_components-0.92 → django_components-0.94}/src/django_components.egg-info/requires.txt +0 -0
- {django_components-0.92 → django_components-0.94}/src/django_components.egg-info/top_level.txt +0 -0
- {django_components-0.92 → django_components-0.94}/tests/test_autodiscover.py +0 -0
- {django_components-0.92 → django_components-0.94}/tests/test_command_startcomponent.py +0 -0
- {django_components-0.92 → django_components-0.94}/tests/test_component.py +0 -0
- {django_components-0.92 → django_components-0.94}/tests/test_component_as_view.py +0 -0
- {django_components-0.92 → django_components-0.94}/tests/test_component_media.py +0 -0
- {django_components-0.92 → django_components-0.94}/tests/test_context.py +0 -0
- {django_components-0.92 → django_components-0.94}/tests/test_dependency_rendering.py +0 -0
- {django_components-0.92 → django_components-0.94}/tests/test_safer_staticfiles.py +0 -0
- {django_components-0.92 → django_components-0.94}/tests/test_settings.py +0 -0
- {django_components-0.92 → django_components-0.94}/tests/test_tag_formatter.py +0 -0
- {django_components-0.92 → django_components-0.94}/tests/test_template_loader.py +0 -0
- {django_components-0.92 → django_components-0.94}/tests/test_templatetags_component.py +0 -0
- {django_components-0.92 → django_components-0.94}/tests/test_templatetags_templating.py +0 -0
- {django_components-0.92 → django_components-0.94}/tests/test_utils.py +0 -0
- {django_components-0.92 → django_components-0.94}/tests/testutils.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: django_components
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.94
|
|
4
4
|
Summary: A way to create simple reusable template components in Django.
|
|
5
5
|
Author-email: Emil Stenström <emil@emilstenstrom.se>
|
|
6
6
|
License: MIT
|
|
@@ -22,14 +22,29 @@ Description-Content-Type: text/markdown
|
|
|
22
22
|
License-File: LICENSE
|
|
23
23
|
Requires-Dist: Django>=4.2
|
|
24
24
|
|
|
25
|
-
# <img src="logo/logo-black-on-white.svg" alt="django-components" style="max-width: 100%; background: white; color: black;">
|
|
25
|
+
# <img src="https://raw.githubusercontent.com/EmilStenstrom/django-components/master/logo/logo-black-on-white.svg" alt="django-components" style="max-width: 100%; background: white; color: black;">
|
|
26
26
|
|
|
27
|
-
|
|
28
|
-
<a href="https://pepy.tech/project/django-components"><img align="right" src="https://pepy.tech/badge/django-components" alt="Show download stats"></a>
|
|
27
|
+
[](https://pypi.org/project/django-components/) [](https://pypi.org/project/django-components/) [](https://EmilStenstrom.github.io/django-components/latest/license/) [](https://pypistats.org/packages/django-components) [](https://github.com/EmilStenstrom/django-components/actions/workflows/tests.yml)
|
|
29
28
|
|
|
30
|
-
|
|
29
|
+
[**Docs (Work in progress)**](https://EmilStenstrom.github.io/django-components/latest/)
|
|
31
30
|
|
|
32
|
-
|
|
31
|
+
Create simple reusable template components in Django
|
|
32
|
+
|
|
33
|
+
## Features
|
|
34
|
+
|
|
35
|
+
<!-- FIXME Links -->
|
|
36
|
+
|
|
37
|
+
- ✨ **Reusable components**: Create components that can be reused in different parts of your project, or even in different projects.
|
|
38
|
+
- 📁 **Single file components**: Keep your Python, CSS, Javascript and HTML in one place (if you wish)
|
|
39
|
+
- 🎰 **Slots**: Define slots in your components to make them more flexible.
|
|
40
|
+
- 💻 **CLI**: A command line interface to help you create new components.
|
|
41
|
+
- 🚀 **Wide compatibility**: Works with [modern and LTS versions of Django](https://emilstenstrom.github.io/django-components/latest/user_guide/requirements_compatibility).
|
|
42
|
+
- **Load assets**: Automatically load the right CSS and Javascript files for your components, with [our middleware](https://emilstenstrom.github.io/django-components/latest/user_guide/creating_using_components/middleware).
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
## Summary
|
|
46
|
+
|
|
47
|
+
It lets you create "template components", that contains both the template, the Javascript and the CSS needed to generate the front end code you need for a modern app. Use components like this:
|
|
33
48
|
|
|
34
49
|
```htmldjango
|
|
35
50
|
{% component "calendar" date="2015-06-19" %}{% endcomponent %}
|
|
@@ -48,7 +63,7 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
|
|
|
48
63
|
- [Release notes](#release-notes)
|
|
49
64
|
- [Security notes 🚨](#security-notes-)
|
|
50
65
|
- [Installation](#installation)
|
|
51
|
-
- [
|
|
66
|
+
- [Compatibility](#compatibility)
|
|
52
67
|
- [Create your first component](#create-your-first-component)
|
|
53
68
|
- [Using single-file components](#using-single-file-components)
|
|
54
69
|
- [Use components in templates](#use-components-in-templates)
|
|
@@ -57,23 +72,36 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
|
|
|
57
72
|
- [Use components as views](#use-components-as-views)
|
|
58
73
|
- [Autodiscovery](#autodiscovery)
|
|
59
74
|
- [Using slots in templates](#using-slots-in-templates)
|
|
60
|
-
- [
|
|
75
|
+
- [Accessing data passed to the component](#accessing-data-passed-to-the-component)
|
|
61
76
|
- [Rendering HTML attributes](#rendering-html-attributes)
|
|
77
|
+
- [Template tag syntax](#template-tag-syntax)
|
|
62
78
|
- [Prop drilling and dependency injection (provide / inject)](#prop-drilling-and-dependency-injection-provide--inject)
|
|
63
79
|
- [Component context and scope](#component-context-and-scope)
|
|
64
80
|
- [Customizing component tags with TagFormatter](#customizing-component-tags-with-tagformatter)
|
|
65
81
|
- [Defining HTML/JS/CSS files](#defining-htmljscss-files)
|
|
66
82
|
- [Rendering JS/CSS dependencies](#rendering-jscss-dependencies)
|
|
67
83
|
- [Available settings](#available-settings)
|
|
84
|
+
- [Running with development server](#running-with-development-server)
|
|
68
85
|
- [Logging and debugging](#logging-and-debugging)
|
|
69
86
|
- [Management Command](#management-command)
|
|
87
|
+
- [Writing and sharing component libraries](#writing-and-sharing-component-libraries)
|
|
70
88
|
- [Community examples](#community-examples)
|
|
71
89
|
- [Running django-components project locally](#running-django-components-project-locally)
|
|
72
90
|
- [Development guides](#development-guides)
|
|
73
91
|
|
|
74
92
|
## Release notes
|
|
75
93
|
|
|
76
|
-
|
|
94
|
+
**Version 0.94**
|
|
95
|
+
- django_components now automatically configures Django to support multi-line tags. (See [Multi-line tags](#multi-line-tags))
|
|
96
|
+
- New setting `reload_on_template_change`. Set this to `True` to reload the dev server on changes to component template files. (See [Reload dev server on component file changes](#reload-dev-server-on-component-file-changes))
|
|
97
|
+
|
|
98
|
+
**Version 0.93**
|
|
99
|
+
- Spread operator `...dict` inside template tags. (See [Spread operator](#spread-operator))
|
|
100
|
+
- Use template tags inside string literals in component inputs. (See [Use template tags inside component inputs](#use-template-tags-inside-component-inputs))
|
|
101
|
+
- Dynamic slots, fills and provides - The `name` argument for these can now be a variable, a template expression, or via spread operator
|
|
102
|
+
- Component library authors can now configure `CONTEXT_BEHAVIOR` and `TAG_FORMATTER` settings independently from user settings.
|
|
103
|
+
|
|
104
|
+
🚨📢 **Version 0.92**
|
|
77
105
|
- 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](#modifying-the-view-class))
|
|
78
106
|
|
|
79
107
|
- 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](#accessing-data-passed-to-the-component))
|
|
@@ -228,6 +256,7 @@ For a step-by-step guide on deploying production server with static files,
|
|
|
228
256
|
4. Modify `TEMPLATES` section of settings.py as follows:
|
|
229
257
|
|
|
230
258
|
- _Remove `'APP_DIRS': True,`_
|
|
259
|
+
- NOTE: Instead of APP_DIRS, for the same effect, we will use [`django.template.loaders.app_directories.Loader`](https://docs.djangoproject.com/en/5.1/ref/templates/api/#django.template.loaders.app_directories.Loader)
|
|
231
260
|
- Add `loaders` to `OPTIONS` list and set it to following value:
|
|
232
261
|
|
|
233
262
|
```python
|
|
@@ -240,8 +269,11 @@ For a step-by-step guide on deploying production server with static files,
|
|
|
240
269
|
],
|
|
241
270
|
'loaders':[(
|
|
242
271
|
'django.template.loaders.cached.Loader', [
|
|
272
|
+
# Default Django loader
|
|
243
273
|
'django.template.loaders.filesystem.Loader',
|
|
274
|
+
# Inluding this is the same as APP_DIRS=True
|
|
244
275
|
'django.template.loaders.app_directories.Loader',
|
|
276
|
+
# Components loader
|
|
245
277
|
'django_components.template_loader.Loader',
|
|
246
278
|
]
|
|
247
279
|
)],
|
|
@@ -286,7 +318,7 @@ TEMPLATES = [
|
|
|
286
318
|
|
|
287
319
|
Read on to find out how to build your first component!
|
|
288
320
|
|
|
289
|
-
##
|
|
321
|
+
## Compatibility
|
|
290
322
|
|
|
291
323
|
Django-components supports all supported combinations versions of [Django](https://docs.djangoproject.com/en/dev/faq/install/#what-python-version-can-i-use-with-django) and [Python](https://devguide.python.org/versions/#versions).
|
|
292
324
|
|
|
@@ -318,9 +350,9 @@ A component in django-components is the combination of four things: CSS, Javascr
|
|
|
318
350
|
|
|
319
351
|
Start by creating empty files in the structure above.
|
|
320
352
|
|
|
321
|
-
First you need a CSS file. Be sure to prefix all rules with a unique class so they don't clash with other rules.
|
|
353
|
+
First, you need a CSS file. Be sure to prefix all rules with a unique class so they don't clash with other rules.
|
|
322
354
|
|
|
323
|
-
```css
|
|
355
|
+
```css title="[project root]/components/calendar/style.css"
|
|
324
356
|
/* In a file called [project root]/components/calendar/style.css */
|
|
325
357
|
.calendar-component {
|
|
326
358
|
width: 200px;
|
|
@@ -333,7 +365,7 @@ First you need a CSS file. Be sure to prefix all rules with a unique class so th
|
|
|
333
365
|
|
|
334
366
|
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.
|
|
335
367
|
|
|
336
|
-
```js
|
|
368
|
+
```js title="[project root]/components/calendar/script.js"
|
|
337
369
|
/* In a file called [project root]/components/calendar/script.js */
|
|
338
370
|
(function () {
|
|
339
371
|
if (document.querySelector(".calendar-component")) {
|
|
@@ -346,7 +378,7 @@ Then you need a javascript file that specifies how you interact with this compon
|
|
|
346
378
|
|
|
347
379
|
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.
|
|
348
380
|
|
|
349
|
-
```htmldjango
|
|
381
|
+
```htmldjango title="[project root]/components/calendar/calendar.html"
|
|
350
382
|
{# In a file called [project root]/components/calendar/template.html #}
|
|
351
383
|
<div class="calendar-component">Today's date is <span>{{ date }}</span></div>
|
|
352
384
|
```
|
|
@@ -355,7 +387,7 @@ Finally, we use django-components to tie this together. Start by creating a file
|
|
|
355
387
|
|
|
356
388
|
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.
|
|
357
389
|
|
|
358
|
-
```python
|
|
390
|
+
```python title="[project root]/components/calendar/calendar.py"
|
|
359
391
|
# In a file called [project root]/components/calendar/calendar.py
|
|
360
392
|
from django_components import Component, register
|
|
361
393
|
|
|
@@ -386,7 +418,7 @@ And voilá!! We've created our first component.
|
|
|
386
418
|
|
|
387
419
|
Components can also be defined in a single file, which is useful for small components. To do this, you can use the `template`, `js`, and `css` class attributes instead of the `template_name` and `Media`. For example, here's the calendar component from above, defined in a single file:
|
|
388
420
|
|
|
389
|
-
```python
|
|
421
|
+
```python title="[project root]/components/calendar.py"
|
|
390
422
|
# In a file called [project root]/components/calendar.py
|
|
391
423
|
from django_components import Component, register, types
|
|
392
424
|
|
|
@@ -561,7 +593,7 @@ Component.render(
|
|
|
561
593
|
context: Mapping | django.template.Context | None = None,
|
|
562
594
|
args: List[Any] | None = None,
|
|
563
595
|
kwargs: Dict[str, Any] | None = None,
|
|
564
|
-
slots: Dict[str, str | SafeString |
|
|
596
|
+
slots: Dict[str, str | SafeString | SlotFunc] | None = None,
|
|
565
597
|
escape_slots_content: bool = True
|
|
566
598
|
) -> str:
|
|
567
599
|
```
|
|
@@ -574,7 +606,7 @@ Component.render(
|
|
|
574
606
|
|
|
575
607
|
- _`slots`_ - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.
|
|
576
608
|
Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string
|
|
577
|
-
or [`
|
|
609
|
+
or [`SlotFunc`](#slotfunc).
|
|
578
610
|
|
|
579
611
|
- _`escape_slots_content`_ - Whether the content from `slots` should be escaped. `True` by default to prevent XSS attacks. If you disable escaping, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.
|
|
580
612
|
|
|
@@ -583,7 +615,7 @@ Component.render(
|
|
|
583
615
|
- NOTE: In "isolated" mode, context is NOT accessible, and data MUST be passed via
|
|
584
616
|
component's args and kwargs.
|
|
585
617
|
|
|
586
|
-
#### `
|
|
618
|
+
#### `SlotFunc`
|
|
587
619
|
|
|
588
620
|
When rendering components with slots in `render` or `render_to_response`, you can pass either a string or a function.
|
|
589
621
|
|
|
@@ -622,28 +654,34 @@ MyComponent.render_to_response(
|
|
|
622
654
|
### Adding type hints with Generics
|
|
623
655
|
|
|
624
656
|
The `Component` class optionally accepts type parameters
|
|
625
|
-
that allow you to specify the types of args, kwargs, slots, and
|
|
657
|
+
that allow you to specify the types of args, kwargs, slots, and
|
|
626
658
|
data.
|
|
627
659
|
|
|
628
660
|
```py
|
|
629
|
-
from typing import NotRequired, Tuple, TypedDict
|
|
661
|
+
from typing import NotRequired, Tuple, TypedDict, SlotFunc
|
|
630
662
|
|
|
631
|
-
# Tuple
|
|
663
|
+
# Positional inputs - Tuple
|
|
632
664
|
Args = Tuple[int, str]
|
|
633
665
|
|
|
634
|
-
# Mapping
|
|
666
|
+
# Kwargs inputs - Mapping
|
|
635
667
|
class Kwargs(TypedDict):
|
|
636
668
|
variable: str
|
|
637
669
|
another: int
|
|
638
670
|
maybe_var: NotRequired[int]
|
|
639
671
|
|
|
640
|
-
# Mapping
|
|
672
|
+
# Data returned from `get_context_data` - Mapping
|
|
641
673
|
class Data(TypedDict):
|
|
642
674
|
variable: str
|
|
643
675
|
|
|
644
|
-
#
|
|
676
|
+
# The data available to the `my_slot` scoped slot
|
|
677
|
+
class MySlotData(TypedDict):
|
|
678
|
+
value: int
|
|
679
|
+
|
|
680
|
+
# Slot functions - Mapping
|
|
645
681
|
class Slots(TypedDict):
|
|
646
|
-
|
|
682
|
+
# Use SlotFunc for slot functions.
|
|
683
|
+
# The generic specifies the `data` dictionary
|
|
684
|
+
my_slot: NotRequired[SlotFunc[MySlotData]]
|
|
647
685
|
|
|
648
686
|
class Button(Component[Args, Kwargs, Data, Slots]):
|
|
649
687
|
def get_context_data(self, variable, another):
|
|
@@ -804,13 +842,13 @@ class ComponentView(View):
|
|
|
804
842
|
|
|
805
843
|
def post(self, request, *args, **kwargs):
|
|
806
844
|
return self.component.post(request, *args, **kwargs)
|
|
807
|
-
|
|
845
|
+
|
|
808
846
|
...
|
|
809
847
|
```
|
|
810
848
|
|
|
811
849
|
If you want to define your own `View` class, you need to:
|
|
812
850
|
1. Set the class as `Component.View`
|
|
813
|
-
2. Subclass from `ComponentView`, so the View instance has access to the component
|
|
851
|
+
2. Subclass from `ComponentView`, so the View instance has access to the component instance.
|
|
814
852
|
|
|
815
853
|
In the example below, we added extra logic into `View.setup()`.
|
|
816
854
|
|
|
@@ -929,8 +967,8 @@ registry.clear()
|
|
|
929
967
|
|
|
930
968
|
### Registering components to custom ComponentRegistry
|
|
931
969
|
|
|
932
|
-
|
|
933
|
-
|
|
970
|
+
If you are writing a component library to be shared with others, you may want to manage your own instance of `ComponentRegistry`
|
|
971
|
+
and register components onto a different `Library` instance than the default one.
|
|
934
972
|
|
|
935
973
|
The `Library` instance can be set at instantiation of `ComponentRegistry`. If omitted,
|
|
936
974
|
then the default Library instance from django_components is used.
|
|
@@ -957,6 +995,34 @@ class MyComponent(Component):
|
|
|
957
995
|
|
|
958
996
|
NOTE: The Library instance can be accessed under `library` attribute of `ComponentRegistry`.
|
|
959
997
|
|
|
998
|
+
### ComponentRegistry settings
|
|
999
|
+
|
|
1000
|
+
When you are creating an instance of `ComponentRegistry`, you can define the components' behavior within the template.
|
|
1001
|
+
|
|
1002
|
+
The registry accepts these settings:
|
|
1003
|
+
- `CONTEXT_BEHAVIOR`
|
|
1004
|
+
- `TAG_FORMATTER`
|
|
1005
|
+
|
|
1006
|
+
```py
|
|
1007
|
+
from django.template import Library
|
|
1008
|
+
from django_components import ComponentRegistry, RegistrySettings
|
|
1009
|
+
|
|
1010
|
+
register = library = django.template.Library()
|
|
1011
|
+
comp_registry = ComponentRegistry(
|
|
1012
|
+
library=library,
|
|
1013
|
+
settings=RegistrySettings(
|
|
1014
|
+
CONTEXT_BEHAVIOR="isolated",
|
|
1015
|
+
TAG_FORMATTER="django_components.component_formatter",
|
|
1016
|
+
),
|
|
1017
|
+
)
|
|
1018
|
+
```
|
|
1019
|
+
|
|
1020
|
+
These settings are [the same as the ones you can set for django_components](#available-settings).
|
|
1021
|
+
|
|
1022
|
+
In fact, when you set `COMPONENT.tag_formatter` or `COMPONENT.context_behavior`, these are forwarded to the default `ComponentRegistry`.
|
|
1023
|
+
|
|
1024
|
+
This makes it possible to have multiple registries with different settings in one projects, and makes sharing of component libraries possible.
|
|
1025
|
+
|
|
960
1026
|
## Autodiscovery
|
|
961
1027
|
|
|
962
1028
|
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:
|
|
@@ -999,7 +1065,7 @@ If you are using autodiscovery, keep a few points in mind:
|
|
|
999
1065
|
- Components inside the auto-imported files still need to be registered with `@register()`
|
|
1000
1066
|
- Auto-imported component files must be valid Python modules, they must use suffix `.py`, and module name should follow [PEP-8](https://peps.python.org/pep-0008/#package-and-module-names).
|
|
1001
1067
|
|
|
1002
|
-
Autodiscovery can be disabled in the [settings](#
|
|
1068
|
+
Autodiscovery can be disabled in the [settings](#autodiscover---toggle-autodiscovery).
|
|
1003
1069
|
|
|
1004
1070
|
### Manually trigger autodiscovery
|
|
1005
1071
|
|
|
@@ -1438,117 +1504,77 @@ to the same name. This raises an error:
|
|
|
1438
1504
|
{% endcomponent %}
|
|
1439
1505
|
```
|
|
1440
1506
|
|
|
1441
|
-
|
|
1507
|
+
### Dynamic slots and fills
|
|
1442
1508
|
|
|
1443
|
-
|
|
1509
|
+
Until now, we were declaring slot and fill names statically, as a string literal, e.g.
|
|
1444
1510
|
|
|
1445
1511
|
```django
|
|
1446
|
-
|
|
1447
|
-
{% component "calendar" date="2015-06-19" %}
|
|
1448
|
-
{% endcomponent %}
|
|
1449
|
-
</body>
|
|
1512
|
+
{% slot "content" / %}
|
|
1450
1513
|
```
|
|
1451
1514
|
|
|
1452
|
-
|
|
1515
|
+
However, sometimes you may want to generate slots based on the given input. One example of this is [a table component like that of Vuetify](https://vuetifyjs.com/en/api/v-data-table/), which creates a header and an item slots for each user-defined column.
|
|
1453
1516
|
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
Keyword arguments can contain special characters `# @ . - _`, so keywords like
|
|
1457
|
-
so are still valid:
|
|
1517
|
+
In django_components you can achieve the same, simply by using a variable (or a [template expression](#use-template-tags-inside-component-inputs)) instead of a string literal:
|
|
1458
1518
|
|
|
1459
1519
|
```django
|
|
1460
|
-
<
|
|
1461
|
-
|
|
1462
|
-
|
|
1520
|
+
<table>
|
|
1521
|
+
<tr>
|
|
1522
|
+
{% for header in headers %}
|
|
1523
|
+
<th>
|
|
1524
|
+
{% slot "header-{{ header.key }}" value=header.title %}
|
|
1525
|
+
{{ header.title }}
|
|
1526
|
+
{% endslot %}
|
|
1527
|
+
</th>
|
|
1528
|
+
{% endfor %}
|
|
1529
|
+
</tr>
|
|
1530
|
+
</table>
|
|
1463
1531
|
```
|
|
1464
1532
|
|
|
1465
|
-
|
|
1533
|
+
When using the component, you can either set the fill explicitly:
|
|
1466
1534
|
|
|
1467
|
-
```
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
return {
|
|
1474
|
-
"date": kwargs["my-date"],
|
|
1475
|
-
"id": kwargs["#some_id"],
|
|
1476
|
-
"on_click": kwargs["@click.native"]
|
|
1477
|
-
}
|
|
1535
|
+
```django
|
|
1536
|
+
{% component "table" headers=headers items=items %}
|
|
1537
|
+
{% fill "header-name" data="data" %}
|
|
1538
|
+
<b>{{ data.value }}</b>
|
|
1539
|
+
{% endfill %}
|
|
1540
|
+
{% endcomponent %}
|
|
1478
1541
|
```
|
|
1479
1542
|
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
_New in version 0.74_:
|
|
1543
|
+
Or also use a variable:
|
|
1483
1544
|
|
|
1484
|
-
|
|
1545
|
+
```django
|
|
1546
|
+
{% component "table" headers=headers items=items %}
|
|
1547
|
+
{# Make only the active column bold #}
|
|
1548
|
+
{% fill "header-{{ active_header_name }}" data="data" %}
|
|
1549
|
+
<b>{{ data.value }}</b>
|
|
1550
|
+
{% endfill %}
|
|
1551
|
+
{% endcomponent %}
|
|
1552
|
+
```
|
|
1485
1553
|
|
|
1486
|
-
|
|
1487
|
-
of HTML attributes (usually called `attrs`) to pass to the underlying template.
|
|
1554
|
+
> NOTE: It's better to use static slot names whenever possible for clarity. The dynamic slot names should be reserved for advanced use only.
|
|
1488
1555
|
|
|
1489
|
-
|
|
1490
|
-
But for that, we need to define this dictionary on Python side:
|
|
1556
|
+
Lastly, in rare cases, you can also pass the slot name via [the spread operator](#spread-operator). This is possible, because the slot name argument is actually a shortcut for a `name` keyword argument.
|
|
1491
1557
|
|
|
1492
|
-
|
|
1493
|
-
@register("my_comp")
|
|
1494
|
-
class MyComp(Component):
|
|
1495
|
-
template = """
|
|
1496
|
-
{% component "other" attrs=attrs / %}
|
|
1497
|
-
"""
|
|
1558
|
+
So this:
|
|
1498
1559
|
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
"class": "pa-4 flex",
|
|
1502
|
-
"data-some-id": some_id,
|
|
1503
|
-
"@click.stop": "onClickHandler",
|
|
1504
|
-
}
|
|
1505
|
-
return {"attrs": attrs}
|
|
1560
|
+
```django
|
|
1561
|
+
{% slot "content" / %}
|
|
1506
1562
|
```
|
|
1507
1563
|
|
|
1508
|
-
|
|
1509
|
-
are disconnected from the template. If the component grew in size and we moved the HTML
|
|
1510
|
-
to a separate file, we would have hard time reasoning about the component's template.
|
|
1511
|
-
|
|
1512
|
-
Luckily, there's a better way.
|
|
1564
|
+
is the same as:
|
|
1513
1565
|
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
we prefix the key with the name of the dict and `:`. So key `class` of input `attrs` becomes
|
|
1517
|
-
`attrs:class`. And our example becomes:
|
|
1518
|
-
|
|
1519
|
-
```py
|
|
1520
|
-
@register("my_comp")
|
|
1521
|
-
class MyComp(Component):
|
|
1522
|
-
template = """
|
|
1523
|
-
{% component "other"
|
|
1524
|
-
attrs:class="pa-4 flex"
|
|
1525
|
-
attrs:data-some-id=some_id
|
|
1526
|
-
attrs:@click.stop="onClickHandler"
|
|
1527
|
-
/ %}
|
|
1528
|
-
"""
|
|
1529
|
-
|
|
1530
|
-
def get_context_data(self, some_id: str):
|
|
1531
|
-
return {"some_id": some_id}
|
|
1566
|
+
```django
|
|
1567
|
+
{% slot name="content" / %}
|
|
1532
1568
|
```
|
|
1533
1569
|
|
|
1534
|
-
|
|
1570
|
+
So it's possible to define a `name` key on a dictionary, and then spread that onto the slot tag:
|
|
1535
1571
|
|
|
1536
1572
|
```django
|
|
1537
|
-
{
|
|
1538
|
-
|
|
1539
|
-
attrs:data-some-id=some_id
|
|
1540
|
-
attrs:@click.stop="onClickHandler"
|
|
1541
|
-
/ %}
|
|
1573
|
+
{# slot_props = {"name": "content"} #}
|
|
1574
|
+
{% slot ...slot_props / %}
|
|
1542
1575
|
```
|
|
1543
1576
|
|
|
1544
|
-
|
|
1545
|
-
> `attrs:my_key:two=2` would be interpreted as:
|
|
1546
|
-
>
|
|
1547
|
-
> ```py
|
|
1548
|
-
> {"attrs": {"my_key:two": 2}}
|
|
1549
|
-
> ```
|
|
1550
|
-
|
|
1551
|
-
### Accessing data passed to the component
|
|
1577
|
+
## Accessing data passed to the component
|
|
1552
1578
|
|
|
1553
1579
|
When you call `Component.render` or `Component.render_to_response`, the inputs to these methods can be accessed from within the instance under `self.input`.
|
|
1554
1580
|
|
|
@@ -1956,6 +1982,294 @@ attributes_to_string(attrs)
|
|
|
1956
1982
|
# 'class="my-class text-red pa-4" data-id="123" required'
|
|
1957
1983
|
```
|
|
1958
1984
|
|
|
1985
|
+
## Template tag syntax
|
|
1986
|
+
|
|
1987
|
+
All template tags in django_component, like `{% component %}` or `{% slot %}`, and so on,
|
|
1988
|
+
support extra syntax that makes it possible to write components like in Vue or React (JSX).
|
|
1989
|
+
|
|
1990
|
+
### Self-closing tags
|
|
1991
|
+
|
|
1992
|
+
When you have a tag like `{% component %}` or `{% slot %}`, but it has no content, you can simply append a forward slash `/` at the end, instead of writing out the closing tags like `{% endcomponent %}` or `{% endslot %}`:
|
|
1993
|
+
|
|
1994
|
+
So this:
|
|
1995
|
+
|
|
1996
|
+
```django
|
|
1997
|
+
{% component "button" %}{% endcomponent %}
|
|
1998
|
+
```
|
|
1999
|
+
|
|
2000
|
+
becomes
|
|
2001
|
+
|
|
2002
|
+
```django
|
|
2003
|
+
{% component "button" / %}
|
|
2004
|
+
```
|
|
2005
|
+
|
|
2006
|
+
### Special characters
|
|
2007
|
+
|
|
2008
|
+
_New in version 0.71_:
|
|
2009
|
+
|
|
2010
|
+
Keyword arguments can contain special characters `# @ . - _`, so keywords like
|
|
2011
|
+
so are still valid:
|
|
2012
|
+
|
|
2013
|
+
```django
|
|
2014
|
+
<body>
|
|
2015
|
+
{% component "calendar" my-date="2015-06-19" @click.native=do_something #some_id=True / %}
|
|
2016
|
+
</body>
|
|
2017
|
+
```
|
|
2018
|
+
|
|
2019
|
+
These can then be accessed inside `get_context_data` so:
|
|
2020
|
+
|
|
2021
|
+
```py
|
|
2022
|
+
@register("calendar")
|
|
2023
|
+
class Calendar(Component):
|
|
2024
|
+
# Since # . @ - are not valid identifiers, we have to
|
|
2025
|
+
# use `**kwargs` so the method can accept these args.
|
|
2026
|
+
def get_context_data(self, **kwargs):
|
|
2027
|
+
return {
|
|
2028
|
+
"date": kwargs["my-date"],
|
|
2029
|
+
"id": kwargs["#some_id"],
|
|
2030
|
+
"on_click": kwargs["@click.native"]
|
|
2031
|
+
}
|
|
2032
|
+
```
|
|
2033
|
+
|
|
2034
|
+
### Spread operator
|
|
2035
|
+
|
|
2036
|
+
_New in version 0.93_:
|
|
2037
|
+
|
|
2038
|
+
Instead of passing keyword arguments one-by-one:
|
|
2039
|
+
|
|
2040
|
+
```django
|
|
2041
|
+
{% component "calendar" title="How to abc" date="2015-06-19" author="John Wick" / %}
|
|
2042
|
+
```
|
|
2043
|
+
|
|
2044
|
+
You can use a spread operator `...dict` to apply key-value pairs from a dictionary:
|
|
2045
|
+
|
|
2046
|
+
```py
|
|
2047
|
+
post_data = {
|
|
2048
|
+
"title": "How to...",
|
|
2049
|
+
"date": "2015-06-19",
|
|
2050
|
+
"author": "John Wick",
|
|
2051
|
+
}
|
|
2052
|
+
```
|
|
2053
|
+
|
|
2054
|
+
```django
|
|
2055
|
+
{% component "calendar" ...post_data / %}
|
|
2056
|
+
```
|
|
2057
|
+
|
|
2058
|
+
This behaves similar to [JSX's spread operator](https://kevinyckim33.medium.com/jsx-spread-operator-component-props-meaning-3c9bcadd2493)
|
|
2059
|
+
or [Vue's `v-bind`](https://vuejs.org/api/built-in-directives.html#v-bind).
|
|
2060
|
+
|
|
2061
|
+
Spread operators are treated as keyword arguments, which means that:
|
|
2062
|
+
1. Spread operators must come after positional arguments.
|
|
2063
|
+
2. You cannot use spread operators for [positional-only arguments](https://martinxpn.medium.com/positional-only-and-keyword-only-arguments-in-python-37-100-days-of-python-310c311657b0).
|
|
2064
|
+
|
|
2065
|
+
Other than that, you can use spread operators multiple times, and even put keyword arguments in-between or after them:
|
|
2066
|
+
|
|
2067
|
+
```django
|
|
2068
|
+
{% component "calendar" ...post_data id=post.id ...extra / %}
|
|
2069
|
+
```
|
|
2070
|
+
|
|
2071
|
+
In a case of conflicts, the values added later (right-most) overwrite previous values.
|
|
2072
|
+
|
|
2073
|
+
### Use template tags inside component inputs
|
|
2074
|
+
|
|
2075
|
+
_New in version 0.93_
|
|
2076
|
+
|
|
2077
|
+
When passing data around, sometimes you may need to do light transformations, like negating booleans or filtering lists.
|
|
2078
|
+
|
|
2079
|
+
Normally, what you would have to do is to define ALL the variables
|
|
2080
|
+
inside `get_context_data()`. But this can get messy if your components contain a lot of logic.
|
|
2081
|
+
|
|
2082
|
+
```py
|
|
2083
|
+
@register("calendar")
|
|
2084
|
+
class Calendar(Component):
|
|
2085
|
+
def get_context_data(self, id: str, editable: bool):
|
|
2086
|
+
return {
|
|
2087
|
+
"editable": editable,
|
|
2088
|
+
"readonly": not editable,
|
|
2089
|
+
"input_id": f"input-{id}",
|
|
2090
|
+
"icon_id": f"icon-{id}",
|
|
2091
|
+
...
|
|
2092
|
+
}
|
|
2093
|
+
```
|
|
2094
|
+
|
|
2095
|
+
Instead, template tags in django_components (`{% component %}`, `{% slot %}`, `{% provide %}`, etc) allow you to treat literal string values as templates:
|
|
2096
|
+
|
|
2097
|
+
```django
|
|
2098
|
+
{% component 'blog_post'
|
|
2099
|
+
"As positional arg {# yay #}"
|
|
2100
|
+
title="{{ person.first_name }} {{ person.last_name }}"
|
|
2101
|
+
id="{% random_int 10 20 %}"
|
|
2102
|
+
readonly="{{ editable|not }}"
|
|
2103
|
+
author="John Wick {# TODO: parametrize #}"
|
|
2104
|
+
/ %}
|
|
2105
|
+
```
|
|
2106
|
+
|
|
2107
|
+
In the example above:
|
|
2108
|
+
- Component `test` receives a positional argument with value `"As positional arg "`. The comment is omitted.
|
|
2109
|
+
- Kwarg `title` is passed as a string, e.g. `John Doe`
|
|
2110
|
+
- Kwarg `id` is passed as `int`, e.g. `15`
|
|
2111
|
+
- Kwarg `readonly` is passed as `bool`, e.g. `False`
|
|
2112
|
+
- Kwarg `author` is passed as a string, e.g. `John Wick ` (Comment omitted)
|
|
2113
|
+
|
|
2114
|
+
This is inspired by [django-cotton](https://github.com/wrabit/django-cotton#template-expressions-in-attributes).
|
|
2115
|
+
|
|
2116
|
+
#### Passing data as string vs original values
|
|
2117
|
+
|
|
2118
|
+
Sometimes you may want to use the template tags to transform
|
|
2119
|
+
or generate the data that is then passed to the component.
|
|
2120
|
+
|
|
2121
|
+
The data doesn't necessarily have to be strings. In the example above, the kwarg `id` was passed as an integer, NOT a string.
|
|
2122
|
+
|
|
2123
|
+
Although the string literals for components inputs are treated as regular Django templates, there is one special case:
|
|
2124
|
+
|
|
2125
|
+
When the string literal contains only a single template tag, with no extra text, then the value is passed as the original type instead of a string.
|
|
2126
|
+
|
|
2127
|
+
Here, `page` is an integer:
|
|
2128
|
+
|
|
2129
|
+
```django
|
|
2130
|
+
{% component 'blog_post' page="{% random_int 10 20 %}" / %}
|
|
2131
|
+
```
|
|
2132
|
+
|
|
2133
|
+
Here, `page` is a string:
|
|
2134
|
+
|
|
2135
|
+
```django
|
|
2136
|
+
{% component 'blog_post' page=" {% random_int 10 20 %} " / %}
|
|
2137
|
+
```
|
|
2138
|
+
|
|
2139
|
+
And same applies to the `{{ }}` variable tags:
|
|
2140
|
+
|
|
2141
|
+
Here, `items` is a list:
|
|
2142
|
+
|
|
2143
|
+
```django
|
|
2144
|
+
{% component 'cat_list' items="{{ cats|slice:':2' }}" / %}
|
|
2145
|
+
```
|
|
2146
|
+
|
|
2147
|
+
Here, `items` is a string:
|
|
2148
|
+
|
|
2149
|
+
```django
|
|
2150
|
+
{% component 'cat_list' items="{{ cats|slice:':2' }} See more" / %}
|
|
2151
|
+
```
|
|
2152
|
+
|
|
2153
|
+
#### Evaluating Python expressions in template
|
|
2154
|
+
|
|
2155
|
+
You can even go a step further and have a similar experience to Vue or React,
|
|
2156
|
+
where you can evaluate arbitrary code expressions:
|
|
2157
|
+
|
|
2158
|
+
```jsx
|
|
2159
|
+
<MyForm
|
|
2160
|
+
value={ isEnabled ? inputValue : null }
|
|
2161
|
+
/>
|
|
2162
|
+
```
|
|
2163
|
+
|
|
2164
|
+
Similar is possible with [`django-expr`](https://pypi.org/project/django-expr/), which adds an `expr` tag and filter that you can use to evaluate Python expressions from within the template:
|
|
2165
|
+
|
|
2166
|
+
```django
|
|
2167
|
+
{% component "my_form"
|
|
2168
|
+
value="{% expr 'input_value if is_enabled else None' %}"
|
|
2169
|
+
/ %}
|
|
2170
|
+
```
|
|
2171
|
+
|
|
2172
|
+
> Note: Never use this feature to mix business logic and template logic. Business logic should still be in the view!
|
|
2173
|
+
|
|
2174
|
+
### Pass dictonary by its key-value pairs
|
|
2175
|
+
|
|
2176
|
+
_New in version 0.74_:
|
|
2177
|
+
|
|
2178
|
+
Sometimes, a component may expect a dictionary as one of its inputs.
|
|
2179
|
+
|
|
2180
|
+
Most commonly, this happens when a component accepts a dictionary
|
|
2181
|
+
of HTML attributes (usually called `attrs`) to pass to the underlying template.
|
|
2182
|
+
|
|
2183
|
+
In such cases, we may want to define some HTML attributes statically, and other dynamically.
|
|
2184
|
+
But for that, we need to define this dictionary on Python side:
|
|
2185
|
+
|
|
2186
|
+
```py
|
|
2187
|
+
@register("my_comp")
|
|
2188
|
+
class MyComp(Component):
|
|
2189
|
+
template = """
|
|
2190
|
+
{% component "other" attrs=attrs / %}
|
|
2191
|
+
"""
|
|
2192
|
+
|
|
2193
|
+
def get_context_data(self, some_id: str):
|
|
2194
|
+
attrs = {
|
|
2195
|
+
"class": "pa-4 flex",
|
|
2196
|
+
"data-some-id": some_id,
|
|
2197
|
+
"@click.stop": "onClickHandler",
|
|
2198
|
+
}
|
|
2199
|
+
return {"attrs": attrs}
|
|
2200
|
+
```
|
|
2201
|
+
|
|
2202
|
+
But as you can see in the case above, the event handler `@click.stop` and styling `pa-4 flex`
|
|
2203
|
+
are disconnected from the template. If the component grew in size and we moved the HTML
|
|
2204
|
+
to a separate file, we would have hard time reasoning about the component's template.
|
|
2205
|
+
|
|
2206
|
+
Luckily, there's a better way.
|
|
2207
|
+
|
|
2208
|
+
When we want to pass a dictionary to a component, we can define individual key-value pairs
|
|
2209
|
+
as component kwargs, so we can keep all the relevant information in the template. For that,
|
|
2210
|
+
we prefix the key with the name of the dict and `:`. So key `class` of input `attrs` becomes
|
|
2211
|
+
`attrs:class`. And our example becomes:
|
|
2212
|
+
|
|
2213
|
+
```py
|
|
2214
|
+
@register("my_comp")
|
|
2215
|
+
class MyComp(Component):
|
|
2216
|
+
template = """
|
|
2217
|
+
{% component "other"
|
|
2218
|
+
attrs:class="pa-4 flex"
|
|
2219
|
+
attrs:data-some-id=some_id
|
|
2220
|
+
attrs:@click.stop="onClickHandler"
|
|
2221
|
+
/ %}
|
|
2222
|
+
"""
|
|
2223
|
+
|
|
2224
|
+
def get_context_data(self, some_id: str):
|
|
2225
|
+
return {"some_id": some_id}
|
|
2226
|
+
```
|
|
2227
|
+
|
|
2228
|
+
Sweet! Now all the relevant HTML is inside the template, and we can move it to a separate file with confidence:
|
|
2229
|
+
|
|
2230
|
+
```django
|
|
2231
|
+
{% component "other"
|
|
2232
|
+
attrs:class="pa-4 flex"
|
|
2233
|
+
attrs:data-some-id=some_id
|
|
2234
|
+
attrs:@click.stop="onClickHandler"
|
|
2235
|
+
/ %}
|
|
2236
|
+
```
|
|
2237
|
+
|
|
2238
|
+
> Note: It is NOT possible to define nested dictionaries, so
|
|
2239
|
+
> `attrs:my_key:two=2` would be interpreted as:
|
|
2240
|
+
>
|
|
2241
|
+
> ```py
|
|
2242
|
+
> {"attrs": {"my_key:two": 2}}
|
|
2243
|
+
> ```
|
|
2244
|
+
|
|
2245
|
+
### Multi-line tags
|
|
2246
|
+
|
|
2247
|
+
By default, Django expects a template tag to be defined on a single line.
|
|
2248
|
+
|
|
2249
|
+
However, this can become unwieldy if you have a component with a lot of inputs:
|
|
2250
|
+
|
|
2251
|
+
```django
|
|
2252
|
+
{% component "card" title="Joanne Arc" subtitle="Head of Kitty Relations" date_last_active="2024-09-03" ... %}
|
|
2253
|
+
```
|
|
2254
|
+
|
|
2255
|
+
Instead, when you install django_components, it automatically configures Django
|
|
2256
|
+
to suport multi-line tags.
|
|
2257
|
+
|
|
2258
|
+
So we can rewrite the above as:
|
|
2259
|
+
|
|
2260
|
+
```django
|
|
2261
|
+
{% component "card"
|
|
2262
|
+
title="Joanne Arc"
|
|
2263
|
+
subtitle="Head of Kitty Relations"
|
|
2264
|
+
date_last_active="2024-09-03"
|
|
2265
|
+
...
|
|
2266
|
+
%}
|
|
2267
|
+
```
|
|
2268
|
+
|
|
2269
|
+
Much better!
|
|
2270
|
+
|
|
2271
|
+
To disable this behavior, set [`COMPONENTS.multiline_tag`](#multiline_tags---enabledisable-multiline-support) to `False`
|
|
2272
|
+
|
|
1959
2273
|
## Prop drilling and dependency injection (provide / inject)
|
|
1960
2274
|
|
|
1961
2275
|
_New in version 0.80_:
|
|
@@ -2002,10 +2316,7 @@ First we use the `{% provide %}` tag to define the data we want to "provide" (ma
|
|
|
2002
2316
|
|
|
2003
2317
|
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.
|
|
2004
2318
|
|
|
2005
|
-
`provide` tag
|
|
2006
|
-
|
|
2007
|
-
- The _key_ must be a string literal
|
|
2008
|
-
- It must be a valid identifier (AKA a valid Python variable name)
|
|
2319
|
+
`provide` tag name must resolve to a valid identifier (AKA a valid Python variable name).
|
|
2009
2320
|
|
|
2010
2321
|
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.
|
|
2011
2322
|
|
|
@@ -2018,6 +2329,15 @@ Once you've set the name, you define the data you want to "provide" by passing i
|
|
|
2018
2329
|
> {% endprovide %}
|
|
2019
2330
|
> ```
|
|
2020
2331
|
|
|
2332
|
+
Similarly to [slots and fills](#dynamic-slots-and-fills), also provide's name argument can be set dynamically via a variable, a template expression, or a spread operator:
|
|
2333
|
+
|
|
2334
|
+
```django
|
|
2335
|
+
{% provide name=name ... %}
|
|
2336
|
+
...
|
|
2337
|
+
{% provide %}
|
|
2338
|
+
</table>
|
|
2339
|
+
```
|
|
2340
|
+
|
|
2021
2341
|
### Using `inject()` method
|
|
2022
2342
|
|
|
2023
2343
|
To "inject" (access) the data defined on the `provide` tag, you can use the `inject()` method inside of `get_context_data()`.
|
|
@@ -2035,7 +2355,7 @@ class ChildComponent(Component):
|
|
|
2035
2355
|
return {}
|
|
2036
2356
|
```
|
|
2037
2357
|
|
|
2038
|
-
First argument to `inject` is the _key_ of the provided data. This
|
|
2358
|
+
First argument to `inject` is the _key_ (or _name_) of the provided data. This
|
|
2039
2359
|
must match the string that you used in the `provide` tag. If no provider
|
|
2040
2360
|
with given key is found, `inject` raises a `KeyError`.
|
|
2041
2361
|
|
|
@@ -2092,7 +2412,7 @@ With this in mind, the `{% component %}` tag behaves similarly to `{% include %}
|
|
|
2092
2412
|
And just like with `{% include %}`, if you don't want a specific component template to have access to the parent context, add `only` to the `{% component %}` tag:
|
|
2093
2413
|
|
|
2094
2414
|
```htmldjango
|
|
2095
|
-
{% component "calendar" date="2015-06-19" only
|
|
2415
|
+
{% component "calendar" date="2015-06-19" only / %}
|
|
2096
2416
|
```
|
|
2097
2417
|
|
|
2098
2418
|
NOTE: `{% csrf_token %}` tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the `only` modifier.
|
|
@@ -2490,9 +2810,23 @@ COMPONENTS = {
|
|
|
2490
2810
|
|
|
2491
2811
|
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.
|
|
2492
2812
|
|
|
2493
|
-
|
|
2813
|
+
Here's overview of all available settings and their defaults:
|
|
2814
|
+
|
|
2815
|
+
```py
|
|
2816
|
+
COMPONENTS = {
|
|
2817
|
+
"autodiscover": True,
|
|
2818
|
+
"context_behavior": "django", # "django" | "isolated"
|
|
2819
|
+
"libraries": [], # ["mysite.components.forms", ...]
|
|
2820
|
+
"multiline_tags": True,
|
|
2821
|
+
"reload_on_template_change": False,
|
|
2822
|
+
"tag_formatter": "django_components.component_formatter",
|
|
2823
|
+
"template_cache_size": 128,
|
|
2824
|
+
}
|
|
2825
|
+
```
|
|
2826
|
+
|
|
2827
|
+
### `libraries` - Load component modules
|
|
2494
2828
|
|
|
2495
|
-
Configure the
|
|
2829
|
+
Configure the locations where components are loaded. To do this, add a `COMPONENTS` variable to you `settings.py` with a list of python paths to load. This allows you to build a structure of components that are independent from your apps.
|
|
2496
2830
|
|
|
2497
2831
|
```python
|
|
2498
2832
|
COMPONENTS = {
|
|
@@ -2532,7 +2866,7 @@ from django_components import import_libraries
|
|
|
2532
2866
|
import_libraries()
|
|
2533
2867
|
```
|
|
2534
2868
|
|
|
2535
|
-
###
|
|
2869
|
+
### `autodiscover` - Toggle autodiscovery
|
|
2536
2870
|
|
|
2537
2871
|
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.
|
|
2538
2872
|
|
|
@@ -2542,9 +2876,21 @@ COMPONENTS = {
|
|
|
2542
2876
|
}
|
|
2543
2877
|
```
|
|
2544
2878
|
|
|
2545
|
-
###
|
|
2879
|
+
### `multiline_tags` - Enable/Disable multiline support
|
|
2880
|
+
|
|
2881
|
+
If `True`, template tags can span multiple lines. Default: `True`
|
|
2882
|
+
|
|
2883
|
+
```python
|
|
2884
|
+
COMPONENTS = {
|
|
2885
|
+
"multiline_tags": True,
|
|
2886
|
+
}
|
|
2887
|
+
```
|
|
2888
|
+
|
|
2889
|
+
### `template_cache_size` - Tune the template cache
|
|
2890
|
+
|
|
2891
|
+
Each time a template is rendered it is cached to a global in-memory cache (using Python's `lru_cache` decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.
|
|
2546
2892
|
|
|
2547
|
-
|
|
2893
|
+
By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are using the `template` method of a component to render lots of dynamic templates, you can increase this number. To remove the cache limit altogether and cache everything, set template_cache_size to `None`.
|
|
2548
2894
|
|
|
2549
2895
|
```python
|
|
2550
2896
|
COMPONENTS = {
|
|
@@ -2552,7 +2898,7 @@ COMPONENTS = {
|
|
|
2552
2898
|
}
|
|
2553
2899
|
```
|
|
2554
2900
|
|
|
2555
|
-
###
|
|
2901
|
+
### `context_behavior` - Make components isolated (or not)
|
|
2556
2902
|
|
|
2557
2903
|
> NOTE: `context_behavior` and `slot_context_behavior` options were merged in v0.70.
|
|
2558
2904
|
>
|
|
@@ -2657,9 +3003,15 @@ But since `"cheese"` is not defined there, it's empty.
|
|
|
2657
3003
|
|
|
2658
3004
|
Notice that the variables defined with the `{% with %}` tag are ignored inside the `{% fill %}` tag with the `"isolated"` mode.
|
|
2659
3005
|
|
|
2660
|
-
###
|
|
3006
|
+
### `reload_on_template_change` - Reload dev server on component file changes
|
|
3007
|
+
|
|
3008
|
+
If `True`, configures Django to reload on component files. See
|
|
3009
|
+
[Reload dev server on component file changes](#reload-dev-server-on-component-file-changes).
|
|
3010
|
+
|
|
3011
|
+
NOTE: This setting should be enabled only for the dev environment!
|
|
2661
3012
|
|
|
2662
|
-
|
|
3013
|
+
### `tag_formatter` - Change how components are used in templates
|
|
3014
|
+
Sets the [`TagFormatter`](#available-tagformatters) instance. See the section [Customizing component tags with TagFormatter](#customizing-component-tags-with-tagformatter).
|
|
2663
3015
|
|
|
2664
3016
|
Can be set either as direct reference, or as an import string;
|
|
2665
3017
|
|
|
@@ -2679,6 +3031,26 @@ COMPONENTS = {
|
|
|
2679
3031
|
}
|
|
2680
3032
|
```
|
|
2681
3033
|
|
|
3034
|
+
## Running with development server
|
|
3035
|
+
|
|
3036
|
+
### Reload dev server on component file changes
|
|
3037
|
+
|
|
3038
|
+
This is relevant if you are using the project structure as shown in our examples, where
|
|
3039
|
+
HTML, JS, CSS and Python are separate and nested in a directory.
|
|
3040
|
+
|
|
3041
|
+
In this case you may notice that when you are running a development server,
|
|
3042
|
+
the server sometimes does not reload when you change comoponent files.
|
|
3043
|
+
|
|
3044
|
+
From relevant [StackOverflow thread](https://stackoverflow.com/a/76722393/9788634):
|
|
3045
|
+
|
|
3046
|
+
> TL;DR is that the server won't reload if it thinks the changed file is in a templates directory,
|
|
3047
|
+
> or in a nested sub directory of a templates directory. This is by design.
|
|
3048
|
+
|
|
3049
|
+
To make the dev server reload on all component files, set [`reload_on_template_change`](#reload_on_template_change---reload-dev-server-on-component-file-changes) to `True`.
|
|
3050
|
+
This configures Django to watch for component files too.
|
|
3051
|
+
|
|
3052
|
+
NOTE: This setting should be enabled only for the dev environment!
|
|
3053
|
+
|
|
2682
3054
|
## Logging and debugging
|
|
2683
3055
|
|
|
2684
3056
|
Django components supports [logging with Django](https://docs.djangoproject.com/en/5.0/howto/logging/#logging-how-to). This can help with troubleshooting.
|
|
@@ -2783,6 +3155,239 @@ python manage.py startcomponent my_component --dry-run
|
|
|
2783
3155
|
|
|
2784
3156
|
This will simulate the creation of `my_component` without creating any files.
|
|
2785
3157
|
|
|
3158
|
+
## Writing and sharing component libraries
|
|
3159
|
+
|
|
3160
|
+
You can publish and share your components for others to use. Here are the steps to do so:
|
|
3161
|
+
|
|
3162
|
+
### Writing component libraries
|
|
3163
|
+
|
|
3164
|
+
1. Create a Django project with the following structure:
|
|
3165
|
+
|
|
3166
|
+
```txt
|
|
3167
|
+
project/
|
|
3168
|
+
|-- myapp/
|
|
3169
|
+
|-- __init__.py
|
|
3170
|
+
|-- apps.py
|
|
3171
|
+
|-- templates/
|
|
3172
|
+
|-- table/
|
|
3173
|
+
|-- table.py
|
|
3174
|
+
|-- table.js
|
|
3175
|
+
|-- table.css
|
|
3176
|
+
|-- table.html
|
|
3177
|
+
|-- menu.py <--- single-file component
|
|
3178
|
+
|-- templatetags/
|
|
3179
|
+
|-- __init__.py
|
|
3180
|
+
|-- mytags.py
|
|
3181
|
+
```
|
|
3182
|
+
|
|
3183
|
+
2. Create custom `Library` and `ComponentRegistry` instances in `mytags.py`
|
|
3184
|
+
|
|
3185
|
+
This will be the entrypoint for using the components inside Django templates.
|
|
3186
|
+
|
|
3187
|
+
Remember that Django requires the `Library` instance to be accessible under the `register` variable ([See Django docs](https://docs.djangoproject.com/en/dev/howto/custom-template-tags)):
|
|
3188
|
+
|
|
3189
|
+
```py
|
|
3190
|
+
from django.template import Library
|
|
3191
|
+
from django_components import ComponentRegistry, RegistrySettings
|
|
3192
|
+
|
|
3193
|
+
register = library = django.template.Library()
|
|
3194
|
+
comp_registry = ComponentRegistry(
|
|
3195
|
+
library=library,
|
|
3196
|
+
settings=RegistrySettings(
|
|
3197
|
+
CONTEXT_BEHAVIOR="isolated",
|
|
3198
|
+
TAG_FORMATTER="django_components.component_formatter",
|
|
3199
|
+
),
|
|
3200
|
+
)
|
|
3201
|
+
```
|
|
3202
|
+
|
|
3203
|
+
As you can see above, this is also the place where we configure how our components should behave, using the `settings` argument. If omitted, default settings are used.
|
|
3204
|
+
|
|
3205
|
+
For library authors, we recommend setting `CONTEXT_BEHAVIOR` to `"isolated"`, so that the state cannot leak into the components, and so the components' behavior is configured solely through the inputs. This means that the components will be more predictable and easier to debug.
|
|
3206
|
+
|
|
3207
|
+
Next, you can decide how will others use your components by settingt the `TAG_FORMATTER` options.
|
|
3208
|
+
|
|
3209
|
+
If omitted or set to `"django_components.component_formatter"`,
|
|
3210
|
+
your components will be used like this:
|
|
3211
|
+
|
|
3212
|
+
```django
|
|
3213
|
+
{% component "table" items=items headers=headers %}
|
|
3214
|
+
{% endcomponent %}
|
|
3215
|
+
```
|
|
3216
|
+
|
|
3217
|
+
Or you can use `"django_components.component_shorthand_formatter"`
|
|
3218
|
+
to use components like so:
|
|
3219
|
+
|
|
3220
|
+
```django
|
|
3221
|
+
{% table items=items headers=headers %}
|
|
3222
|
+
{% endtable %}
|
|
3223
|
+
```
|
|
3224
|
+
|
|
3225
|
+
Or you can define a [custom TagFormatter](#tagformatter).
|
|
3226
|
+
|
|
3227
|
+
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:
|
|
3228
|
+
|
|
3229
|
+
```django
|
|
3230
|
+
{% load mytags %}
|
|
3231
|
+
|
|
3232
|
+
{# Component from your library "mytags", using the "shorthand" formatter #}
|
|
3233
|
+
{% table items=items headers=header %}
|
|
3234
|
+
{% endtable %}
|
|
3235
|
+
|
|
3236
|
+
{# User-created components using the default settings #}
|
|
3237
|
+
{% component "my_comp" title="Abc..." %}
|
|
3238
|
+
{% endcomponent %}
|
|
3239
|
+
```
|
|
3240
|
+
|
|
3241
|
+
3. Write your components and register them with your instance of `ComponentRegistry`
|
|
3242
|
+
|
|
3243
|
+
There's one difference when you are writing components that are to be shared, and that's that the components must be explicitly registered with your instance of `ComponentRegistry` from the previous step.
|
|
3244
|
+
|
|
3245
|
+
For better user experience, you can also define the types for the args, kwargs, slots and data.
|
|
3246
|
+
|
|
3247
|
+
It's also a good idea to have a common prefix for your components, so they can be easily distinguished from users' components. In the example below, we use the prefix `my_` / `My`.
|
|
3248
|
+
|
|
3249
|
+
```py
|
|
3250
|
+
from typing import Dict, NotRequired, Optional, Tuple, TypedDict
|
|
3251
|
+
|
|
3252
|
+
from django_components import Component, SlotFunc, register, types
|
|
3253
|
+
|
|
3254
|
+
from myapp.templatetags.mytags import comp_registry
|
|
3255
|
+
|
|
3256
|
+
# Define the types
|
|
3257
|
+
class EmptyDict(TypedDict):
|
|
3258
|
+
pass
|
|
3259
|
+
|
|
3260
|
+
type MyMenuArgs = Tuple[int, str]
|
|
3261
|
+
|
|
3262
|
+
class MyMenuSlots(TypedDict):
|
|
3263
|
+
default: NotRequired[Optional[SlotFunc[EmptyDict]]]
|
|
3264
|
+
|
|
3265
|
+
class MyMenuProps(TypedDict):
|
|
3266
|
+
vertical: NotRequired[bool]
|
|
3267
|
+
klass: NotRequired[str]
|
|
3268
|
+
style: NotRequired[str]
|
|
3269
|
+
|
|
3270
|
+
# Define the component
|
|
3271
|
+
# NOTE: Don't forget to set the `registry`!
|
|
3272
|
+
@register("my_menu", registry=comp_registry)
|
|
3273
|
+
class MyMenu(Component[MyMenuArgs, MyMenuProps, MyMenuSlots, Any]):
|
|
3274
|
+
def get_context_data(
|
|
3275
|
+
self,
|
|
3276
|
+
*args,
|
|
3277
|
+
attrs: Optional[Dict] = None,
|
|
3278
|
+
):
|
|
3279
|
+
return {
|
|
3280
|
+
"attrs": attrs,
|
|
3281
|
+
}
|
|
3282
|
+
|
|
3283
|
+
template: types.django_html = """
|
|
3284
|
+
{# Load django_components template tags #}
|
|
3285
|
+
{% load component_tags %}
|
|
3286
|
+
|
|
3287
|
+
<div {% html_attrs attrs class="my-menu" %}>
|
|
3288
|
+
<div class="my-menu__content">
|
|
3289
|
+
{% slot "default" default / %}
|
|
3290
|
+
</div>
|
|
3291
|
+
</div>
|
|
3292
|
+
"""
|
|
3293
|
+
```
|
|
3294
|
+
|
|
3295
|
+
4. Import the components in `apps.py`
|
|
3296
|
+
|
|
3297
|
+
Normally, users rely on [autodiscovery](#autodiscovery) and `STATICFILES_DIRS` to load the component files.
|
|
3298
|
+
|
|
3299
|
+
Since you, as the library author, are not in control of the file system, it is recommended to load the components manually.
|
|
3300
|
+
|
|
3301
|
+
We recommend doing this in the `AppConfig.ready()` hook of your `apps.py`:
|
|
3302
|
+
|
|
3303
|
+
```py
|
|
3304
|
+
from django.apps import AppConfig
|
|
3305
|
+
|
|
3306
|
+
class MyAppConfig(AppConfig):
|
|
3307
|
+
default_auto_field = "django.db.models.BigAutoField"
|
|
3308
|
+
name = "myapp"
|
|
3309
|
+
|
|
3310
|
+
# This is the code that gets run when user adds myapp
|
|
3311
|
+
# to Django's INSTALLED_APPS
|
|
3312
|
+
def ready(self) -> None:
|
|
3313
|
+
# Import the components that you want to make available
|
|
3314
|
+
# inside the templates.
|
|
3315
|
+
from myapp.templates import (
|
|
3316
|
+
menu,
|
|
3317
|
+
table,
|
|
3318
|
+
)
|
|
3319
|
+
```
|
|
3320
|
+
|
|
3321
|
+
Note that you can also include any other startup logic within `AppConfig.ready()`.
|
|
3322
|
+
|
|
3323
|
+
And that's it! The next step is to publish it.
|
|
3324
|
+
|
|
3325
|
+
### Publishing component libraries
|
|
3326
|
+
|
|
3327
|
+
Once you are ready to share your library, you need to build
|
|
3328
|
+
a distribution and then publish it to PyPI.
|
|
3329
|
+
|
|
3330
|
+
django_components uses the [`build`](https://build.pypa.io/en/stable/) utility to build a distribution:
|
|
3331
|
+
|
|
3332
|
+
```bash
|
|
3333
|
+
python -m build --sdist --wheel --outdir dist/ .
|
|
3334
|
+
```
|
|
3335
|
+
|
|
3336
|
+
And to publish to PyPI, you can use `twine` ([See Python user guide](https://packaging.python.org/en/latest/tutorials/packaging-projects/#uploading-the-distribution-archives))
|
|
3337
|
+
|
|
3338
|
+
```bash
|
|
3339
|
+
twine upload --repository pypi dist/* -u __token__ -p <PyPI_TOKEN>
|
|
3340
|
+
```
|
|
3341
|
+
|
|
3342
|
+
Notes on publishing:
|
|
3343
|
+
- The user of the package NEEDS to have installed and configured `django_components`.
|
|
3344
|
+
- If you use components where the HTML / CSS / JS files are separate, you may need to define `MANIFEST.in` to include those files with the distribution ([see user guide](https://setuptools.pypa.io/en/latest/userguide/miscellaneous.html)).
|
|
3345
|
+
|
|
3346
|
+
### Installing and using component libraries
|
|
3347
|
+
|
|
3348
|
+
After the package has been published, all that remains is to install it in other django projects:
|
|
3349
|
+
|
|
3350
|
+
1. Install the package:
|
|
3351
|
+
|
|
3352
|
+
```bash
|
|
3353
|
+
pip install myapp
|
|
3354
|
+
```
|
|
3355
|
+
|
|
3356
|
+
2. Add the package to `INSTALLED_APPS`
|
|
3357
|
+
|
|
3358
|
+
```py
|
|
3359
|
+
INSTALLED_APPS = [
|
|
3360
|
+
...
|
|
3361
|
+
"myapp",
|
|
3362
|
+
]
|
|
3363
|
+
```
|
|
3364
|
+
|
|
3365
|
+
3. Optionally add the template tags to the `builtins`, so you don't have to call `{% load mytags %}` in every template:
|
|
3366
|
+
|
|
3367
|
+
```py
|
|
3368
|
+
TEMPLATES = [
|
|
3369
|
+
{
|
|
3370
|
+
...,
|
|
3371
|
+
'OPTIONS': {
|
|
3372
|
+
'context_processors': [
|
|
3373
|
+
...
|
|
3374
|
+
],
|
|
3375
|
+
'builtins': [
|
|
3376
|
+
'myapp.templatetags.mytags',
|
|
3377
|
+
]
|
|
3378
|
+
},
|
|
3379
|
+
},
|
|
3380
|
+
]
|
|
3381
|
+
```
|
|
3382
|
+
|
|
3383
|
+
4. And, at last, you can use the components in your own project!
|
|
3384
|
+
|
|
3385
|
+
```django
|
|
3386
|
+
{% my_menu title="Abc..." %}
|
|
3387
|
+
Hello World!
|
|
3388
|
+
{% endmy_menu %}
|
|
3389
|
+
```
|
|
3390
|
+
|
|
2786
3391
|
## Community examples
|
|
2787
3392
|
|
|
2788
3393
|
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.
|