How do I access dictionary keys that contain hyphens from within a Django template?

A custom template tag is probably the only way to go here if you don’t want to restructure your objects. For accessing dictionaries with an arbitrary string key, the answer to this question provides a good example.

For the lazy:

from django import template
register = template.Library()

@register.simple_tag
def dictKeyLookup(the_dict, key):
   # Try to fetch from the dict, and if it's not found return an empty string.
   return the_dict.get(key, '')

Which you use like so:

{% dictKeyLookup your_dict_passed_into_context "phone-number" %}

If you want to access an object’s attribute with an arbitrary string name, you could use the following:

from django import template
register = template.Library()

@register.simple_tag
def attributeLookup(the_object, attribute_name):
   # Try to fetch from the object, and if it's not found return None.
   return getattr(the_object, attribute_name, None)

Which you would use like:

{% attributeLookup your_object_passed_into_context "phone-number" %}

You could even come up with some sort of string seperator (like ‘__’) for subattributes, but I’ll leave that for homework 🙂

Leave a Comment