Express 和 ejs <%= 渲染一个 JSON [英] Express and ejs &lt;%= to render a JSON

查看:27
本文介绍了Express 和 ejs <%= 渲染一个 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 index.ejs 中有这样的代码:

In my index.ejs I have this code:

var current_user = <%= user %>

在我的节点中我有

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

但是,在我获得的页面上

However, on the page I obtain

var current_user = [object Object]

如果我写

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

我得到:

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

有没有办法传递一个JS可读的JSON?

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

推荐答案

哦,那很简单,不要使用 <%=,使用 <%-反而.例如:

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

 <%- JSON.stringify(user) %>

第一个将在 HTML 中呈现,第二个将呈现变量(就像它们一样,eval)

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

这篇关于Express 和 ejs <%= 渲染一个 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆