Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template: how to show dict whose key has a dot in it? d['key.name']

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!

like image 428
Jay Avatar asked Jan 16 '23 22:01

Jay


2 Answers

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" }}
like image 174
Timmy O'Mahony Avatar answered Jan 30 '23 20:01

Timmy O'Mahony


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, '')
like image 21
user773328 Avatar answered Jan 30 '23 19:01

user773328