簡體   English   中英

在Jinja的Python字典

[英]Python dictionary in Jinja

我在jinja遇到了一個奇怪的問題。 看起來很簡單,但我做對了。 在一個帶有{{tag["tag"] }}的jinja模板中,它回應{u'type': u'literal', u'value': u'tourism'}但是當我試圖通過{{tag["tag"]["value"] }}獲得價值時{{tag["tag"]["value"] }} ,我收到錯誤jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'tag'來自以下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"}}]}

下面的jinja代碼失敗了我提供的stacktrace:

{% 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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM