I have a dictionary like this:
dict_name['keyname.with.manydots']
Problem: I can't do a
{{ dict_name.keyname.with.manydots }}
I know it's not possible to do this with Django's templating.. but what is the best work-around you've found? Thanks!
You could write a custom template filter:
from django import template
register = template.Library()
@register.filter
def get_key(value, arg):
return value.get(arg, None)
And in your template
{{ my_dict|get_key:"dotted.key.value" }}
One possible solution, is to create a template tag with the dictionary as the variable and the key as the argument. Remember to emulate Django's default behavior for attribute lookups that fail, this should not throw an error, so return an empty string.
{{ dict_name|get_value:"keyname.with.manydots" }}
@register.filter
def get_value(dict_name, key_name):
return dict_name.get(key_name, '')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With