我在jinja遇到了一个奇怪的问题。看起来很简单,但我做对了。在包含{{tag["tag"] }}
的jinja模板中,它回显{u'type': u'literal', u'value': u'tourism'}
,但当我尝试使用{{tag["tag"]["value"] }}
获取值时,我从以下字符中收到错误jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'tag'
:< / p>
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'
实际上我正在加载一个包含标签对象的json字符串,如
{"tags": [{"tagObj": {"type": "uri", "value": "http://ci.emse.fr/opensensingcity/ns/sca/tourism"}, "tag": {"type": "literal", "value": "tourism"}}]}
以下的jinja代码失败了我提供的stacktrace:
{% for tag in row["tags"]%}
<span class="label label-info">{{tag["tag"]["value"] }}</span>
{% endfor %}
答案 0 :(得分:1)
请尝试以下代码 -
{% for key, value in dict.iteritems() %}
{{ key }}
{{ value }}
{% endfor %}
答案 1 :(得分:0)
tag = {"tags": [{"tagObj": {"type": "uri", "value": "http://ci.emse.fr/opensensingcity/ns/sca/tourism"}, "tag": {"type": "literal", "value": "tourism"}}]}
你可以使用tag['tags'][0]['tag']['value']
获得价值
以这种方式你的出局将是'tourism'
。