django-components 0.70__tar.gz → 0.72__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {django_components-0.70/src/django_components.egg-info → django_components-0.72}/PKG-INFO +44 -6
- {django_components-0.70 → django_components-0.72}/README.md +43 -5
- {django_components-0.70 → django_components-0.72}/pyproject.toml +1 -1
- {django_components-0.70 → django_components-0.72}/src/django_components/component.py +8 -0
- django_components-0.72/src/django_components/node.py +100 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/slots.py +19 -5
- django_components-0.72/src/django_components/template_parser.py +204 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/templatetags/component_tags.py +1 -7
- {django_components-0.70 → django_components-0.72}/src/django_components/types.py +3 -0
- {django_components-0.70 → django_components-0.72/src/django_components.egg-info}/PKG-INFO +44 -6
- {django_components-0.70 → django_components-0.72}/src/django_components.egg-info/SOURCES.txt +2 -0
- {django_components-0.70 → django_components-0.72}/tests/test_component.py +184 -110
- django_components-0.72/tests/test_component_as_view.py +183 -0
- {django_components-0.70 → django_components-0.72}/tests/test_context.py +200 -134
- {django_components-0.70 → django_components-0.72}/tests/test_dependency_rendering.py +118 -69
- django_components-0.72/tests/test_template_parser.py +89 -0
- {django_components-0.70 → django_components-0.72}/tests/test_templatetags.py +940 -516
- django_components-0.70/src/django_components/node.py +0 -45
- django_components-0.70/tests/test_component_as_view.py +0 -179
- {django_components-0.70 → django_components-0.72}/LICENSE +0 -0
- {django_components-0.70 → django_components-0.72}/setup.cfg +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/__init__.py +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/app_settings.py +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/apps.py +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/component_registry.py +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/context.py +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/logger.py +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/management/__init__.py +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/management/commands/__init__.py +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/management/commands/startcomponent.py +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/management/commands/upgradecomponent.py +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/middleware.py +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/py.typed +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/safer_staticfiles/__init__.py +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/safer_staticfiles/apps.py +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/template_loader.py +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/templatetags/__init__.py +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components/utils.py +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components.egg-info/dependency_links.txt +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components.egg-info/requires.txt +0 -0
- {django_components-0.70 → django_components-0.72}/src/django_components.egg-info/top_level.txt +0 -0
- {django_components-0.70 → django_components-0.72}/tests/test_autodiscover.py +0 -0
- {django_components-0.70 → django_components-0.72}/tests/test_registry.py +0 -0
- {django_components-0.70 → django_components-0.72}/tests/test_settings.py +0 -0
- {django_components-0.70 → django_components-0.72}/tests/test_startcomponent_command.py +0 -0
- {django_components-0.70 → django_components-0.72}/tests/testutils.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: django_components
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.72
|
|
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
|
|
@@ -691,6 +691,44 @@ COMPONENTS = {
|
|
|
691
691
|
}
|
|
692
692
|
```
|
|
693
693
|
|
|
694
|
+
## Passing data to components
|
|
695
|
+
|
|
696
|
+
As seen above, you can pass arguments to components like so:
|
|
697
|
+
|
|
698
|
+
```django
|
|
699
|
+
<body>
|
|
700
|
+
{% component "calendar" date="2015-06-19" %}
|
|
701
|
+
{% endcomponent %}
|
|
702
|
+
</body>
|
|
703
|
+
```
|
|
704
|
+
|
|
705
|
+
### Special characters
|
|
706
|
+
|
|
707
|
+
Keyword arguments can contain special characters `# @ . - _`, so keywords like
|
|
708
|
+
so are still valid:
|
|
709
|
+
|
|
710
|
+
```django
|
|
711
|
+
<body>
|
|
712
|
+
{% component "calendar" my-date="2015-06-19" @click.native=do_something #some_id=True %}
|
|
713
|
+
{% endcomponent %}
|
|
714
|
+
</body>
|
|
715
|
+
```
|
|
716
|
+
|
|
717
|
+
These can then be accessed inside `get_context_data` so:
|
|
718
|
+
|
|
719
|
+
```py
|
|
720
|
+
@component.register("calendar")
|
|
721
|
+
class Calendar(component.Component):
|
|
722
|
+
# Since # . @ - are not valid identifiers, we have to
|
|
723
|
+
# use `**kwargs` so the method can accept these args.
|
|
724
|
+
def get_context_data(self, **kwargs):
|
|
725
|
+
return {
|
|
726
|
+
"date": kwargs["my-date"],
|
|
727
|
+
"id": kwargs["#some_id"],
|
|
728
|
+
"@click.native": kwargs["@click.native"]
|
|
729
|
+
}
|
|
730
|
+
```
|
|
731
|
+
|
|
694
732
|
## Component context and scope
|
|
695
733
|
|
|
696
734
|
By default, components are ISOLATED and CANNOT access context variables from the parent template. This is useful if you want to make sure that components don't accidentally access the outer context.
|
|
@@ -841,7 +879,7 @@ Django components supports [logging with Django](https://docs.djangoproject.com/
|
|
|
841
879
|
|
|
842
880
|
To configure logging for Django components, set the `django_components` logger in `LOGGING` in `settings.py` (below).
|
|
843
881
|
|
|
844
|
-
Also see the [`settings.py` file in sampleproject](
|
|
882
|
+
Also see the [`settings.py` file in sampleproject](https://github.com/EmilStenstrom/django-components/blob/master/sampleproject/sampleproject/settings.py) for a real-life example.
|
|
845
883
|
|
|
846
884
|
```py
|
|
847
885
|
import logging
|
|
@@ -983,15 +1021,15 @@ tox -p
|
|
|
983
1021
|
|
|
984
1022
|
How do you check that your changes to django-components project will work in an actual Django project?
|
|
985
1023
|
|
|
986
|
-
Use the [sampleproject](
|
|
1024
|
+
Use the [sampleproject](https://github.com/EmilStenstrom/django-components/tree/master/sampleproject/) demo project to validate the changes:
|
|
987
1025
|
|
|
988
|
-
1. Navigate to [sampleproject](
|
|
1026
|
+
1. Navigate to [sampleproject](https://github.com/EmilStenstrom/django-components/tree/master/sampleproject/) directory:
|
|
989
1027
|
|
|
990
1028
|
```sh
|
|
991
1029
|
cd sampleproject
|
|
992
1030
|
```
|
|
993
1031
|
|
|
994
|
-
2. Install dependencies from the [requirements.txt](
|
|
1032
|
+
2. Install dependencies from the [requirements.txt](https://github.com/EmilStenstrom/django-components/blob/master/sampleproject/requirements.txt) file:
|
|
995
1033
|
|
|
996
1034
|
```sh
|
|
997
1035
|
pip install -r requirements.txt
|
|
@@ -1016,4 +1054,4 @@ To display individual components, add them to the `urls.py`, like in the case of
|
|
|
1016
1054
|
|
|
1017
1055
|
## Development guides
|
|
1018
1056
|
|
|
1019
|
-
- [Slot rendering flot](
|
|
1057
|
+
- [Slot rendering flot](https://github.com/EmilStenstrom/django-components/blob/master/docs/slot_rendering.md)
|
|
@@ -667,6 +667,44 @@ COMPONENTS = {
|
|
|
667
667
|
}
|
|
668
668
|
```
|
|
669
669
|
|
|
670
|
+
## Passing data to components
|
|
671
|
+
|
|
672
|
+
As seen above, you can pass arguments to components like so:
|
|
673
|
+
|
|
674
|
+
```django
|
|
675
|
+
<body>
|
|
676
|
+
{% component "calendar" date="2015-06-19" %}
|
|
677
|
+
{% endcomponent %}
|
|
678
|
+
</body>
|
|
679
|
+
```
|
|
680
|
+
|
|
681
|
+
### Special characters
|
|
682
|
+
|
|
683
|
+
Keyword arguments can contain special characters `# @ . - _`, so keywords like
|
|
684
|
+
so are still valid:
|
|
685
|
+
|
|
686
|
+
```django
|
|
687
|
+
<body>
|
|
688
|
+
{% component "calendar" my-date="2015-06-19" @click.native=do_something #some_id=True %}
|
|
689
|
+
{% endcomponent %}
|
|
690
|
+
</body>
|
|
691
|
+
```
|
|
692
|
+
|
|
693
|
+
These can then be accessed inside `get_context_data` so:
|
|
694
|
+
|
|
695
|
+
```py
|
|
696
|
+
@component.register("calendar")
|
|
697
|
+
class Calendar(component.Component):
|
|
698
|
+
# Since # . @ - are not valid identifiers, we have to
|
|
699
|
+
# use `**kwargs` so the method can accept these args.
|
|
700
|
+
def get_context_data(self, **kwargs):
|
|
701
|
+
return {
|
|
702
|
+
"date": kwargs["my-date"],
|
|
703
|
+
"id": kwargs["#some_id"],
|
|
704
|
+
"@click.native": kwargs["@click.native"]
|
|
705
|
+
}
|
|
706
|
+
```
|
|
707
|
+
|
|
670
708
|
## Component context and scope
|
|
671
709
|
|
|
672
710
|
By default, components are ISOLATED and CANNOT access context variables from the parent template. This is useful if you want to make sure that components don't accidentally access the outer context.
|
|
@@ -817,7 +855,7 @@ Django components supports [logging with Django](https://docs.djangoproject.com/
|
|
|
817
855
|
|
|
818
856
|
To configure logging for Django components, set the `django_components` logger in `LOGGING` in `settings.py` (below).
|
|
819
857
|
|
|
820
|
-
Also see the [`settings.py` file in sampleproject](
|
|
858
|
+
Also see the [`settings.py` file in sampleproject](https://github.com/EmilStenstrom/django-components/blob/master/sampleproject/sampleproject/settings.py) for a real-life example.
|
|
821
859
|
|
|
822
860
|
```py
|
|
823
861
|
import logging
|
|
@@ -959,15 +997,15 @@ tox -p
|
|
|
959
997
|
|
|
960
998
|
How do you check that your changes to django-components project will work in an actual Django project?
|
|
961
999
|
|
|
962
|
-
Use the [sampleproject](
|
|
1000
|
+
Use the [sampleproject](https://github.com/EmilStenstrom/django-components/tree/master/sampleproject/) demo project to validate the changes:
|
|
963
1001
|
|
|
964
|
-
1. Navigate to [sampleproject](
|
|
1002
|
+
1. Navigate to [sampleproject](https://github.com/EmilStenstrom/django-components/tree/master/sampleproject/) directory:
|
|
965
1003
|
|
|
966
1004
|
```sh
|
|
967
1005
|
cd sampleproject
|
|
968
1006
|
```
|
|
969
1007
|
|
|
970
|
-
2. Install dependencies from the [requirements.txt](
|
|
1008
|
+
2. Install dependencies from the [requirements.txt](https://github.com/EmilStenstrom/django-components/blob/master/sampleproject/requirements.txt) file:
|
|
971
1009
|
|
|
972
1010
|
```sh
|
|
973
1011
|
pip install -r requirements.txt
|
|
@@ -992,4 +1030,4 @@ To display individual components, add them to the `urls.py`, like in the case of
|
|
|
992
1030
|
|
|
993
1031
|
## Development guides
|
|
994
1032
|
|
|
995
|
-
- [Slot rendering flot](
|
|
1033
|
+
- [Slot rendering flot](https://github.com/EmilStenstrom/django-components/blob/master/docs/slot_rendering.md)
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "django_components"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.72"
|
|
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"]
|
|
@@ -9,6 +9,7 @@ from django.forms.widgets import Media, MediaDefiningClass
|
|
|
9
9
|
from django.http import HttpResponse
|
|
10
10
|
from django.template.base import FilterExpression, Node, NodeList, Template, TextNode
|
|
11
11
|
from django.template.context import Context
|
|
12
|
+
from django.template.exceptions import TemplateSyntaxError
|
|
12
13
|
from django.template.loader import get_template
|
|
13
14
|
from django.utils.html import escape
|
|
14
15
|
from django.utils.safestring import SafeString, mark_safe
|
|
@@ -291,6 +292,7 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
|
|
|
291
292
|
context_data = {}
|
|
292
293
|
|
|
293
294
|
slots, resolved_fills = resolve_slots(
|
|
295
|
+
context,
|
|
294
296
|
template,
|
|
295
297
|
component_name=self.registered_name,
|
|
296
298
|
context_data=context_data,
|
|
@@ -402,6 +404,12 @@ class ComponentNode(Node):
|
|
|
402
404
|
# Note that outer component context is used to resolve variables in
|
|
403
405
|
# fill tag.
|
|
404
406
|
resolved_name = fill_node.name_fexp.resolve(context)
|
|
407
|
+
if resolved_name in fill_content:
|
|
408
|
+
raise TemplateSyntaxError(
|
|
409
|
+
f"Multiple fill tags cannot target the same slot name: "
|
|
410
|
+
f"Detected duplicate fill tag name '{resolved_name}'."
|
|
411
|
+
)
|
|
412
|
+
|
|
405
413
|
resolved_fill_alias = fill_node.resolve_alias(context, resolved_component_name)
|
|
406
414
|
fill_content[resolved_name] = FillContent(fill_node.nodelist, resolved_fill_alias)
|
|
407
415
|
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
from typing import Callable, List, NamedTuple, Optional
|
|
2
|
+
|
|
3
|
+
from django.template import Context, Template
|
|
4
|
+
from django.template.base import Node, NodeList, TextNode
|
|
5
|
+
from django.template.defaulttags import CommentNode
|
|
6
|
+
from django.template.loader_tags import ExtendsNode, IncludeNode, construct_relative_path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def nodelist_has_content(nodelist: NodeList) -> bool:
|
|
10
|
+
for node in nodelist:
|
|
11
|
+
if isinstance(node, TextNode) and node.s.isspace():
|
|
12
|
+
pass
|
|
13
|
+
elif isinstance(node, CommentNode):
|
|
14
|
+
pass
|
|
15
|
+
else:
|
|
16
|
+
return True
|
|
17
|
+
return False
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class NodeTraverse(NamedTuple):
|
|
21
|
+
node: Node
|
|
22
|
+
parent: Optional["NodeTraverse"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def walk_nodelist(
|
|
26
|
+
nodes: NodeList,
|
|
27
|
+
callback: Callable[[Node], Optional[str]],
|
|
28
|
+
context: Optional[Context] = None,
|
|
29
|
+
) -> None:
|
|
30
|
+
"""Recursively walk a NodeList, calling `callback` for each Node."""
|
|
31
|
+
node_queue: List[NodeTraverse] = [NodeTraverse(node=node, parent=None) for node in nodes]
|
|
32
|
+
while len(node_queue):
|
|
33
|
+
traverse = node_queue.pop()
|
|
34
|
+
callback(traverse)
|
|
35
|
+
child_nodes = get_node_children(traverse.node, context)
|
|
36
|
+
child_traverses = [NodeTraverse(node=child_node, parent=traverse) for child_node in child_nodes]
|
|
37
|
+
node_queue.extend(child_traverses)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def get_node_children(node: Node, context: Optional[Context] = None) -> NodeList:
|
|
41
|
+
"""
|
|
42
|
+
Get child Nodes from Node's nodelist atribute.
|
|
43
|
+
|
|
44
|
+
This function is taken from `get_nodes_by_type` method of `django.template.base.Node`.
|
|
45
|
+
"""
|
|
46
|
+
# Special case - {% extends %} tag - Load the template and go deeper
|
|
47
|
+
if isinstance(node, ExtendsNode):
|
|
48
|
+
# NOTE: When {% extends %} node is being parsed, it collects all remaining template
|
|
49
|
+
# under node.nodelist.
|
|
50
|
+
# Hence, when we come across ExtendsNode in the template, we:
|
|
51
|
+
# 1. Go over all nodes in the template using `node.nodelist`
|
|
52
|
+
# 2. Go over all nodes in the "parent" template, via `node.get_parent`
|
|
53
|
+
nodes = NodeList()
|
|
54
|
+
nodes.extend(node.nodelist)
|
|
55
|
+
template = node.get_parent(context)
|
|
56
|
+
nodes.extend(template.nodelist)
|
|
57
|
+
return nodes
|
|
58
|
+
|
|
59
|
+
# Special case - {% include %} tag - Load the template and go deeper
|
|
60
|
+
elif isinstance(node, IncludeNode):
|
|
61
|
+
template = get_template_for_include_node(node, context)
|
|
62
|
+
return template.nodelist
|
|
63
|
+
|
|
64
|
+
nodes = NodeList()
|
|
65
|
+
for attr in node.child_nodelists:
|
|
66
|
+
nodelist = getattr(node, attr, [])
|
|
67
|
+
if nodelist:
|
|
68
|
+
nodes.extend(nodelist)
|
|
69
|
+
return nodes
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def get_template_for_include_node(include_node: IncludeNode, context: Context) -> Template:
|
|
73
|
+
"""
|
|
74
|
+
This snippet is taken directly from `IncludeNode.render()`. Unfortunately the
|
|
75
|
+
render logic doesn't separate out template loading logic from rendering, so we
|
|
76
|
+
have to copy the method.
|
|
77
|
+
"""
|
|
78
|
+
template = include_node.template.resolve(context)
|
|
79
|
+
# Does this quack like a Template?
|
|
80
|
+
if not callable(getattr(template, "render", None)):
|
|
81
|
+
# If not, try the cache and select_template().
|
|
82
|
+
template_name = template or ()
|
|
83
|
+
if isinstance(template_name, str):
|
|
84
|
+
template_name = (
|
|
85
|
+
construct_relative_path(
|
|
86
|
+
include_node.origin.template_name,
|
|
87
|
+
template_name,
|
|
88
|
+
),
|
|
89
|
+
)
|
|
90
|
+
else:
|
|
91
|
+
template_name = tuple(template_name)
|
|
92
|
+
cache = context.render_context.dicts[0].setdefault(include_node, {})
|
|
93
|
+
template = cache.get(template_name)
|
|
94
|
+
if template is None:
|
|
95
|
+
template = context.template.engine.select_template(template_name)
|
|
96
|
+
cache[template_name] = template
|
|
97
|
+
# Use the base.Template of a backends.django.Template.
|
|
98
|
+
elif hasattr(template, "template"):
|
|
99
|
+
template = template.template
|
|
100
|
+
return template
|
|
@@ -258,15 +258,18 @@ def _try_parse_as_named_fill_tag_set(
|
|
|
258
258
|
ComponentNodeCls: Type[Node],
|
|
259
259
|
) -> List[FillNode]:
|
|
260
260
|
result = []
|
|
261
|
-
seen_name_fexps: Set[
|
|
261
|
+
seen_name_fexps: Set[str] = set()
|
|
262
262
|
for node in nodelist:
|
|
263
263
|
if isinstance(node, FillNode):
|
|
264
|
-
|
|
264
|
+
# Check that, after we've resolved the names, that there's still no duplicates.
|
|
265
|
+
# This makes sure that if two different variables refer to same string, we detect
|
|
266
|
+
# them.
|
|
267
|
+
if node.name_fexp.token in seen_name_fexps:
|
|
265
268
|
raise TemplateSyntaxError(
|
|
266
269
|
f"Multiple fill tags cannot target the same slot name: "
|
|
267
270
|
f"Detected duplicate fill tag name '{node.name_fexp}'."
|
|
268
271
|
)
|
|
269
|
-
seen_name_fexps.add(node.name_fexp)
|
|
272
|
+
seen_name_fexps.add(node.name_fexp.token)
|
|
270
273
|
result.append(node)
|
|
271
274
|
elif isinstance(node, CommentNode):
|
|
272
275
|
pass
|
|
@@ -308,6 +311,7 @@ def _try_parse_as_default_fill(
|
|
|
308
311
|
|
|
309
312
|
|
|
310
313
|
def resolve_slots(
|
|
314
|
+
context: Context,
|
|
311
315
|
template: Template,
|
|
312
316
|
component_name: Optional[str],
|
|
313
317
|
context_data: Dict[str, Any],
|
|
@@ -374,7 +378,7 @@ def resolve_slots(
|
|
|
374
378
|
slot_children[parent_slot_id].append(node.node_id)
|
|
375
379
|
break
|
|
376
380
|
|
|
377
|
-
walk_nodelist(template.nodelist, on_node)
|
|
381
|
+
walk_nodelist(template.nodelist, on_node, context)
|
|
378
382
|
|
|
379
383
|
# 3. Figure out which slot the default/implicit fill belongs to
|
|
380
384
|
slot_fills = _resolve_default_slot(
|
|
@@ -457,7 +461,17 @@ def _resolve_default_slot(
|
|
|
457
461
|
|
|
458
462
|
# Here we've identified which slot the default/implicit fill belongs to
|
|
459
463
|
if default_fill:
|
|
460
|
-
|
|
464
|
+
# NOTE: We recreate new instance, passing all fields, instead of using
|
|
465
|
+
# `NamedTuple._replace`, because `_replace` is not typed.
|
|
466
|
+
named_fills[slot.name] = SlotFill(
|
|
467
|
+
is_filled=default_fill.is_filled,
|
|
468
|
+
nodelist=default_fill.nodelist,
|
|
469
|
+
context_data=default_fill.context_data,
|
|
470
|
+
alias=default_fill.alias,
|
|
471
|
+
# Updated fields
|
|
472
|
+
name=slot.name,
|
|
473
|
+
escaped_name=_escape_slot_name(slot.name),
|
|
474
|
+
)
|
|
461
475
|
|
|
462
476
|
# Check: Only component templates that include a 'default' slot
|
|
463
477
|
# can be invoked with implicit filling.
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Overrides for the Django Template system to allow finer control over template parsing.
|
|
3
|
+
|
|
4
|
+
Based on Django Slippers v0.6.2 - https://github.com/mixxorz/slippers/blob/main/slippers/template.py
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import re
|
|
8
|
+
from typing import Any, Dict, List, Tuple
|
|
9
|
+
|
|
10
|
+
from django.template.base import (
|
|
11
|
+
FILTER_ARGUMENT_SEPARATOR,
|
|
12
|
+
FILTER_SEPARATOR,
|
|
13
|
+
FilterExpression,
|
|
14
|
+
Parser,
|
|
15
|
+
Variable,
|
|
16
|
+
VariableDoesNotExist,
|
|
17
|
+
constant_string,
|
|
18
|
+
)
|
|
19
|
+
from django.template.exceptions import TemplateSyntaxError
|
|
20
|
+
from django.utils.regex_helper import _lazy_re_compile
|
|
21
|
+
|
|
22
|
+
######################################################################################################################
|
|
23
|
+
# Custom FilterExpression
|
|
24
|
+
#
|
|
25
|
+
# This is a copy of the original FilterExpression. The only difference is to allow variable names to have extra special
|
|
26
|
+
# characters: - : . @ #
|
|
27
|
+
######################################################################################################################
|
|
28
|
+
filter_raw_string = r"""
|
|
29
|
+
^(?P<constant>{constant})|
|
|
30
|
+
^(?P<var>[{var_chars}]+|{num})|
|
|
31
|
+
(?:\s*{filter_sep}\s*
|
|
32
|
+
(?P<filter_name>\w+)
|
|
33
|
+
(?:{arg_sep}
|
|
34
|
+
(?:
|
|
35
|
+
(?P<constant_arg>{constant})|
|
|
36
|
+
(?P<var_arg>[{var_chars}]+|{num})
|
|
37
|
+
)
|
|
38
|
+
)?
|
|
39
|
+
)""".format(
|
|
40
|
+
constant=constant_string,
|
|
41
|
+
num=r"[-+\.]?\d[\d\.e]*",
|
|
42
|
+
# The following is the only difference from the original FilterExpression. We allow variable names to have extra
|
|
43
|
+
# special characters: - : . @ #
|
|
44
|
+
var_chars=r"\w\-\:\@\.\#",
|
|
45
|
+
filter_sep=re.escape(FILTER_SEPARATOR),
|
|
46
|
+
arg_sep=re.escape(FILTER_ARGUMENT_SEPARATOR),
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
filter_re = _lazy_re_compile(filter_raw_string, re.VERBOSE)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class ComponentsFilterExpression(FilterExpression):
|
|
53
|
+
def __init__(self, token: str, parser: Parser) -> None:
|
|
54
|
+
# This method is exactly the same as the original FilterExpression.__init__ method, the only difference being
|
|
55
|
+
# the value of `filter_re`.
|
|
56
|
+
self.token = token
|
|
57
|
+
matches = filter_re.finditer(token)
|
|
58
|
+
var_obj = None
|
|
59
|
+
filters: List[Any] = []
|
|
60
|
+
upto = 0
|
|
61
|
+
for match in matches:
|
|
62
|
+
start = match.start()
|
|
63
|
+
if upto != start:
|
|
64
|
+
raise TemplateSyntaxError(
|
|
65
|
+
"Could not parse some characters: " "%s|%s|%s" % (token[:upto], token[upto:start], token[start:])
|
|
66
|
+
)
|
|
67
|
+
if var_obj is None:
|
|
68
|
+
var, constant = match["var"], match["constant"]
|
|
69
|
+
if constant:
|
|
70
|
+
try:
|
|
71
|
+
var_obj = Variable(constant).resolve({})
|
|
72
|
+
except VariableDoesNotExist:
|
|
73
|
+
var_obj = None
|
|
74
|
+
elif var is None:
|
|
75
|
+
raise TemplateSyntaxError("Could not find variable at " "start of %s." % token)
|
|
76
|
+
else:
|
|
77
|
+
var_obj = Variable(var)
|
|
78
|
+
else:
|
|
79
|
+
filter_name = match["filter_name"]
|
|
80
|
+
args = []
|
|
81
|
+
constant_arg, var_arg = match["constant_arg"], match["var_arg"]
|
|
82
|
+
if constant_arg:
|
|
83
|
+
args.append((False, Variable(constant_arg).resolve({})))
|
|
84
|
+
elif var_arg:
|
|
85
|
+
args.append((True, Variable(var_arg)))
|
|
86
|
+
filter_func = parser.find_filter(filter_name)
|
|
87
|
+
self.args_check(filter_name, filter_func, args)
|
|
88
|
+
filters.append((filter_func, args))
|
|
89
|
+
upto = match.end()
|
|
90
|
+
if upto != len(token):
|
|
91
|
+
raise TemplateSyntaxError("Could not parse the remainder: '%s' " "from '%s'" % (token[upto:], token))
|
|
92
|
+
|
|
93
|
+
self.filters = filters
|
|
94
|
+
self.var = var_obj
|
|
95
|
+
self.is_var = isinstance(var_obj, Variable)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
######################################################################################################################
|
|
99
|
+
# Custom token_kwargs
|
|
100
|
+
#
|
|
101
|
+
# Same as the original token_kwargs, but uses the ComponentsFilterExpression instead of the original FilterExpression.
|
|
102
|
+
######################################################################################################################
|
|
103
|
+
|
|
104
|
+
# Regex for token keyword arguments
|
|
105
|
+
kwarg_re = _lazy_re_compile(r"(?:([\w\-\:\@\.\#]+)=)?(.+)")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def token_kwargs(bits: List[str], parser: Parser) -> Dict[str, FilterExpression]:
|
|
109
|
+
"""
|
|
110
|
+
Parse token keyword arguments and return a dictionary of the arguments
|
|
111
|
+
retrieved from the ``bits`` token list.
|
|
112
|
+
|
|
113
|
+
`bits` is a list containing the remainder of the token (split by spaces)
|
|
114
|
+
that is to be checked for arguments. Valid arguments are removed from this
|
|
115
|
+
list.
|
|
116
|
+
|
|
117
|
+
There is no requirement for all remaining token ``bits`` to be keyword
|
|
118
|
+
arguments, so return the dictionary as soon as an invalid argument format
|
|
119
|
+
is reached.
|
|
120
|
+
"""
|
|
121
|
+
if not bits:
|
|
122
|
+
return {}
|
|
123
|
+
match = kwarg_re.match(bits[0])
|
|
124
|
+
kwarg_format = match and match[1]
|
|
125
|
+
if not kwarg_format:
|
|
126
|
+
return {}
|
|
127
|
+
|
|
128
|
+
kwargs: Dict[str, FilterExpression] = {}
|
|
129
|
+
while bits:
|
|
130
|
+
if kwarg_format:
|
|
131
|
+
match = kwarg_re.match(bits[0])
|
|
132
|
+
if not match or not match[1]:
|
|
133
|
+
return kwargs
|
|
134
|
+
key, value = match.groups()
|
|
135
|
+
del bits[:1]
|
|
136
|
+
else:
|
|
137
|
+
if len(bits) < 3 or bits[1] != "as":
|
|
138
|
+
return kwargs
|
|
139
|
+
key, value = bits[2], bits[0]
|
|
140
|
+
del bits[:3]
|
|
141
|
+
|
|
142
|
+
# This is the only difference from the original token_kwargs. We use
|
|
143
|
+
# the ComponentsFilterExpression instead of the original FilterExpression.
|
|
144
|
+
kwargs[key] = ComponentsFilterExpression(value, parser)
|
|
145
|
+
if bits and not kwarg_format:
|
|
146
|
+
if bits[0] != "and":
|
|
147
|
+
return kwargs
|
|
148
|
+
del bits[:1]
|
|
149
|
+
return kwargs
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def parse_bits(
|
|
153
|
+
parser: Parser,
|
|
154
|
+
bits: List[str],
|
|
155
|
+
params: List[str],
|
|
156
|
+
name: str,
|
|
157
|
+
) -> Tuple[List, Dict]:
|
|
158
|
+
"""
|
|
159
|
+
Parse bits for template tag helpers simple_tag and inclusion_tag, in
|
|
160
|
+
particular by detecting syntax errors and by extracting positional and
|
|
161
|
+
keyword arguments.
|
|
162
|
+
|
|
163
|
+
This is a simplified version of `django.template.library.parse_bits`
|
|
164
|
+
where we use custom regex to handle special characters in keyword names.
|
|
165
|
+
"""
|
|
166
|
+
args = []
|
|
167
|
+
kwargs = {}
|
|
168
|
+
unhandled_params = list(params)
|
|
169
|
+
for bit in bits:
|
|
170
|
+
# First we try to extract a potential kwarg from the bit
|
|
171
|
+
kwarg = token_kwargs([bit], parser)
|
|
172
|
+
if kwarg:
|
|
173
|
+
# The kwarg was successfully extracted
|
|
174
|
+
param, value = kwarg.popitem()
|
|
175
|
+
if param in kwargs:
|
|
176
|
+
# The keyword argument has already been supplied once
|
|
177
|
+
raise TemplateSyntaxError("'%s' received multiple values for keyword argument '%s'" % (name, param))
|
|
178
|
+
else:
|
|
179
|
+
# All good, record the keyword argument
|
|
180
|
+
kwargs[str(param)] = value
|
|
181
|
+
if param in unhandled_params:
|
|
182
|
+
# If using the keyword syntax for a positional arg, then
|
|
183
|
+
# consume it.
|
|
184
|
+
unhandled_params.remove(param)
|
|
185
|
+
else:
|
|
186
|
+
if kwargs:
|
|
187
|
+
raise TemplateSyntaxError(
|
|
188
|
+
"'%s' received some positional argument(s) after some " "keyword argument(s)" % name
|
|
189
|
+
)
|
|
190
|
+
else:
|
|
191
|
+
# Record the positional argument
|
|
192
|
+
args.append(parser.compile_filter(bit))
|
|
193
|
+
try:
|
|
194
|
+
# Consume from the list of expected positional arguments
|
|
195
|
+
unhandled_params.pop(0)
|
|
196
|
+
except IndexError:
|
|
197
|
+
pass
|
|
198
|
+
if unhandled_params:
|
|
199
|
+
# Some positional arguments were not supplied
|
|
200
|
+
raise TemplateSyntaxError(
|
|
201
|
+
"'%s' did not receive value(s) for the argument(s): %s"
|
|
202
|
+
% (name, ", ".join("'%s'" % p for p in unhandled_params))
|
|
203
|
+
)
|
|
204
|
+
return args, kwargs
|
|
@@ -3,7 +3,6 @@ from typing import TYPE_CHECKING, List, Mapping, Optional, Tuple
|
|
|
3
3
|
import django.template
|
|
4
4
|
from django.template.base import FilterExpression, Node, NodeList, Parser, TextNode, Token, TokenType
|
|
5
5
|
from django.template.exceptions import TemplateSyntaxError
|
|
6
|
-
from django.template.library import parse_bits
|
|
7
6
|
from django.utils.safestring import SafeString, mark_safe
|
|
8
7
|
|
|
9
8
|
from django_components.app_settings import ContextBehavior, app_settings
|
|
@@ -17,6 +16,7 @@ from django_components.middleware import (
|
|
|
17
16
|
is_dependency_middleware_active,
|
|
18
17
|
)
|
|
19
18
|
from django_components.slots import FillNode, SlotNode, parse_slot_fill_nodes_from_component_nodelist
|
|
19
|
+
from django_components.template_parser import parse_bits
|
|
20
20
|
from django_components.utils import gen_id
|
|
21
21
|
|
|
22
22
|
if TYPE_CHECKING:
|
|
@@ -279,13 +279,7 @@ def parse_component_with_args(
|
|
|
279
279
|
parser=parser,
|
|
280
280
|
bits=bits,
|
|
281
281
|
params=["tag_name", "name"],
|
|
282
|
-
takes_context=False,
|
|
283
282
|
name=tag_name,
|
|
284
|
-
varargs=True,
|
|
285
|
-
varkw=[],
|
|
286
|
-
defaults=None,
|
|
287
|
-
kwonly=[],
|
|
288
|
-
kwonly_defaults=None,
|
|
289
283
|
)
|
|
290
284
|
|
|
291
285
|
if tag_name != tag_args[0].token:
|
|
@@ -19,6 +19,9 @@ except ImportError:
|
|
|
19
19
|
params = (params,)
|
|
20
20
|
return Annotated(self.type_, *params, **self.metadata[1]) # type: ignore
|
|
21
21
|
|
|
22
|
+
def __class_getitem__(self, *params: Any) -> "Annotated": # type: ignore
|
|
23
|
+
return Annotated(*params) # type: ignore
|
|
24
|
+
|
|
22
25
|
|
|
23
26
|
css = Annotated[str, "css"]
|
|
24
27
|
django_html = Annotated[str, "django_html"]
|