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

I make my page as follows:

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

And on the first page I want to save dataas a globe variable, so I tried:

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

but the result:

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

So how can I do it right?

+4
source share
2 answers

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

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

, , . [{ a : { b : 3 }}] . .

+6

, , "" , .

tl; dr - , .

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>

, , , , ( , ).

+3

Source: https://habr.com/ru/post/1541084/


All Articles