【发布时间】:2012-01-04 13:04:12
【问题描述】:
如果您使用 Django 或 Jinja2,您可能以前遇到过这个问题。 我有一个如下所示的 JSON 字符串:
{
"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 值转换为视图所需的任何内容。
-
更新了那个选项标签。我在这里使用的循环语法是为了清楚起见。我只是想展示这个问题:如何将 c.fav_colors 输出为有效的 javascript 兼容数组:
['blue','red']