在Django / Jinja2模板中将dict对象转换为字符串

时间:2020-12-04 20:46:27

If you use Django or Jinja2, you've probably ran into this problem before. I have a JSON string that looks like this:

如果你使用Django或Jinja2,你可能以前遇到过这个问题。我有一个JSON字符串,如下所示:

{
  "data":{
    "name":"parent",
    "children":[
      {
        "name":"child_a",
        "fav_colors":[
          "blue",
          "red"
        ]
      },
      {
        "name":"child_b",
        "fav_colors":[
          "yellow",
          "pink"
        ]
      }
    ]
  }
}

Now I want to pass this to my Jinja2 template:

现在我想将它传递给我的Jinja2模板:

j = json.loads('<the above json here>')
self.render_response('my_template.html', j)

...and iterate it like this:

...并像这样迭代:

<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>

This is where I'm having the problem: everything works except Jinja2 outputs unicode encoded values for c.fav_colors. I need c.fav_colors as a valid javascript array so that I can access it from javascript. How can I get Jinja to print that value as ascii text like: ['blue','red'] instead of [u'blue', u'red'] ?

这就是我遇到问题的地方:除了Jinja2输出c.fav_colors的unicode编码值之外,一切正常。我需要c.fav_colors作为有效的javascript数组,以便我可以从javascript访问它。我如何让Jinja将该值打印为ascii文本,如:['blue','red']而不是[u'blue',u'red']?

1 个解决方案

#1


13  

You need to convert the fav_colors list back to JSON. Probably the easiest way to do this would be with a quick template filter:

您需要将fav_colors列表转换回JSON。可能最简单的方法是使用快速模板过滤器:

@register.filter
def to_json(value):
    return mark_safe(simplejson.dumps(value))

So now you could do

所以现在你可以做到

<option value="{{ c.fav_colors|to_json }}">

#1


13  

You need to convert the fav_colors list back to JSON. Probably the easiest way to do this would be with a quick template filter:

您需要将fav_colors列表转换回JSON。可能最简单的方法是使用快速模板过滤器:

@register.filter
def to_json(value):
    return mark_safe(simplejson.dumps(value))

So now you could do

所以现在你可以做到

<option value="{{ c.fav_colors|to_json }}">