4
4
5
5
register = template .Library ()
6
6
7
+ _TUPLE_RE = re .compile (r"^(.*?)\s*<([^>]+)>\s?$" )
8
+
7
9
8
10
@register .simple_tag (takes_context = True )
9
11
def cms_component (context : template .Context , * args , ** kwargs : dict ) -> str :
@@ -59,17 +61,17 @@ def _to_tuple_if_needed(value: str) -> str | tuple[str, str]:
59
61
value (str): The string to be converted.
60
62
61
63
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
+ str | tuple[str, str]: A tuple containing the two parts of the string if it contains
65
+ a delimiter, otherwise returns the original string .
64
66
"""
65
- match = re . match ( r"^(.*?)\s*<([^>]+)>\s?$" , value )
67
+ match = _TUPLE_RE . fullmatch ( value )
66
68
if match :
67
69
return (match .group (2 ).strip (), match .group (1 ).strip ())
68
70
return value
69
71
70
72
71
73
@register .filter
72
- def split (value : str , delimiter : str = "|" ) -> list [str ] | list [ tuple [str , str ]]:
74
+ def split (value : str , delimiter : str = "|" ) -> list [str | tuple [str , str ]]:
73
75
"""
74
76
Helper that splits a given string into a list of substrings based on a specified delimiter.
75
77
If the substring is of the format "Verbose name <value>" it is turned into a 2-tuple
@@ -80,7 +82,8 @@ def split(value: str, delimiter: str = "|") -> list[str] | list[tuple[str, str]]
80
82
delimiter (str, optional): The delimiter to use for splitting the string. Defaults to "|".
81
83
82
84
Returns:
83
- list[str]: A list of substrings obtained by splitting the input string using the delimiter.
85
+ list[str | tuple[str, str]: A list of substrings or 2-tuples obtained by splitting the
86
+ input string using the delimiter.
84
87
"""
85
88
split_list = value .split (delimiter )
86
89
return [_to_tuple_if_needed (item ) for item in split_list ]
0 commit comments