We have a system built on a custom database, where many of the attributes are named containing hyphens, ie:
user-name
phone-number
These pr
Unfortunately, I think you may be out of luck. From the docs:
Variable names must consist of any letter (A-Z), any digit (0-9), an underscore or a dot.
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 :-)
OrderedDict dictionary types support dashes: https://docs.python.org/2/library/collections.html#ordereddict-objects
This seems to be a side effect of the implementation of OrderedDict. Notice below that the key value pairs are actually passed in as sets. I would bet that the implementation of OrderedDict doesn't use the "key" passed in the set as a true dict key thus getting around this issue.
Since this is a side-effect of the implementation of OrderedDict, it may not be something you want to rely on. But it works.
from collections import OrderedDict
my_dict = OrderedDict([
('has-dash', 'has dash value'),
('no dash', 'no dash value')
])
print( 'has-dash: ' + my_dict['has-dash'] )
print( 'no dash: ' + my_dict['no dash'] )
Result:
has-dash: has dash value
no dash: no dash value