Django template tags in JavaScript - invalid syntax without quotes, invalid syntax with quotes

本秂侑毒 提交于 2019-12-13 06:20:57

问题


It is possible you have Javascript read vars from Django template tags like var spec = "{{ foo }}";.

However, if foo needs to be a JSON object. it becomes like this:

var spec = "{"2": {"guid": 2, "contentBlocks": {"2_1": {"guid": "2_1", "type": "list"}}}}";

The preceding and closing quotes make this an invalid JavaScript syntax, however, if I leave them out, it is also an invalid syntax var spec = {{ foo }};

What would be the best way to solve this problem? Either to have foo output the complete <script></script> block, or to have JavaScript request this object from the server, instead of outputting it via a template tag? ......


回答1:


If it's a JSON object, it doesn't need to be quoted at all. JSON syntax is valid Javascript syntax (although of course the reverse is not necessarily true).

var spec = {{ foo }};

is perfectly good if foo evaluates to a JSON string.




回答2:


If for some reason you wanted it to be a string, try single quotes:

var spec = '{"2": {"guid": 2, "contentBlocks": {"2_1": {"guid": "2_1", "type": "list"}}}}';

If you want it to be a JavaScript object, don't use the quotes at all.

var spec = {"2": {"guid": 2, "contentBlocks": {"2_1": {"guid": "2_1", "type": "list"}}}};

This is valid syntax.

However, Django will escape the quotes if you don't mark it as safe. So, say that json block is the_json in your template,

var spec={{ the_json |safe }}

is what you want. Without the safe filter, the quotes would be output as &quot;, invalidating the JSON.




回答3:


The other answers are perfectly ok if JS is embedded in a template. And if you have a separate .js files that are served statically, then you can expose the nesessary variables in your templates:

<script type="text/javascript">
    var g_foo = {{ foo }};
</script>

-- and then in .js use this g_foo.




回答4:


Thanks for your answers. It turned out to be that Dreamweaver tells me syntax is invalid, but when executing the script it works perfect.



来源:https://stackoverflow.com/questions/4153268/django-template-tags-in-javascript-invalid-syntax-without-quotes-invalid-synt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!