如何在node.js ejs模板中将variables从后端传递到前端

我像这样渲染我的页面:

response.render('index', { data: list // the `list` is an array variable }); 

而在头版,我想存储的data作为全球variables,所以我试着:

 <script> window.app = <%= data %> </script> 

但结果是:

 window.app = [object Object],[object Object],[object Object] 

那么我怎样才能正确地做到这一点呢?

您可以将数据string化为JSON,这是javascript的一个子集,并将被parsing为确切的数据结构。 另外使用<%- expression %>来确保你的javascript不会被转义。

 <script> window.app = <%- JSON.stringify(data) %> </script> 

请注意,这不包括函数,它会抛出循环数据结构。 但是像[{ a : { b : 3 }}]应该可以正常工作。 date也转换为string。

这里有一个要点,因为如果你的一些对象的值有“或”,那么你可能会感到困惑,然后你试图在前端parsing它。

tl;博士 – 我们逃避斜线和引号,因为这些将解决string化的麻烦。

https://gist.github.com/danschumann/ae0b5bdcf2e1cd1f4b61

js:

 myObject = { ... } // This should cover all the bases for what kinds of text the object has. this.injectString = JSON.stringify( myObject ).replace(/\\/g, '\\\\').replace(/"/g, '\\\"') 

和html:

 We only worry about parsing now, since everything should have been properly escaped <script> window.myObjectFrontend = JSON.parse("<%- @injectString %>"); </script> 

注意到前端已经完成了parsing,所以你把对象放回来了,而不仅仅是一个string,就像你在上一个答案中一样(因为string没有引号,这也会中断)。