如果您使用Django或Jinja2,您可能会遇到此问题。 我有一个JSON字符串,看起来像这样:将dict对象转换为Django/Jinja2模板中的字符串
{
"data":{
"name":"parent",
"children":[
{
"name":"child_a",
"fav_colors":[
"blue",
"red"
]
},
{
"name":"child_b",
"fav_colors":[
"yellow",
"pink"
]
}
]
}
}
现在我想这个传递给我的Jinja2模板:
j = json.loads('<the above json here>')
self.render_response('my_template.html', j)
...并反复这样说:
<select>
{% for p in data recursive %}
<option disabled>{{ p.name }}</option>
{% for c in p.children %}
<option value="{{ c.fav_colors|safe }}">{{ c.name }}</option>
{% endfor %}
{% endfor %}
</select>
这是我遇到问题的地方:除了Jinja2输出c.fav_colors的unicode编码值以外,所有东西都可以工作。我需要c.fav_colors作为有效的javascript数组,以便我可以从javascript访问它。我如何让Jinja以ascii文本打印该值:['blue','red']
而不是[u'blue', u'red']
?
没有关闭标签?另外,为什么不[{%for item in c%}“item”{%if not forloop.last%},{%endif%} {%endfor%}]?毕竟这是模板的用途:将python值转换为任何需要的视图。 – jpic 2012-01-04 13:10:53
更新了该选项标签。我在这里使用的循环语法是为了清晰起见。我只是想展示这个问题:如何输出c.fav_colors作为有效的javascript兼容数组:'['blue','red']' – ofko 2012-01-04 13:17:24