Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 697
hh54188 Avatar asked May 19 '14 09:05

hh54188


People also ask

How do you declare a variable in EJS?

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.

Is EJS front end?

EJS work for both server side and client side.


1 Answers

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.

like image 66
Farid Nouri Neshat Avatar answered Sep 28 '22 02:09

Farid Nouri Neshat