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

Izz ad-Din Ruhulessin
  • 5,955
  • 7
  • 28
  • 28

4 Answers4

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.

Mark Snidovich
  • 1,055
  • 7
  • 11
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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
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.

Tomasz Zieliński
  • 16,136
  • 7
  • 59
  • 83
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.

Izz ad-Din Ruhulessin
  • 5,955
  • 7
  • 28
  • 28