Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...