Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express and ejs <%= to render a JSON

In my index.ejs I have this code:

var current_user = <%= user %> 

In my node I have

app.get("/", function(req, res){     res.locals.user = req.user     res.render("index") }) 

However, on the page I obtain

var current_user = [object Object] 

and if I write

var current_user = <%= JSON.stringify(user) %> 

I obtain:

var current_user = {&quot;__v&quot;:0,&quot;_id&quot;:&quot;50bc01938f164ee80b000001&quot;,&quot;agents&quot;:... 

Is there a way to pass a JSON that will be JS readable?

like image 726
piggyback Avatar asked Dec 09 '12 14:12

piggyback


People also ask

What does res JSON () do in Express?

json() Function. The res. json() function sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using the JSON.

Is EJS A Express?

set('view engine', 'ejs') is self-explanatory. We are setting EJS as the Express app view engine. By default, Express will look inside of a views folder when resolving the template files, which is why we had to create a views folder.


1 Answers

Oh that was easy, don't use <%=, use <%- instead. For example:

 <%- JSON.stringify(user) %> 

The first one will render in HTML, the second one will render variables (as they are, eval)

like image 136
piggyback Avatar answered Oct 01 '22 04:10

piggyback