Django template tags in JavaScript - invalid syntax without quotes, invalid syntax with quotes
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 als开发者_运维技巧o 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? ......
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 "
, invalidating the JSON.
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.
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
.
Thanks for your answers. It turned out to be that Dreamweaver tells me syntax is invalid, but when executing the script it works perfect.
精彩评论