from django import template from django.utils.safestring import SafeString, mark_safe @register.simple_tag def list_punctuation(loop, conjunction: str = "or") -> SafeString: # return commas between items if > 2, and the appropriate conjunction num_items = loop["counter"] + loop["revcounter"] - 1 if loop["revcounter0"] > 1: # if >2 remaining, add commas return mark_safe(", ") elif loop["revcounter0"] == 1: return mark_safe(f"{',' if num_items >= 3 else ''} {conjunction} ") return mark_safe("") # unit tests import pytest from django.template import Context, Template @pytest.mark.parametrize( "input, conj, expected", [ (["a"], "", "a"), (["a", "b"], "", "a or b"), (["a", "b"], "'and'", "a and b"), (["a", "b", "c"], "", "a, b, or c"), (["a", "b", "c"], "'and'", "a, b, and c"), ], ) def test_list_punctuation(input, conj, expected): template_to_render = "{% load bs4 %}{% for item in items %}{{item}}{% list_punctuation forloop ZZZ %}{% endfor %}" rendered_template = Template(template_to_render.replace("ZZZ", conj)).render( Context({"items": input}) ) assert rendered_template.strip() == expected