django-components 0.79__tar.gz → 0.81__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.79/src/django_components.egg-info → django_components-0.81}/PKG-INFO +268 -4
- {django_components-0.79 → django_components-0.81}/README.md +267 -3
- {django_components-0.79 → django_components-0.81}/pyproject.toml +1 -1
- {django_components-0.79 → django_components-0.81}/src/django_components/component.py +327 -111
- {django_components-0.79 → django_components-0.81}/src/django_components/component_registry.py +1 -1
- django_components-0.81/src/django_components/context.py +136 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/logger.py +1 -1
- django_components-0.81/src/django_components/provide.py +52 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/slots.py +31 -16
- {django_components-0.79 → django_components-0.81}/src/django_components/templatetags/component_tags.py +51 -0
- {django_components-0.79 → django_components-0.81/src/django_components.egg-info}/PKG-INFO +268 -4
- {django_components-0.79 → django_components-0.81}/src/django_components.egg-info/SOURCES.txt +2 -0
- django_components-0.81/tests/test_component.py +511 -0
- {django_components-0.79 → django_components-0.81}/tests/test_component_as_view.py +8 -8
- {django_components-0.79 → django_components-0.81}/tests/test_component_media.py +2 -4
- {django_components-0.79 → django_components-0.81}/tests/test_templatetags.py +39 -0
- django_components-0.81/tests/test_templatetags_provide.py +601 -0
- django_components-0.79/src/django_components/context.py +0 -64
- django_components-0.79/tests/test_component.py +0 -128
- {django_components-0.79 → django_components-0.81}/LICENSE +0 -0
- {django_components-0.79 → django_components-0.81}/setup.cfg +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/__init__.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/app_settings.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/apps.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/attributes.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/expression.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/management/__init__.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/management/commands/__init__.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/management/commands/startcomponent.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/management/commands/upgradecomponent.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/middleware.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/node.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/py.typed +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/safer_staticfiles/__init__.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/safer_staticfiles/apps.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/template_loader.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/template_parser.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/templatetags/__init__.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/types.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components/utils.py +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components.egg-info/dependency_links.txt +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components.egg-info/requires.txt +0 -0
- {django_components-0.79 → django_components-0.81}/src/django_components.egg-info/top_level.txt +0 -0
- {django_components-0.79 → django_components-0.81}/tests/test_attributes.py +0 -0
- {django_components-0.79 → django_components-0.81}/tests/test_autodiscover.py +0 -0
- {django_components-0.79 → django_components-0.81}/tests/test_command_startcomponent.py +0 -0
- {django_components-0.79 → django_components-0.81}/tests/test_context.py +0 -0
- {django_components-0.79 → django_components-0.81}/tests/test_dependency_rendering.py +0 -0
- {django_components-0.79 → django_components-0.81}/tests/test_registry.py +0 -0
- {django_components-0.79 → django_components-0.81}/tests/test_settings.py +0 -0
- {django_components-0.79 → django_components-0.81}/tests/test_template_parser.py +0 -0
- {django_components-0.79 → django_components-0.81}/tests/test_templatetags_component.py +0 -0
- {django_components-0.79 → django_components-0.81}/tests/test_templatetags_slot_fill.py +0 -0
- {django_components-0.79 → django_components-0.81}/tests/test_templatetags_templating.py +0 -0
- {django_components-0.79 → django_components-0.81}/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.81
|
|
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
|
|
@@ -57,6 +57,7 @@ Read on to learn about the details!
|
|
|
57
57
|
- [Using slots in templates](#using-slots-in-templates)
|
|
58
58
|
- [Passing data to components](#passing-data-to-components)
|
|
59
59
|
- [Rendering HTML attributes](#rendering-html-attributes)
|
|
60
|
+
- [Prop drilling and dependency injection (provide / inject)](#prop-drilling-and-dependency-injection-provide--inject)
|
|
60
61
|
- [Component context and scope](#component-context-and-scope)
|
|
61
62
|
- [Rendering JS and CSS dependencies](#rendering-js-and-css-dependencies)
|
|
62
63
|
- [Available settings](#available-settings)
|
|
@@ -68,6 +69,12 @@ Read on to learn about the details!
|
|
|
68
69
|
|
|
69
70
|
## Release notes
|
|
70
71
|
|
|
72
|
+
🚨📢 **Version 0.81** Aligned the `render_to_response` method with the (now public) `render` method of `Component` class. Moreover, slots passed to these can now be rendered also as functions.
|
|
73
|
+
|
|
74
|
+
- BREAKING CHANGE: The order of arguments to `render_to_response` has changed.
|
|
75
|
+
|
|
76
|
+
**Version 0.80** introduces dependency injection with the `{% provide %}` tag and `inject()` method.
|
|
77
|
+
|
|
71
78
|
🚨📢 **Version 0.79**
|
|
72
79
|
|
|
73
80
|
- BREAKING CHANGE: Default value for the `COMPONENTS.context_behavior` setting was changes from `"isolated"` to `"django"`. If you did not set this value explicitly before, this may be a breaking change. See the rationale for change [here](https://github.com/EmilStenstrom/django-components/issues/498).
|
|
@@ -334,7 +341,7 @@ This makes it easy to create small components without having to create a separat
|
|
|
334
341
|
|
|
335
342
|
Note that the `t.django_html`, `t.css`, and `t.js` types are used to specify the type of the template, CSS, and JS files, respectively. This is not necessary, but if you're using VSCode with the [Python Inline Source Syntax Highlighting](https://marketplace.visualstudio.com/items?itemName=samwillis.python-inline-source) extension, it will give you syntax highlighting for the template, CSS, and JS.
|
|
336
343
|
|
|
337
|
-
## Use
|
|
344
|
+
## Use components in templates
|
|
338
345
|
|
|
339
346
|
First load the `component_tags` tag library, then use the `component_[js/css]_dependencies` and `component` tags to render the component to the page.
|
|
340
347
|
|
|
@@ -379,13 +386,143 @@ The output from the above template will be:
|
|
|
379
386
|
|
|
380
387
|
This makes it possible to organize your front-end around reusable components. Instead of relying on template tags and keeping your CSS and Javascript in the static directory.
|
|
381
388
|
|
|
389
|
+
## Use components outside of templates
|
|
390
|
+
|
|
391
|
+
_New in version 0.81_
|
|
392
|
+
|
|
393
|
+
Components can be rendered outside of Django templates, calling them as regular functions ("React-style").
|
|
394
|
+
|
|
395
|
+
The component class defines `render` and `render_to_response` class methods. These methods accept positional args, kwargs, and slots, offering the same flexibility as the `{% component %}` tag:
|
|
396
|
+
|
|
397
|
+
```py
|
|
398
|
+
class SimpleComponent(component.Component):
|
|
399
|
+
template = """
|
|
400
|
+
{% load component_tags %}
|
|
401
|
+
hello: {{ hello }}
|
|
402
|
+
foo: {{ foo }}
|
|
403
|
+
kwargs: {{ kwargs|safe }}
|
|
404
|
+
slot_first: {% slot "first" required %}{% endslot %}
|
|
405
|
+
"""
|
|
406
|
+
|
|
407
|
+
def get_context_data(self, arg1, arg2, **kwargs):
|
|
408
|
+
return {
|
|
409
|
+
"hello": arg1,
|
|
410
|
+
"foo": arg2,
|
|
411
|
+
"kwargs": kwargs,
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
rendered = SimpleComponent.render(
|
|
415
|
+
args=["world", "bar"],
|
|
416
|
+
kwargs={"kw1": "test", "kw2": "ooo"},
|
|
417
|
+
slots={"first": "FIRST_SLOT"},
|
|
418
|
+
context={"from_context": 98},
|
|
419
|
+
)
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
Renders:
|
|
423
|
+
|
|
424
|
+
```
|
|
425
|
+
hello: world
|
|
426
|
+
foo: bar
|
|
427
|
+
kwargs: {'kw1': 'test', 'kw2': 'ooo'}
|
|
428
|
+
slot_first: FIRST_SLOT
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
### Inputs of `render` and `render_to_response`
|
|
432
|
+
|
|
433
|
+
Both `render` and `render_to_response` accept the same input:
|
|
434
|
+
|
|
435
|
+
```py
|
|
436
|
+
Component.render(
|
|
437
|
+
context: Mapping | django.template.Context | None = None,
|
|
438
|
+
args: List[Any] | None = None,
|
|
439
|
+
kwargs: Dict[str, Any] | None = None,
|
|
440
|
+
slots: Dict[str, str | SafeString | SlotRenderFunc] | None = None,
|
|
441
|
+
escape_slots_content: bool = True
|
|
442
|
+
) -> str:
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
- _`args`_ - Positional args for the component. This is the same as calling the component
|
|
446
|
+
as `{% component "my_comp" arg1 arg2 ... %}`
|
|
447
|
+
|
|
448
|
+
- _`kwargs`_ - Keyword args for the component. This is the same as calling the component
|
|
449
|
+
as `{% component "my_comp" key1=val1 key2=val2 ... %}`
|
|
450
|
+
|
|
451
|
+
- _`slots`_ - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.
|
|
452
|
+
Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string
|
|
453
|
+
or [`SlotRenderFunc`](#slotrenderfunc).
|
|
454
|
+
|
|
455
|
+
- _`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.
|
|
456
|
+
|
|
457
|
+
- _`context`_ - A context (dictionary or Django's Context) within which the component
|
|
458
|
+
is rendered. The keys on the context can be accessed from within the template.
|
|
459
|
+
- NOTE: In "isolated" mode, context is NOT accessible, and data MUST be passed via
|
|
460
|
+
component's args and kwargs.
|
|
461
|
+
|
|
462
|
+
#### `SlotRenderFunc`
|
|
463
|
+
|
|
464
|
+
When rendering components with slots in `render` or `render_to_response`, you can pass either a string or a function.
|
|
465
|
+
|
|
466
|
+
The function has following signature:
|
|
467
|
+
|
|
468
|
+
```py
|
|
469
|
+
def render_func(
|
|
470
|
+
context: Context,
|
|
471
|
+
data: Dict[str, Any],
|
|
472
|
+
slot_ref: SlotRef,
|
|
473
|
+
) -> str | SafeString:
|
|
474
|
+
return nodelist.render(ctx)
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
- _`context`_ - Django's Context available to the Slot Node.
|
|
478
|
+
- _`data`_ - Data passed to the `{% slot %}` tag. See [Scoped Slots](#scoped-slots).
|
|
479
|
+
- _`slot_ref`_ - The default slot content. See [Accessing original content of slots](#accessing-original-content-of-slots).
|
|
480
|
+
- NOTE: The slot is lazily evaluated. To render the slot, convert it to string with `str(slot_ref)`.
|
|
481
|
+
|
|
482
|
+
Example:
|
|
483
|
+
```py
|
|
484
|
+
def footer_slot(ctx, data, slot_ref):
|
|
485
|
+
return f"""
|
|
486
|
+
SLOT_DATA: {data['abc']}
|
|
487
|
+
ORIGINAL: {slot_ref}
|
|
488
|
+
"""
|
|
489
|
+
|
|
490
|
+
MyComponent.render_to_response(
|
|
491
|
+
slots={
|
|
492
|
+
"footer": footer_slot,
|
|
493
|
+
},
|
|
494
|
+
)
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
### Response class of `render_to_response`
|
|
498
|
+
|
|
499
|
+
While `render` method returns a plain string, `render_to_response` wraps the rendered content in a "Response" class. By default, this is `django.http.HttpResponse`.
|
|
500
|
+
|
|
501
|
+
If you want to use a different Response class in `render_to_response`, set the `Component.response_class` attribute:
|
|
502
|
+
|
|
503
|
+
```py
|
|
504
|
+
class MyResponse(HttpResponse):
|
|
505
|
+
def __init__(self, *args, **kwargs) -> None:
|
|
506
|
+
super().__init__(*args, **kwargs)
|
|
507
|
+
# Configure response
|
|
508
|
+
self.headers = ...
|
|
509
|
+
self.status = ...
|
|
510
|
+
|
|
511
|
+
class SimpleComponent(component.Component):
|
|
512
|
+
response_class = MyResponse
|
|
513
|
+
template: types.django_html = "HELLO"
|
|
514
|
+
|
|
515
|
+
response = SimpleComponent.render_to_response()
|
|
516
|
+
assert isinstance(response, MyResponse)
|
|
517
|
+
```
|
|
518
|
+
|
|
382
519
|
## Use components as views
|
|
383
520
|
|
|
384
521
|
_New in version 0.34_
|
|
385
522
|
|
|
386
523
|
Components can now be used as views. To do this, `Component` subclasses Django's `View` class. This means that you can use all of the [methods](https://docs.djangoproject.com/en/5.0/ref/class-based-views/base/#view) of `View` in your component. For example, you can override `get` and `post` to handle GET and POST requests, respectively.
|
|
387
524
|
|
|
388
|
-
In addition, `Component` now has a `render_to_response` method that renders the component template based on the provided context and slots' data and returns an `HttpResponse` object.
|
|
525
|
+
In addition, `Component` now has a [`render_to_response`](#inputs-of-render-and-render_to_response) method that renders the component template based on the provided context and slots' data and returns an `HttpResponse` object.
|
|
389
526
|
|
|
390
527
|
Here's an example of a calendar component defined as a view:
|
|
391
528
|
|
|
@@ -414,7 +551,7 @@ class Calendar(component.Component):
|
|
|
414
551
|
slots = {
|
|
415
552
|
"header": "Calendar header",
|
|
416
553
|
}
|
|
417
|
-
return self.render_to_response(context, slots)
|
|
554
|
+
return self.render_to_response(context=context, slots=slots)
|
|
418
555
|
```
|
|
419
556
|
|
|
420
557
|
Then, to use this component as a view, you should create a `urls.py` file in your components directory, and add a path to the component's view:
|
|
@@ -1387,6 +1524,133 @@ attributes_to_string(attrs)
|
|
|
1387
1524
|
# 'class="my-class text-red pa-4" data-id="123" required'
|
|
1388
1525
|
```
|
|
1389
1526
|
|
|
1527
|
+
## Prop drilling and dependency injection (provide / inject)
|
|
1528
|
+
|
|
1529
|
+
_New in version 0.80_:
|
|
1530
|
+
|
|
1531
|
+
Django components supports dependency injection with the combination of:
|
|
1532
|
+
1. `{% provide %}` tag
|
|
1533
|
+
1. `inject()` method of the `Component` class
|
|
1534
|
+
|
|
1535
|
+
### What is "dependency injection" and "prop drilling"?
|
|
1536
|
+
|
|
1537
|
+
Prop drilling refers to a scenario in UI development where you need to pass data through many layers of a component tree to reach the nested components that actually need the data.
|
|
1538
|
+
|
|
1539
|
+
Normally, you'd use props to send data from a parent component to its children. However, this straightforward method becomes cumbersome and inefficient if the data has to travel through many levels or if several components scattered at different depths all need the same piece of information.
|
|
1540
|
+
|
|
1541
|
+
This results in a situation where the intermediate components, which don't need the data for their own functioning, end up having to manage and pass along these props. This clutters the component tree and makes the code verbose and harder to manage.
|
|
1542
|
+
|
|
1543
|
+
A neat solution to avoid prop drilling is using the "provide and inject" technique, AKA dependency injection.
|
|
1544
|
+
|
|
1545
|
+
With dependency injection, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.
|
|
1546
|
+
|
|
1547
|
+
This feature is inspired by Vue's [Provide / Inject](https://vuejs.org/guide/components/provide-inject) and React's [Context / useContext](https://react.dev/learn/passing-data-deeply-with-context).
|
|
1548
|
+
|
|
1549
|
+
### How to use provide / inject
|
|
1550
|
+
|
|
1551
|
+
As the name suggest, using provide / inject consists of 2 steps
|
|
1552
|
+
1. Providing data
|
|
1553
|
+
2. Injecting provided data
|
|
1554
|
+
|
|
1555
|
+
For examples of advanced uses of provide / inject, [see this discussion](https://github.com/EmilStenstrom/django-components/pull/506#issuecomment-2132102584).
|
|
1556
|
+
|
|
1557
|
+
### Using `{% provide %}` tag
|
|
1558
|
+
|
|
1559
|
+
First we use the `{% provide %}` tag to define the data we want to "provide" (make available).
|
|
1560
|
+
|
|
1561
|
+
```django
|
|
1562
|
+
{% provide "my_data" key="hi" another=123 %}
|
|
1563
|
+
{% component "child" %} <--- Can access "my_data"
|
|
1564
|
+
{% endcomponent %}
|
|
1565
|
+
{% endprovide %}
|
|
1566
|
+
|
|
1567
|
+
{% component "child" %} <--- Cannot access "my_data"
|
|
1568
|
+
{% endcomponent %}
|
|
1569
|
+
```
|
|
1570
|
+
|
|
1571
|
+
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.
|
|
1572
|
+
|
|
1573
|
+
`provide` tag _key_, similarly to the _name_ argument in `component` or `slot` tags, has these requirements:
|
|
1574
|
+
- The _key_ must be a string literal
|
|
1575
|
+
- It must be a valid identifier (AKA a valid Python variable name)
|
|
1576
|
+
|
|
1577
|
+
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.
|
|
1578
|
+
|
|
1579
|
+
> NOTE: Kwargs passed to `{% provide %}` are NOT added to the context.
|
|
1580
|
+
> In the example below, the `{{ key }}` won't render anything:
|
|
1581
|
+
> ```django
|
|
1582
|
+
> {% provide "my_data" key="hi" another=123 %}
|
|
1583
|
+
> {{ key }}
|
|
1584
|
+
> {% endprovide %}
|
|
1585
|
+
> ```
|
|
1586
|
+
|
|
1587
|
+
### Using `inject()` method
|
|
1588
|
+
|
|
1589
|
+
To "inject" (access) the data defined on the `provide` tag, you can use the `inject()` method inside of `get_context_data()`.
|
|
1590
|
+
|
|
1591
|
+
For a component to be able to "inject" some data, the component (`{% component %}` tag) must be nested inside the `{% provide %}` tag.
|
|
1592
|
+
|
|
1593
|
+
In the example from previous section, we've defined two kwargs: `key="hi" another=123`. That means that if we now inject `"my_data"`, we get an object with 2 attributes - `key` and `another`.
|
|
1594
|
+
|
|
1595
|
+
```py
|
|
1596
|
+
class ChildComponent(component.Component):
|
|
1597
|
+
def get_context_data(self):
|
|
1598
|
+
my_data = self.inject("my_data")
|
|
1599
|
+
print(my_data.key) # hi
|
|
1600
|
+
print(my_data.another) # 123
|
|
1601
|
+
return {}
|
|
1602
|
+
```
|
|
1603
|
+
|
|
1604
|
+
First argument to `inject` is the _key_ of the provided data. This
|
|
1605
|
+
must match the string that you used in the `provide` tag. If no provider
|
|
1606
|
+
with given key is found, `inject` raises a `KeyError`.
|
|
1607
|
+
|
|
1608
|
+
To avoid the error, you can pass a second argument to `inject` to which will act as a default value, similar to `dict.get(key, default)`:
|
|
1609
|
+
|
|
1610
|
+
```py
|
|
1611
|
+
class ChildComponent(component.Component):
|
|
1612
|
+
def get_context_data(self):
|
|
1613
|
+
my_data = self.inject("invalid_key", DEFAULT_DATA)
|
|
1614
|
+
assert my_data == DEFAUKT_DATA
|
|
1615
|
+
return {}
|
|
1616
|
+
```
|
|
1617
|
+
|
|
1618
|
+
The instance returned from `inject()` is a subclass of `NamedTuple`, so the instance is immutable. This ensures that the data returned from `inject` will always
|
|
1619
|
+
have all the keys that were passed to the `provide` tag.
|
|
1620
|
+
|
|
1621
|
+
> NOTE: `inject()` works strictly only in `get_context_data`. If you try to call it from elsewhere, it will raise an error.
|
|
1622
|
+
|
|
1623
|
+
|
|
1624
|
+
### Full example
|
|
1625
|
+
|
|
1626
|
+
```py
|
|
1627
|
+
@component.register("child")
|
|
1628
|
+
class ChildComponent(component.Component):
|
|
1629
|
+
template = """
|
|
1630
|
+
<div> {{ my_data.key }} </div>
|
|
1631
|
+
<div> {{ my_data.another }} </div>
|
|
1632
|
+
"""
|
|
1633
|
+
|
|
1634
|
+
def get_context_data(self):
|
|
1635
|
+
my_data = self.inject("my_data", "default")
|
|
1636
|
+
return {"my_data": my_data}
|
|
1637
|
+
|
|
1638
|
+
template_str = """
|
|
1639
|
+
{% load component_tags %}
|
|
1640
|
+
{% provide "my_data" key="hi" another=123 %}
|
|
1641
|
+
{% component "child" %}
|
|
1642
|
+
{% endcomponent %}
|
|
1643
|
+
{% endprovide %}
|
|
1644
|
+
"""
|
|
1645
|
+
```
|
|
1646
|
+
|
|
1647
|
+
renders:
|
|
1648
|
+
|
|
1649
|
+
```html
|
|
1650
|
+
<div> hi </div>
|
|
1651
|
+
<div> 123 </div>
|
|
1652
|
+
```
|
|
1653
|
+
|
|
1390
1654
|
## Component context and scope
|
|
1391
1655
|
|
|
1392
1656
|
By default, context variables are passed down the template as in regular Django - deeper scopes can access the variables from the outer scopes. So if you have several nested forloops, then inside the deep-most loop you can access variables defined by all previous loops.
|
|
@@ -33,6 +33,7 @@ Read on to learn about the details!
|
|
|
33
33
|
- [Using slots in templates](#using-slots-in-templates)
|
|
34
34
|
- [Passing data to components](#passing-data-to-components)
|
|
35
35
|
- [Rendering HTML attributes](#rendering-html-attributes)
|
|
36
|
+
- [Prop drilling and dependency injection (provide / inject)](#prop-drilling-and-dependency-injection-provide--inject)
|
|
36
37
|
- [Component context and scope](#component-context-and-scope)
|
|
37
38
|
- [Rendering JS and CSS dependencies](#rendering-js-and-css-dependencies)
|
|
38
39
|
- [Available settings](#available-settings)
|
|
@@ -44,6 +45,12 @@ Read on to learn about the details!
|
|
|
44
45
|
|
|
45
46
|
## Release notes
|
|
46
47
|
|
|
48
|
+
🚨📢 **Version 0.81** Aligned the `render_to_response` method with the (now public) `render` method of `Component` class. Moreover, slots passed to these can now be rendered also as functions.
|
|
49
|
+
|
|
50
|
+
- BREAKING CHANGE: The order of arguments to `render_to_response` has changed.
|
|
51
|
+
|
|
52
|
+
**Version 0.80** introduces dependency injection with the `{% provide %}` tag and `inject()` method.
|
|
53
|
+
|
|
47
54
|
🚨📢 **Version 0.79**
|
|
48
55
|
|
|
49
56
|
- BREAKING CHANGE: Default value for the `COMPONENTS.context_behavior` setting was changes from `"isolated"` to `"django"`. If you did not set this value explicitly before, this may be a breaking change. See the rationale for change [here](https://github.com/EmilStenstrom/django-components/issues/498).
|
|
@@ -310,7 +317,7 @@ This makes it easy to create small components without having to create a separat
|
|
|
310
317
|
|
|
311
318
|
Note that the `t.django_html`, `t.css`, and `t.js` types are used to specify the type of the template, CSS, and JS files, respectively. This is not necessary, but if you're using VSCode with the [Python Inline Source Syntax Highlighting](https://marketplace.visualstudio.com/items?itemName=samwillis.python-inline-source) extension, it will give you syntax highlighting for the template, CSS, and JS.
|
|
312
319
|
|
|
313
|
-
## Use
|
|
320
|
+
## Use components in templates
|
|
314
321
|
|
|
315
322
|
First load the `component_tags` tag library, then use the `component_[js/css]_dependencies` and `component` tags to render the component to the page.
|
|
316
323
|
|
|
@@ -355,13 +362,143 @@ The output from the above template will be:
|
|
|
355
362
|
|
|
356
363
|
This makes it possible to organize your front-end around reusable components. Instead of relying on template tags and keeping your CSS and Javascript in the static directory.
|
|
357
364
|
|
|
365
|
+
## Use components outside of templates
|
|
366
|
+
|
|
367
|
+
_New in version 0.81_
|
|
368
|
+
|
|
369
|
+
Components can be rendered outside of Django templates, calling them as regular functions ("React-style").
|
|
370
|
+
|
|
371
|
+
The component class defines `render` and `render_to_response` class methods. These methods accept positional args, kwargs, and slots, offering the same flexibility as the `{% component %}` tag:
|
|
372
|
+
|
|
373
|
+
```py
|
|
374
|
+
class SimpleComponent(component.Component):
|
|
375
|
+
template = """
|
|
376
|
+
{% load component_tags %}
|
|
377
|
+
hello: {{ hello }}
|
|
378
|
+
foo: {{ foo }}
|
|
379
|
+
kwargs: {{ kwargs|safe }}
|
|
380
|
+
slot_first: {% slot "first" required %}{% endslot %}
|
|
381
|
+
"""
|
|
382
|
+
|
|
383
|
+
def get_context_data(self, arg1, arg2, **kwargs):
|
|
384
|
+
return {
|
|
385
|
+
"hello": arg1,
|
|
386
|
+
"foo": arg2,
|
|
387
|
+
"kwargs": kwargs,
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
rendered = SimpleComponent.render(
|
|
391
|
+
args=["world", "bar"],
|
|
392
|
+
kwargs={"kw1": "test", "kw2": "ooo"},
|
|
393
|
+
slots={"first": "FIRST_SLOT"},
|
|
394
|
+
context={"from_context": 98},
|
|
395
|
+
)
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
Renders:
|
|
399
|
+
|
|
400
|
+
```
|
|
401
|
+
hello: world
|
|
402
|
+
foo: bar
|
|
403
|
+
kwargs: {'kw1': 'test', 'kw2': 'ooo'}
|
|
404
|
+
slot_first: FIRST_SLOT
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
### Inputs of `render` and `render_to_response`
|
|
408
|
+
|
|
409
|
+
Both `render` and `render_to_response` accept the same input:
|
|
410
|
+
|
|
411
|
+
```py
|
|
412
|
+
Component.render(
|
|
413
|
+
context: Mapping | django.template.Context | None = None,
|
|
414
|
+
args: List[Any] | None = None,
|
|
415
|
+
kwargs: Dict[str, Any] | None = None,
|
|
416
|
+
slots: Dict[str, str | SafeString | SlotRenderFunc] | None = None,
|
|
417
|
+
escape_slots_content: bool = True
|
|
418
|
+
) -> str:
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
- _`args`_ - Positional args for the component. This is the same as calling the component
|
|
422
|
+
as `{% component "my_comp" arg1 arg2 ... %}`
|
|
423
|
+
|
|
424
|
+
- _`kwargs`_ - Keyword args for the component. This is the same as calling the component
|
|
425
|
+
as `{% component "my_comp" key1=val1 key2=val2 ... %}`
|
|
426
|
+
|
|
427
|
+
- _`slots`_ - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.
|
|
428
|
+
Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string
|
|
429
|
+
or [`SlotRenderFunc`](#slotrenderfunc).
|
|
430
|
+
|
|
431
|
+
- _`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.
|
|
432
|
+
|
|
433
|
+
- _`context`_ - A context (dictionary or Django's Context) within which the component
|
|
434
|
+
is rendered. The keys on the context can be accessed from within the template.
|
|
435
|
+
- NOTE: In "isolated" mode, context is NOT accessible, and data MUST be passed via
|
|
436
|
+
component's args and kwargs.
|
|
437
|
+
|
|
438
|
+
#### `SlotRenderFunc`
|
|
439
|
+
|
|
440
|
+
When rendering components with slots in `render` or `render_to_response`, you can pass either a string or a function.
|
|
441
|
+
|
|
442
|
+
The function has following signature:
|
|
443
|
+
|
|
444
|
+
```py
|
|
445
|
+
def render_func(
|
|
446
|
+
context: Context,
|
|
447
|
+
data: Dict[str, Any],
|
|
448
|
+
slot_ref: SlotRef,
|
|
449
|
+
) -> str | SafeString:
|
|
450
|
+
return nodelist.render(ctx)
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
- _`context`_ - Django's Context available to the Slot Node.
|
|
454
|
+
- _`data`_ - Data passed to the `{% slot %}` tag. See [Scoped Slots](#scoped-slots).
|
|
455
|
+
- _`slot_ref`_ - The default slot content. See [Accessing original content of slots](#accessing-original-content-of-slots).
|
|
456
|
+
- NOTE: The slot is lazily evaluated. To render the slot, convert it to string with `str(slot_ref)`.
|
|
457
|
+
|
|
458
|
+
Example:
|
|
459
|
+
```py
|
|
460
|
+
def footer_slot(ctx, data, slot_ref):
|
|
461
|
+
return f"""
|
|
462
|
+
SLOT_DATA: {data['abc']}
|
|
463
|
+
ORIGINAL: {slot_ref}
|
|
464
|
+
"""
|
|
465
|
+
|
|
466
|
+
MyComponent.render_to_response(
|
|
467
|
+
slots={
|
|
468
|
+
"footer": footer_slot,
|
|
469
|
+
},
|
|
470
|
+
)
|
|
471
|
+
```
|
|
472
|
+
|
|
473
|
+
### Response class of `render_to_response`
|
|
474
|
+
|
|
475
|
+
While `render` method returns a plain string, `render_to_response` wraps the rendered content in a "Response" class. By default, this is `django.http.HttpResponse`.
|
|
476
|
+
|
|
477
|
+
If you want to use a different Response class in `render_to_response`, set the `Component.response_class` attribute:
|
|
478
|
+
|
|
479
|
+
```py
|
|
480
|
+
class MyResponse(HttpResponse):
|
|
481
|
+
def __init__(self, *args, **kwargs) -> None:
|
|
482
|
+
super().__init__(*args, **kwargs)
|
|
483
|
+
# Configure response
|
|
484
|
+
self.headers = ...
|
|
485
|
+
self.status = ...
|
|
486
|
+
|
|
487
|
+
class SimpleComponent(component.Component):
|
|
488
|
+
response_class = MyResponse
|
|
489
|
+
template: types.django_html = "HELLO"
|
|
490
|
+
|
|
491
|
+
response = SimpleComponent.render_to_response()
|
|
492
|
+
assert isinstance(response, MyResponse)
|
|
493
|
+
```
|
|
494
|
+
|
|
358
495
|
## Use components as views
|
|
359
496
|
|
|
360
497
|
_New in version 0.34_
|
|
361
498
|
|
|
362
499
|
Components can now be used as views. To do this, `Component` subclasses Django's `View` class. This means that you can use all of the [methods](https://docs.djangoproject.com/en/5.0/ref/class-based-views/base/#view) of `View` in your component. For example, you can override `get` and `post` to handle GET and POST requests, respectively.
|
|
363
500
|
|
|
364
|
-
In addition, `Component` now has a `render_to_response` method that renders the component template based on the provided context and slots' data and returns an `HttpResponse` object.
|
|
501
|
+
In addition, `Component` now has a [`render_to_response`](#inputs-of-render-and-render_to_response) method that renders the component template based on the provided context and slots' data and returns an `HttpResponse` object.
|
|
365
502
|
|
|
366
503
|
Here's an example of a calendar component defined as a view:
|
|
367
504
|
|
|
@@ -390,7 +527,7 @@ class Calendar(component.Component):
|
|
|
390
527
|
slots = {
|
|
391
528
|
"header": "Calendar header",
|
|
392
529
|
}
|
|
393
|
-
return self.render_to_response(context, slots)
|
|
530
|
+
return self.render_to_response(context=context, slots=slots)
|
|
394
531
|
```
|
|
395
532
|
|
|
396
533
|
Then, to use this component as a view, you should create a `urls.py` file in your components directory, and add a path to the component's view:
|
|
@@ -1363,6 +1500,133 @@ attributes_to_string(attrs)
|
|
|
1363
1500
|
# 'class="my-class text-red pa-4" data-id="123" required'
|
|
1364
1501
|
```
|
|
1365
1502
|
|
|
1503
|
+
## Prop drilling and dependency injection (provide / inject)
|
|
1504
|
+
|
|
1505
|
+
_New in version 0.80_:
|
|
1506
|
+
|
|
1507
|
+
Django components supports dependency injection with the combination of:
|
|
1508
|
+
1. `{% provide %}` tag
|
|
1509
|
+
1. `inject()` method of the `Component` class
|
|
1510
|
+
|
|
1511
|
+
### What is "dependency injection" and "prop drilling"?
|
|
1512
|
+
|
|
1513
|
+
Prop drilling refers to a scenario in UI development where you need to pass data through many layers of a component tree to reach the nested components that actually need the data.
|
|
1514
|
+
|
|
1515
|
+
Normally, you'd use props to send data from a parent component to its children. However, this straightforward method becomes cumbersome and inefficient if the data has to travel through many levels or if several components scattered at different depths all need the same piece of information.
|
|
1516
|
+
|
|
1517
|
+
This results in a situation where the intermediate components, which don't need the data for their own functioning, end up having to manage and pass along these props. This clutters the component tree and makes the code verbose and harder to manage.
|
|
1518
|
+
|
|
1519
|
+
A neat solution to avoid prop drilling is using the "provide and inject" technique, AKA dependency injection.
|
|
1520
|
+
|
|
1521
|
+
With dependency injection, a parent component acts like a data hub for all its descendants. This setup allows any component, no matter how deeply nested it is, to access the required data directly from this centralized provider without having to messily pass props down the chain. This approach significantly cleans up the code and makes it easier to maintain.
|
|
1522
|
+
|
|
1523
|
+
This feature is inspired by Vue's [Provide / Inject](https://vuejs.org/guide/components/provide-inject) and React's [Context / useContext](https://react.dev/learn/passing-data-deeply-with-context).
|
|
1524
|
+
|
|
1525
|
+
### How to use provide / inject
|
|
1526
|
+
|
|
1527
|
+
As the name suggest, using provide / inject consists of 2 steps
|
|
1528
|
+
1. Providing data
|
|
1529
|
+
2. Injecting provided data
|
|
1530
|
+
|
|
1531
|
+
For examples of advanced uses of provide / inject, [see this discussion](https://github.com/EmilStenstrom/django-components/pull/506#issuecomment-2132102584).
|
|
1532
|
+
|
|
1533
|
+
### Using `{% provide %}` tag
|
|
1534
|
+
|
|
1535
|
+
First we use the `{% provide %}` tag to define the data we want to "provide" (make available).
|
|
1536
|
+
|
|
1537
|
+
```django
|
|
1538
|
+
{% provide "my_data" key="hi" another=123 %}
|
|
1539
|
+
{% component "child" %} <--- Can access "my_data"
|
|
1540
|
+
{% endcomponent %}
|
|
1541
|
+
{% endprovide %}
|
|
1542
|
+
|
|
1543
|
+
{% component "child" %} <--- Cannot access "my_data"
|
|
1544
|
+
{% endcomponent %}
|
|
1545
|
+
```
|
|
1546
|
+
|
|
1547
|
+
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.
|
|
1548
|
+
|
|
1549
|
+
`provide` tag _key_, similarly to the _name_ argument in `component` or `slot` tags, has these requirements:
|
|
1550
|
+
- The _key_ must be a string literal
|
|
1551
|
+
- It must be a valid identifier (AKA a valid Python variable name)
|
|
1552
|
+
|
|
1553
|
+
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.
|
|
1554
|
+
|
|
1555
|
+
> NOTE: Kwargs passed to `{% provide %}` are NOT added to the context.
|
|
1556
|
+
> In the example below, the `{{ key }}` won't render anything:
|
|
1557
|
+
> ```django
|
|
1558
|
+
> {% provide "my_data" key="hi" another=123 %}
|
|
1559
|
+
> {{ key }}
|
|
1560
|
+
> {% endprovide %}
|
|
1561
|
+
> ```
|
|
1562
|
+
|
|
1563
|
+
### Using `inject()` method
|
|
1564
|
+
|
|
1565
|
+
To "inject" (access) the data defined on the `provide` tag, you can use the `inject()` method inside of `get_context_data()`.
|
|
1566
|
+
|
|
1567
|
+
For a component to be able to "inject" some data, the component (`{% component %}` tag) must be nested inside the `{% provide %}` tag.
|
|
1568
|
+
|
|
1569
|
+
In the example from previous section, we've defined two kwargs: `key="hi" another=123`. That means that if we now inject `"my_data"`, we get an object with 2 attributes - `key` and `another`.
|
|
1570
|
+
|
|
1571
|
+
```py
|
|
1572
|
+
class ChildComponent(component.Component):
|
|
1573
|
+
def get_context_data(self):
|
|
1574
|
+
my_data = self.inject("my_data")
|
|
1575
|
+
print(my_data.key) # hi
|
|
1576
|
+
print(my_data.another) # 123
|
|
1577
|
+
return {}
|
|
1578
|
+
```
|
|
1579
|
+
|
|
1580
|
+
First argument to `inject` is the _key_ of the provided data. This
|
|
1581
|
+
must match the string that you used in the `provide` tag. If no provider
|
|
1582
|
+
with given key is found, `inject` raises a `KeyError`.
|
|
1583
|
+
|
|
1584
|
+
To avoid the error, you can pass a second argument to `inject` to which will act as a default value, similar to `dict.get(key, default)`:
|
|
1585
|
+
|
|
1586
|
+
```py
|
|
1587
|
+
class ChildComponent(component.Component):
|
|
1588
|
+
def get_context_data(self):
|
|
1589
|
+
my_data = self.inject("invalid_key", DEFAULT_DATA)
|
|
1590
|
+
assert my_data == DEFAUKT_DATA
|
|
1591
|
+
return {}
|
|
1592
|
+
```
|
|
1593
|
+
|
|
1594
|
+
The instance returned from `inject()` is a subclass of `NamedTuple`, so the instance is immutable. This ensures that the data returned from `inject` will always
|
|
1595
|
+
have all the keys that were passed to the `provide` tag.
|
|
1596
|
+
|
|
1597
|
+
> NOTE: `inject()` works strictly only in `get_context_data`. If you try to call it from elsewhere, it will raise an error.
|
|
1598
|
+
|
|
1599
|
+
|
|
1600
|
+
### Full example
|
|
1601
|
+
|
|
1602
|
+
```py
|
|
1603
|
+
@component.register("child")
|
|
1604
|
+
class ChildComponent(component.Component):
|
|
1605
|
+
template = """
|
|
1606
|
+
<div> {{ my_data.key }} </div>
|
|
1607
|
+
<div> {{ my_data.another }} </div>
|
|
1608
|
+
"""
|
|
1609
|
+
|
|
1610
|
+
def get_context_data(self):
|
|
1611
|
+
my_data = self.inject("my_data", "default")
|
|
1612
|
+
return {"my_data": my_data}
|
|
1613
|
+
|
|
1614
|
+
template_str = """
|
|
1615
|
+
{% load component_tags %}
|
|
1616
|
+
{% provide "my_data" key="hi" another=123 %}
|
|
1617
|
+
{% component "child" %}
|
|
1618
|
+
{% endcomponent %}
|
|
1619
|
+
{% endprovide %}
|
|
1620
|
+
"""
|
|
1621
|
+
```
|
|
1622
|
+
|
|
1623
|
+
renders:
|
|
1624
|
+
|
|
1625
|
+
```html
|
|
1626
|
+
<div> hi </div>
|
|
1627
|
+
<div> 123 </div>
|
|
1628
|
+
```
|
|
1629
|
+
|
|
1366
1630
|
## Component context and scope
|
|
1367
1631
|
|
|
1368
1632
|
By default, context variables are passed down the template as in regular Django - deeper scopes can access the variables from the outer scopes. So if you have several nested forloops, then inside the deep-most loop you can access variables defined by all previous loops.
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "django_components"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.81"
|
|
8
8
|
requires-python = ">=3.8, <4.0"
|
|
9
9
|
description = "A way to create simple reusable template components in Django."
|
|
10
10
|
keywords = ["django", "components", "css", "js", "html"]
|