django-components 0.65__tar.gz → 0.67__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 (46) hide show
  1. {django_components-0.65/src/django_components.egg-info → django_components-0.67}/PKG-INFO +38 -2
  2. {django_components-0.65 → django_components-0.67}/README.md +37 -1
  3. {django_components-0.65 → django_components-0.67}/pyproject.toml +1 -1
  4. django_components-0.67/src/django_components/__init__.py +63 -0
  5. django_components-0.67/src/django_components/app_settings.py +146 -0
  6. {django_components-0.65 → django_components-0.67}/src/django_components/component.py +71 -32
  7. django_components-0.67/src/django_components/context.py +122 -0
  8. django_components-0.67/src/django_components/logger.py +93 -0
  9. django_components-0.67/src/django_components/node.py +38 -0
  10. {django_components-0.65 → django_components-0.67}/src/django_components/slots.py +177 -152
  11. {django_components-0.65 → django_components-0.67}/src/django_components/templatetags/component_tags.py +39 -4
  12. django_components-0.67/src/django_components/utils.py +51 -0
  13. {django_components-0.65 → django_components-0.67/src/django_components.egg-info}/PKG-INFO +38 -2
  14. {django_components-0.65 → django_components-0.67}/src/django_components.egg-info/SOURCES.txt +2 -0
  15. {django_components-0.65 → django_components-0.67}/tests/test_autodiscover.py +43 -1
  16. {django_components-0.65 → django_components-0.67}/tests/test_component.py +205 -0
  17. {django_components-0.65 → django_components-0.67}/tests/test_context.py +17 -2
  18. {django_components-0.65 → django_components-0.67}/tests/test_templatetags.py +24 -24
  19. django_components-0.65/src/django_components/__init__.py +0 -40
  20. django_components-0.65/src/django_components/app_settings.py +0 -41
  21. django_components-0.65/src/django_components/logger.py +0 -3
  22. django_components-0.65/src/django_components/utils.py +0 -32
  23. {django_components-0.65 → django_components-0.67}/LICENSE +0 -0
  24. {django_components-0.65 → django_components-0.67}/setup.cfg +0 -0
  25. {django_components-0.65 → django_components-0.67}/src/django_components/apps.py +0 -0
  26. {django_components-0.65 → django_components-0.67}/src/django_components/component_registry.py +0 -0
  27. {django_components-0.65 → django_components-0.67}/src/django_components/management/__init__.py +0 -0
  28. {django_components-0.65 → django_components-0.67}/src/django_components/management/commands/__init__.py +0 -0
  29. {django_components-0.65 → django_components-0.67}/src/django_components/management/commands/startcomponent.py +0 -0
  30. {django_components-0.65 → django_components-0.67}/src/django_components/management/commands/upgradecomponent.py +0 -0
  31. {django_components-0.65 → django_components-0.67}/src/django_components/middleware.py +0 -0
  32. {django_components-0.65 → django_components-0.67}/src/django_components/py.typed +0 -0
  33. {django_components-0.65 → django_components-0.67}/src/django_components/safer_staticfiles/__init__.py +0 -0
  34. {django_components-0.65 → django_components-0.67}/src/django_components/safer_staticfiles/apps.py +0 -0
  35. {django_components-0.65 → django_components-0.67}/src/django_components/template_loader.py +0 -0
  36. {django_components-0.65 → django_components-0.67}/src/django_components/templatetags/__init__.py +0 -0
  37. {django_components-0.65 → django_components-0.67}/src/django_components/types.py +0 -0
  38. {django_components-0.65 → django_components-0.67}/src/django_components.egg-info/dependency_links.txt +0 -0
  39. {django_components-0.65 → django_components-0.67}/src/django_components.egg-info/requires.txt +0 -0
  40. {django_components-0.65 → django_components-0.67}/src/django_components.egg-info/top_level.txt +0 -0
  41. {django_components-0.65 → django_components-0.67}/tests/test_component_as_view.py +0 -0
  42. {django_components-0.65 → django_components-0.67}/tests/test_dependency_rendering.py +0 -0
  43. {django_components-0.65 → django_components-0.67}/tests/test_registry.py +0 -0
  44. {django_components-0.65 → django_components-0.67}/tests/test_settings.py +0 -0
  45. {django_components-0.65 → django_components-0.67}/tests/test_startcomponent_command.py +0 -0
  46. {django_components-0.65 → django_components-0.67}/tests/testutils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.65
3
+ Version: 0.67
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
@@ -25,7 +25,7 @@ Description-Content-Type: text/markdown
25
25
  License-File: LICENSE
26
26
  Requires-Dist: Django>=3.2
27
27
 
28
- # django-components
28
+ # <img src="logo/logo-black-on-white.svg" alt="django-components" style="max-width: 100%; background: white; color: black;">
29
29
  <a href="https://github.com/EmilStenstrom/django-components/actions?query=workflow%3A%22Run+tests%22"><img align="right" src="https://github.com/EmilStenstrom/django-components/workflows/Run%20tests/badge.svg" alt="Show test status"></a>
30
30
  <a href="https://pepy.tech/project/django-components"><img align="right" src="https://pepy.tech/badge/django-components" alt="Show download stats"></a>
31
31
 
@@ -47,6 +47,8 @@ Read on to learn about the details!
47
47
 
48
48
  ## Release notes
49
49
 
50
+ **Version 0.67** CHANGED the default way how context variables are resolved in slots. See the [documentation](#isolate-components-slots) for more details.
51
+
50
52
  🚨📢 **Version 0.5** CHANGES THE SYNTAX for components. `component_block` is now `component`, and `component` blocks need an ending `endcomponent` tag. The new `python manage.py upgradecomponent` command can be used to upgrade a directory (use --path argument to point to each dir) of components to the new syntax automatically.
51
53
 
52
54
  This change is done to simplify the API in anticipation of a 1.0 release of django_components. After 1.0 we intend to be stricter with big changes like this in point releases.
@@ -248,6 +250,19 @@ class Calendar(component.Component):
248
250
 
249
251
  And voilá!! We've created our first component.
250
252
 
253
+ ## Autodiscovery
254
+
255
+ By default, the Python files in the `components` app are auto-imported in order to auto-register the components (e.g. `components/button/button.py`).
256
+
257
+ Autodiscovery occurs when Django is loaded, during the `ready` hook of the `apps.py` file.
258
+
259
+ If you are using autodiscovery, keep a few points in mind:
260
+ - Avoid defining any logic on the module-level inside the `components` dir, that you would not want to run anyway.
261
+ - Components inside the auto-imported files still need to be registered with `@component.register()`
262
+ - 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).
263
+
264
+ Autodiscovery can be disabled via in the [settings](#disable-autodiscovery).
265
+
251
266
  ## Use the component in a template
252
267
 
253
268
  First load the `component_tags` tag library, then use the `component_[js/css]_dependencies` and `component` tags to render the component to the page.
@@ -718,6 +733,27 @@ COMPONENTS = {
718
733
  }
719
734
  ```
720
735
 
736
+ ### Isolate components' slots
737
+
738
+ What variables should be available from inside a component slot?
739
+
740
+ By default, variables inside component slots are preferentially taken from the root context.
741
+ This is similar to [how Vue renders slots](https://vuejs.org/guide/components/slots.html#render-scope),
742
+ except that, if variable is not found in the root, then the surrounding context is searched too.
743
+
744
+ You can change this with the `slot_contet_behavior` setting. Options are:
745
+ - `"prefer_root"` - Default - as described above
746
+ - `"isolated"` - Same behavior as Vue - variables are taken ONLY from the root context
747
+ - `"allow_override"` - slot context variables are taken from its surroundings (default before v0.67)
748
+
749
+ ```python
750
+ COMPONENTS = {
751
+ "slot_context_behavior": "isolated",
752
+ }
753
+ ```
754
+
755
+ For further details and examples, see [SlotContextBehavior](https://github.com/EmilStenstrom/django-components/blob/master/src/django_components/app_settings.py#L12).
756
+
721
757
  ## Logging and debugging
722
758
 
723
759
  Django components supports [logging with Django](https://docs.djangoproject.com/en/5.0/howto/logging/#logging-how-to). This can help with troubleshooting.
@@ -1,4 +1,4 @@
1
- # django-components
1
+ # <img src="logo/logo-black-on-white.svg" alt="django-components" style="max-width: 100%; background: white; color: black;">
2
2
  <a href="https://github.com/EmilStenstrom/django-components/actions?query=workflow%3A%22Run+tests%22"><img align="right" src="https://github.com/EmilStenstrom/django-components/workflows/Run%20tests/badge.svg" alt="Show test status"></a>
3
3
  <a href="https://pepy.tech/project/django-components"><img align="right" src="https://pepy.tech/badge/django-components" alt="Show download stats"></a>
4
4
 
@@ -20,6 +20,8 @@ Read on to learn about the details!
20
20
 
21
21
  ## Release notes
22
22
 
23
+ **Version 0.67** CHANGED the default way how context variables are resolved in slots. See the [documentation](#isolate-components-slots) for more details.
24
+
23
25
  🚨📢 **Version 0.5** CHANGES THE SYNTAX for components. `component_block` is now `component`, and `component` blocks need an ending `endcomponent` tag. The new `python manage.py upgradecomponent` command can be used to upgrade a directory (use --path argument to point to each dir) of components to the new syntax automatically.
24
26
 
25
27
  This change is done to simplify the API in anticipation of a 1.0 release of django_components. After 1.0 we intend to be stricter with big changes like this in point releases.
@@ -221,6 +223,19 @@ class Calendar(component.Component):
221
223
 
222
224
  And voilá!! We've created our first component.
223
225
 
226
+ ## Autodiscovery
227
+
228
+ By default, the Python files in the `components` app are auto-imported in order to auto-register the components (e.g. `components/button/button.py`).
229
+
230
+ Autodiscovery occurs when Django is loaded, during the `ready` hook of the `apps.py` file.
231
+
232
+ If you are using autodiscovery, keep a few points in mind:
233
+ - Avoid defining any logic on the module-level inside the `components` dir, that you would not want to run anyway.
234
+ - Components inside the auto-imported files still need to be registered with `@component.register()`
235
+ - 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).
236
+
237
+ Autodiscovery can be disabled via in the [settings](#disable-autodiscovery).
238
+
224
239
  ## Use the component in a template
225
240
 
226
241
  First load the `component_tags` tag library, then use the `component_[js/css]_dependencies` and `component` tags to render the component to the page.
@@ -691,6 +706,27 @@ COMPONENTS = {
691
706
  }
692
707
  ```
693
708
 
709
+ ### Isolate components' slots
710
+
711
+ What variables should be available from inside a component slot?
712
+
713
+ By default, variables inside component slots are preferentially taken from the root context.
714
+ This is similar to [how Vue renders slots](https://vuejs.org/guide/components/slots.html#render-scope),
715
+ except that, if variable is not found in the root, then the surrounding context is searched too.
716
+
717
+ You can change this with the `slot_contet_behavior` setting. Options are:
718
+ - `"prefer_root"` - Default - as described above
719
+ - `"isolated"` - Same behavior as Vue - variables are taken ONLY from the root context
720
+ - `"allow_override"` - slot context variables are taken from its surroundings (default before v0.67)
721
+
722
+ ```python
723
+ COMPONENTS = {
724
+ "slot_context_behavior": "isolated",
725
+ }
726
+ ```
727
+
728
+ For further details and examples, see [SlotContextBehavior](https://github.com/EmilStenstrom/django-components/blob/master/src/django_components/app_settings.py#L12).
729
+
694
730
  ## Logging and debugging
695
731
 
696
732
  Django components supports [logging with Django](https://docs.djangoproject.com/en/5.0/howto/logging/#logging-how-to). This can help with troubleshooting.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "django_components"
7
- version = "0.65"
7
+ version = "0.67"
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"]
@@ -0,0 +1,63 @@
1
+ import importlib
2
+ import importlib.util
3
+ import os
4
+ from pathlib import Path
5
+
6
+ import django
7
+ from django.conf import settings
8
+ from django.utils.module_loading import autodiscover_modules
9
+
10
+ from django_components.logger import logger
11
+ from django_components.utils import search
12
+
13
+ if django.VERSION < (3, 2):
14
+ default_app_config = "django_components.apps.ComponentsConfig"
15
+
16
+
17
+ def autodiscover() -> None:
18
+ from django_components.app_settings import app_settings
19
+
20
+ if app_settings.AUTODISCOVER:
21
+ # Autodetect a components.py file in each app directory
22
+ autodiscover_modules("components")
23
+
24
+ # Autodetect a <component>.py file in a components dir
25
+ component_filepaths = search(search_glob="**/*.py").matched_files
26
+ logger.debug(f"Autodiscover found {len(component_filepaths)} files in component directories.")
27
+
28
+ for path in component_filepaths:
29
+ # This imports the file and runs it's code. So if the file defines any
30
+ # django components, they will be registered.
31
+ module_name = _filepath_to_python_module(path)
32
+ logger.debug(f'Importing module "{module_name}" (derived from path "{path}")')
33
+ importlib.import_module(module_name)
34
+
35
+ for path_lib in app_settings.LIBRARIES:
36
+ importlib.import_module(path_lib)
37
+
38
+
39
+ def _filepath_to_python_module(file_path: Path) -> str:
40
+ """
41
+ Derive python import path from the filesystem path.
42
+
43
+ Example:
44
+ - If project root is `/path/to/project`
45
+ - And file_path is `/path/to/project/app/components/mycomp.py`
46
+ - Then the path relative to project root is `app/components/mycomp.py`
47
+ - Which we then turn into python import path `app.components.mycomp`
48
+ """
49
+ if hasattr(settings, "BASE_DIR"):
50
+ project_root = str(settings.BASE_DIR)
51
+ else:
52
+ # Fallback for getting the root dir, see https://stackoverflow.com/a/16413955/9788634
53
+ project_root = os.path.abspath(os.path.dirname(__name__))
54
+
55
+ rel_path = os.path.relpath(file_path, start=project_root)
56
+ rel_path_without_suffix = str(Path(rel_path).with_suffix(""))
57
+
58
+ # NOTE: Path normalizes paths to use `/` as separator, while os.path
59
+ # uses `os.path.sep`.
60
+ sep = os.path.sep if os.path.sep in rel_path_without_suffix else "/"
61
+ module_name = rel_path_without_suffix.replace(sep, ".")
62
+
63
+ return module_name
@@ -0,0 +1,146 @@
1
+ from enum import Enum
2
+ from typing import Dict, List
3
+
4
+ from django.conf import settings
5
+
6
+
7
+ class ContextBehavior(str, Enum):
8
+ GLOBAL = "global"
9
+ ISOLATED = "isolated"
10
+
11
+
12
+ class SlotContextBehavior(str, Enum):
13
+ ALLOW_OVERRIDE = "allow_override"
14
+ """
15
+ Components CAN override the slot context variables passed from the outer scopes.
16
+ Contexts of deeper components take precedence over shallower ones.
17
+
18
+ Example:
19
+
20
+ Given this template
21
+
22
+ ```txt
23
+ {% component 'my_comp' %}
24
+ {{ my_var }}
25
+ {% endcomponent %}
26
+ ```
27
+
28
+ and this context passed to the render function (AKA root context)
29
+ ```py
30
+ { "my_var": 123 }
31
+ ```
32
+
33
+ Then if component "my_comp" defines context
34
+ ```py
35
+ { "my_var": 456 }
36
+ ```
37
+
38
+ Then since "my_comp" overrides the varialbe "my_var", so `{{ my_var }}` will equal `456`.
39
+ """
40
+
41
+ PREFER_ROOT = "prefer_root"
42
+ """
43
+ This is the same as "allow_override", except any variables defined in the root context
44
+ take precedence over anything else.
45
+
46
+ So if a variable is found in the root context, then root context is used.
47
+ Otherwise, the context of the component where the slot fill is located is used.
48
+
49
+ Example:
50
+
51
+ Given this template
52
+
53
+ ```txt
54
+ {% component 'my_comp' %}
55
+ {{ my_var_one }}
56
+ {{ my_var_two }}
57
+ {% endcomponent %}
58
+ ```
59
+
60
+ and this context passed to the render function (AKA root context)
61
+ ```py
62
+ { "my_var_one": 123 }
63
+ ```
64
+
65
+ Then if component "my_comp" defines context
66
+ ```py
67
+ { "my_var": 456, "my_var_two": "abc" }
68
+ ```
69
+
70
+ Then the rendered `{{ my_var_one }}` will equal to `123`, and `{{ my_var_two }}`
71
+ will equal to "abc".
72
+ """
73
+
74
+ ISOLATED = "isolated"
75
+ """
76
+ This setting makes the slots behave similar to Vue or React, where
77
+ the slot uses EXCLUSIVELY the root context, and nested components CANNOT
78
+ override context variables inside the slots.
79
+
80
+ Example:
81
+
82
+ Given this template
83
+
84
+ ```txt
85
+ {% component 'my_comp' %}
86
+ {{ my_var }}
87
+ {% endcomponent %}
88
+ ```
89
+
90
+ and this context passed to the render function (AKA root context)
91
+ ```py
92
+ { "my_var": 123 }
93
+ ```
94
+
95
+ Then if component "my_comp" defines context
96
+ ```py
97
+ { "my_var": 456 }
98
+ ```
99
+
100
+ Then the rendered `{{ my_var }}` will equal `123`.
101
+ """
102
+
103
+
104
+ class AppSettings:
105
+ @property
106
+ def settings(self) -> Dict:
107
+ return getattr(settings, "COMPONENTS", {})
108
+
109
+ @property
110
+ def AUTODISCOVER(self) -> bool:
111
+ return self.settings.get("autodiscover", True)
112
+
113
+ @property
114
+ def LIBRARIES(self) -> List:
115
+ return self.settings.get("libraries", [])
116
+
117
+ @property
118
+ def TEMPLATE_CACHE_SIZE(self) -> int:
119
+ return self.settings.get("template_cache_size", 128)
120
+
121
+ @property
122
+ def CONTEXT_BEHAVIOR(self) -> ContextBehavior:
123
+ raw_value = self.settings.get("context_behavior", ContextBehavior.GLOBAL.value)
124
+ return self._validate_context_behavior(raw_value)
125
+
126
+ def _validate_context_behavior(self, raw_value: ContextBehavior) -> ContextBehavior:
127
+ try:
128
+ return ContextBehavior(raw_value)
129
+ except ValueError:
130
+ valid_values = [behavior.value for behavior in ContextBehavior]
131
+ raise ValueError(f"Invalid context behavior: {raw_value}. Valid options are {valid_values}")
132
+
133
+ @property
134
+ def SLOT_CONTEXT_BEHAVIOR(self) -> SlotContextBehavior:
135
+ raw_value = self.settings.get("slot_context_behavior", SlotContextBehavior.PREFER_ROOT.value)
136
+ return self._validate_slot_context_behavior(raw_value)
137
+
138
+ def _validate_slot_context_behavior(self, raw_value: SlotContextBehavior) -> SlotContextBehavior:
139
+ try:
140
+ return SlotContextBehavior(raw_value)
141
+ except ValueError:
142
+ valid_values = [behavior.value for behavior in SlotContextBehavior]
143
+ raise ValueError(f"Invalid slot context behavior: {raw_value}. Valid options are {valid_values}")
144
+
145
+
146
+ app_settings = AppSettings()
@@ -2,7 +2,7 @@ import inspect
2
2
  import os
3
3
  import sys
4
4
  from pathlib import Path
5
- from typing import Any, ClassVar, Dict, Iterable, List, Mapping, MutableMapping, Optional, Tuple, Type, Union
5
+ from typing import Any, ClassVar, Dict, List, Mapping, MutableMapping, Optional, Tuple, Type, Union
6
6
 
7
7
  from django.core.exceptions import ImproperlyConfigured
8
8
  from django.forms.widgets import Media, MediaDefiningClass
@@ -20,17 +20,24 @@ from django.views import View
20
20
  # way the two modules depend on one another.
21
21
  from django_components.component_registry import registry # NOQA
22
22
  from django_components.component_registry import AlreadyRegistered, ComponentRegistry, NotRegistered, register # NOQA
23
- from django_components.logger import logger
23
+ from django_components.context import (
24
+ capture_root_context,
25
+ get_root_context,
26
+ set_root_context,
27
+ set_slot_component_association,
28
+ )
29
+ from django_components.logger import logger, trace_msg
24
30
  from django_components.middleware import is_dependency_middleware_active
31
+ from django_components.node import walk_nodelist
25
32
  from django_components.slots import (
26
- DefaultFillContent,
27
- ImplicitFillNode,
28
- NamedFillContent,
29
- NamedFillNode,
33
+ DEFAULT_SLOT_KEY,
34
+ FillContent,
35
+ FillNode,
30
36
  SlotName,
37
+ SlotNode,
31
38
  render_component_template_with_slots,
32
39
  )
33
- from django_components.utils import search
40
+ from django_components.utils import gen_id, search
34
41
 
35
42
  RENDERED_COMMENT_TEMPLATE = "<!-- _RENDERED {name} -->"
36
43
 
@@ -89,7 +96,7 @@ def _resolve_component_relative_files(attrs: MutableMapping) -> None:
89
96
 
90
97
  # Prepare all possible directories we need to check when searching for
91
98
  # component's template and media files
92
- components_dirs = search()
99
+ components_dirs = search().searched_dirs
93
100
 
94
101
  # Get the directory where the component class is defined
95
102
  try:
@@ -185,12 +192,14 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
185
192
  def __init__(
186
193
  self,
187
194
  registered_name: Optional[str] = None,
195
+ component_id: Optional[str] = None,
188
196
  outer_context: Optional[Context] = None,
189
- fill_content: Union[DefaultFillContent, Iterable[NamedFillContent]] = (), # type: ignore
197
+ fill_content: Dict[str, FillContent] = {},
190
198
  ):
191
199
  self.registered_name: Optional[str] = registered_name
192
200
  self.outer_context: Context = outer_context or Context()
193
201
  self.fill_content = fill_content
202
+ self.component_id = component_id or gen_id()
194
203
 
195
204
  def __init_subclass__(cls, **kwargs: Any) -> None:
196
205
  cls.class_hash = hash(inspect.getfile(cls) + cls.__name__)
@@ -230,6 +239,12 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
230
239
  return mark_safe(f"<script>{self.js}</script>")
231
240
  return mark_safe("\n".join(self.media.render_js()))
232
241
 
242
+ # NOTE: When the template is taken from a file (AKA
243
+ # specified via `template_name`), then we leverage
244
+ # Django's template caching. This means that the same
245
+ # instance of Template is reused. This is important to keep
246
+ # in mind, because the implication is that we should
247
+ # treat Templates AND their nodelists as IMMUTABLE.
233
248
  def get_template(self, context: Mapping) -> Template:
234
249
  template_string = self.get_template_string(context)
235
250
  if template_string is not None:
@@ -246,7 +261,7 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
246
261
 
247
262
  def render(
248
263
  self,
249
- context_data: Dict[str, Any],
264
+ context_data: Union[Dict[str, Any], Context],
250
265
  slots_data: Optional[Dict[SlotName, str]] = None,
251
266
  escape_slots_content: bool = True,
252
267
  ) -> str:
@@ -255,14 +270,25 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
255
270
  context = context_data if isinstance(context_data, Context) else Context(context_data)
256
271
  template = self.get_template(context)
257
272
 
273
+ # Associate the slots with this component for this context
274
+ # This allows us to look up component-specific slot fills.
275
+ def on_node(node: Node) -> None:
276
+ if isinstance(node, SlotNode):
277
+ trace_msg("ASSOC", "SLOT", node.name, node.node_id, component_id=self.component_id)
278
+ set_slot_component_association(context, node.node_id, self.component_id)
279
+
280
+ walk_nodelist(template.nodelist, on_node)
281
+
258
282
  if slots_data:
259
283
  self._fill_slots(slots_data, escape_slots_content)
260
284
 
261
- return render_component_template_with_slots(template, context, self.fill_content, self.registered_name)
285
+ return render_component_template_with_slots(
286
+ self.component_id, template, context, self.fill_content, self.registered_name
287
+ )
262
288
 
263
289
  def render_to_response(
264
290
  self,
265
- context_data: Dict[str, Any],
291
+ context_data: Union[Dict[str, Any], Context],
266
292
  slots_data: Optional[Dict[SlotName, str]] = None,
267
293
  escape_slots_content: bool = True,
268
294
  *args: Any,
@@ -280,14 +306,13 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
280
306
  escape_content: bool = True,
281
307
  ) -> None:
282
308
  """Fill component slots outside of template rendering."""
283
- self.fill_content = [
284
- (
285
- slot_name,
309
+ self.fill_content = {
310
+ slot_name: FillContent(
286
311
  TextNode(escape(content) if escape_content else content),
287
312
  None,
288
313
  )
289
314
  for (slot_name, content) in slots_data.items()
290
- ]
315
+ }
291
316
 
292
317
 
293
318
  class ComponentNode(Node):
@@ -299,20 +324,16 @@ class ComponentNode(Node):
299
324
  context_args: List[FilterExpression],
300
325
  context_kwargs: Mapping[str, FilterExpression],
301
326
  isolated_context: bool = False,
302
- fill_nodes: Union[ImplicitFillNode, Iterable[NamedFillNode]] = (),
327
+ fill_nodes: Optional[List[FillNode]] = None,
328
+ component_id: Optional[str] = None,
303
329
  ) -> None:
330
+ self.component_id = component_id or gen_id()
304
331
  self.name_fexp = name_fexp
305
332
  self.context_args = context_args or []
306
333
  self.context_kwargs = context_kwargs or {}
307
334
  self.isolated_context = isolated_context
308
- self.fill_nodes = fill_nodes
309
- self.nodelist = self._create_nodelist(fill_nodes)
310
-
311
- def _create_nodelist(self, fill_nodes: Union[Iterable[Node], ImplicitFillNode]) -> NodeList:
312
- if isinstance(fill_nodes, ImplicitFillNode):
313
- return NodeList([fill_nodes])
314
- else:
315
- return NodeList(fill_nodes)
335
+ self.fill_nodes = fill_nodes or []
336
+ self.nodelist = NodeList(fill_nodes)
316
337
 
317
338
  def __repr__(self) -> str:
318
339
  return "<ComponentNode: {}. Contents: {!r}>".format(
@@ -321,46 +342,64 @@ class ComponentNode(Node):
321
342
  )
322
343
 
323
344
  def render(self, context: Context) -> str:
345
+ trace_msg("RENDR", "COMP", self.name_fexp, self.component_id)
346
+
324
347
  resolved_component_name = self.name_fexp.resolve(context)
325
348
  component_cls: Type[Component] = registry.get(resolved_component_name)
326
349
 
350
+ # If this is the outer-/top-most component node, then save the outer context,
351
+ # so it can be used by nested Slots.
352
+ capture_root_context(context)
353
+
327
354
  # Resolve FilterExpressions and Variables that were passed as args to the
328
355
  # component, then call component's context method
329
356
  # to get values to insert into the context
330
357
  resolved_context_args = [safe_resolve(arg, context) for arg in self.context_args]
331
358
  resolved_context_kwargs = {key: safe_resolve(kwarg, context) for key, kwarg in self.context_kwargs.items()}
332
359
 
333
- if isinstance(self.fill_nodes, ImplicitFillNode):
334
- fill_content = self.fill_nodes.nodelist
360
+ is_default_slot = len(self.fill_nodes) == 1 and self.fill_nodes[0].is_implicit
361
+ if is_default_slot:
362
+ fill_content: Dict[str, FillContent] = {DEFAULT_SLOT_KEY: FillContent(self.fill_nodes[0].nodelist, None)}
335
363
  else:
336
- fill_content = []
364
+ fill_content = {}
337
365
  for fill_node in self.fill_nodes:
338
366
  # Note that outer component context is used to resolve variables in
339
367
  # fill tag.
340
368
  resolved_name = fill_node.name_fexp.resolve(context)
341
369
  resolved_fill_alias = fill_node.resolve_alias(context, resolved_component_name)
342
- fill_content.append((resolved_name, fill_node.nodelist, resolved_fill_alias))
370
+ fill_content[resolved_name] = FillContent(fill_node.nodelist, resolved_fill_alias)
343
371
 
344
372
  component: Component = component_cls(
345
373
  registered_name=resolved_component_name,
346
374
  outer_context=context,
347
375
  fill_content=fill_content,
376
+ component_id=self.component_id,
348
377
  )
349
378
 
350
379
  component_context: dict = component.get_context_data(*resolved_context_args, **resolved_context_kwargs)
351
380
 
381
+ # Prevent outer context from leaking into the template of the component
352
382
  if self.isolated_context:
383
+ # Even if contexts are isolated, we still need to pass down the
384
+ # original context so variables in slots can be rendered using
385
+ # the original context.
386
+ root_ctx = get_root_context(context)
353
387
  context = context.new()
388
+ set_root_context(context, root_ctx)
389
+
354
390
  with context.update(component_context):
355
391
  rendered_component = component.render(context)
356
392
 
357
393
  if is_dependency_middleware_active():
358
- return RENDERED_COMMENT_TEMPLATE.format(name=resolved_component_name) + rendered_component
394
+ output = RENDERED_COMMENT_TEMPLATE.format(name=resolved_component_name) + rendered_component
359
395
  else:
360
- return rendered_component
396
+ output = rendered_component
397
+
398
+ trace_msg("RENDR", "COMP", self.name_fexp, self.component_id, "...Done!")
399
+ return output
361
400
 
362
401
 
363
402
  def safe_resolve(context_item: FilterExpression, context: Context) -> Any:
364
- """Resolve FilterExpressions and Variables in context if possible. Return other items unchanged."""
403
+ """Resolve FilterExpressions and Variables in context if possible. Return other items unchanged."""
365
404
 
366
405
  return context_item.resolve(context) if hasattr(context_item, "resolve") else context_item