Convert dict object to string in Django / Jinja2 template

If you are using Django or Jinja2, you have probably encountered this problem before. I have a JSON string that looks like this:

{ "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:

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

... and repeat 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 ran into the problem: everything works, except Jinja2 prints 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 this value as ascii text, for example: ['blue','red'] instead of [u'blue', u'red'] ?

+6
source share
1 answer

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

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

So now you can do

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

Source: https://habr.com/ru/post/905095/


All Articles