Django Template Variables and Javascript

后端 未结 15 2372
误落风尘
误落风尘 2020-11-22 05:59

When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using {{ myVar }}

相关标签:
15条回答
  • 2020-11-22 06:21

    For a JavaScript object stored in a Django field as text, which needs to again become a JavaScript object dynamically inserted into on-page script, you need to use both escapejs and JSON.parse():

    var CropOpts = JSON.parse("{{ profile.last_crop_coords|escapejs }}");
    

    Django's escapejs handles the quoting properly, and JSON.parse() converts the string back into a JS object.

    0 讨论(0)
  • 2020-11-22 06:24

    I use this way in Django 2.1 and work for me and this way is secure (reference):

    Django side:

    def age(request):
        mydata = {'age':12}
        return render(request, 'test.html', context={"mydata_json": json.dumps(mydata)})
    

    Html side:

    <script type='text/javascript'>
         const  mydata = {{ mydata_json|safe }};
    console.log(mydata)
     </script>
    
    0 讨论(0)
  • 2020-11-22 06:24

    There is a nice easy way implemented from Django 2.1+ using a built in template tag json_script. A quick example would be:

    Declare your variable in your template:

    {{ variable|json_script:'name' }}

    And then call the variable in your <script> Javascript:

    var js_variable = JSON.parse(document.getElementById('name').textContent);

    It is possible that for more complex variables like 'User' you may get an error like "Object of type User is not JSON serializable" using Django's built in serializer. In this case you could make use of the Django Rest Framework to allow for more complex variables.

    0 讨论(0)
  • 2020-11-22 06:25

    A solution that worked for me is using the hidden input field in the template

    <input type="hidden" id="myVar" name="variable" value="{{ variable }}">
    

    Then getting the value in javascript this way,

    var myVar = document.getElementById("myVar").value;
    
    0 讨论(0)
  • 2020-11-22 06:26

    As of Django 2.1, a new built in template tag has been introduced specifically for this use case: json_script.

    https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#json-script

    The new tag will safely serialize template values and protects against XSS.

    Django docs excerpt:

    Safely outputs a Python object as JSON, wrapped in a tag, ready for use with JavaScript.

    0 讨论(0)
  • 2020-11-22 06:28

    I was facing simillar issue and answer suggested by S.Lott worked for me.

    <script type="text/javascript"> 
       var a = "{{someDjangoVariable}}"
    </script>
    

    However I would like to point out major implementation limitation here. If you are planning to put your javascript code in different file and include that file in your template. This won't work.

    This works only when you main template and javascript code is in same file. Probably django team can address this limitation.

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