Skip to content

Commit 5c31533

Browse files
robwaadamghill
authored andcommitted
feature: #235 Allow dynamic component parameter
1 parent 5e9142b commit 5c31533

File tree

1 file changed

+7
-13
lines changed

1 file changed

+7
-13
lines changed

django_unicorn/templatetags/unicorn.py

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from django import template
44
from django.conf import settings
5+
from django.template.base import FilterExpression
56

67
import shortuuid
78

@@ -42,15 +43,7 @@ def unicorn(parser, token):
4243
"%r tag requires at least a single argument" % token.contents.split()[0]
4344
)
4445

45-
tag_name = contents[0]
46-
component_name = contents[1]
47-
48-
if not (
49-
component_name[0] == component_name[-1] and component_name[0] in ('"', "'")
50-
):
51-
raise template.TemplateSyntaxError(
52-
"%r tag's argument should be in quotes" % tag_name
53-
)
46+
component_name = parser.compile_filter(contents[1])
5447

5548
kwargs = {}
5649

@@ -61,11 +54,11 @@ def unicorn(parser, token):
6154
except InvalidKwarg:
6255
pass
6356

64-
return UnicornNode(component_name[1:-1], kwargs)
57+
return UnicornNode(component_name, kwargs)
6558

6659

6760
class UnicornNode(template.Node):
68-
def __init__(self, component_name: str, kwargs: Dict = {}):
61+
def __init__(self, component_name: FilterExpression, kwargs: Dict = {}):
6962
self.component_name = component_name
7063
self.kwargs = kwargs
7164
self.component_key = ""
@@ -106,10 +99,11 @@ def render(self, context):
10699
self.parent = resolved_kwargs.pop("parent")
107100

108101
component_id = None
102+
component_name = self.component_name.resolve(context)
109103

110104
if self.parent:
111105
# Child components use the parent for part of the `component_id`
112-
component_id = f"{self.parent.component_id}:{self.component_name}"
106+
component_id = f"{self.parent.component_id}:{component_name}"
113107

114108
if self.component_key:
115109
component_id = f"{component_id}:{self.component_key}"
@@ -140,7 +134,7 @@ def render(self, context):
140134

141135
view = UnicornView.create(
142136
component_id=component_id,
143-
component_name=self.component_name,
137+
component_name=component_name,
144138
component_key=self.component_key,
145139
parent=self.parent,
146140
kwargs=resolved_kwargs,

0 commit comments

Comments
 (0)