Returning JSON array from a Django view to a template

后端 未结 3 889
野趣味
野趣味 2020-11-30 09:42

I\'m using Django to create a web-based app for a project, and I\'m running into issues returning an array from a Django view to a template.

The array will be used b

3条回答
  •  既然无缘
    2020-11-30 10:08

    You want to JSON-ify the data in the template; JSON is already Javascript really (it's a subset:

    {% if tags %}
      var tgs = {{ tags }};
    {% endif %}
    

    Note that tags is already JSON (thus JavaScript) data and can be inserted directly; no need to escape (there is no HTML here, it's JavaScript instead).

    Or you could use this Django snippet and do it straight in the template (no need to call serializers.serialize in the annotate method):

    var tgs = {{ tags|jsonify }};
    

提交回复
热议问题