Django Template Variables and Javascript

后端 未结 15 2377
误落风尘
误落风尘 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.

提交回复
热议问题