How to pass variable from back-end to front-end in node.js ejs template

扶醉桌前 提交于 2021-02-07 03:25:45

问题


I render my page like this:

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

And in the front page, I want store the data as globe variable, so I tried:

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

but the result is :

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

So how can I do it in right way?


回答1:


You can stringify the data as JSON, which is a subset of javascript, and will be parsed as the exact data structure. Also use <%- expression %> to make sure your javascript won't be escaped.

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

Note that this won't include functions and it will throw on cyclic data structures. But stuff like [{ a : { b : 3 }}] should work fine. Dates are also converted to strings.




回答2:


Here's a gist, because it can get confusing if some of your objects values have " or ' in them, and then you try to parse that on the frontend.

tl;dr - we escape slashes and quotes, since those will mess with parsing the stringified string.

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

the 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, '\\\"')

and the html:

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

notice the parse is being done on the frontend, so you have your object back, not just a string as you would in the previous answer ( which would also break since there were no quotes on the string ).



来源:https://stackoverflow.com/questions/23733748/how-to-pass-variable-from-back-end-to-front-end-in-node-js-ejs-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!