Python Jinja 字典

Python dictionary in Jinja

我在 jinja 遇到了一个奇怪的问题。这看起来很简单,但我做对了。在带有 {{tag["tag"] }} 的神社模板中,它回显 {u'type': u'literal', u'value': u'tourism'} 但是当我尝试使用 {{tag["tag"]["value"] }} 获取值时,我从以下 strace 中收到错误 jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'tag'

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"}}]}

下面的神社代码因我提供的堆栈跟踪而失败:

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

试试下面的代码-

{% for key, value in dict.iteritems() %}
            {{ key }}
            {{ value }}
{% endfor %}
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'