django-components 0.92__tar.gz → 0.93__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.93}/PKG-INFO +647 -130
- {django_components-0.92 → django_components-0.93}/README.md +647 -130
- {django_components-0.92 → django_components-0.93}/pyproject.toml +35 -1
- {django_components-0.92 → django_components-0.93}/src/django_components/__init__.py +8 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/attributes.py +23 -14
- {django_components-0.92 → django_components-0.93}/src/django_components/component.py +38 -43
- {django_components-0.92 → django_components-0.93}/src/django_components/component_registry.py +53 -5
- {django_components-0.92 → django_components-0.93}/src/django_components/context.py +2 -0
- django_components-0.93/src/django_components/expression.py +311 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/library.py +11 -8
- {django_components-0.92 → django_components-0.93}/src/django_components/node.py +19 -0
- django_components-0.93/src/django_components/provide.py +63 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/slots.py +175 -74
- {django_components-0.92 → django_components-0.93}/src/django_components/tag_formatter.py +7 -4
- {django_components-0.92 → django_components-0.93}/src/django_components/template_parser.py +1 -86
- {django_components-0.92 → django_components-0.93}/src/django_components/templatetags/component_tags.py +254 -181
- {django_components-0.92 → django_components-0.93}/src/django_components/types.py +4 -2
- {django_components-0.92 → django_components-0.93/src/django_components.egg-info}/PKG-INFO +647 -130
- {django_components-0.92 → django_components-0.93}/src/django_components.egg-info/SOURCES.txt +1 -0
- {django_components-0.92 → django_components-0.93}/tests/test_attributes.py +32 -0
- django_components-0.93/tests/test_expression.py +846 -0
- {django_components-0.92 → django_components-0.93}/tests/test_registry.py +82 -1
- {django_components-0.92 → django_components-0.93}/tests/test_template_parser.py +20 -19
- {django_components-0.92 → django_components-0.93}/tests/test_templatetags_provide.py +88 -8
- {django_components-0.92 → django_components-0.93}/tests/test_templatetags_slot_fill.py +164 -2
- 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.93}/LICENSE +0 -0
- {django_components-0.92 → django_components-0.93}/setup.cfg +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/app_settings.py +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/apps.py +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/autodiscover.py +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/component_media.py +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/logger.py +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/management/__init__.py +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/management/commands/__init__.py +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/management/commands/startcomponent.py +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/management/commands/upgradecomponent.py +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/middleware.py +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/py.typed +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/safer_staticfiles/__init__.py +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/safer_staticfiles/apps.py +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/template_loader.py +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/templatetags/__init__.py +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components/utils.py +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components.egg-info/dependency_links.txt +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components.egg-info/requires.txt +0 -0
- {django_components-0.92 → django_components-0.93}/src/django_components.egg-info/top_level.txt +0 -0
- {django_components-0.92 → django_components-0.93}/tests/test_autodiscover.py +0 -0
- {django_components-0.92 → django_components-0.93}/tests/test_command_startcomponent.py +0 -0
- {django_components-0.92 → django_components-0.93}/tests/test_component.py +0 -0
- {django_components-0.92 → django_components-0.93}/tests/test_component_as_view.py +0 -0
- {django_components-0.92 → django_components-0.93}/tests/test_component_media.py +0 -0
- {django_components-0.92 → django_components-0.93}/tests/test_context.py +0 -0
- {django_components-0.92 → django_components-0.93}/tests/test_dependency_rendering.py +0 -0
- {django_components-0.92 → django_components-0.93}/tests/test_safer_staticfiles.py +0 -0
- {django_components-0.92 → django_components-0.93}/tests/test_settings.py +0 -0
- {django_components-0.92 → django_components-0.93}/tests/test_tag_formatter.py +0 -0
- {django_components-0.92 → django_components-0.93}/tests/test_template_loader.py +0 -0
- {django_components-0.92 → django_components-0.93}/tests/test_templatetags.py +0 -0
- {django_components-0.92 → django_components-0.93}/tests/test_templatetags_component.py +0 -0
- {django_components-0.92 → django_components-0.93}/tests/test_templatetags_templating.py +0 -0
- {django_components-0.92 → django_components-0.93}/tests/test_utils.py +0 -0
- {django_components-0.92 → django_components-0.93}/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.93
|
|
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,8 +72,9 @@ 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)
|
|
@@ -67,13 +83,20 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
|
|
|
67
83
|
- [Available settings](#available-settings)
|
|
68
84
|
- [Logging and debugging](#logging-and-debugging)
|
|
69
85
|
- [Management Command](#management-command)
|
|
86
|
+
- [Writing and sharing component libraries](#writing-and-sharing-component-libraries)
|
|
70
87
|
- [Community examples](#community-examples)
|
|
71
88
|
- [Running django-components project locally](#running-django-components-project-locally)
|
|
72
89
|
- [Development guides](#development-guides)
|
|
73
90
|
|
|
74
91
|
## Release notes
|
|
75
92
|
|
|
76
|
-
|
|
93
|
+
**Version 0.93**
|
|
94
|
+
- Spread operator `...dict` inside template tags. See [Spread operator](#spread-operator))
|
|
95
|
+
- Use template tags inside string literals in component inputs. See [Use template tags inside component inputs](#use-template-tags-inside-component-inputs))
|
|
96
|
+
- Dynamic slots, fills and provides - The `name` argument for these can now be a variable, a template expression, or via spread operator
|
|
97
|
+
- Component library authors can now configure `CONTEXT_BEHAVIOR` and `TAG_FORMATTER` settings independently from user settings.
|
|
98
|
+
|
|
99
|
+
🚨📢 **Version 0.92**
|
|
77
100
|
- 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
101
|
|
|
79
102
|
- 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))
|
|
@@ -286,7 +309,7 @@ TEMPLATES = [
|
|
|
286
309
|
|
|
287
310
|
Read on to find out how to build your first component!
|
|
288
311
|
|
|
289
|
-
##
|
|
312
|
+
## Compatibility
|
|
290
313
|
|
|
291
314
|
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
315
|
|
|
@@ -318,9 +341,9 @@ A component in django-components is the combination of four things: CSS, Javascr
|
|
|
318
341
|
|
|
319
342
|
Start by creating empty files in the structure above.
|
|
320
343
|
|
|
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.
|
|
344
|
+
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
345
|
|
|
323
|
-
```css
|
|
346
|
+
```css title="[project root]/components/calendar/style.css"
|
|
324
347
|
/* In a file called [project root]/components/calendar/style.css */
|
|
325
348
|
.calendar-component {
|
|
326
349
|
width: 200px;
|
|
@@ -333,7 +356,7 @@ First you need a CSS file. Be sure to prefix all rules with a unique class so th
|
|
|
333
356
|
|
|
334
357
|
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
358
|
|
|
336
|
-
```js
|
|
359
|
+
```js title="[project root]/components/calendar/script.js"
|
|
337
360
|
/* In a file called [project root]/components/calendar/script.js */
|
|
338
361
|
(function () {
|
|
339
362
|
if (document.querySelector(".calendar-component")) {
|
|
@@ -346,7 +369,7 @@ Then you need a javascript file that specifies how you interact with this compon
|
|
|
346
369
|
|
|
347
370
|
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
371
|
|
|
349
|
-
```htmldjango
|
|
372
|
+
```htmldjango title="[project root]/components/calendar/calendar.html"
|
|
350
373
|
{# In a file called [project root]/components/calendar/template.html #}
|
|
351
374
|
<div class="calendar-component">Today's date is <span>{{ date }}</span></div>
|
|
352
375
|
```
|
|
@@ -355,7 +378,7 @@ Finally, we use django-components to tie this together. Start by creating a file
|
|
|
355
378
|
|
|
356
379
|
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
380
|
|
|
358
|
-
```python
|
|
381
|
+
```python title="[project root]/components/calendar/calendar.py"
|
|
359
382
|
# In a file called [project root]/components/calendar/calendar.py
|
|
360
383
|
from django_components import Component, register
|
|
361
384
|
|
|
@@ -386,7 +409,7 @@ And voilá!! We've created our first component.
|
|
|
386
409
|
|
|
387
410
|
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
411
|
|
|
389
|
-
```python
|
|
412
|
+
```python title="[project root]/components/calendar.py"
|
|
390
413
|
# In a file called [project root]/components/calendar.py
|
|
391
414
|
from django_components import Component, register, types
|
|
392
415
|
|
|
@@ -561,7 +584,7 @@ Component.render(
|
|
|
561
584
|
context: Mapping | django.template.Context | None = None,
|
|
562
585
|
args: List[Any] | None = None,
|
|
563
586
|
kwargs: Dict[str, Any] | None = None,
|
|
564
|
-
slots: Dict[str, str | SafeString |
|
|
587
|
+
slots: Dict[str, str | SafeString | SlotFunc] | None = None,
|
|
565
588
|
escape_slots_content: bool = True
|
|
566
589
|
) -> str:
|
|
567
590
|
```
|
|
@@ -574,7 +597,7 @@ Component.render(
|
|
|
574
597
|
|
|
575
598
|
- _`slots`_ - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.
|
|
576
599
|
Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string
|
|
577
|
-
or [`
|
|
600
|
+
or [`SlotFunc`](#slotfunc).
|
|
578
601
|
|
|
579
602
|
- _`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
603
|
|
|
@@ -583,7 +606,7 @@ Component.render(
|
|
|
583
606
|
- NOTE: In "isolated" mode, context is NOT accessible, and data MUST be passed via
|
|
584
607
|
component's args and kwargs.
|
|
585
608
|
|
|
586
|
-
#### `
|
|
609
|
+
#### `SlotFunc`
|
|
587
610
|
|
|
588
611
|
When rendering components with slots in `render` or `render_to_response`, you can pass either a string or a function.
|
|
589
612
|
|
|
@@ -622,28 +645,34 @@ MyComponent.render_to_response(
|
|
|
622
645
|
### Adding type hints with Generics
|
|
623
646
|
|
|
624
647
|
The `Component` class optionally accepts type parameters
|
|
625
|
-
that allow you to specify the types of args, kwargs, slots, and
|
|
648
|
+
that allow you to specify the types of args, kwargs, slots, and
|
|
626
649
|
data.
|
|
627
650
|
|
|
628
651
|
```py
|
|
629
|
-
from typing import NotRequired, Tuple, TypedDict
|
|
652
|
+
from typing import NotRequired, Tuple, TypedDict, SlotFunc
|
|
630
653
|
|
|
631
|
-
# Tuple
|
|
654
|
+
# Positional inputs - Tuple
|
|
632
655
|
Args = Tuple[int, str]
|
|
633
656
|
|
|
634
|
-
# Mapping
|
|
657
|
+
# Kwargs inputs - Mapping
|
|
635
658
|
class Kwargs(TypedDict):
|
|
636
659
|
variable: str
|
|
637
660
|
another: int
|
|
638
661
|
maybe_var: NotRequired[int]
|
|
639
662
|
|
|
640
|
-
# Mapping
|
|
663
|
+
# Data returned from `get_context_data` - Mapping
|
|
641
664
|
class Data(TypedDict):
|
|
642
665
|
variable: str
|
|
643
666
|
|
|
644
|
-
#
|
|
667
|
+
# The data available to the `my_slot` scoped slot
|
|
668
|
+
class MySlotData(TypedDict):
|
|
669
|
+
value: int
|
|
670
|
+
|
|
671
|
+
# Slot functions - Mapping
|
|
645
672
|
class Slots(TypedDict):
|
|
646
|
-
|
|
673
|
+
# Use SlotFunc for slot functions.
|
|
674
|
+
# The generic specifies the `data` dictionary
|
|
675
|
+
my_slot: NotRequired[SlotFunc[MySlotData]]
|
|
647
676
|
|
|
648
677
|
class Button(Component[Args, Kwargs, Data, Slots]):
|
|
649
678
|
def get_context_data(self, variable, another):
|
|
@@ -804,13 +833,13 @@ class ComponentView(View):
|
|
|
804
833
|
|
|
805
834
|
def post(self, request, *args, **kwargs):
|
|
806
835
|
return self.component.post(request, *args, **kwargs)
|
|
807
|
-
|
|
836
|
+
|
|
808
837
|
...
|
|
809
838
|
```
|
|
810
839
|
|
|
811
840
|
If you want to define your own `View` class, you need to:
|
|
812
841
|
1. Set the class as `Component.View`
|
|
813
|
-
2. Subclass from `ComponentView`, so the View instance has access to the component
|
|
842
|
+
2. Subclass from `ComponentView`, so the View instance has access to the component instance.
|
|
814
843
|
|
|
815
844
|
In the example below, we added extra logic into `View.setup()`.
|
|
816
845
|
|
|
@@ -929,8 +958,8 @@ registry.clear()
|
|
|
929
958
|
|
|
930
959
|
### Registering components to custom ComponentRegistry
|
|
931
960
|
|
|
932
|
-
|
|
933
|
-
|
|
961
|
+
If you are writing a component library to be shared with others, you may want to manage your own instance of `ComponentRegistry`
|
|
962
|
+
and register components onto a different `Library` instance than the default one.
|
|
934
963
|
|
|
935
964
|
The `Library` instance can be set at instantiation of `ComponentRegistry`. If omitted,
|
|
936
965
|
then the default Library instance from django_components is used.
|
|
@@ -957,6 +986,34 @@ class MyComponent(Component):
|
|
|
957
986
|
|
|
958
987
|
NOTE: The Library instance can be accessed under `library` attribute of `ComponentRegistry`.
|
|
959
988
|
|
|
989
|
+
### ComponentRegistry settings
|
|
990
|
+
|
|
991
|
+
When you are creating an instance of `ComponentRegistry`, you can define the components' behavior within the template.
|
|
992
|
+
|
|
993
|
+
The registry accepts these settings:
|
|
994
|
+
- `CONTEXT_BEHAVIOR`
|
|
995
|
+
- `TAG_FORMATTER`
|
|
996
|
+
|
|
997
|
+
```py
|
|
998
|
+
from django.template import Library
|
|
999
|
+
from django_components import ComponentRegistry, RegistrySettings
|
|
1000
|
+
|
|
1001
|
+
register = library = django.template.Library()
|
|
1002
|
+
comp_registry = ComponentRegistry(
|
|
1003
|
+
library=library,
|
|
1004
|
+
settings=RegistrySettings(
|
|
1005
|
+
CONTEXT_BEHAVIOR="isolated",
|
|
1006
|
+
TAG_FORMATTER="django_components.component_formatter",
|
|
1007
|
+
),
|
|
1008
|
+
)
|
|
1009
|
+
```
|
|
1010
|
+
|
|
1011
|
+
These settings are [the same as the ones you can set for django_components](#available-settings).
|
|
1012
|
+
|
|
1013
|
+
In fact, when you set `COMPONENT.tag_formatter` or `COMPONENT.context_behavior`, these are forwarded to the default `ComponentRegistry`.
|
|
1014
|
+
|
|
1015
|
+
This makes it possible to have multiple registries with different settings in one projects, and makes sharing of component libraries possible.
|
|
1016
|
+
|
|
960
1017
|
## Autodiscovery
|
|
961
1018
|
|
|
962
1019
|
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 +1056,7 @@ If you are using autodiscovery, keep a few points in mind:
|
|
|
999
1056
|
- Components inside the auto-imported files still need to be registered with `@register()`
|
|
1000
1057
|
- 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
1058
|
|
|
1002
|
-
Autodiscovery can be disabled in the [settings](#
|
|
1059
|
+
Autodiscovery can be disabled in the [settings](#autodiscover---toggle-autodiscovery).
|
|
1003
1060
|
|
|
1004
1061
|
### Manually trigger autodiscovery
|
|
1005
1062
|
|
|
@@ -1438,117 +1495,77 @@ to the same name. This raises an error:
|
|
|
1438
1495
|
{% endcomponent %}
|
|
1439
1496
|
```
|
|
1440
1497
|
|
|
1441
|
-
|
|
1498
|
+
### Dynamic slots and fills
|
|
1442
1499
|
|
|
1443
|
-
|
|
1500
|
+
Until now, we were declaring slot and fill names statically, as a string literal, e.g.
|
|
1444
1501
|
|
|
1445
1502
|
```django
|
|
1446
|
-
|
|
1447
|
-
{% component "calendar" date="2015-06-19" %}
|
|
1448
|
-
{% endcomponent %}
|
|
1449
|
-
</body>
|
|
1503
|
+
{% slot "content" / %}
|
|
1450
1504
|
```
|
|
1451
1505
|
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
_New in version 0.71_:
|
|
1506
|
+
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.
|
|
1455
1507
|
|
|
1456
|
-
|
|
1457
|
-
so are still valid:
|
|
1508
|
+
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
1509
|
|
|
1459
1510
|
```django
|
|
1460
|
-
<
|
|
1461
|
-
|
|
1462
|
-
|
|
1511
|
+
<table>
|
|
1512
|
+
<tr>
|
|
1513
|
+
{% for header in headers %}
|
|
1514
|
+
<th>
|
|
1515
|
+
{% slot "header-{{ header.key }}" value=header.title %}
|
|
1516
|
+
{{ header.title }}
|
|
1517
|
+
{% endslot %}
|
|
1518
|
+
</th>
|
|
1519
|
+
{% endfor %}
|
|
1520
|
+
</tr>
|
|
1521
|
+
</table>
|
|
1463
1522
|
```
|
|
1464
1523
|
|
|
1465
|
-
|
|
1524
|
+
When using the component, you can either set the fill explicitly:
|
|
1466
1525
|
|
|
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
|
-
}
|
|
1526
|
+
```django
|
|
1527
|
+
{% component "table" headers=headers items=items %}
|
|
1528
|
+
{% fill "header-name" data="data" %}
|
|
1529
|
+
<b>{{ data.value }}</b>
|
|
1530
|
+
{% endfill %}
|
|
1531
|
+
{% endcomponent %}
|
|
1478
1532
|
```
|
|
1479
1533
|
|
|
1480
|
-
|
|
1534
|
+
Or also use a variable:
|
|
1481
1535
|
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1536
|
+
```django
|
|
1537
|
+
{% component "table" headers=headers items=items %}
|
|
1538
|
+
{# Make only the active column bold #}
|
|
1539
|
+
{% fill "header-{{ active_header_name }}" data="data" %}
|
|
1540
|
+
<b>{{ data.value }}</b>
|
|
1541
|
+
{% endfill %}
|
|
1542
|
+
{% endcomponent %}
|
|
1543
|
+
```
|
|
1485
1544
|
|
|
1486
|
-
|
|
1487
|
-
of HTML attributes (usually called `attrs`) to pass to the underlying template.
|
|
1545
|
+
> 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
1546
|
|
|
1489
|
-
|
|
1490
|
-
But for that, we need to define this dictionary on Python side:
|
|
1547
|
+
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
1548
|
|
|
1492
|
-
|
|
1493
|
-
@register("my_comp")
|
|
1494
|
-
class MyComp(Component):
|
|
1495
|
-
template = """
|
|
1496
|
-
{% component "other" attrs=attrs / %}
|
|
1497
|
-
"""
|
|
1549
|
+
So this:
|
|
1498
1550
|
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
"class": "pa-4 flex",
|
|
1502
|
-
"data-some-id": some_id,
|
|
1503
|
-
"@click.stop": "onClickHandler",
|
|
1504
|
-
}
|
|
1505
|
-
return {"attrs": attrs}
|
|
1551
|
+
```django
|
|
1552
|
+
{% slot "content" / %}
|
|
1506
1553
|
```
|
|
1507
1554
|
|
|
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.
|
|
1513
|
-
|
|
1514
|
-
When we want to pass a dictionary to a component, we can define individual key-value pairs
|
|
1515
|
-
as component kwargs, so we can keep all the relevant information in the template. For that,
|
|
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
|
-
"""
|
|
1555
|
+
is the same as:
|
|
1529
1556
|
|
|
1530
|
-
|
|
1531
|
-
|
|
1557
|
+
```django
|
|
1558
|
+
{% slot name="content" / %}
|
|
1532
1559
|
```
|
|
1533
1560
|
|
|
1534
|
-
|
|
1561
|
+
So it's possible to define a `name` key on a dictionary, and then spread that onto the slot tag:
|
|
1535
1562
|
|
|
1536
1563
|
```django
|
|
1537
|
-
{
|
|
1538
|
-
|
|
1539
|
-
attrs:data-some-id=some_id
|
|
1540
|
-
attrs:@click.stop="onClickHandler"
|
|
1541
|
-
/ %}
|
|
1564
|
+
{# slot_props = {"name": "content"} #}
|
|
1565
|
+
{% slot ...slot_props / %}
|
|
1542
1566
|
```
|
|
1543
1567
|
|
|
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
|
|
1568
|
+
## Accessing data passed to the component
|
|
1552
1569
|
|
|
1553
1570
|
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
1571
|
|
|
@@ -1956,6 +1973,266 @@ attributes_to_string(attrs)
|
|
|
1956
1973
|
# 'class="my-class text-red pa-4" data-id="123" required'
|
|
1957
1974
|
```
|
|
1958
1975
|
|
|
1976
|
+
## Template tag syntax
|
|
1977
|
+
|
|
1978
|
+
All template tags in django_component, like `{% component %}` or `{% slot %}`, and so on,
|
|
1979
|
+
support extra syntax that makes it possible to write components like in Vue or React (JSX).
|
|
1980
|
+
|
|
1981
|
+
### Self-closing tags
|
|
1982
|
+
|
|
1983
|
+
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 %}`:
|
|
1984
|
+
|
|
1985
|
+
So this:
|
|
1986
|
+
|
|
1987
|
+
```django
|
|
1988
|
+
{% component "button" %}{% endcomponent %}
|
|
1989
|
+
```
|
|
1990
|
+
|
|
1991
|
+
becomes
|
|
1992
|
+
|
|
1993
|
+
```django
|
|
1994
|
+
{% component "button" / %}
|
|
1995
|
+
```
|
|
1996
|
+
|
|
1997
|
+
### Special characters
|
|
1998
|
+
|
|
1999
|
+
_New in version 0.71_:
|
|
2000
|
+
|
|
2001
|
+
Keyword arguments can contain special characters `# @ . - _`, so keywords like
|
|
2002
|
+
so are still valid:
|
|
2003
|
+
|
|
2004
|
+
```django
|
|
2005
|
+
<body>
|
|
2006
|
+
{% component "calendar" my-date="2015-06-19" @click.native=do_something #some_id=True / %}
|
|
2007
|
+
</body>
|
|
2008
|
+
```
|
|
2009
|
+
|
|
2010
|
+
These can then be accessed inside `get_context_data` so:
|
|
2011
|
+
|
|
2012
|
+
```py
|
|
2013
|
+
@register("calendar")
|
|
2014
|
+
class Calendar(Component):
|
|
2015
|
+
# Since # . @ - are not valid identifiers, we have to
|
|
2016
|
+
# use `**kwargs` so the method can accept these args.
|
|
2017
|
+
def get_context_data(self, **kwargs):
|
|
2018
|
+
return {
|
|
2019
|
+
"date": kwargs["my-date"],
|
|
2020
|
+
"id": kwargs["#some_id"],
|
|
2021
|
+
"on_click": kwargs["@click.native"]
|
|
2022
|
+
}
|
|
2023
|
+
```
|
|
2024
|
+
|
|
2025
|
+
### Spread operator
|
|
2026
|
+
|
|
2027
|
+
_New in version 0.93_:
|
|
2028
|
+
|
|
2029
|
+
Instead of passing keyword arguments one-by-one:
|
|
2030
|
+
|
|
2031
|
+
```django
|
|
2032
|
+
{% component "calendar" title="How to abc" date="2015-06-19" author="John Wick" / %}
|
|
2033
|
+
```
|
|
2034
|
+
|
|
2035
|
+
You can use a spread operator `...dict` to apply key-value pairs from a dictionary:
|
|
2036
|
+
|
|
2037
|
+
```py
|
|
2038
|
+
post_data = {
|
|
2039
|
+
"title": "How to...",
|
|
2040
|
+
"date": "2015-06-19",
|
|
2041
|
+
"author": "John Wick",
|
|
2042
|
+
}
|
|
2043
|
+
```
|
|
2044
|
+
|
|
2045
|
+
```django
|
|
2046
|
+
{% component "calendar" ...post_data / %}
|
|
2047
|
+
```
|
|
2048
|
+
|
|
2049
|
+
This behaves similar to [JSX's spread operator](https://kevinyckim33.medium.com/jsx-spread-operator-component-props-meaning-3c9bcadd2493)
|
|
2050
|
+
or [Vue's `v-bind`](https://vuejs.org/api/built-in-directives.html#v-bind).
|
|
2051
|
+
|
|
2052
|
+
Spread operators are treated as keyword arguments, which means that:
|
|
2053
|
+
1. Spread operators must come after positional arguments.
|
|
2054
|
+
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).
|
|
2055
|
+
|
|
2056
|
+
Other than that, you can use spread operators multiple times, and even put keyword arguments in-between or after them:
|
|
2057
|
+
|
|
2058
|
+
```django
|
|
2059
|
+
{% component "calendar" ...post_data id=post.id ...extra / %}
|
|
2060
|
+
```
|
|
2061
|
+
|
|
2062
|
+
In a case of conflicts, the values added later (right-most) overwrite previous values.
|
|
2063
|
+
|
|
2064
|
+
### Use template tags inside component inputs
|
|
2065
|
+
|
|
2066
|
+
_New in version 0.93_
|
|
2067
|
+
|
|
2068
|
+
When passing data around, sometimes you may need to do light transformations, like negating booleans or filtering lists.
|
|
2069
|
+
|
|
2070
|
+
Normally, what you would have to do is to define ALL the variables
|
|
2071
|
+
inside `get_context_data()`. But this can get messy if your components contain a lot of logic.
|
|
2072
|
+
|
|
2073
|
+
```py
|
|
2074
|
+
@register("calendar")
|
|
2075
|
+
class Calendar(Component):
|
|
2076
|
+
def get_context_data(self, id: str, editable: bool):
|
|
2077
|
+
return {
|
|
2078
|
+
"editable": editable,
|
|
2079
|
+
"readonly": not editable,
|
|
2080
|
+
"input_id": f"input-{id}",
|
|
2081
|
+
"icon_id": f"icon-{id}",
|
|
2082
|
+
...
|
|
2083
|
+
}
|
|
2084
|
+
```
|
|
2085
|
+
|
|
2086
|
+
Instead, template tags in django_components (`{% component %}`, `{% slot %}`, `{% provide %}`, etc) allow you to treat literal string values as templates:
|
|
2087
|
+
|
|
2088
|
+
```django
|
|
2089
|
+
{% component 'blog_post'
|
|
2090
|
+
"As positional arg {# yay #}"
|
|
2091
|
+
title="{{ person.first_name }} {{ person.last_name }}"
|
|
2092
|
+
id="{% random_int 10 20 %}"
|
|
2093
|
+
readonly="{{ editable|not }}"
|
|
2094
|
+
author="John Wick {# TODO: parametrize #}"
|
|
2095
|
+
/ %}
|
|
2096
|
+
```
|
|
2097
|
+
|
|
2098
|
+
In the example above:
|
|
2099
|
+
- Component `test` receives a positional argument with value `"As positional arg "`. The comment is omitted.
|
|
2100
|
+
- Kwarg `title` is passed as a string, e.g. `John Doe`
|
|
2101
|
+
- Kwarg `id` is passed as `int`, e.g. `15`
|
|
2102
|
+
- Kwarg `readonly` is passed as `bool`, e.g. `False`
|
|
2103
|
+
- Kwarg `author` is passed as a string, e.g. `John Wick ` (Comment omitted)
|
|
2104
|
+
|
|
2105
|
+
This is inspired by [django-cotton](https://github.com/wrabit/django-cotton#template-expressions-in-attributes).
|
|
2106
|
+
|
|
2107
|
+
#### Passing data as string vs original values
|
|
2108
|
+
|
|
2109
|
+
Sometimes you may want to use the template tags to transform
|
|
2110
|
+
or generate the data that is then passed to the component.
|
|
2111
|
+
|
|
2112
|
+
The data doesn't necessarily have to be strings. In the example above, the kwarg `id` was passed as an integer, NOT a string.
|
|
2113
|
+
|
|
2114
|
+
Although the string literals for components inputs are treated as regular Django templates, there is one special case:
|
|
2115
|
+
|
|
2116
|
+
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.
|
|
2117
|
+
|
|
2118
|
+
Here, `page` is an integer:
|
|
2119
|
+
|
|
2120
|
+
```django
|
|
2121
|
+
{% component 'blog_post' page="{% random_int 10 20 %}" / %}
|
|
2122
|
+
```
|
|
2123
|
+
|
|
2124
|
+
Here, `page` is a string:
|
|
2125
|
+
|
|
2126
|
+
```django
|
|
2127
|
+
{% component 'blog_post' page=" {% random_int 10 20 %} " / %}
|
|
2128
|
+
```
|
|
2129
|
+
|
|
2130
|
+
And same applies to the `{{ }}` variable tags:
|
|
2131
|
+
|
|
2132
|
+
Here, `items` is a list:
|
|
2133
|
+
|
|
2134
|
+
```django
|
|
2135
|
+
{% component 'cat_list' items="{{ cats|slice:':2' }}" / %}
|
|
2136
|
+
```
|
|
2137
|
+
|
|
2138
|
+
Here, `items` is a string:
|
|
2139
|
+
|
|
2140
|
+
```django
|
|
2141
|
+
{% component 'cat_list' items="{{ cats|slice:':2' }} See more" / %}
|
|
2142
|
+
```
|
|
2143
|
+
|
|
2144
|
+
#### Evaluating Python expressions in template
|
|
2145
|
+
|
|
2146
|
+
You can even go a step further and have a similar experience to Vue or React,
|
|
2147
|
+
where you can evaluate arbitrary code expressions:
|
|
2148
|
+
|
|
2149
|
+
```jsx
|
|
2150
|
+
<MyForm
|
|
2151
|
+
value={ isEnabled ? inputValue : null }
|
|
2152
|
+
/>
|
|
2153
|
+
```
|
|
2154
|
+
|
|
2155
|
+
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:
|
|
2156
|
+
|
|
2157
|
+
```django
|
|
2158
|
+
{% component "my_form"
|
|
2159
|
+
value="{% expr 'input_value if is_enabled else None' %}"
|
|
2160
|
+
/ %}
|
|
2161
|
+
```
|
|
2162
|
+
|
|
2163
|
+
> Note: Never use this feature to mix business logic and template logic. Business logic should still be in the view!
|
|
2164
|
+
|
|
2165
|
+
### Pass dictonary by its key-value pairs
|
|
2166
|
+
|
|
2167
|
+
_New in version 0.74_:
|
|
2168
|
+
|
|
2169
|
+
Sometimes, a component may expect a dictionary as one of its inputs.
|
|
2170
|
+
|
|
2171
|
+
Most commonly, this happens when a component accepts a dictionary
|
|
2172
|
+
of HTML attributes (usually called `attrs`) to pass to the underlying template.
|
|
2173
|
+
|
|
2174
|
+
In such cases, we may want to define some HTML attributes statically, and other dynamically.
|
|
2175
|
+
But for that, we need to define this dictionary on Python side:
|
|
2176
|
+
|
|
2177
|
+
```py
|
|
2178
|
+
@register("my_comp")
|
|
2179
|
+
class MyComp(Component):
|
|
2180
|
+
template = """
|
|
2181
|
+
{% component "other" attrs=attrs / %}
|
|
2182
|
+
"""
|
|
2183
|
+
|
|
2184
|
+
def get_context_data(self, some_id: str):
|
|
2185
|
+
attrs = {
|
|
2186
|
+
"class": "pa-4 flex",
|
|
2187
|
+
"data-some-id": some_id,
|
|
2188
|
+
"@click.stop": "onClickHandler",
|
|
2189
|
+
}
|
|
2190
|
+
return {"attrs": attrs}
|
|
2191
|
+
```
|
|
2192
|
+
|
|
2193
|
+
But as you can see in the case above, the event handler `@click.stop` and styling `pa-4 flex`
|
|
2194
|
+
are disconnected from the template. If the component grew in size and we moved the HTML
|
|
2195
|
+
to a separate file, we would have hard time reasoning about the component's template.
|
|
2196
|
+
|
|
2197
|
+
Luckily, there's a better way.
|
|
2198
|
+
|
|
2199
|
+
When we want to pass a dictionary to a component, we can define individual key-value pairs
|
|
2200
|
+
as component kwargs, so we can keep all the relevant information in the template. For that,
|
|
2201
|
+
we prefix the key with the name of the dict and `:`. So key `class` of input `attrs` becomes
|
|
2202
|
+
`attrs:class`. And our example becomes:
|
|
2203
|
+
|
|
2204
|
+
```py
|
|
2205
|
+
@register("my_comp")
|
|
2206
|
+
class MyComp(Component):
|
|
2207
|
+
template = """
|
|
2208
|
+
{% component "other"
|
|
2209
|
+
attrs:class="pa-4 flex"
|
|
2210
|
+
attrs:data-some-id=some_id
|
|
2211
|
+
attrs:@click.stop="onClickHandler"
|
|
2212
|
+
/ %}
|
|
2213
|
+
"""
|
|
2214
|
+
|
|
2215
|
+
def get_context_data(self, some_id: str):
|
|
2216
|
+
return {"some_id": some_id}
|
|
2217
|
+
```
|
|
2218
|
+
|
|
2219
|
+
Sweet! Now all the relevant HTML is inside the template, and we can move it to a separate file with confidence:
|
|
2220
|
+
|
|
2221
|
+
```django
|
|
2222
|
+
{% component "other"
|
|
2223
|
+
attrs:class="pa-4 flex"
|
|
2224
|
+
attrs:data-some-id=some_id
|
|
2225
|
+
attrs:@click.stop="onClickHandler"
|
|
2226
|
+
/ %}
|
|
2227
|
+
```
|
|
2228
|
+
|
|
2229
|
+
> Note: It is NOT possible to define nested dictionaries, so
|
|
2230
|
+
> `attrs:my_key:two=2` would be interpreted as:
|
|
2231
|
+
>
|
|
2232
|
+
> ```py
|
|
2233
|
+
> {"attrs": {"my_key:two": 2}}
|
|
2234
|
+
> ```
|
|
2235
|
+
|
|
1959
2236
|
## Prop drilling and dependency injection (provide / inject)
|
|
1960
2237
|
|
|
1961
2238
|
_New in version 0.80_:
|
|
@@ -2002,10 +2279,7 @@ First we use the `{% provide %}` tag to define the data we want to "provide" (ma
|
|
|
2002
2279
|
|
|
2003
2280
|
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
2281
|
|
|
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)
|
|
2282
|
+
`provide` tag name must resolve to a valid identifier (AKA a valid Python variable name).
|
|
2009
2283
|
|
|
2010
2284
|
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
2285
|
|
|
@@ -2018,6 +2292,15 @@ Once you've set the name, you define the data you want to "provide" by passing i
|
|
|
2018
2292
|
> {% endprovide %}
|
|
2019
2293
|
> ```
|
|
2020
2294
|
|
|
2295
|
+
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:
|
|
2296
|
+
|
|
2297
|
+
```django
|
|
2298
|
+
{% provide name=name ... %}
|
|
2299
|
+
...
|
|
2300
|
+
{% provide %}
|
|
2301
|
+
</table>
|
|
2302
|
+
```
|
|
2303
|
+
|
|
2021
2304
|
### Using `inject()` method
|
|
2022
2305
|
|
|
2023
2306
|
To "inject" (access) the data defined on the `provide` tag, you can use the `inject()` method inside of `get_context_data()`.
|
|
@@ -2035,7 +2318,7 @@ class ChildComponent(Component):
|
|
|
2035
2318
|
return {}
|
|
2036
2319
|
```
|
|
2037
2320
|
|
|
2038
|
-
First argument to `inject` is the _key_ of the provided data. This
|
|
2321
|
+
First argument to `inject` is the _key_ (or _name_) of the provided data. This
|
|
2039
2322
|
must match the string that you used in the `provide` tag. If no provider
|
|
2040
2323
|
with given key is found, `inject` raises a `KeyError`.
|
|
2041
2324
|
|
|
@@ -2092,7 +2375,7 @@ With this in mind, the `{% component %}` tag behaves similarly to `{% include %}
|
|
|
2092
2375
|
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
2376
|
|
|
2094
2377
|
```htmldjango
|
|
2095
|
-
{% component "calendar" date="2015-06-19" only
|
|
2378
|
+
{% component "calendar" date="2015-06-19" only / %}
|
|
2096
2379
|
```
|
|
2097
2380
|
|
|
2098
2381
|
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 +2773,9 @@ COMPONENTS = {
|
|
|
2490
2773
|
|
|
2491
2774
|
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
2775
|
|
|
2493
|
-
###
|
|
2776
|
+
### `libraries` - Load component modules
|
|
2494
2777
|
|
|
2495
|
-
Configure the
|
|
2778
|
+
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
2779
|
|
|
2497
2780
|
```python
|
|
2498
2781
|
COMPONENTS = {
|
|
@@ -2532,7 +2815,7 @@ from django_components import import_libraries
|
|
|
2532
2815
|
import_libraries()
|
|
2533
2816
|
```
|
|
2534
2817
|
|
|
2535
|
-
###
|
|
2818
|
+
### `autodiscover` - Toggle autodiscovery
|
|
2536
2819
|
|
|
2537
2820
|
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
2821
|
|
|
@@ -2542,9 +2825,11 @@ COMPONENTS = {
|
|
|
2542
2825
|
}
|
|
2543
2826
|
```
|
|
2544
2827
|
|
|
2545
|
-
### Tune the template cache
|
|
2828
|
+
### `template_cache_size` - Tune the template cache
|
|
2829
|
+
|
|
2830
|
+
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
2831
|
|
|
2547
|
-
|
|
2832
|
+
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
2833
|
|
|
2549
2834
|
```python
|
|
2550
2835
|
COMPONENTS = {
|
|
@@ -2552,7 +2837,7 @@ COMPONENTS = {
|
|
|
2552
2837
|
}
|
|
2553
2838
|
```
|
|
2554
2839
|
|
|
2555
|
-
###
|
|
2840
|
+
### `context_behavior` - Make components isolated (or not)
|
|
2556
2841
|
|
|
2557
2842
|
> NOTE: `context_behavior` and `slot_context_behavior` options were merged in v0.70.
|
|
2558
2843
|
>
|
|
@@ -2657,9 +2942,8 @@ But since `"cheese"` is not defined there, it's empty.
|
|
|
2657
2942
|
|
|
2658
2943
|
Notice that the variables defined with the `{% with %}` tag are ignored inside the `{% fill %}` tag with the `"isolated"` mode.
|
|
2659
2944
|
|
|
2660
|
-
###
|
|
2661
|
-
|
|
2662
|
-
Set the [`TagFormatter`](#available-tagformatters) instance.
|
|
2945
|
+
### `tag_formatter` - Change how components are used in templates
|
|
2946
|
+
Sets the [`TagFormatter`](#available-tagformatters) instance. See the section [Customizing component tags with TagFormatter](#customizing-component-tags-with-tagformatter).
|
|
2663
2947
|
|
|
2664
2948
|
Can be set either as direct reference, or as an import string;
|
|
2665
2949
|
|
|
@@ -2783,6 +3067,239 @@ python manage.py startcomponent my_component --dry-run
|
|
|
2783
3067
|
|
|
2784
3068
|
This will simulate the creation of `my_component` without creating any files.
|
|
2785
3069
|
|
|
3070
|
+
## Writing and sharing component libraries
|
|
3071
|
+
|
|
3072
|
+
You can publish and share your components for others to use. Here are the steps to do so:
|
|
3073
|
+
|
|
3074
|
+
### Writing component libraries
|
|
3075
|
+
|
|
3076
|
+
1. Create a Django project with the following structure:
|
|
3077
|
+
|
|
3078
|
+
```txt
|
|
3079
|
+
project/
|
|
3080
|
+
|-- myapp/
|
|
3081
|
+
|-- __init__.py
|
|
3082
|
+
|-- apps.py
|
|
3083
|
+
|-- templates/
|
|
3084
|
+
|-- table/
|
|
3085
|
+
|-- table.py
|
|
3086
|
+
|-- table.js
|
|
3087
|
+
|-- table.css
|
|
3088
|
+
|-- table.html
|
|
3089
|
+
|-- menu.py <--- single-file component
|
|
3090
|
+
|-- templatetags/
|
|
3091
|
+
|-- __init__.py
|
|
3092
|
+
|-- mytags.py
|
|
3093
|
+
```
|
|
3094
|
+
|
|
3095
|
+
2. Create custom `Library` and `ComponentRegistry` instances in `mytags.py`
|
|
3096
|
+
|
|
3097
|
+
This will be the entrypoint for using the components inside Django templates.
|
|
3098
|
+
|
|
3099
|
+
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)):
|
|
3100
|
+
|
|
3101
|
+
```py
|
|
3102
|
+
from django.template import Library
|
|
3103
|
+
from django_components import ComponentRegistry, RegistrySettings
|
|
3104
|
+
|
|
3105
|
+
register = library = django.template.Library()
|
|
3106
|
+
comp_registry = ComponentRegistry(
|
|
3107
|
+
library=library,
|
|
3108
|
+
settings=RegistrySettings(
|
|
3109
|
+
CONTEXT_BEHAVIOR="isolated",
|
|
3110
|
+
TAG_FORMATTER="django_components.component_formatter",
|
|
3111
|
+
),
|
|
3112
|
+
)
|
|
3113
|
+
```
|
|
3114
|
+
|
|
3115
|
+
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.
|
|
3116
|
+
|
|
3117
|
+
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.
|
|
3118
|
+
|
|
3119
|
+
Next, you can decide how will others use your components by settingt the `TAG_FORMATTER` options.
|
|
3120
|
+
|
|
3121
|
+
If omitted or set to `"django_components.component_formatter"`,
|
|
3122
|
+
your components will be used like this:
|
|
3123
|
+
|
|
3124
|
+
```django
|
|
3125
|
+
{% component "table" items=items headers=headers %}
|
|
3126
|
+
{% endcomponent %}
|
|
3127
|
+
```
|
|
3128
|
+
|
|
3129
|
+
Or you can use `"django_components.component_shorthand_formatter"`
|
|
3130
|
+
to use components like so:
|
|
3131
|
+
|
|
3132
|
+
```django
|
|
3133
|
+
{% table items=items headers=headers %}
|
|
3134
|
+
{% endtable %}
|
|
3135
|
+
```
|
|
3136
|
+
|
|
3137
|
+
Or you can define a [custom TagFormatter](#tagformatter).
|
|
3138
|
+
|
|
3139
|
+
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:
|
|
3140
|
+
|
|
3141
|
+
```django
|
|
3142
|
+
{% load mytags %}
|
|
3143
|
+
|
|
3144
|
+
{# Component from your library "mytags", using the "shorthand" formatter #}
|
|
3145
|
+
{% table items=items headers=header %}
|
|
3146
|
+
{% endtable %}
|
|
3147
|
+
|
|
3148
|
+
{# User-created components using the default settings #}
|
|
3149
|
+
{% component "my_comp" title="Abc..." %}
|
|
3150
|
+
{% endcomponent %}
|
|
3151
|
+
```
|
|
3152
|
+
|
|
3153
|
+
3. Write your components and register them with your instance of `ComponentRegistry`
|
|
3154
|
+
|
|
3155
|
+
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.
|
|
3156
|
+
|
|
3157
|
+
For better user experience, you can also define the types for the args, kwargs, slots and data.
|
|
3158
|
+
|
|
3159
|
+
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`.
|
|
3160
|
+
|
|
3161
|
+
```py
|
|
3162
|
+
from typing import Dict, NotRequired, Optional, Tuple, TypedDict
|
|
3163
|
+
|
|
3164
|
+
from django_components import Component, SlotFunc, register, types
|
|
3165
|
+
|
|
3166
|
+
from myapp.templatetags.mytags import comp_registry
|
|
3167
|
+
|
|
3168
|
+
# Define the types
|
|
3169
|
+
class EmptyDict(TypedDict):
|
|
3170
|
+
pass
|
|
3171
|
+
|
|
3172
|
+
type MyMenuArgs = Tuple[int, str]
|
|
3173
|
+
|
|
3174
|
+
class MyMenuSlots(TypedDict):
|
|
3175
|
+
default: NotRequired[Optional[SlotFunc[EmptyDict]]]
|
|
3176
|
+
|
|
3177
|
+
class MyMenuProps(TypedDict):
|
|
3178
|
+
vertical: NotRequired[bool]
|
|
3179
|
+
klass: NotRequired[str]
|
|
3180
|
+
style: NotRequired[str]
|
|
3181
|
+
|
|
3182
|
+
# Define the component
|
|
3183
|
+
# NOTE: Don't forget to set the `registry`!
|
|
3184
|
+
@register("my_menu", registry=comp_registry)
|
|
3185
|
+
class MyMenu(Component[MyMenuArgs, MyMenuProps, MyMenuSlots, Any]):
|
|
3186
|
+
def get_context_data(
|
|
3187
|
+
self,
|
|
3188
|
+
*args,
|
|
3189
|
+
attrs: Optional[Dict] = None,
|
|
3190
|
+
):
|
|
3191
|
+
return {
|
|
3192
|
+
"attrs": attrs,
|
|
3193
|
+
}
|
|
3194
|
+
|
|
3195
|
+
template: types.django_html = """
|
|
3196
|
+
{# Load django_components template tags #}
|
|
3197
|
+
{% load component_tags %}
|
|
3198
|
+
|
|
3199
|
+
<div {% html_attrs attrs class="my-menu" %}>
|
|
3200
|
+
<div class="my-menu__content">
|
|
3201
|
+
{% slot "default" default / %}
|
|
3202
|
+
</div>
|
|
3203
|
+
</div>
|
|
3204
|
+
"""
|
|
3205
|
+
```
|
|
3206
|
+
|
|
3207
|
+
4. Import the components in `apps.py`
|
|
3208
|
+
|
|
3209
|
+
Normally, users rely on [autodiscovery](#autodiscovery) and `STATICFILES_DIRS` to load the component files.
|
|
3210
|
+
|
|
3211
|
+
Since you, as the library author, are not in control of the file system, it is recommended to load the components manually.
|
|
3212
|
+
|
|
3213
|
+
We recommend doing this in the `AppConfig.ready()` hook of your `apps.py`:
|
|
3214
|
+
|
|
3215
|
+
```py
|
|
3216
|
+
from django.apps import AppConfig
|
|
3217
|
+
|
|
3218
|
+
class MyAppConfig(AppConfig):
|
|
3219
|
+
default_auto_field = "django.db.models.BigAutoField"
|
|
3220
|
+
name = "myapp"
|
|
3221
|
+
|
|
3222
|
+
# This is the code that gets run when user adds myapp
|
|
3223
|
+
# to Django's INSTALLED_APPS
|
|
3224
|
+
def ready(self) -> None:
|
|
3225
|
+
# Import the components that you want to make available
|
|
3226
|
+
# inside the templates.
|
|
3227
|
+
from myapp.templates import (
|
|
3228
|
+
menu,
|
|
3229
|
+
table,
|
|
3230
|
+
)
|
|
3231
|
+
```
|
|
3232
|
+
|
|
3233
|
+
Note that you can also include any other startup logic within `AppConfig.ready()`.
|
|
3234
|
+
|
|
3235
|
+
And that's it! The next step is to publish it.
|
|
3236
|
+
|
|
3237
|
+
### Publishing component libraries
|
|
3238
|
+
|
|
3239
|
+
Once you are ready to share your library, you need to build
|
|
3240
|
+
a distribution and then publish it to PyPI.
|
|
3241
|
+
|
|
3242
|
+
django_components uses the [`build`](https://build.pypa.io/en/stable/) utility to build a distribution:
|
|
3243
|
+
|
|
3244
|
+
```bash
|
|
3245
|
+
python -m build --sdist --wheel --outdir dist/ .
|
|
3246
|
+
```
|
|
3247
|
+
|
|
3248
|
+
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))
|
|
3249
|
+
|
|
3250
|
+
```bash
|
|
3251
|
+
twine upload --repository pypi dist/* -u __token__ -p <PyPI_TOKEN>
|
|
3252
|
+
```
|
|
3253
|
+
|
|
3254
|
+
Notes on publishing:
|
|
3255
|
+
- The user of the package NEEDS to have installed and configured `django_components`.
|
|
3256
|
+
- 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)).
|
|
3257
|
+
|
|
3258
|
+
### Installing and using component libraries
|
|
3259
|
+
|
|
3260
|
+
After the package has been published, all that remains is to install it in other django projects:
|
|
3261
|
+
|
|
3262
|
+
1. Install the package:
|
|
3263
|
+
|
|
3264
|
+
```bash
|
|
3265
|
+
pip install myapp
|
|
3266
|
+
```
|
|
3267
|
+
|
|
3268
|
+
2. Add the package to `INSTALLED_APPS`
|
|
3269
|
+
|
|
3270
|
+
```py
|
|
3271
|
+
INSTALLED_APPS = [
|
|
3272
|
+
...
|
|
3273
|
+
"myapp",
|
|
3274
|
+
]
|
|
3275
|
+
```
|
|
3276
|
+
|
|
3277
|
+
3. Optionally add the template tags to the `builtins`, so you don't have to call `{% load mytags %}` in every template:
|
|
3278
|
+
|
|
3279
|
+
```py
|
|
3280
|
+
TEMPLATES = [
|
|
3281
|
+
{
|
|
3282
|
+
...,
|
|
3283
|
+
'OPTIONS': {
|
|
3284
|
+
'context_processors': [
|
|
3285
|
+
...
|
|
3286
|
+
],
|
|
3287
|
+
'builtins': [
|
|
3288
|
+
'myapp.templatetags.mytags',
|
|
3289
|
+
]
|
|
3290
|
+
},
|
|
3291
|
+
},
|
|
3292
|
+
]
|
|
3293
|
+
```
|
|
3294
|
+
|
|
3295
|
+
4. And, at last, you can use the components in your own project!
|
|
3296
|
+
|
|
3297
|
+
```django
|
|
3298
|
+
{% my_menu title="Abc..." %}
|
|
3299
|
+
Hello World!
|
|
3300
|
+
{% endmy_menu %}
|
|
3301
|
+
```
|
|
3302
|
+
|
|
2786
3303
|
## Community examples
|
|
2787
3304
|
|
|
2788
3305
|
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.
|