开发者

Django how to handle # in variable name

开发者 https://www.devze.com 2023-01-01 07:58 出处:网络
I\'ve got a dictionary in python which is assigned as a template variable. One of the keys is named \"#text\" but when i try to access it using {{ artist.image.3.\"#text\"}} I get an error which is

I've got a dictionary in python which is assigned as a template variable. One of the keys is named "#text" but when i try to access it using {{ artist.image.3."#text"}} I get an error which is

  File "/home/jack/Desktop/test/appengine/lib/django/django/template/__init__.py", line 558, in __init__
    raise TemplateSyntaxError, "Could not parse the remainder: %s" % token[upto:]
TemplateSyntaxError: Could not parse the remainder: "#text"

So how can I use this in the template? I've tried putting quotes around it but to no avail. I'd like to not modify the dictionary if possible, but if its easy enough to do then I guess its okay.

Th开发者_Go百科anks


Django except such variables to be proper names, you have two options

  1. if possible just change #text to text or something like that
  2. else write a template filter which excepts key name and returns value

e.g.

@register.filter
def get_key(d, key):
    return d[key]

usage:

 {{ my_dict|get_key:'#text' }}

Read http://docs.djangoproject.com/en/dev/howto/custom-template-tags/ to see how to write and use template filters and tags.

0

精彩评论

暂无评论...
验证码 换一张
取 消