Home > database >  Django Template, how to parse items with symbols
Django Template, how to parse items with symbols

Time:08-04

I have an XML file that I've converted to a python dictionary and passed into a template. I am attempting to do something like this:

<audio controls>
    <source src={{ episode.enclosure.@url }} type={{ episode.enclosure.@type }}>
    Your current browser does not support the audio player.
</audio>

The XML file uses @ at the beginning of the key for URL and TYPE. The problem is, this throws off the parser and crashes the site. How can I call a key with a symbol like @?

CodePudding user response:

You can get the value of dictionary with the help of django template tags.

Template tag example

@register.filter
def get_attr(obj, attr):
    return obj.get(attr)    

As you mentioned context is dict therefore I used obj.get but you can use any other methods depending on obj.

Template usage

{{ result|get_attr:'@url' }}

I defined result in views.py as

context = {
        'result' : {'@url':'a123'}
}
  • Related