0

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

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I usually use mark_safe() in the return values, or would you not recommend that?
Either way works fine, of course - just depends if you'd rather do it in the template or the view.
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.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.