django-components 0.77__tar.gz → 0.78__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.77/src/django_components.egg-info → django_components-0.78}/PKG-INFO +1 -1
  2. {django_components-0.77 → django_components-0.78}/pyproject.toml +1 -1
  3. {django_components-0.77 → django_components-0.78}/src/django_components/attributes.py +9 -6
  4. {django_components-0.77 → django_components-0.78}/src/django_components/component.py +53 -0
  5. {django_components-0.77 → django_components-0.78/src/django_components.egg-info}/PKG-INFO +1 -1
  6. {django_components-0.77 → django_components-0.78}/src/django_components.egg-info/SOURCES.txt +5 -1
  7. {django_components-0.77 → django_components-0.78}/tests/test_attributes.py +3 -3
  8. django_components-0.78/tests/test_component.py +128 -0
  9. {django_components-0.77 → django_components-0.78}/tests/test_component_as_view.py +25 -1
  10. django_components-0.78/tests/test_component_media.py +388 -0
  11. {django_components-0.77 → django_components-0.78}/tests/test_context.py +257 -127
  12. {django_components-0.77 → django_components-0.78}/tests/test_dependency_rendering.py +3 -1
  13. {django_components-0.77 → django_components-0.78}/tests/test_template_parser.py +17 -15
  14. django_components-0.78/tests/test_templatetags.py +455 -0
  15. django_components-0.78/tests/test_templatetags_component.py +417 -0
  16. django_components-0.78/tests/test_templatetags_slot_fill.py +1294 -0
  17. django_components-0.78/tests/test_templatetags_templating.py +826 -0
  18. django_components-0.78/tests/testutils.py +176 -0
  19. django_components-0.77/tests/test_component.py +0 -1021
  20. django_components-0.77/tests/test_templatetags.py +0 -2699
  21. django_components-0.77/tests/testutils.py +0 -77
  22. {django_components-0.77 → django_components-0.78}/LICENSE +0 -0
  23. {django_components-0.77 → django_components-0.78}/README.md +0 -0
  24. {django_components-0.77 → django_components-0.78}/setup.cfg +0 -0
  25. {django_components-0.77 → django_components-0.78}/src/django_components/__init__.py +0 -0
  26. {django_components-0.77 → django_components-0.78}/src/django_components/app_settings.py +0 -0
  27. {django_components-0.77 → django_components-0.78}/src/django_components/apps.py +0 -0
  28. {django_components-0.77 → django_components-0.78}/src/django_components/component_registry.py +0 -0
  29. {django_components-0.77 → django_components-0.78}/src/django_components/context.py +0 -0
  30. {django_components-0.77 → django_components-0.78}/src/django_components/expression.py +0 -0
  31. {django_components-0.77 → django_components-0.78}/src/django_components/logger.py +0 -0
  32. {django_components-0.77 → django_components-0.78}/src/django_components/management/__init__.py +0 -0
  33. {django_components-0.77 → django_components-0.78}/src/django_components/management/commands/__init__.py +0 -0
  34. {django_components-0.77 → django_components-0.78}/src/django_components/management/commands/startcomponent.py +0 -0
  35. {django_components-0.77 → django_components-0.78}/src/django_components/management/commands/upgradecomponent.py +0 -0
  36. {django_components-0.77 → django_components-0.78}/src/django_components/middleware.py +0 -0
  37. {django_components-0.77 → django_components-0.78}/src/django_components/node.py +0 -0
  38. {django_components-0.77 → django_components-0.78}/src/django_components/py.typed +0 -0
  39. {django_components-0.77 → django_components-0.78}/src/django_components/safer_staticfiles/__init__.py +0 -0
  40. {django_components-0.77 → django_components-0.78}/src/django_components/safer_staticfiles/apps.py +0 -0
  41. {django_components-0.77 → django_components-0.78}/src/django_components/slots.py +0 -0
  42. {django_components-0.77 → django_components-0.78}/src/django_components/template_loader.py +0 -0
  43. {django_components-0.77 → django_components-0.78}/src/django_components/template_parser.py +0 -0
  44. {django_components-0.77 → django_components-0.78}/src/django_components/templatetags/__init__.py +0 -0
  45. {django_components-0.77 → django_components-0.78}/src/django_components/templatetags/component_tags.py +0 -0
  46. {django_components-0.77 → django_components-0.78}/src/django_components/types.py +0 -0
  47. {django_components-0.77 → django_components-0.78}/src/django_components/utils.py +0 -0
  48. {django_components-0.77 → django_components-0.78}/src/django_components.egg-info/dependency_links.txt +0 -0
  49. {django_components-0.77 → django_components-0.78}/src/django_components.egg-info/requires.txt +0 -0
  50. {django_components-0.77 → django_components-0.78}/src/django_components.egg-info/top_level.txt +0 -0
  51. {django_components-0.77 → django_components-0.78}/tests/test_autodiscover.py +0 -0
  52. /django_components-0.77/tests/test_startcomponent_command.py → /django_components-0.78/tests/test_command_startcomponent.py +0 -0
  53. {django_components-0.77 → django_components-0.78}/tests/test_registry.py +0 -0
  54. {django_components-0.77 → django_components-0.78}/tests/test_settings.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.77
3
+ Version: 0.78
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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "django_components"
7
- version = "0.77"
7
+ version = "0.78"
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"]
@@ -11,6 +11,9 @@ from django.utils.safestring import SafeString, mark_safe
11
11
 
12
12
  from django_components.template_parser import process_aggregate_kwargs
13
13
 
14
+ HTML_ATTRS_DEFAULTS_KEY = "defaults"
15
+ HTML_ATTRS_ATTRS_KEY = "attrs"
16
+
14
17
 
15
18
  class HtmlAttrsNode(Node):
16
19
  def __init__(
@@ -30,12 +33,12 @@ class HtmlAttrsNode(Node):
30
33
  # Resolve kwargs, while also extracting attrs and defaults keys
31
34
  for key, value in self.kwargs:
32
35
  resolved_value = value.resolve(context)
33
- if key.startswith("attrs:") or key.startswith("defaults:"):
36
+ if key.startswith(f"{HTML_ATTRS_ATTRS_KEY}:") or key.startswith(f"{HTML_ATTRS_DEFAULTS_KEY}:"):
34
37
  attrs_and_defaults_from_kwargs[key] = resolved_value
35
38
  continue
36
39
  # NOTE: These were already extracted into separate variables, so
37
40
  # ignore them here.
38
- elif key == "attrs" or key == "defaults":
41
+ elif key == HTML_ATTRS_ATTRS_KEY or key == HTML_ATTRS_DEFAULTS_KEY:
39
42
  continue
40
43
 
41
44
  append_attrs.append((key, resolved_value))
@@ -46,16 +49,16 @@ class HtmlAttrsNode(Node):
46
49
  # So by assigning the `attrs` and `defaults` keys, users are forced to use only
47
50
  # one approach or the other, but not both simultaneously.
48
51
  if self.attributes:
49
- attrs_and_defaults_from_kwargs["attrs"] = self.attributes.resolve(context)
52
+ attrs_and_defaults_from_kwargs[HTML_ATTRS_ATTRS_KEY] = self.attributes.resolve(context)
50
53
  if self.default_attrs:
51
- attrs_and_defaults_from_kwargs["defaults"] = self.default_attrs.resolve(context)
54
+ attrs_and_defaults_from_kwargs[HTML_ATTRS_DEFAULTS_KEY] = self.default_attrs.resolve(context)
52
55
 
53
56
  # Turn `{"attrs:blabla": 1}` into `{"attrs": {"blabla": 1}}`
54
57
  attrs_and_defaults_from_kwargs = process_aggregate_kwargs(attrs_and_defaults_from_kwargs)
55
58
 
56
59
  # NOTE: We want to allow to use `html_attrs` even without `attrs` or `defaults` params
57
- attrs = attrs_and_defaults_from_kwargs.get("attrs", {})
58
- default_attrs = attrs_and_defaults_from_kwargs.get("defualts", {})
60
+ attrs = attrs_and_defaults_from_kwargs.get(HTML_ATTRS_ATTRS_KEY, {})
61
+ default_attrs = attrs_and_defaults_from_kwargs.get(HTML_ATTRS_DEFAULTS_KEY, {})
59
62
 
60
63
  final_attrs = {**default_attrs, **attrs}
61
64
  final_attrs = append_attributes(*final_attrs.items(), *append_attrs)
@@ -1,6 +1,7 @@
1
1
  import inspect
2
2
  import os
3
3
  import sys
4
+ import types
4
5
  from pathlib import Path
5
6
  from typing import Any, ClassVar, Dict, List, Mapping, MutableMapping, Optional, Tuple, Type, Union
6
7
 
@@ -11,6 +12,7 @@ from django.template.base import FilterExpression, Node, NodeList, Template, Tex
11
12
  from django.template.context import Context
12
13
  from django.template.exceptions import TemplateSyntaxError
13
14
  from django.template.loader import get_template
15
+ from django.template.loader_tags import BLOCK_CONTEXT_KEY
14
16
  from django.utils.html import escape
15
17
  from django.utils.safestring import SafeString, mark_safe
16
18
  from django.views import View
@@ -285,7 +287,14 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
285
287
  # See https://github.com/EmilStenstrom/django-components/issues/414
286
288
  context = context if isinstance(context, Context) else Context(context)
287
289
  prepare_context(context, self.component_id)
290
+
288
291
  template = self.get_template(context)
292
+ _monkeypatch_template(template)
293
+
294
+ # Set `Template._is_component_nested` based on whether we're currently INSIDE
295
+ # the `{% extends %}` tag.
296
+ # Part of fix for https://github.com/EmilStenstrom/django-components/issues/508
297
+ template._is_component_nested = bool(context.render_context.get(BLOCK_CONTEXT_KEY))
289
298
 
290
299
  # Support passing slots explicitly to `render` method
291
300
  if slots_data:
@@ -445,3 +454,47 @@ class ComponentNode(Node):
445
454
 
446
455
  trace_msg("RENDR", "COMP", self.name_fexp, self.component_id, "...Done!")
447
456
  return output
457
+
458
+
459
+ def _monkeypatch_template(template: Template) -> None:
460
+ # Modify `Template.render` to set `isolated_context` kwarg of `push_state`
461
+ # based on our custom `Template._is_component_nested`.
462
+ #
463
+ # Part of fix for https://github.com/EmilStenstrom/django-components/issues/508
464
+ #
465
+ # NOTE 1: While we could've subclassed Template, then we would need to either
466
+ # 1) ask the user to change the backend, so all templates are of our subclass, or
467
+ # 2) copy the data from user's Template class instance to our subclass instance,
468
+ # which could lead to doubly parsing the source, and could be problematic if users
469
+ # used more exotic subclasses of Template.
470
+ #
471
+ # Instead, modifying only the `render` method of an already-existing instance
472
+ # should work well with any user-provided custom subclasses of Template, and it
473
+ # doesn't require the source to be parsed multiple times. User can pass extra args/kwargs,
474
+ # and can modify the rendering behavior by overriding the `_render` method.
475
+ #
476
+ # NOTE 2: Instead of setting `Template._is_component_nested`, alternatively we could
477
+ # have passed the value to `_monkeypatch_template` directly. However, we intentionally
478
+ # did NOT do that, so the monkey-patched method is more robust, and can be e.g. copied
479
+ # to other.
480
+ def _template_render(self: Template, context: Context, *args: Any, **kwargs: Any) -> str:
481
+ # ---------------- OUR CHANGES START ----------------
482
+ # We parametrized `isolated_context`, which was `True` in the original method.
483
+ if not hasattr(self, "_is_component_nested"):
484
+ isolated_context = True
485
+ else:
486
+ # MUST be `True` for templates that are NOT import with `{% extends %}` tag,
487
+ # and `False` otherwise.
488
+ isolated_context = not self._is_component_nested
489
+ # ---------------- OUR CHANGES END ----------------
490
+
491
+ with context.render_context.push_state(self, isolated_context=isolated_context):
492
+ if context.template is None:
493
+ with context.bind_template(self):
494
+ context.template_name = self.name
495
+ return self._render(context, *args, **kwargs)
496
+ else:
497
+ return self._render(context, *args, **kwargs)
498
+
499
+ # See https://stackoverflow.com/a/42154067/9788634
500
+ template.render = types.MethodType(_template_render, template)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.77
3
+ Version: 0.78
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
@@ -33,13 +33,17 @@ src/django_components/templatetags/__init__.py
33
33
  src/django_components/templatetags/component_tags.py
34
34
  tests/test_attributes.py
35
35
  tests/test_autodiscover.py
36
+ tests/test_command_startcomponent.py
36
37
  tests/test_component.py
37
38
  tests/test_component_as_view.py
39
+ tests/test_component_media.py
38
40
  tests/test_context.py
39
41
  tests/test_dependency_rendering.py
40
42
  tests/test_registry.py
41
43
  tests/test_settings.py
42
- tests/test_startcomponent_command.py
43
44
  tests/test_template_parser.py
44
45
  tests/test_templatetags.py
46
+ tests/test_templatetags_component.py
47
+ tests/test_templatetags_slot_fill.py
48
+ tests/test_templatetags_templating.py
45
49
  tests/testutils.py
@@ -6,7 +6,7 @@ from django_components.attributes import append_attributes, attributes_to_string
6
6
 
7
7
  # isort: off
8
8
  from .django_test_setup import * # NOQA
9
- from .testutils import BaseTestCase
9
+ from .testutils import BaseTestCase, parametrize_context_behavior
10
10
 
11
11
  # isort: on
12
12
 
@@ -83,6 +83,7 @@ class HtmlAttrsTests(BaseTestCase):
83
83
  {% endcomponent %}
84
84
  """ # noqa: E501
85
85
 
86
+ @parametrize_context_behavior(["django", "isolated"])
86
87
  def test_tag_positional_args(self):
87
88
  @component.register("test")
88
89
  class AttrsComponent(component.Component):
@@ -273,12 +274,11 @@ class HtmlAttrsTests(BaseTestCase):
273
274
  self.assertHTMLEqual(
274
275
  rendered,
275
276
  """
276
- <div class="added_class another-class" data-id=123>
277
+ <div class="added_class another-class override-me" data-id=123>
277
278
  content
278
279
  </div>
279
280
  """,
280
281
  )
281
- self.assertNotIn("override-me", rendered)
282
282
 
283
283
  def test_tag_no_defaults(self):
284
284
  @component.register("test")
@@ -0,0 +1,128 @@
1
+ """
2
+ Tests focusing on the Component class.
3
+ For tests focusing on the `component` tag, see `test_templatetags_component.py`
4
+ """
5
+
6
+ from django.core.exceptions import ImproperlyConfigured
7
+ from django.template import Context
8
+
9
+ # isort: off
10
+ from .django_test_setup import * # NOQA
11
+ from .testutils import BaseTestCase, parametrize_context_behavior
12
+
13
+ # isort: on
14
+
15
+ from django_components import component, types
16
+
17
+
18
+ class ComponentTest(BaseTestCase):
19
+ class ParentComponent(component.Component):
20
+ template: types.django_html = """
21
+ {% load component_tags %}
22
+ <div>
23
+ <h1>Parent content</h1>
24
+ {% component name="variable_display" shadowing_variable='override' new_variable='unique_val' %}
25
+ {% endcomponent %}
26
+ </div>
27
+ <div>
28
+ {% slot 'content' %}
29
+ <h2>Slot content</h2>
30
+ {% component name="variable_display" shadowing_variable='slot_default_override' new_variable='slot_default_unique' %}
31
+ {% endcomponent %}
32
+ {% endslot %}
33
+ </div>
34
+ """ # noqa
35
+
36
+ def get_context_data(self):
37
+ return {"shadowing_variable": "NOT SHADOWED"}
38
+
39
+ class VariableDisplay(component.Component):
40
+ template: types.django_html = """
41
+ {% load component_tags %}
42
+ <h1>Shadowing variable = {{ shadowing_variable }}</h1>
43
+ <h1>Uniquely named variable = {{ unique_variable }}</h1>
44
+ """
45
+
46
+ def get_context_data(self, shadowing_variable=None, new_variable=None):
47
+ context = {}
48
+ if shadowing_variable is not None:
49
+ context["shadowing_variable"] = shadowing_variable
50
+ if new_variable is not None:
51
+ context["unique_variable"] = new_variable
52
+ return context
53
+
54
+ @classmethod
55
+ def setUpClass(cls):
56
+ super().setUpClass()
57
+ component.registry.register(name="parent_component", component=cls.ParentComponent)
58
+ component.registry.register(name="variable_display", component=cls.VariableDisplay)
59
+
60
+ @parametrize_context_behavior(["django", "isolated"])
61
+ def test_empty_component(self):
62
+ class EmptyComponent(component.Component):
63
+ pass
64
+
65
+ with self.assertRaises(ImproperlyConfigured):
66
+ EmptyComponent("empty_component").get_template(Context({}))
67
+
68
+ @parametrize_context_behavior(["django", "isolated"])
69
+ def test_simple_component(self):
70
+ class SimpleComponent(component.Component):
71
+ template: types.django_html = """
72
+ Variable: <strong>{{ variable }}</strong>
73
+ """
74
+
75
+ def get_context_data(self, variable=None):
76
+ return {
77
+ "variable": variable,
78
+ }
79
+
80
+ class Media:
81
+ css = "style.css"
82
+ js = "script.js"
83
+
84
+ comp = SimpleComponent("simple_component")
85
+ context = Context(comp.get_context_data(variable="test"))
86
+
87
+ self.assertHTMLEqual(
88
+ comp.render_dependencies(),
89
+ """
90
+ <link href="style.css" media="all" rel="stylesheet">
91
+ <script src="script.js"></script>
92
+ """,
93
+ )
94
+
95
+ self.assertHTMLEqual(
96
+ comp.render(context),
97
+ """
98
+ Variable: <strong>test</strong>
99
+ """,
100
+ )
101
+
102
+ @parametrize_context_behavior(["django", "isolated"])
103
+ def test_component_with_dynamic_template(self):
104
+ class SvgComponent(component.Component):
105
+ def get_context_data(self, name, css_class="", title="", **attrs):
106
+ return {
107
+ "name": name,
108
+ "css_class": css_class,
109
+ "title": title,
110
+ **attrs,
111
+ }
112
+
113
+ def get_template_name(self, context):
114
+ return f"dynamic_{context['name']}.svg"
115
+
116
+ comp = SvgComponent("svg_component")
117
+ self.assertHTMLEqual(
118
+ comp.render(Context(comp.get_context_data(name="svg1"))),
119
+ """
120
+ <svg>Dynamic1</svg>
121
+ """,
122
+ )
123
+ self.assertHTMLEqual(
124
+ comp.render(Context(comp.get_context_data(name="svg2"))),
125
+ """
126
+ <svg>Dynamic2</svg>
127
+ """,
128
+ )
@@ -8,7 +8,7 @@ from django.urls import path
8
8
 
9
9
  # isort: off
10
10
  from .django_test_setup import * # noqa
11
- from .testutils import BaseTestCase
11
+ from .testutils import BaseTestCase, parametrize_context_behavior
12
12
 
13
13
  # isort: on
14
14
 
@@ -113,6 +113,7 @@ class TestComponentAsView(BaseTestCase):
113
113
  response.content,
114
114
  )
115
115
 
116
+ @parametrize_context_behavior(["django", "isolated"])
116
117
  def test_replace_slot_in_view(self):
117
118
  class MockComponentSlot(component.Component):
118
119
  template = """
@@ -141,6 +142,7 @@ class TestComponentAsView(BaseTestCase):
141
142
  response.content,
142
143
  )
143
144
 
145
+ @parametrize_context_behavior(["django", "isolated"])
144
146
  def test_replace_slot_in_view_with_insecure_content(self):
145
147
  class MockInsecureComponentSlot(component.Component):
146
148
  template = """
@@ -162,6 +164,28 @@ class TestComponentAsView(BaseTestCase):
162
164
  response.content,
163
165
  )
164
166
 
167
+ @parametrize_context_behavior(["django", "isolated"])
168
+ def test_replace_context_in_view(self):
169
+ class TestComponent(component.Component):
170
+ template = """
171
+ {% load component_tags %}
172
+ <div>
173
+ Hey, I'm {{ name }}
174
+ </div>
175
+ """
176
+
177
+ def get(self, request, *args, **kwargs) -> HttpResponse:
178
+ return self.render_to_response({"name": "Bob"})
179
+
180
+ client = CustomClient(urlpatterns=[path("test_context_django/", TestComponent.as_view())])
181
+ response = client.get("/test_context_django/")
182
+ self.assertEqual(response.status_code, 200)
183
+ self.assertIn(
184
+ b"Hey, I'm Bob",
185
+ response.content,
186
+ )
187
+
188
+ @parametrize_context_behavior(["django", "isolated"])
165
189
  def test_replace_context_in_view_with_insecure_content(self):
166
190
  class MockInsecureComponentContext(component.Component):
167
191
  template = """