publik: add |get template filter (#65540)

This commit is contained in:
Lauréline Guérin 2022-05-20 23:17:15 +02:00
parent a37ceab9cd
commit 4508a505ec
No known key found for this signature in database
GPG Key ID: 1FAB9B9B4F93D473
2 changed files with 65 additions and 0 deletions

View File

@ -19,6 +19,17 @@ from django import template
register = template.Library()
@register.filter(name='get')
def get(obj, key):
try:
return obj.get(key)
except AttributeError:
try:
return obj[key]
except (IndexError, KeyError, TypeError):
return None
@register.filter
def getlist(mapping, key):
if mapping is None:

54
tests/test_publik.py Normal file
View File

@ -0,0 +1,54 @@
from django.template import Context, Template
def test_get():
t = Template('{{ foo|get:"foo-bar" }}')
context = Context({'foo': {'foo-bar': 'hello'}})
assert t.render(context) == 'hello'
context = Context({'foo': {'bar-foo': 'hello'}})
assert t.render(context) == 'None'
context = Context({'foo': None})
assert t.render(context) == 'None'
t = Template('{{ foo|get:"foo-bar"|default:"" }}')
context = Context({'foo': {'rab': 'hello'}})
assert t.render(context) == ''
t = Template('{{ foo|get:key }}')
context = Context({'foo': {'foo-bar': 'hello'}, 'key': 'foo-bar'})
assert t.render(context) == 'hello'
def test_getlist():
# nothing in context
t = Template('{% for v in values|getlist:"foo" %}{{ v }},{% endfor %}')
context = Context()
assert t.render(context) == ''
# non value
t = Template('{% for v in values|getlist:"foo" %}{{ v }},{% endfor %}')
context = Context({'values': None})
assert t.render(context) == ''
# not a list
t = Template('{% for v in values|getlist:"foo" %}{{ v }},{% endfor %}')
context = Context({'values': 'foo'})
assert t.render(context) == 'None,None,None,'
# not a list of dict
t = Template('{% for v in values|getlist:"foo" %}{{ v }},{% endfor %}')
context = Context({'values': ['foo']})
assert t.render(context) == 'None,'
t = Template('{% for v in values|getlist:"foo" %}{{ v }},{% endfor %}')
context = Context({'values': [{'foo': 'bar'}, {'foo': 'baz'}]})
assert t.render(context) == 'bar,baz,'
t = Template('{% for v in values|getlist:"unknown" %}{{ v }},{% endfor %}')
context = Context({'values': [{'foo': 'bar'}, {'foo': 'baz'}]})
assert t.render(context) == 'None,None,'
t = Template('{% for v in values|getlist:"k"|getlist:"v" %}{{ v }},{% endfor %}')
context = Context({'values': [{'k': {'v': 'bar'}}, {'k': {'v': 'baz'}}]})
assert t.render(context) == 'bar,baz,'
t = Template('{% for v in values|getlist:"k"|getlist:"unknown" %}{{ v }},{% endfor %}')
context = Context({'values': [{'k': {'v': 'bar'}}, {'k': {'v': 'baz'}}]})
assert t.render(context) == 'None,None,'
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,'