Add support for nested arrays in `classnames` template tag

pull/11128/head
LB Johnston 2023-09-17 16:26:29 +10:00 zatwierdzone przez LB (Ben Johnston)
rodzic 502dd7c723
commit 243b126811
2 zmienionych plików z 31 dodań i 1 usunięć

Wyświetl plik

@ -223,7 +223,15 @@ def classnames(*classes):
Usage <div class="{% classnames "w-base" classname active|yesno:"w-base--active," any_other_var %}"></div>
Returns any args as a space-separated joined string for using in HTML class names.
"""
return " ".join([classname.strip() for classname in classes if classname])
flattened = []
for classname in classes:
if isinstance(classname, str):
flattened.append(classname)
elif hasattr(classname, "__iter__"):
flattened.extend(classname)
return " ".join([classname.strip() for classname in flattened if classname])
@register.simple_tag(takes_context=True)

Wyświetl plik

@ -479,6 +479,28 @@ class ClassnamesTagTest(SimpleTestCase):
self.assertEqual(expected.strip(), actual.strip())
def test_with_nested_lists(self):
context = Context(
{
"nested": ["button-add", "button-base "],
"has_falsey": ["", False, [], {}],
"simple": " wagtail ",
}
)
template = """
{% load wagtailadmin_tags %}
<button class="{% classnames nested "add-second " has_falsey simple %}">Hello!</button>
"""
expected = """
<button class="button-add button-base add-second wagtail">Hello!</button>
"""
actual = Template(template).render(context)
self.assertEqual(expected.strip(), actual.strip())
class IconTagTest(SimpleTestCase):
def test_basic(self):