- Author:
- shapiromatron
- Posted:
- January 12, 2024
- Language:
- Python
- Version:
- 3.2
- Score:
- 1 (after 1 ratings)
If you have multiple items in a list and want them to be displayed as human readable list of items, this will add the proper punctuation to generate the text. You'll need to provide a conjugation to the end of the list like "or" or "and"; it defaults to "or".
Intended use:
{% for item in items %}{{item}}{% list_punctuation forloop "and" %}{% endfor %}
- If items was
['a']
; the template would returna
. - If items was
['a', 'b']
; the template would returna and b
. - If items was
['a', 'b', 'c']
; the template would returna, b, and c
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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 |
More like this
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
- Stuff by NixonDash 1 year, 9 months ago
Comments
Please login first before commenting.