From fae07a449eb4eccba2ffab3c082534f3a4eda0f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Corentin=20S=C3=A9chet?= Date: Mon, 4 Jul 2022 21:22:00 +0200 Subject: [PATCH] publik: add |first template filter (#66955) --- .../publik/templatetags/publik.py | 9 +++++++++ tests/test_publik.py | 16 ++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/publik_django_templatetags/publik/templatetags/publik.py b/publik_django_templatetags/publik/templatetags/publik.py index 97b7265..8a03e34 100644 --- a/publik_django_templatetags/publik/templatetags/publik.py +++ b/publik_django_templatetags/publik/templatetags/publik.py @@ -15,6 +15,7 @@ # along with this program. If not, see . from django import template +from django.template import defaultfilters register = template.Library() @@ -45,3 +46,11 @@ def getlist(mapping, key): @register.filter(name='list') def as_list(obj): return list(obj) + + +@register.filter +def first(value): + try: + return defaultfilters.first(value) + except TypeError: + return '' diff --git a/tests/test_publik.py b/tests/test_publik.py index c5bd16f..d83d244 100644 --- a/tests/test_publik.py +++ b/tests/test_publik.py @@ -52,3 +52,19 @@ def test_getlist(): t = Template('{% for v in values|getlist:"k"|getlist:"v" %}{{ v }},{% endfor %}') context = Context({'values': [{'k': None}, {'k': {'v': 'baz'}}]}) assert t.render(context) == 'None,baz,' + + +def test_first(): + t = Template('{{ foo|first }}') + + context = Context({'foo': ['foo']}) + assert t.render(context) == 'foo' + + context = Context({'foo': 'foo'}) + assert t.render(context) == 'f' + + context = Context({'foo': ''}) + assert t.render(context) == '' + + context = Context({'foo': None}) + assert t.render(context) == ''