Skip to content Skip to sidebar Skip to footer

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 = '{'

Solution 1:

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.

Solution 2:

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.

Solution 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:

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

-- and then in .js use this g_foo.

Solution 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.

Post a Comment for "Django Template Tags In Javascript - Invalid Syntax Without Quotes, Invalid Syntax With Quotes"