Skip to content

Commit 9428018

Browse files
committed
feat: Add syntax for choices
1 parent 3cd8767 commit 9428018

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

djangocms_frontend/templatetags/cms_component.py

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
import re
13
from django import forms, template
24

35
register = template.Library()
@@ -49,10 +51,29 @@ def field(context: template.Context, field_name: str, field_type: forms.Field, *
4951
return ""
5052

5153

54+
def _to_tuple_if_needed(value: str) -> str | tuple[str, str]:
55+
"""
56+
Helper function to convert a string into a tuple if it contains a delimiter.
57+
58+
Args:
59+
value (str): The string to be converted.
60+
61+
Returns:
62+
tuple[str, str]: A tuple containing the two parts of the string if it contains a delimiter,
63+
otherwise returns the original string as a single-element tuple.
64+
"""
65+
match = re.match(r"^(.*?)\s*<([^>]+)>\s?$", value)
66+
if match:
67+
return [match.group(1).strip(), match.group(2).strip()]
68+
return value
69+
70+
5271
@register.filter
53-
def split(value: str, delimiter: str = "|") -> list[str]:
72+
def split(value: str, delimiter: str = "|") -> list[str] | list[tuple[str, str]]:
5473
"""
5574
Helper that splits a given string into a list of substrings based on a specified delimiter.
75+
If the substring is of the format "Verbose name <value>" it is turned into a 2-tuple
76+
as used by a form field's choices argument.
5677
5778
Args:
5879
value (str): The string to be split.
@@ -61,4 +82,5 @@ def split(value: str, delimiter: str = "|") -> list[str]:
6182
Returns:
6283
list[str]: A list of substrings obtained by splitting the input string using the delimiter.
6384
"""
64-
return value.split(delimiter)
85+
split_list = value.split(delimiter)
86+
return [_to_tuple_if_needed(item) for item in split_list]

0 commit comments

Comments
 (0)