如何将数组传递给下划线模板中的脚本?

How to pass an array to a script in an underscore template?

我正在尝试将文件名数组传递到模板中,这样 var 就可以访问该数组。这样我的页面就不必在页面加载后执行 AJAX 请求。从我的快速路线,我呈现模板:

var a = ['a.jpg','b.jpg','c.jpg'];
res.render('clean', {images: a});

在我的模板中:

<script type="text/javascript">
    var images = <%- JSON.stringify(images) %>;
</script>

我的期望:

var images = ["a.jpg", "b.jpg", "c.jpeg"];

我得到的:

var images = [&quot;a.jpg&quot;,&quot;b.jpg&quot;,&quot;c.jpg&quot;];

我试过在路由代码而不是模板中进行字符串化,但结果相同。

检查documentation,您可以阅读:

Template functions can both interpolate values, using <%= … %>, as well as execute arbitrary JavaScript code, with <% … %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %>.

您正在使用 <%- 因此输出是 HTML 转义。我建议你使用 <%= 来避免这个问题。

希望对您有所帮助。

// Your current code.
var templFnc = _.template('var images = <%- JSON.stringify(images) %>');

console.log(templFnc({
  images: ["a.jpg", "b.jpg", "c.jpeg"]
}));

// Code using <%= instead of <%-
var templFnc = _.template('var images = <%= JSON.stringify(images) %>');

console.log(templFnc({
  images: ["a.jpg", "b.jpg", "c.jpeg"]
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>