Accessing dict elements with leading underscores in Django Templates Accessing dict elements with leading underscores in Django Templates elasticsearch elasticsearch

Accessing dict elements with leading underscores in Django Templates


The docs mention that you can't have a variable start with an underscore:

Variable names must consist of any letter (A-Z), any digit (0-9), an underscore (but they must not start with an underscore) or a dot.

but you can easily write a custom template filter to mimic the dictionary's get method:

@register.filter(name='get')def get(d, k):    return d.get(k, None)

and

{{ my_dict|get:"_my_key" }}


In my case, if I know the dict elements, and it's only one, I prefer to rename the dict key using pop:

my_dict['new_key'] = my_dict.pop('_old_key')

That way I get a new name on the dict, and I can access in the template without problems.