How to pass an array in Django to a template and use it with JavaScript

前端 未结 4 654
無奈伤痛
無奈伤痛 2020-12-05 03:57

I want to pass an Array to a template and afterwards use it via JavaScript.

In my views.py I have:

arry1 = [\'Str\',500,20]
return render_to         


        
相关标签:
4条回答
  • 2020-12-05 04:30

    In Django:

    from django.utils import simplejson
    json_list = simplejson.dumps(YOUR_LIST)
    

    AND PASS "json_list" IN CONTEXT

    IN JS:

    var YOUR_JS_LIST = {{YOUR_LIST|safe}}; 
    
    0 讨论(0)
  • 2020-12-05 04:40

    Try using {{ array1|safe }} and see if that makes any difference. I haven't tested this, so I hope I don't get too downvoted if this is incorrect...

    0 讨论(0)
  • 2020-12-05 04:44

    It could be done by django core serializers. All you need to do is to serialize your data in json and than pass it to template.

    data = serializers.serialize("json", <list>)
    return render(request, 'view.html', {'data':data})
    

    In your template save this list into javascript variable.

    var list = {{data|safe}}
    
    0 讨论(0)
  • 2020-12-05 04:53

    As mentioned, you could use the |safe filter so Django doesn't sanitize the array and leaves it as is.

    Another option, and probably the better one for the long term is to use the simplejson module (it's included with django) to format your Python list into a JSON object in which you can spit back to the Javascript. You can loop through the JSON object just like you would any array really.

    from django.utils import simplejson
    list = [1,2,3,'String1']
    json_list = simplejson.dumps(list)
    render_to_response(template_name, {'json_list': json_list})
    

    And in your Javascript, just {{ json_list }}

    0 讨论(0)
提交回复
热议问题