django-components 0.82__tar.gz → 0.83__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 (55) hide show
  1. {django_components-0.82/src/django_components.egg-info → django_components-0.83}/PKG-INFO +19 -4
  2. {django_components-0.82 → django_components-0.83}/README.md +18 -3
  3. {django_components-0.82 → django_components-0.83}/pyproject.toml +1 -1
  4. {django_components-0.82 → django_components-0.83}/src/django_components/attributes.py +7 -2
  5. {django_components-0.82 → django_components-0.83}/src/django_components/component.py +17 -3
  6. {django_components-0.82 → django_components-0.83}/src/django_components/context.py +1 -1
  7. {django_components-0.82 → django_components-0.83}/src/django_components/safer_staticfiles/apps.py +2 -0
  8. {django_components-0.82 → django_components-0.83}/src/django_components/slots.py +15 -1
  9. {django_components-0.82 → django_components-0.83/src/django_components.egg-info}/PKG-INFO +19 -4
  10. {django_components-0.82 → django_components-0.83}/src/django_components.egg-info/SOURCES.txt +1 -0
  11. {django_components-0.82 → django_components-0.83}/tests/test_attributes.py +2 -0
  12. {django_components-0.82 → django_components-0.83}/tests/test_autodiscover.py +1 -1
  13. {django_components-0.82 → django_components-0.83}/tests/test_component_media.py +8 -1
  14. django_components-0.83/tests/test_safer_staticfiles.py +103 -0
  15. {django_components-0.82 → django_components-0.83}/tests/test_templatetags_provide.py +41 -0
  16. {django_components-0.82 → django_components-0.83}/tests/test_templatetags_slot_fill.py +23 -23
  17. {django_components-0.82 → django_components-0.83}/LICENSE +0 -0
  18. {django_components-0.82 → django_components-0.83}/setup.cfg +0 -0
  19. {django_components-0.82 → django_components-0.83}/src/django_components/__init__.py +0 -0
  20. {django_components-0.82 → django_components-0.83}/src/django_components/app_settings.py +0 -0
  21. {django_components-0.82 → django_components-0.83}/src/django_components/apps.py +0 -0
  22. {django_components-0.82 → django_components-0.83}/src/django_components/component_media.py +0 -0
  23. {django_components-0.82 → django_components-0.83}/src/django_components/component_registry.py +0 -0
  24. {django_components-0.82 → django_components-0.83}/src/django_components/expression.py +0 -0
  25. {django_components-0.82 → django_components-0.83}/src/django_components/logger.py +0 -0
  26. {django_components-0.82 → django_components-0.83}/src/django_components/management/__init__.py +0 -0
  27. {django_components-0.82 → django_components-0.83}/src/django_components/management/commands/__init__.py +0 -0
  28. {django_components-0.82 → django_components-0.83}/src/django_components/management/commands/startcomponent.py +0 -0
  29. {django_components-0.82 → django_components-0.83}/src/django_components/management/commands/upgradecomponent.py +0 -0
  30. {django_components-0.82 → django_components-0.83}/src/django_components/middleware.py +0 -0
  31. {django_components-0.82 → django_components-0.83}/src/django_components/node.py +0 -0
  32. {django_components-0.82 → django_components-0.83}/src/django_components/provide.py +0 -0
  33. {django_components-0.82 → django_components-0.83}/src/django_components/py.typed +0 -0
  34. {django_components-0.82 → django_components-0.83}/src/django_components/safer_staticfiles/__init__.py +0 -0
  35. {django_components-0.82 → django_components-0.83}/src/django_components/template_loader.py +0 -0
  36. {django_components-0.82 → django_components-0.83}/src/django_components/template_parser.py +0 -0
  37. {django_components-0.82 → django_components-0.83}/src/django_components/templatetags/__init__.py +0 -0
  38. {django_components-0.82 → django_components-0.83}/src/django_components/templatetags/component_tags.py +0 -0
  39. {django_components-0.82 → django_components-0.83}/src/django_components/types.py +0 -0
  40. {django_components-0.82 → django_components-0.83}/src/django_components/utils.py +0 -0
  41. {django_components-0.82 → django_components-0.83}/src/django_components.egg-info/dependency_links.txt +0 -0
  42. {django_components-0.82 → django_components-0.83}/src/django_components.egg-info/requires.txt +0 -0
  43. {django_components-0.82 → django_components-0.83}/src/django_components.egg-info/top_level.txt +0 -0
  44. {django_components-0.82 → django_components-0.83}/tests/test_command_startcomponent.py +0 -0
  45. {django_components-0.82 → django_components-0.83}/tests/test_component.py +0 -0
  46. {django_components-0.82 → django_components-0.83}/tests/test_component_as_view.py +0 -0
  47. {django_components-0.82 → django_components-0.83}/tests/test_context.py +0 -0
  48. {django_components-0.82 → django_components-0.83}/tests/test_dependency_rendering.py +0 -0
  49. {django_components-0.82 → django_components-0.83}/tests/test_registry.py +0 -0
  50. {django_components-0.82 → django_components-0.83}/tests/test_settings.py +0 -0
  51. {django_components-0.82 → django_components-0.83}/tests/test_template_parser.py +0 -0
  52. {django_components-0.82 → django_components-0.83}/tests/test_templatetags.py +0 -0
  53. {django_components-0.82 → django_components-0.83}/tests/test_templatetags_component.py +0 -0
  54. {django_components-0.82 → django_components-0.83}/tests/test_templatetags_templating.py +0 -0
  55. {django_components-0.82 → django_components-0.83}/tests/testutils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.82
3
+ Version: 0.83
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
@@ -40,7 +40,7 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
40
40
  <div class="calendar-component">Today's date is <span>2015-06-19</span></div>
41
41
  ```
42
42
 
43
- Read on to learn about the details!
43
+ [See the example project](./sampleproject) or read on to learn about the details!
44
44
 
45
45
  ## Table of Contents
46
46
 
@@ -50,9 +50,9 @@ Read on to learn about the details!
50
50
  - [Compatiblity](#compatiblity)
51
51
  - [Create your first component](#create-your-first-component)
52
52
  - [Using single-file components](#using-single-file-components)
53
- - [Use the component in a template](#use-the-component-in-a-template)
53
+ - [Use components in templates](#use-components-in-templates)
54
+ - [Use components outside of templates](#use-components-outside-of-templates)
54
55
  - [Use components as views](#use-components-as-views)
55
- - [Registering components](#registering-components)
56
56
  - [Autodiscovery](#autodiscovery)
57
57
  - [Using slots in templates](#using-slots-in-templates)
58
58
  - [Passing data to components](#passing-data-to-components)
@@ -142,6 +142,21 @@ INSTALLED_APPS = [
142
142
  If you are on an older version of django-components, your alternatives are a) passing `--ignore <pattern>` options to the _collecstatic_ CLI command, or b) defining a subclass of StaticFilesConfig.
143
143
  Both routes are described in the official [docs of the _staticfiles_ app](https://docs.djangoproject.com/en/4.2/ref/contrib/staticfiles/#customizing-the-ignored-pattern-list).
144
144
 
145
+ Note that `safer_staticfiles` excludes the `.py` and `.html` files for [collectstatic command](https://docs.djangoproject.com/en/5.0/ref/contrib/staticfiles/#collectstatic):
146
+
147
+ ```sh
148
+ python manage.py collectstatic
149
+ ```
150
+
151
+ but it is ignored on the [development server](https://docs.djangoproject.com/en/5.0/ref/django-admin/#runserver):
152
+
153
+ ```sh
154
+ python manage.py runserver
155
+ ```
156
+
157
+ For a step-by-step guide on deploying production server with static files,
158
+ [see the demo project](./sampleproject/README.md).
159
+
145
160
  ## Installation
146
161
 
147
162
  Install the app into your environment:
@@ -16,7 +16,7 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
16
16
  <div class="calendar-component">Today's date is <span>2015-06-19</span></div>
17
17
  ```
18
18
 
19
- Read on to learn about the details!
19
+ [See the example project](./sampleproject) or read on to learn about the details!
20
20
 
21
21
  ## Table of Contents
22
22
 
@@ -26,9 +26,9 @@ Read on to learn about the details!
26
26
  - [Compatiblity](#compatiblity)
27
27
  - [Create your first component](#create-your-first-component)
28
28
  - [Using single-file components](#using-single-file-components)
29
- - [Use the component in a template](#use-the-component-in-a-template)
29
+ - [Use components in templates](#use-components-in-templates)
30
+ - [Use components outside of templates](#use-components-outside-of-templates)
30
31
  - [Use components as views](#use-components-as-views)
31
- - [Registering components](#registering-components)
32
32
  - [Autodiscovery](#autodiscovery)
33
33
  - [Using slots in templates](#using-slots-in-templates)
34
34
  - [Passing data to components](#passing-data-to-components)
@@ -118,6 +118,21 @@ INSTALLED_APPS = [
118
118
  If you are on an older version of django-components, your alternatives are a) passing `--ignore <pattern>` options to the _collecstatic_ CLI command, or b) defining a subclass of StaticFilesConfig.
119
119
  Both routes are described in the official [docs of the _staticfiles_ app](https://docs.djangoproject.com/en/4.2/ref/contrib/staticfiles/#customizing-the-ignored-pattern-list).
120
120
 
121
+ Note that `safer_staticfiles` excludes the `.py` and `.html` files for [collectstatic command](https://docs.djangoproject.com/en/5.0/ref/contrib/staticfiles/#collectstatic):
122
+
123
+ ```sh
124
+ python manage.py collectstatic
125
+ ```
126
+
127
+ but it is ignored on the [development server](https://docs.djangoproject.com/en/5.0/ref/django-admin/#runserver):
128
+
129
+ ```sh
130
+ python manage.py runserver
131
+ ```
132
+
133
+ For a step-by-step guide on deploying production server with static files,
134
+ [see the demo project](./sampleproject/README.md).
135
+
121
136
  ## Installation
122
137
 
123
138
  Install the app into your environment:
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "django_components"
7
- version = "0.82"
7
+ version = "0.83"
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"]
@@ -15,6 +15,10 @@ HTML_ATTRS_DEFAULTS_KEY = "defaults"
15
15
  HTML_ATTRS_ATTRS_KEY = "attrs"
16
16
 
17
17
 
18
+ def _default(val: Any, default_val: Any) -> Any:
19
+ return val if val is not None else default_val
20
+
21
+
18
22
  class HtmlAttrsNode(Node):
19
23
  def __init__(
20
24
  self,
@@ -57,8 +61,9 @@ class HtmlAttrsNode(Node):
57
61
  attrs_and_defaults_from_kwargs = process_aggregate_kwargs(attrs_and_defaults_from_kwargs)
58
62
 
59
63
  # NOTE: We want to allow to use `html_attrs` even without `attrs` or `defaults` params
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, {})
64
+ # Or when they are None
65
+ attrs = _default(attrs_and_defaults_from_kwargs.get(HTML_ATTRS_ATTRS_KEY, None), {})
66
+ default_attrs = _default(attrs_and_defaults_from_kwargs.get(HTML_ATTRS_DEFAULTS_KEY, None), {})
62
67
 
63
68
  final_attrs = {**default_attrs, **attrs}
64
69
  final_attrs = append_attributes(*final_attrs.items(), *append_attrs)
@@ -10,7 +10,7 @@ from django.template.context import Context
10
10
  from django.template.exceptions import TemplateSyntaxError
11
11
  from django.template.loader import get_template
12
12
  from django.template.loader_tags import BLOCK_CONTEXT_KEY
13
- from django.utils.html import escape
13
+ from django.utils.html import conditional_escape
14
14
  from django.utils.safestring import SafeString, mark_safe
15
15
  from django.views import View
16
16
 
@@ -337,6 +337,7 @@ class Component(View, metaclass=ComponentMeta):
337
337
 
338
338
  return comp._render(context, args, kwargs, slots, escape_slots_content)
339
339
 
340
+ # This is the internal entrypoint for the render function
340
341
  def _render(
341
342
  self,
342
343
  context: Union[Dict[str, Any], Context] = None,
@@ -344,6 +345,19 @@ class Component(View, metaclass=ComponentMeta):
344
345
  kwargs: Optional[Dict[str, Any]] = None,
345
346
  slots: Optional[Mapping[SlotName, SlotContent]] = None,
346
347
  escape_slots_content: bool = True,
348
+ ) -> str:
349
+ try:
350
+ return self._render_impl(context, args, kwargs, slots, escape_slots_content)
351
+ except Exception as err:
352
+ raise type(err)(f"An error occured while rendering component '{self.name}':\n{repr(err)}") from err
353
+
354
+ def _render_impl(
355
+ self,
356
+ context: Union[Dict[str, Any], Context] = None,
357
+ args: Optional[Union[List, Tuple]] = None,
358
+ kwargs: Optional[Dict[str, Any]] = None,
359
+ slots: Optional[Mapping[SlotName, SlotContent]] = None,
360
+ escape_slots_content: bool = True,
347
361
  ) -> str:
348
362
  # Allow to provide no args/kwargs
349
363
  args = args or []
@@ -441,13 +455,13 @@ class Component(View, metaclass=ComponentMeta):
441
455
  for slot_name, content in slots_data.items():
442
456
  if isinstance(content, (str, SafeString)):
443
457
  content_func = _nodelist_to_slot_render_func(
444
- NodeList([TextNode(escape(content) if escape_content else content)])
458
+ NodeList([TextNode(conditional_escape(content) if escape_content else content)])
445
459
  )
446
460
  else:
447
461
 
448
462
  def content_func(ctx: Context, kwargs: Dict[str, Any], slot_ref: SlotRef) -> SlotRenderedContent:
449
463
  rendered = content(ctx, kwargs, slot_ref)
450
- return escape(rendered) if escape_content else rendered
464
+ return conditional_escape(rendered) if escape_content else rendered
451
465
 
452
466
  slot_fills[slot_name] = FillContent(
453
467
  content_func=content_func,
@@ -100,7 +100,7 @@ def get_injected_context_var(
100
100
  # Otherwise raise error
101
101
  raise KeyError(
102
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"
103
+ f" To fix this, make sure that at least one ancestor of component '{component_name}' has"
104
104
  f" the variable '{key}' in their 'provide' attribute."
105
105
  )
106
106
 
@@ -10,6 +10,8 @@ class SaferStaticFilesConfig(StaticFilesConfig):
10
10
  `$ ./manage.py collectstatic` will ignore .py and .html files,
11
11
  preventing potentially sensitive backend logic from being leaked
12
12
  by the static file server.
13
+
14
+ See https://docs.djangoproject.com/en/5.0/ref/contrib/staticfiles/#customizing-the-ignored-pattern-list
13
15
  """
14
16
 
15
17
  default = True # Ensure that _this_ app is registered, as opposed to parent cls.
@@ -11,7 +11,11 @@ from django.template.exceptions import TemplateSyntaxError
11
11
  from django.utils.safestring import SafeString, mark_safe
12
12
 
13
13
  from django_components.app_settings import ContextBehavior, app_settings
14
- from django_components.context import _FILLED_SLOTS_CONTENT_CONTEXT_KEY, _ROOT_CTX_CONTEXT_KEY
14
+ from django_components.context import (
15
+ _FILLED_SLOTS_CONTENT_CONTEXT_KEY,
16
+ _INJECT_CONTEXT_KEY_PREFIX,
17
+ _ROOT_CTX_CONTEXT_KEY,
18
+ )
15
19
  from django_components.expression import resolve_expression_as_identifier, safe_resolve_dict
16
20
  from django_components.logger import trace_msg
17
21
  from django_components.node import NodeTraverse, nodelist_has_content, walk_nodelist
@@ -144,6 +148,16 @@ class SlotNode(Node):
144
148
 
145
149
  extra_context: Dict[str, Any] = {}
146
150
 
151
+ # Irrespective of which context we use ("root" context or the one passed to this
152
+ # render function), pass down the keys used by inject/provide feature. This makes it
153
+ # possible to pass the provided values down the slots, e.g.:
154
+ # {% provide "abc" val=123 %}
155
+ # {% slot "content" %}{% endslot %}
156
+ # {% endprovide %}
157
+ for key, value in context.flatten().items():
158
+ if key.startswith(_INJECT_CONTEXT_KEY_PREFIX):
159
+ extra_context[key] = value
160
+
147
161
  # If slot fill is using `{% fill "myslot" default="abc" %}`, then set the "abc" to
148
162
  # the context, so users can refer to the default slot from within the fill content.
149
163
  slot_ref = SlotRef(self, context)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.82
3
+ Version: 0.83
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
@@ -40,7 +40,7 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
40
40
  <div class="calendar-component">Today's date is <span>2015-06-19</span></div>
41
41
  ```
42
42
 
43
- Read on to learn about the details!
43
+ [See the example project](./sampleproject) or read on to learn about the details!
44
44
 
45
45
  ## Table of Contents
46
46
 
@@ -50,9 +50,9 @@ Read on to learn about the details!
50
50
  - [Compatiblity](#compatiblity)
51
51
  - [Create your first component](#create-your-first-component)
52
52
  - [Using single-file components](#using-single-file-components)
53
- - [Use the component in a template](#use-the-component-in-a-template)
53
+ - [Use components in templates](#use-components-in-templates)
54
+ - [Use components outside of templates](#use-components-outside-of-templates)
54
55
  - [Use components as views](#use-components-as-views)
55
- - [Registering components](#registering-components)
56
56
  - [Autodiscovery](#autodiscovery)
57
57
  - [Using slots in templates](#using-slots-in-templates)
58
58
  - [Passing data to components](#passing-data-to-components)
@@ -142,6 +142,21 @@ INSTALLED_APPS = [
142
142
  If you are on an older version of django-components, your alternatives are a) passing `--ignore <pattern>` options to the _collecstatic_ CLI command, or b) defining a subclass of StaticFilesConfig.
143
143
  Both routes are described in the official [docs of the _staticfiles_ app](https://docs.djangoproject.com/en/4.2/ref/contrib/staticfiles/#customizing-the-ignored-pattern-list).
144
144
 
145
+ Note that `safer_staticfiles` excludes the `.py` and `.html` files for [collectstatic command](https://docs.djangoproject.com/en/5.0/ref/contrib/staticfiles/#collectstatic):
146
+
147
+ ```sh
148
+ python manage.py collectstatic
149
+ ```
150
+
151
+ but it is ignored on the [development server](https://docs.djangoproject.com/en/5.0/ref/django-admin/#runserver):
152
+
153
+ ```sh
154
+ python manage.py runserver
155
+ ```
156
+
157
+ For a step-by-step guide on deploying production server with static files,
158
+ [see the demo project](./sampleproject/README.md).
159
+
145
160
  ## Installation
146
161
 
147
162
  Install the app into your environment:
@@ -42,6 +42,7 @@ tests/test_component_media.py
42
42
  tests/test_context.py
43
43
  tests/test_dependency_rendering.py
44
44
  tests/test_registry.py
45
+ tests/test_safer_staticfiles.py
45
46
  tests/test_settings.py
46
47
  tests/test_template_parser.py
47
48
  tests/test_templatetags.py
@@ -233,6 +233,7 @@ class HtmlAttrsTests(BaseTestCase):
233
233
  return {"attrs": attrs}
234
234
 
235
235
  template = Template(self.template_str)
236
+
236
237
  with self.assertRaisesMessage(TemplateSyntaxError, "Received argument 'attrs' both as a regular input"):
237
238
  template.render(Context({"class_var": "padding-top-8"}))
238
239
 
@@ -250,6 +251,7 @@ class HtmlAttrsTests(BaseTestCase):
250
251
  return {"attrs": attrs}
251
252
 
252
253
  template = Template(self.template_str)
254
+
253
255
  with self.assertRaisesMessage(
254
256
  TemplateSyntaxError,
255
257
  "Received argument 'defaults' both as a regular input",
@@ -38,7 +38,7 @@ class TestAutodiscover(BaseTestCase):
38
38
 
39
39
  all_components_after = component_registry.registry.all().copy()
40
40
  imported_components_count = len(all_components_after) - len(all_components_before)
41
- self.assertEqual(imported_components_count, 2)
41
+ self.assertEqual(imported_components_count, 3)
42
42
 
43
43
 
44
44
  class TestLoaderSettingsModule(BaseTestCase):
@@ -770,7 +770,14 @@ class MediaRelativePathTests(BaseTestCase):
770
770
 
771
771
  # Fix the paths, since the "components" dir is nested
772
772
  with autodiscover_with_cleanup(map_import_paths=lambda p: f"tests.{p}"):
773
- component.registry.unregister("relative_file_pathobj_component")
773
+ # Make sure that only relevant components are registered:
774
+ comps_to_remove = [
775
+ comp_name
776
+ for comp_name in component.registry.all()
777
+ if comp_name not in ["relative_file_component", "parent_component", "variable_display"]
778
+ ]
779
+ for comp_name in comps_to_remove:
780
+ component.registry.unregister(comp_name)
774
781
 
775
782
  template_str: types.django_html = """
776
783
  {% load component_tags %}{% component_dependencies %}
@@ -0,0 +1,103 @@
1
+ from pathlib import Path
2
+
3
+ from django.contrib.staticfiles.management.commands.collectstatic import Command
4
+ from django.test import SimpleTestCase, override_settings
5
+
6
+ from .django_test_setup import * # NOQA
7
+
8
+
9
+ # This subclass allows us to call the `collectstatic` command from within Python.
10
+ # We call the `collect` method, which returns info about what files were collected.
11
+ #
12
+ # The methods below are overriden to ensure we don't make any filesystem changes
13
+ # (copy/delete), as the original command copies files. Thus we can safely test that
14
+ # our `safer_staticfiles` app works as intended.
15
+ class MockCollectstaticCommand(Command):
16
+ # NOTE: We do not expect this to be called
17
+ def clear_dir(self, path):
18
+ raise NotImplementedError()
19
+
20
+ # NOTE: We do not expect this to be called
21
+ def link_file(self, path, prefixed_path, source_storage):
22
+ raise NotImplementedError()
23
+
24
+ def copy_file(self, path, prefixed_path, source_storage):
25
+ # Skip this file if it was already copied earlier
26
+ if prefixed_path in self.copied_files:
27
+ return self.log("Skipping '%s' (already copied earlier)" % path)
28
+ # Delete the target file if needed or break
29
+ if not self.delete_file(path, prefixed_path, source_storage):
30
+ return
31
+ # The full path of the source file
32
+ source_path = source_storage.path(path)
33
+ # Finally start copying
34
+ if self.dry_run:
35
+ self.log("Pretending to copy '%s'" % source_path, level=1)
36
+ else:
37
+ self.log("Copying '%s'" % source_path, level=2)
38
+ # ############# OUR CHANGE ##############
39
+ # with source_storage.open(path) as source_file:
40
+ # self.storage.save(prefixed_path, source_file)
41
+ # ############# OUR CHANGE ##############
42
+ self.copied_files.append(prefixed_path)
43
+
44
+
45
+ def do_collect():
46
+ cmd = MockCollectstaticCommand()
47
+ cmd.set_options(
48
+ interactive=False,
49
+ verbosity=1,
50
+ link=False,
51
+ clear=False,
52
+ dry_run=False,
53
+ ignore_patterns=[],
54
+ use_default_ignore_patterns=True,
55
+ post_process=True,
56
+ )
57
+ collected = cmd.collect()
58
+ return collected
59
+
60
+
61
+ common_settings = {
62
+ "STATIC_URL": "static/",
63
+ "STATICFILES_DIRS": [Path(__file__).resolve().parent / "components"],
64
+ "STATIC_ROOT": "staticfiles",
65
+ "ROOT_URLCONF": __name__,
66
+ "SECRET_KEY": "secret",
67
+ }
68
+
69
+
70
+ # Check that .py and .html files are INCLUDED with the original staticfiles app
71
+ @override_settings(
72
+ **common_settings,
73
+ INSTALLED_APPS=("django_components", "django.contrib.staticfiles"),
74
+ )
75
+ class OrigStaticFileTests(SimpleTestCase):
76
+ def test_python_and_html_included(self):
77
+ collected = do_collect()
78
+
79
+ self.assertIn("safer_staticfiles/safer_staticfiles.css", collected["modified"])
80
+ self.assertIn("safer_staticfiles/safer_staticfiles.js", collected["modified"])
81
+ self.assertIn("safer_staticfiles/safer_staticfiles.html", collected["modified"])
82
+ self.assertIn("safer_staticfiles/safer_staticfiles.py", collected["modified"])
83
+
84
+ self.assertListEqual(collected["unmodified"], [])
85
+ self.assertListEqual(collected["post_processed"], [])
86
+
87
+
88
+ # Check that .py and .html files are OMITTED from our version of staticfiles app
89
+ @override_settings(
90
+ **common_settings,
91
+ INSTALLED_APPS=("django_components", "django_components.safer_staticfiles"),
92
+ )
93
+ class SaferStaticFileTests(SimpleTestCase):
94
+ def test_python_and_html_omitted(self):
95
+ collected = do_collect()
96
+
97
+ self.assertIn("safer_staticfiles/safer_staticfiles.css", collected["modified"])
98
+ self.assertIn("safer_staticfiles/safer_staticfiles.js", collected["modified"])
99
+ self.assertNotIn("safer_staticfiles/safer_staticfiles.html", collected["modified"])
100
+ self.assertNotIn("safer_staticfiles/safer_staticfiles.py", collected["modified"])
101
+
102
+ self.assertListEqual(collected["unmodified"], [])
103
+ self.assertListEqual(collected["post_processed"], [])
@@ -481,6 +481,45 @@ class ProvideTemplateTagTest(BaseTestCase):
481
481
  """,
482
482
  )
483
483
 
484
+ @parametrize_context_behavior(["django", "isolated"])
485
+ def test_slot_in_provide(self):
486
+ @component.register("injectee")
487
+ class InjectComponent(component.Component):
488
+ template: types.django_html = """
489
+ <div> injected: {{ var|safe }} </div>
490
+ """
491
+
492
+ def get_context_data(self):
493
+ var = self.inject("my_provide", "default")
494
+ return {"var": var}
495
+
496
+ @component.register("parent")
497
+ class ParentComponent(component.Component):
498
+ template: types.django_html = """
499
+ {% load component_tags %}
500
+ {% provide "my_provide" key="hi" another=123 %}
501
+ {% slot "content" default %}{% endslot %}
502
+ {% endprovide %}
503
+ """
504
+
505
+ template_str: types.django_html = """
506
+ {% load component_tags %}
507
+ {% component "parent" %}
508
+ {% component "injectee" %}{% endcomponent %}
509
+ {% endcomponent %}
510
+ """
511
+ template = Template(template_str)
512
+ rendered = template.render(Context({}))
513
+
514
+ self.assertHTMLEqual(
515
+ rendered,
516
+ """
517
+ <div>
518
+ injected: DepInject(key='hi', another=123)
519
+ </div>
520
+ """,
521
+ )
522
+
484
523
 
485
524
  class InjectTest(BaseTestCase):
486
525
  @parametrize_context_behavior(["django", "isolated"])
@@ -530,6 +569,7 @@ class InjectTest(BaseTestCase):
530
569
  {% endcomponent %}
531
570
  """
532
571
  template = Template(template_str)
572
+
533
573
  with self.assertRaises(KeyError):
534
574
  template.render(Context({}))
535
575
 
@@ -581,6 +621,7 @@ class InjectTest(BaseTestCase):
581
621
  {% endcomponent %}
582
622
  """
583
623
  template = Template(template_str)
624
+
584
625
  with self.assertRaises(KeyError):
585
626
  template.render(Context({}))
586
627
 
@@ -1,4 +1,3 @@
1
- import textwrap
2
1
  from typing import Any, Dict, List, Optional
3
2
 
4
3
  from django.template import Context, Template, TemplateSyntaxError
@@ -210,6 +209,7 @@ class ComponentSlottedTemplateTagTest(BaseTestCase):
210
209
  {% endcomponent %}
211
210
  """
212
211
  template = Template(template_str)
212
+
213
213
  with self.assertRaises(TemplateSyntaxError):
214
214
  template.render(Context({}))
215
215
 
@@ -284,6 +284,7 @@ class ComponentSlottedTemplateTagTest(BaseTestCase):
284
284
  {% endcomponent %}
285
285
  """
286
286
  template = Template(template_str)
287
+
287
288
  with self.assertRaises(TemplateSyntaxError):
288
289
  template.render(Context({}))
289
290
 
@@ -381,6 +382,7 @@ class ComponentSlottedTemplateTagTest(BaseTestCase):
381
382
  {% endcomponent %}
382
383
  """
383
384
  template = Template(template_str)
385
+
384
386
  with self.assertRaises(TemplateSyntaxError):
385
387
  template.render(Context({}))
386
388
 
@@ -398,6 +400,7 @@ class ComponentSlottedTemplateTagTest(BaseTestCase):
398
400
  return Template(template_str)
399
401
 
400
402
  c = BadComponent("name")
403
+
401
404
  with self.assertRaises(TemplateSyntaxError):
402
405
  c.render(Context({}))
403
406
 
@@ -417,20 +420,16 @@ class ComponentSlottedTemplateTagTest(BaseTestCase):
417
420
  {% endcomponent %}
418
421
  """
419
422
  template = Template(template_str)
420
- with self.assertRaises(TemplateSyntaxError):
421
- try:
422
- template.render(Context({}))
423
- except TemplateSyntaxError as e:
424
- self.assertEqual(
425
- textwrap.dedent(
426
- """\
427
- Component 'test1' passed fill that refers to undefined slot: 'haeder'.
428
- Unfilled slot names are: ['footer', 'header'].
429
- Did you mean 'header'?"""
430
- ),
431
- str(e),
432
- )
433
- raise e
423
+
424
+ with self.assertRaisesMessage(
425
+ TemplateSyntaxError,
426
+ (
427
+ "Component 'test1' passed fill that refers to undefined slot: 'haeder'.\\n"
428
+ "Unfilled slot names are: ['footer', 'header'].\\n"
429
+ "Did you mean 'header'?"
430
+ ),
431
+ ):
432
+ template.render(Context({}))
434
433
 
435
434
  # NOTE: This is relevant only for the "isolated" mode
436
435
  @parametrize_context_behavior(["isolated"])
@@ -1144,15 +1143,16 @@ class SlotFillTemplateSyntaxErrorTests(BaseTestCase):
1144
1143
  {% include 'slotted_template.html' with context=None only %}
1145
1144
  """
1146
1145
 
1146
+ template_str: types.django_html = """
1147
+ {% load component_tags %}
1148
+ {% component "broken_component" %}
1149
+ {% fill "header" %}Custom header {% endfill %}
1150
+ {% fill "main" %}Custom main{% endfill %}
1151
+ {% fill "footer" %}Custom footer{% endfill %}
1152
+ {% endcomponent %}
1153
+ """
1154
+
1147
1155
  with self.assertRaises(KeyError):
1148
- template_str: types.django_html = """
1149
- {% load component_tags %}
1150
- {% component "broken_component" %}
1151
- {% fill "header" %}Custom header {% endfill %}
1152
- {% fill "main" %}Custom main{% endfill %}
1153
- {% fill "footer" %}Custom footer{% endfill %}
1154
- {% endcomponent %}
1155
- """
1156
1156
  Template(template_str).render(Context({}))
1157
1157
 
1158
1158
  @parametrize_context_behavior(["django", "isolated"])