publik: add |first template filter (#66955)

This commit is contained in:
Corentin Sechet 2022-07-04 21:22:00 +02:00
parent 4508a505ec
commit fae07a449e
2 changed files with 25 additions and 0 deletions

View File

@ -15,6 +15,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
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 ''

View File

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