django-components 0.79__tar.gz → 0.80__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.
Files changed (54) hide show
  1. {django_components-0.79/src/django_components.egg-info → django_components-0.80}/PKG-INFO +131 -1
  2. {django_components-0.79 → django_components-0.80}/README.md +130 -0
  3. {django_components-0.79 → django_components-0.80}/pyproject.toml +1 -1
  4. {django_components-0.79 → django_components-0.80}/src/django_components/component.py +64 -4
  5. django_components-0.80/src/django_components/context.py +136 -0
  6. {django_components-0.79 → django_components-0.80}/src/django_components/logger.py +1 -1
  7. django_components-0.80/src/django_components/provide.py +52 -0
  8. {django_components-0.79 → django_components-0.80}/src/django_components/templatetags/component_tags.py +51 -0
  9. {django_components-0.79 → django_components-0.80/src/django_components.egg-info}/PKG-INFO +131 -1
  10. {django_components-0.79 → django_components-0.80}/src/django_components.egg-info/SOURCES.txt +2 -0
  11. {django_components-0.79 → django_components-0.80}/tests/test_templatetags.py +39 -0
  12. django_components-0.80/tests/test_templatetags_provide.py +601 -0
  13. django_components-0.79/src/django_components/context.py +0 -64
  14. {django_components-0.79 → django_components-0.80}/LICENSE +0 -0
  15. {django_components-0.79 → django_components-0.80}/setup.cfg +0 -0
  16. {django_components-0.79 → django_components-0.80}/src/django_components/__init__.py +0 -0
  17. {django_components-0.79 → django_components-0.80}/src/django_components/app_settings.py +0 -0
  18. {django_components-0.79 → django_components-0.80}/src/django_components/apps.py +0 -0
  19. {django_components-0.79 → django_components-0.80}/src/django_components/attributes.py +0 -0
  20. {django_components-0.79 → django_components-0.80}/src/django_components/component_registry.py +0 -0
  21. {django_components-0.79 → django_components-0.80}/src/django_components/expression.py +0 -0
  22. {django_components-0.79 → django_components-0.80}/src/django_components/management/__init__.py +0 -0
  23. {django_components-0.79 → django_components-0.80}/src/django_components/management/commands/__init__.py +0 -0
  24. {django_components-0.79 → django_components-0.80}/src/django_components/management/commands/startcomponent.py +0 -0
  25. {django_components-0.79 → django_components-0.80}/src/django_components/management/commands/upgradecomponent.py +0 -0
  26. {django_components-0.79 → django_components-0.80}/src/django_components/middleware.py +0 -0
  27. {django_components-0.79 → django_components-0.80}/src/django_components/node.py +0 -0
  28. {django_components-0.79 → django_components-0.80}/src/django_components/py.typed +0 -0
  29. {django_components-0.79 → django_components-0.80}/src/django_components/safer_staticfiles/__init__.py +0 -0
  30. {django_components-0.79 → django_components-0.80}/src/django_components/safer_staticfiles/apps.py +0 -0
  31. {django_components-0.79 → django_components-0.80}/src/django_components/slots.py +0 -0
  32. {django_components-0.79 → django_components-0.80}/src/django_components/template_loader.py +0 -0
  33. {django_components-0.79 → django_components-0.80}/src/django_components/template_parser.py +0 -0
  34. {django_components-0.79 → django_components-0.80}/src/django_components/templatetags/__init__.py +0 -0
  35. {django_components-0.79 → django_components-0.80}/src/django_components/types.py +0 -0
  36. {django_components-0.79 → django_components-0.80}/src/django_components/utils.py +0 -0
  37. {django_components-0.79 → django_components-0.80}/src/django_components.egg-info/dependency_links.txt +0 -0
  38. {django_components-0.79 → django_components-0.80}/src/django_components.egg-info/requires.txt +0 -0
  39. {django_components-0.79 → django_components-0.80}/src/django_components.egg-info/top_level.txt +0 -0
  40. {django_components-0.79 → django_components-0.80}/tests/test_attributes.py +0 -0
  41. {django_components-0.79 → django_components-0.80}/tests/test_autodiscover.py +0 -0
  42. {django_components-0.79 → django_components-0.80}/tests/test_command_startcomponent.py +0 -0
  43. {django_components-0.79 → django_components-0.80}/tests/test_component.py +0 -0
  44. {django_components-0.79 → django_components-0.80}/tests/test_component_as_view.py +0 -0
  45. {django_components-0.79 → django_components-0.80}/tests/test_component_media.py +0 -0
  46. {django_components-0.79 → django_components-0.80}/tests/test_context.py +0 -0
  47. {django_components-0.79 → django_components-0.80}/tests/test_dependency_rendering.py +0 -0
  48. {django_components-0.79 → django_components-0.80}/tests/test_registry.py +0 -0
  49. {django_components-0.79 → django_components-0.80}/tests/test_settings.py +0 -0
  50. {django_components-0.79 → django_components-0.80}/tests/test_template_parser.py +0 -0
  51. {django_components-0.79 → django_components-0.80}/tests/test_templatetags_component.py +0 -0
  52. {django_components-0.79 → django_components-0.80}/tests/test_templatetags_slot_fill.py +0 -0
  53. {django_components-0.79 → django_components-0.80}/tests/test_templatetags_templating.py +0 -0
  54. {django_components-0.79 → django_components-0.80}/tests/testutils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.79
3
+ Version: 0.80
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,8 @@ Read on to learn about the details!
68
69
 
69
70
  ## Release notes
70
71
 
72
+ **Version 0.80** introduces dependency injection with the `{% provide %}` tag and `inject()` method.
73
+
71
74
  🚨📢 **Version 0.79**
72
75
 
73
76
  - 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).
@@ -1387,6 +1390,133 @@ attributes_to_string(attrs)
1387
1390
  # 'class="my-class text-red pa-4" data-id="123" required'
1388
1391
  ```
1389
1392
 
1393
+ ## Prop drilling and dependency injection (provide / inject)
1394
+
1395
+ _New in version 0.80_:
1396
+
1397
+ Django components supports dependency injection with the combination of:
1398
+ 1. `{% provide %}` tag
1399
+ 1. `inject()` method of the `Component` class
1400
+
1401
+ ### What is "dependency injection" and "prop drilling"?
1402
+
1403
+ 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.
1404
+
1405
+ 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.
1406
+
1407
+ 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.
1408
+
1409
+ A neat solution to avoid prop drilling is using the "provide and inject" technique, AKA dependency injection.
1410
+
1411
+ 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.
1412
+
1413
+ 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).
1414
+
1415
+ ### How to use provide / inject
1416
+
1417
+ As the name suggest, using provide / inject consists of 2 steps
1418
+ 1. Providing data
1419
+ 2. Injecting provided data
1420
+
1421
+ For examples of advanced uses of provide / inject, [see this discussion](https://github.com/EmilStenstrom/django-components/pull/506#issuecomment-2132102584).
1422
+
1423
+ ### Using `{% provide %}` tag
1424
+
1425
+ First we use the `{% provide %}` tag to define the data we want to "provide" (make available).
1426
+
1427
+ ```django
1428
+ {% provide "my_data" key="hi" another=123 %}
1429
+ {% component "child" %} <--- Can access "my_data"
1430
+ {% endcomponent %}
1431
+ {% endprovide %}
1432
+
1433
+ {% component "child" %} <--- Cannot access "my_data"
1434
+ {% endcomponent %}
1435
+ ```
1436
+
1437
+ 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.
1438
+
1439
+ `provide` tag _key_, similarly to the _name_ argument in `component` or `slot` tags, has these requirements:
1440
+ - The _key_ must be a string literal
1441
+ - It must be a valid identifier (AKA a valid Python variable name)
1442
+
1443
+ 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.
1444
+
1445
+ > NOTE: Kwargs passed to `{% provide %}` are NOT added to the context.
1446
+ > In the example below, the `{{ key }}` won't render anything:
1447
+ > ```django
1448
+ > {% provide "my_data" key="hi" another=123 %}
1449
+ > {{ key }}
1450
+ > {% endprovide %}
1451
+ > ```
1452
+
1453
+ ### Using `inject()` method
1454
+
1455
+ To "inject" (access) the data defined on the `provide` tag, you can use the `inject()` method inside of `get_context_data()`.
1456
+
1457
+ For a component to be able to "inject" some data, the component (`{% component %}` tag) must be nested inside the `{% provide %}` tag.
1458
+
1459
+ 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`.
1460
+
1461
+ ```py
1462
+ class ChildComponent(component.Component):
1463
+ def get_context_data(self):
1464
+ my_data = self.inject("my_data")
1465
+ print(my_data.key) # hi
1466
+ print(my_data.another) # 123
1467
+ return {}
1468
+ ```
1469
+
1470
+ First argument to `inject` is the _key_ of the provided data. This
1471
+ must match the string that you used in the `provide` tag. If no provider
1472
+ with given key is found, `inject` raises a `KeyError`.
1473
+
1474
+ 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)`:
1475
+
1476
+ ```py
1477
+ class ChildComponent(component.Component):
1478
+ def get_context_data(self):
1479
+ my_data = self.inject("invalid_key", DEFAULT_DATA)
1480
+ assert my_data == DEFAUKT_DATA
1481
+ return {}
1482
+ ```
1483
+
1484
+ 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
1485
+ have all the keys that were passed to the `provide` tag.
1486
+
1487
+ > NOTE: `inject()` works strictly only in `get_context_data`. If you try to call it from elsewhere, it will raise an error.
1488
+
1489
+
1490
+ ### Full example
1491
+
1492
+ ```py
1493
+ @component.register("child")
1494
+ class ChildComponent(component.Component):
1495
+ template = """
1496
+ <div> {{ my_data.key }} </div>
1497
+ <div> {{ my_data.another }} </div>
1498
+ """
1499
+
1500
+ def get_context_data(self):
1501
+ my_data = self.inject("my_data", "default")
1502
+ return {"my_data": my_data}
1503
+
1504
+ template_str = """
1505
+ {% load component_tags %}
1506
+ {% provide "my_data" key="hi" another=123 %}
1507
+ {% component "child" %}
1508
+ {% endcomponent %}
1509
+ {% endprovide %}
1510
+ """
1511
+ ```
1512
+
1513
+ renders:
1514
+
1515
+ ```html
1516
+ <div> hi </div>
1517
+ <div> 123 </div>
1518
+ ```
1519
+
1390
1520
  ## Component context and scope
1391
1521
 
1392
1522
  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,8 @@ Read on to learn about the details!
44
45
 
45
46
  ## Release notes
46
47
 
48
+ **Version 0.80** introduces dependency injection with the `{% provide %}` tag and `inject()` method.
49
+
47
50
  🚨📢 **Version 0.79**
48
51
 
49
52
  - 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).
@@ -1363,6 +1366,133 @@ attributes_to_string(attrs)
1363
1366
  # 'class="my-class text-red pa-4" data-id="123" required'
1364
1367
  ```
1365
1368
 
1369
+ ## Prop drilling and dependency injection (provide / inject)
1370
+
1371
+ _New in version 0.80_:
1372
+
1373
+ Django components supports dependency injection with the combination of:
1374
+ 1. `{% provide %}` tag
1375
+ 1. `inject()` method of the `Component` class
1376
+
1377
+ ### What is "dependency injection" and "prop drilling"?
1378
+
1379
+ 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.
1380
+
1381
+ 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.
1382
+
1383
+ 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.
1384
+
1385
+ A neat solution to avoid prop drilling is using the "provide and inject" technique, AKA dependency injection.
1386
+
1387
+ 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.
1388
+
1389
+ 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).
1390
+
1391
+ ### How to use provide / inject
1392
+
1393
+ As the name suggest, using provide / inject consists of 2 steps
1394
+ 1. Providing data
1395
+ 2. Injecting provided data
1396
+
1397
+ For examples of advanced uses of provide / inject, [see this discussion](https://github.com/EmilStenstrom/django-components/pull/506#issuecomment-2132102584).
1398
+
1399
+ ### Using `{% provide %}` tag
1400
+
1401
+ First we use the `{% provide %}` tag to define the data we want to "provide" (make available).
1402
+
1403
+ ```django
1404
+ {% provide "my_data" key="hi" another=123 %}
1405
+ {% component "child" %} <--- Can access "my_data"
1406
+ {% endcomponent %}
1407
+ {% endprovide %}
1408
+
1409
+ {% component "child" %} <--- Cannot access "my_data"
1410
+ {% endcomponent %}
1411
+ ```
1412
+
1413
+ 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.
1414
+
1415
+ `provide` tag _key_, similarly to the _name_ argument in `component` or `slot` tags, has these requirements:
1416
+ - The _key_ must be a string literal
1417
+ - It must be a valid identifier (AKA a valid Python variable name)
1418
+
1419
+ 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.
1420
+
1421
+ > NOTE: Kwargs passed to `{% provide %}` are NOT added to the context.
1422
+ > In the example below, the `{{ key }}` won't render anything:
1423
+ > ```django
1424
+ > {% provide "my_data" key="hi" another=123 %}
1425
+ > {{ key }}
1426
+ > {% endprovide %}
1427
+ > ```
1428
+
1429
+ ### Using `inject()` method
1430
+
1431
+ To "inject" (access) the data defined on the `provide` tag, you can use the `inject()` method inside of `get_context_data()`.
1432
+
1433
+ For a component to be able to "inject" some data, the component (`{% component %}` tag) must be nested inside the `{% provide %}` tag.
1434
+
1435
+ 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`.
1436
+
1437
+ ```py
1438
+ class ChildComponent(component.Component):
1439
+ def get_context_data(self):
1440
+ my_data = self.inject("my_data")
1441
+ print(my_data.key) # hi
1442
+ print(my_data.another) # 123
1443
+ return {}
1444
+ ```
1445
+
1446
+ First argument to `inject` is the _key_ of the provided data. This
1447
+ must match the string that you used in the `provide` tag. If no provider
1448
+ with given key is found, `inject` raises a `KeyError`.
1449
+
1450
+ 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)`:
1451
+
1452
+ ```py
1453
+ class ChildComponent(component.Component):
1454
+ def get_context_data(self):
1455
+ my_data = self.inject("invalid_key", DEFAULT_DATA)
1456
+ assert my_data == DEFAUKT_DATA
1457
+ return {}
1458
+ ```
1459
+
1460
+ 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
1461
+ have all the keys that were passed to the `provide` tag.
1462
+
1463
+ > NOTE: `inject()` works strictly only in `get_context_data`. If you try to call it from elsewhere, it will raise an error.
1464
+
1465
+
1466
+ ### Full example
1467
+
1468
+ ```py
1469
+ @component.register("child")
1470
+ class ChildComponent(component.Component):
1471
+ template = """
1472
+ <div> {{ my_data.key }} </div>
1473
+ <div> {{ my_data.another }} </div>
1474
+ """
1475
+
1476
+ def get_context_data(self):
1477
+ my_data = self.inject("my_data", "default")
1478
+ return {"my_data": my_data}
1479
+
1480
+ template_str = """
1481
+ {% load component_tags %}
1482
+ {% provide "my_data" key="hi" another=123 %}
1483
+ {% component "child" %}
1484
+ {% endcomponent %}
1485
+ {% endprovide %}
1486
+ """
1487
+ ```
1488
+
1489
+ renders:
1490
+
1491
+ ```html
1492
+ <div> hi </div>
1493
+ <div> 123 </div>
1494
+ ```
1495
+
1366
1496
  ## Component context and scope
1367
1497
 
1368
1498
  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.79"
7
+ version = "0.80"
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"]
@@ -30,6 +30,7 @@ from django_components.context import (
30
30
  _FILLED_SLOTS_CONTENT_CONTEXT_KEY,
31
31
  _PARENT_COMP_CONTEXT_KEY,
32
32
  _ROOT_CTX_CONTEXT_KEY,
33
+ get_injected_context_var,
33
34
  make_isolated_context_copy,
34
35
  prepare_context,
35
36
  )
@@ -201,6 +202,7 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
201
202
  self.outer_context: Context = outer_context or Context()
202
203
  self.fill_content = fill_content or {}
203
204
  self.component_id = component_id or gen_id()
205
+ self._context: Optional[Context] = None
204
206
 
205
207
  def __init_subclass__(cls, **kwargs: Any) -> None:
206
208
  cls.class_hash = hash(inspect.getfile(cls) + cls.__name__)
@@ -260,13 +262,71 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
260
262
  f"Note: this attribute is not required if you are overriding the class's `get_template*()` methods."
261
263
  )
262
264
 
263
- def render_from_input(self, context: Context, args: Union[List, Tuple], kwargs: Dict[str, Any]) -> str:
264
- component_context: dict = self.get_context_data(*args, **kwargs)
265
+ def inject(self, key: str, default: Optional[Any] = None) -> Any:
266
+ """
267
+ Use this method to retrieve the data that was passed to a `{% provide %}` tag
268
+ with the corresponding key.
269
+
270
+ To retrieve the data, `inject()` must be called inside a component that's
271
+ inside the `{% provide %}` tag.
272
+
273
+ You may also pass a default that will be used if the `provide` tag with given
274
+ key was NOT found.
275
+
276
+ This method mut be used inside the `get_context_data()` method and raises
277
+ an error if called elsewhere.
278
+
279
+ Example:
280
+
281
+ Given this template:
282
+ ```django
283
+ {% provide "provider" hello="world" %}
284
+ {% component "my_comp" %}
285
+ {% endcomponent %}
286
+ {% endprovide %}
287
+ ```
288
+
289
+ And given this definition of "my_comp" component:
290
+ ```py
291
+ @component.register("my_comp")
292
+ class MyComp(component.Component):
293
+ template = "hi {{ data.hello }}!"
294
+ def get_context_data(self):
295
+ data = self.inject("provider")
296
+ return {"data": data}
297
+ ```
298
+
299
+ This renders into:
300
+ ```
301
+ hi world!
302
+ ```
303
+
304
+ As the `{{ data.hello }}` is taken from the "provider".
305
+ """
306
+ comp_name = self.registered_name or self.__class__.__name__
307
+ if self._context is None:
308
+ raise RuntimeError(
309
+ f"Method 'inject()' of component '{comp_name}' was called outside of 'get_context_data()'"
310
+ )
311
+
312
+ return get_injected_context_var(comp_name, self._context, key, default)
313
+
314
+ def render_from_input(
315
+ self,
316
+ context: Context,
317
+ args: Union[List, Tuple],
318
+ kwargs: Dict[str, Any],
319
+ ) -> str:
320
+ # Temporarily populate _context so user can call `self.inject()` from
321
+ # within `get_context_data()`
322
+ self._context = context
323
+ context_data = self.get_context_data(*args, **kwargs)
324
+ self._context = None
265
325
 
266
- with context.update(component_context):
326
+ with context.update(context_data):
267
327
  rendered_component = self.render(
268
328
  context=context,
269
- context_data=component_context,
329
+ context_data=context_data,
270
330
  )
271
331
 
272
332
  if is_dependency_middleware_active():
@@ -0,0 +1,136 @@
1
+ """
2
+ This file centralizes various ways we use Django's Context class
3
+ pass data across components, nodes, slots, and contexts.
4
+
5
+ You can think of the Context as our storage system.
6
+ """
7
+
8
+ from collections import namedtuple
9
+ from typing import Any, Dict, Optional
10
+
11
+ from django.template import Context, TemplateSyntaxError
12
+
13
+ from django_components.utils import find_last_index
14
+
15
+ _FILLED_SLOTS_CONTENT_CONTEXT_KEY = "_DJANGO_COMPONENTS_FILLED_SLOTS"
16
+ _ROOT_CTX_CONTEXT_KEY = "_DJANGO_COMPONENTS_ROOT_CTX"
17
+ _PARENT_COMP_CONTEXT_KEY = "_DJANGO_COMPONENTS_PARENT_COMP"
18
+ _CURRENT_COMP_CONTEXT_KEY = "_DJANGO_COMPONENTS_CURRENT_COMP"
19
+ _INJECT_CONTEXT_KEY_PREFIX = "_DJANGO_COMPONENTS_INJECT__"
20
+
21
+
22
+ def prepare_context(
23
+ context: Context,
24
+ component_id: str,
25
+ ) -> None:
26
+ """Initialize the internal context state."""
27
+ # Initialize mapping dicts within this rendering run.
28
+ # This is shared across the whole render chain, thus we set it only once.
29
+ if _FILLED_SLOTS_CONTENT_CONTEXT_KEY not in context:
30
+ context[_FILLED_SLOTS_CONTENT_CONTEXT_KEY] = {}
31
+
32
+ set_component_id(context, component_id)
33
+
34
+
35
+ def make_isolated_context_copy(context: Context) -> Context:
36
+ context_copy = context.new()
37
+ copy_forloop_context(context, context_copy)
38
+
39
+ # Pass through our internal keys
40
+ context_copy[_FILLED_SLOTS_CONTENT_CONTEXT_KEY] = context.get(_FILLED_SLOTS_CONTENT_CONTEXT_KEY, {})
41
+ if _ROOT_CTX_CONTEXT_KEY in context:
42
+ context_copy[_ROOT_CTX_CONTEXT_KEY] = context[_ROOT_CTX_CONTEXT_KEY]
43
+
44
+ # Make inject/provide to work in isolated mode
45
+ context_keys = context.flatten().keys()
46
+ for key in context_keys:
47
+ if key.startswith(_INJECT_CONTEXT_KEY_PREFIX):
48
+ context_copy[key] = context[key]
49
+
50
+ return context_copy
51
+
52
+
53
+ def set_component_id(context: Context, component_id: str) -> None:
54
+ """
55
+ We use the Context object to pass down info on inside of which component
56
+ we are currently rendering.
57
+ """
58
+ # Store the previous component so we can detect if the current component
59
+ # is the top-most or not. If it is, then "_parent_component_id" is None
60
+ context[_PARENT_COMP_CONTEXT_KEY] = context.get(_CURRENT_COMP_CONTEXT_KEY, None)
61
+ context[_CURRENT_COMP_CONTEXT_KEY] = component_id
62
+
63
+
64
+ def copy_forloop_context(from_context: Context, to_context: Context) -> None:
65
+ """Forward the info about the current loop"""
66
+ # Note that the ForNode (which implements for loop behavior) does not
67
+ # only add the `forloop` key, but also keys corresponding to the loop elements
68
+ # So if the loop syntax is `{% for my_val in my_lists %}`, then ForNode also
69
+ # sets a `my_val` key.
70
+ # For this reason, instead of copying individual keys, we copy the whole stack layer
71
+ # set by ForNode.
72
+ if "forloop" in from_context:
73
+ forloop_dict_index = find_last_index(from_context.dicts, lambda d: "forloop" in d)
74
+ to_context.update(from_context.dicts[forloop_dict_index])
75
+
76
+
77
+ def get_injected_context_var(
78
+ component_name: str,
79
+ context: Context,
80
+ key: str,
81
+ default: Optional[Any] = None,
82
+ ) -> Any:
83
+ """
84
+ Retrieve a 'provided' field. The field MUST have been previously 'provided'
85
+ by the component's ancestors using the `{% provide %}` template tag.
86
+ """
87
+ # NOTE: For simplicity, we keep the provided values directly on the context.
88
+ # This plays nicely with Django's Context, which behaves like a stack, so "newer"
89
+ # values overshadow the "older" ones.
90
+ internal_key = _INJECT_CONTEXT_KEY_PREFIX + key
91
+
92
+ # Return provided value if found
93
+ if internal_key in context:
94
+ return context[internal_key]
95
+
96
+ # If a default was given, return that
97
+ if default is not None:
98
+ return default
99
+
100
+ # Otherwise raise error
101
+ raise KeyError(
102
+ f"Component '{component_name}' tried to inject a variable '{key}' before it was provided."
103
+ f"To fix this, make sure that at least one ancestor of component '{component_name}' has"
104
+ f" the variable '{key}' in their 'provide' attribute."
105
+ )
106
+
107
+
108
+ def set_provided_context_var(
109
+ context: Context,
110
+ key: str,
111
+ provided_kwargs: Dict[str, Any],
112
+ ) -> None:
113
+ """
114
+ 'Provide' given data under given key. In other words, this data can be retrieved
115
+ using `self.inject(key)` inside of `get_context_data()` method of components that
116
+ are nested inside the `{% provide %}` tag.
117
+ """
118
+ # NOTE: We raise TemplateSyntaxError since this func should be called only from
119
+ # within template.
120
+ if not key:
121
+ raise TemplateSyntaxError(
122
+ "Provide tag received an empty string. Key must be non-empty and a valid identifier."
123
+ )
124
+ if not key.isidentifier():
125
+ raise TemplateSyntaxError(
126
+ "Provide tag received a non-identifier string. Key must be non-empty and a valid identifier."
127
+ )
128
+
129
+ # We turn the kwargs into a NamedTuple so that the object that's "provided"
130
+ # is immutable. This ensures that the data returned from `inject` will always
131
+ # have all the keys that were passed to the `provide` tag.
132
+ tpl_cls = namedtuple("DepInject", provided_kwargs.keys()) # type: ignore[misc]
133
+ payload = tpl_cls(**provided_kwargs)
134
+
135
+ internal_key = _INJECT_CONTEXT_KEY_PREFIX + key
136
+ context[internal_key] = payload
@@ -63,7 +63,7 @@ def trace(logger: logging.Logger, message: str, *args: Any, **kwargs: Any) -> No
63
63
 
64
64
  def trace_msg(
65
65
  action: Literal["PARSE", "ASSOC", "RENDR", "GET", "SET"],
66
- node_type: Literal["COMP", "FILL", "SLOT", "N/A"],
66
+ node_type: Literal["COMP", "FILL", "SLOT", "PROVIDE", "N/A"],
67
67
  node_name: str,
68
68
  node_id: str,
69
69
  msg: str = "",
@@ -0,0 +1,52 @@
1
+ from typing import Dict, Optional
2
+
3
+ from django.template import Context
4
+ from django.template.base import FilterExpression, Node, NodeList
5
+ from django.utils.safestring import SafeString
6
+
7
+ from django_components.context import set_provided_context_var
8
+ from django_components.expression import safe_resolve_dict
9
+ from django_components.logger import trace_msg
10
+ from django_components.template_parser import process_aggregate_kwargs
11
+ from django_components.utils import gen_id
12
+
13
+
14
+ class ProvideNode(Node):
15
+ """
16
+ Implementation of the `{% provide %}` tag.
17
+ For more info see `Component.inject`.
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ name: str,
23
+ nodelist: NodeList,
24
+ node_id: Optional[str] = None,
25
+ provide_kwargs: Optional[Dict[str, FilterExpression]] = None,
26
+ ):
27
+ self.name = name
28
+ self.nodelist = nodelist
29
+ self.node_id = node_id or gen_id()
30
+ self.provide_kwargs = provide_kwargs or {}
31
+
32
+ def __repr__(self) -> str:
33
+ return f"<Provide Node: {self.name}. Contents: {repr(self.nodelist)}. Data: {self.provide_kwargs}>"
34
+
35
+ def render(self, context: Context) -> SafeString:
36
+ trace_msg("RENDR", "PROVIDE", self.name, self.node_id)
37
+
38
+ data = safe_resolve_dict(self.provide_kwargs, context)
39
+ # Allow user to use the var:key=value syntax
40
+ data = process_aggregate_kwargs(data)
41
+
42
+ # NOTE: The "provided" kwargs are meant to be shared privately, meaning that components
43
+ # have to explicitly opt in by using the `Component.inject()` method. That's why we don't
44
+ # add the provided kwargs into the Context.
45
+ with context.update({}):
46
+ # "Provide" the data to child nodes
47
+ set_provided_context_var(context, self.name, data)
48
+
49
+ output = self.nodelist.render(context)
50
+
51
+ trace_msg("RENDR", "PROVIDE", self.name, self.node_id, msg="...Done!")
52
+ return output
@@ -17,6 +17,7 @@ from django_components.middleware import (
17
17
  JS_DEPENDENCY_PLACEHOLDER,
18
18
  is_dependency_middleware_active,
19
19
  )
20
+ from django_components.provide import ProvideNode
20
21
  from django_components.slots import FillNode, SlotNode, parse_slot_fill_nodes_from_component_nodelist
21
22
  from django_components.template_parser import parse_bits
22
23
  from django_components.utils import gen_id
@@ -216,6 +217,30 @@ def do_component(parser: Parser, token: Token) -> ComponentNode:
216
217
  return component_node
217
218
 
218
219
 
220
+ @register.tag("provide")
221
+ def do_provide(parser: Parser, token: Token) -> SlotNode:
222
+ # e.g. {% provide <name> key=val key2=val2 %}
223
+ tag_name, *args = token.split_contents()
224
+ provide_key, kwargs = _parse_provide_args(parser, args, tag_name)
225
+
226
+ # Use a unique ID to be able to tie the fill nodes with components and slots
227
+ # NOTE: MUST be called BEFORE `parser.parse()` to ensure predictable numbering
228
+ slot_id = gen_id()
229
+ trace_msg("PARSE", "PROVIDE", provide_key, slot_id)
230
+
231
+ nodelist = parser.parse(parse_until=["endprovide"])
232
+ parser.delete_first_token()
233
+ slot_node = ProvideNode(
234
+ provide_key,
235
+ nodelist,
236
+ node_id=slot_id,
237
+ provide_kwargs=kwargs,
238
+ )
239
+
240
+ trace_msg("PARSE", "PROVIDE", provide_key, slot_id, "...Done!")
241
+ return slot_node
242
+
243
+
219
244
  @register.tag("html_attrs")
220
245
  def do_html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode:
221
246
  """
@@ -438,6 +463,32 @@ def _parse_fill_args(
438
463
  return slot_name_fexp, slot_default_var_fexp, slot_data_var_fexp
439
464
 
440
465
 
466
+ def _parse_provide_args(
467
+ parser: Parser,
468
+ bits: List[str],
469
+ tag_name: str,
470
+ ) -> Tuple[str, Dict[str, FilterExpression]]:
471
+ if not len(bits):
472
+ raise TemplateSyntaxError("'provide' tag does not match pattern {% provide <key> [key=val, ...] %}. ")
473
+
474
+ provide_key, *options = bits
475
+ if not is_wrapped_in_quotes(provide_key):
476
+ raise TemplateSyntaxError(f"'{tag_name}' key must be a string 'literal'.")
477
+
478
+ provide_key = resolve_string(provide_key, parser)
479
+
480
+ # Parse kwargs that will be 'provided' under the given key
481
+ _, tag_kwarg_pairs = parse_bits(parser=parser, bits=options, params=[], name=tag_name)
482
+ tag_kwargs: Dict[str, FilterExpression] = {}
483
+ for key, val in tag_kwarg_pairs:
484
+ if key in tag_kwargs:
485
+ # The keyword argument has already been supplied once
486
+ raise TemplateSyntaxError(f"'{tag_name}' received multiple values for keyword argument '{key}'")
487
+ tag_kwargs[key] = val
488
+
489
+ return provide_key, tag_kwargs
490
+
491
+
441
492
  def _get_positional_param(
442
493
  tag_name: str,
443
494
  param_name: str,