In my index.ejs I have this code:
JavaScript
x
2
1
var current_user = <%= user %>
2
In my node I have
JavaScript
1
5
1
app.get("/", function(req, res){
2
res.locals.user = req.user
3
res.render("index")
4
})
5
However, on the page I obtain
JavaScript
1
2
1
var current_user = [object Object]
2
and if I write
JavaScript
1
2
1
var current_user = <%= JSON.stringify(user) %>
2
I obtain:
JavaScript
1
2
1
var current_user = {"__v":0,"_id":"50bc01938f164ee80b000001","agents":
2
Is there a way to pass a JSON that will be JS readable?
Advertisement
Answer
Oh that was easy, don’t use <%=
, use <%-
instead. For example:
JavaScript
1
2
1
<%- JSON.stringify(user) %>
2
The first one will render in HTML, the second one will render variables (as they are, eval)