add get templatetag (#17284)
This commit is contained in:
parent
4118b6a0ca
commit
df88df87a4
|
@ -157,3 +157,10 @@ def has_role(user, groupname):
|
|||
if not user or user.is_anonymous():
|
||||
return False
|
||||
return user.groups.filter(name=groupname).exists()
|
||||
|
||||
@register.filter(name='get')
|
||||
def get(obj, key):
|
||||
try:
|
||||
return obj.get(key)
|
||||
except AttributeError:
|
||||
return None
|
||||
|
|
|
@ -58,3 +58,20 @@ def test_has_role():
|
|||
assert t.render(context) == 'False'
|
||||
request.user = AnonymousUser()
|
||||
assert t.render(context) == 'False'
|
||||
|
||||
def test_get():
|
||||
t = Template('{% load combo %}{{ 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('{% load combo %}{{ foo|get:"foo-bar"|default:"" }}')
|
||||
context = Context({'foo': {'rab': 'hello'}})
|
||||
assert t.render(context) == ''
|
||||
|
||||
t = Template('{% load combo %}{{ foo|get:key }}')
|
||||
context = Context({'foo': {'foo-bar': 'hello'}, 'key': 'foo-bar'})
|
||||
assert t.render(context) == 'hello'
|
||||
|
|
Loading…
Reference in New Issue