[Answer]-How to escape $ in the variable name in django

1👍

Django Template does not allow of dollor character to be inside variable name, ref the doc:

Variable names consist of any combination of alphanumeric characters and the underscore (“_”). The dot (“.”) also appears…

In Django shell

>>> from django.template import *
>>> Template("{{ data.user$id }}").render(Context({'data':{'user$id':'foo'}}))
...
TemplateSyntaxError: Could not parse the remainder: '$id' from 'data.user$id'

# "{[" also does not work
>>> Template("{[ data.user$id }}").render(Context({'data':{'user$id':'foo'}}))
u'{[ data.user$id }}'

Thus you need to represent the key explicitly as a string

{% for k, v in data.iteritems %}
    {% if k == 'user$id' %}{{ v }}{% endif %}
{% endfor %}

Or write a template tag which works as {% get_value data "user$id" %}

👤okm

Leave a comment