Express i ejs <%= do renderowania JSON

W moim indeksie.ejs mam ten kod:

var current_user = <%= user %>

W moim węźle mam

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

Jednak na stronie otrzymuję

var current_user = [object Object]

A jeśli napiszę

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

Otrzymuję:

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

Czy jest sposób na podanie JSON, który będzie czytelny dla JS?

Author: Talha Awan, 2012-12-09

2 answers

To było proste, nie używaj <%=, zamiast tego używaj <%-. Na przykład:

 <%- JSON.stringify(user) %>

Pierwsza będzie renderować w HTML, druga będzie renderować zmienne (takie jak są, eval)

 157
Author: nick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-05 19:23:14

Uwaga!

Jeśli użytkownik może zostać utworzony przez wywołania API,

Przekazywanie zmiennych do JavaScript w ExpressJS

 2
Author: user732456,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-09 07:14:04