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) == ''