From 243b12681157d1ba3e8787a7e0486b7a17321d2c Mon Sep 17 00:00:00 2001 From: LB Johnston Date: Sun, 17 Sep 2023 16:26:29 +1000 Subject: [PATCH] Add support for nested arrays in `classnames` template tag --- .../admin/templatetags/wagtailadmin_tags.py | 10 ++++++++- wagtail/admin/tests/test_templatetags.py | 22 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/wagtail/admin/templatetags/wagtailadmin_tags.py b/wagtail/admin/templatetags/wagtailadmin_tags.py index 84a95c64c6..4b06f16013 100644 --- a/wagtail/admin/templatetags/wagtailadmin_tags.py +++ b/wagtail/admin/templatetags/wagtailadmin_tags.py @@ -223,7 +223,15 @@ def classnames(*classes): Usage
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) diff --git a/wagtail/admin/tests/test_templatetags.py b/wagtail/admin/tests/test_templatetags.py index 9d5aced80b..96d8c25991 100644 --- a/wagtail/admin/tests/test_templatetags.py +++ b/wagtail/admin/tests/test_templatetags.py @@ -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 %} + + """ + + expected = """ + + """ + + actual = Template(template).render(context) + + self.assertEqual(expected.strip(), actual.strip()) + class IconTagTest(SimpleTestCase): def test_basic(self):