Noor
Noor

Reputation: 20150

Python dictionary in Jinja

I'm getting a weird problem in jinja. It seems simple but i'm getting it right. In a jinja template with {{tag["tag"] }} it is echoing {u'type': u'literal', u'value': u'tourism'} but when I am trying to get the value with {{tag["tag"]["value"] }}, I am getting the error jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'tag' from the following strace:

Traceback (most recent call last):
  File "vocabularies.py", line 16, in <module>
    table_html = ontology_table.render(fields=["title","domain","tags","expressivity"],rows=table_data["data"])
  File "/usr/lib/python2.7/site-packages/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 969, in render
    return self.environment.handle_exception(exc_info, True)
  File "/usr/lib/python2.7/site-packages/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 742, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "<template>", line 42, in top-level template code
  File "/usr/lib/python2.7/site-packages/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 378, in getitem
    return obj[argument]
jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'tag'

In fact i'm loading a json string which contains a tags object like

{"tags": [{"tagObj": {"type": "uri", "value": "http://ci.emse.fr/opensensingcity/ns/sca/tourism"}, "tag": {"type": "literal", "value": "tourism"}}]}

and the jinja code below is failing with the stacktrace i provided:

{% for tag in row["tags"]%}
    <span class="label label-info">{{tag["tag"]["value"] }}</span>
{% endfor %}

Upvotes: 5

Views: 13516

Answers (2)

Usman Maqbool
Usman Maqbool

Reputation: 3371

tag = {"tags": [{"tagObj": {"type": "uri", "value": "http://ci.emse.fr/opensensingcity/ns/sca/tourism"}, "tag": {"type": "literal", "value": "tourism"}}]}

you can get value using tag['tags'][0]['tag']['value'] and your out put will be 'tourism' in this way.

Upvotes: 4

utkbansal
utkbansal

Reputation: 2817

Try the following code -

{% for key, value in dict.iteritems() %}
            {{ key }}
            {{ value }}
{% endfor %}

Upvotes: 3

Related Questions