JavaScript中的Django模板标记 - 无引号的无效语法,带引号的无效语法 [英] Django template tags in JavaScript - invalid syntax without quotes, invalid syntax with quotes

查看:246
本文介绍了JavaScript中的Django模板标记 - 无引号的无效语法,带引号的无效语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以从Django模板标签(如 var spec ={{foo}};

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

但是,如果foo需要是一个JSON对象。它变成如下:

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"}}}}";

前面和后面的引号使得这是一个无效的JavaScript语法,但是如果我把它留下,也是一个无效的语法 var spec = {{foo}};

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 }};

什么是最好的解决方法这个问题?要么有 foo 输出完整的< script>< / script> 块,或者让JavaScript请求对象,而不是通过模板标签输出? ......

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

推荐答案

如果是JSON对象,则不需要引用它。 JSON语法是有效的Javascript语法(尽管当然不一定是正确的)。

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 }};

如果 foo 评估为JSON字符串。

is perfectly good if foo evaluates to a JSON string.

这篇关于JavaScript中的Django模板标记 - 无引号的无效语法,带引号的无效语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆