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?
A variable declaration starts with the keyword var followed by the variable name, e.g. : var myVariable; The variable declaration ends with a semi-colon. The names of the variables in EJS-templates are case-sensitive: myVariable and myvariable are different variables.
EJS work for both server side and client side.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With