node.js Jade 模板,如何将具体对象传递给页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8437295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:52:34  来源:igfitidea点击:

Jade template, how to pass concrete object to pages?

node.jspug

提问by Masiar

I have a jade template for my node.js project. I would like to send an object to the jade template and pass it to a function inside the page (to render something).

我的 node.js 项目有一个 jade 模板。我想将一个对象发送到 jade 模板并将其传递给页面内的一个函数(以呈现某些内容)。

I am sure I send the right stuff from the server like this

我确定我像这样从服务器发送了正确的东西

res.render(__dirname + '/pages/viz.jade', {
    vizJson: newJson,
});

in the client I do something like this:

在客户端我做这样的事情:

script
    sunburst(#{vizJson})

Thus, inside a script function, I want to call a function that creates my visualization with some json I created on the server side.

因此,在脚本函数中,我想调用一个函数,该函数使用我在服务器端创建的一些 json 来创建我的可视化。

The problem is that when rendered I have something like sunburst([Object object]). I also tried to send the stringified version of the JSON but when I do JSON.parse(#{vizJson})it complains like Unexpected token &.

问题是,渲染时我有类似sunburst([Object object]). 我还尝试发送 JSON 的字符串化版本,但是当我这样做时,JSON.parse(#{vizJson})它会抱怨Unexpected token &.

The json I send is always different and has different level of depths.

我发送的 json 总是不同的,并且具有不同的深度级别。

Does anyone knows what to do?

有谁知道该怎么做?

Thanks

谢谢

回答by Masiar

I hope this is going to help someone. I solved it like this:

我希望这会帮助某人。我是这样解决的:

script
    sunburst(!{JSON.stringify(vizJson)})

Notice the !and the {...}wrapping the stringify method.

注意!{...}包装 stringify 方法。

回答by btford

For this to work, you need to stringify on the server.

为此,您需要在服务器上进行字符串化。

res.render(__dirname + '/pages/viz.jade', {
    vizJson: JSON.stringify(newJson),
});

Then, as you mentioned, parse the JSON on the client.

然后,正如您所提到的,在客户端解析 JSON。

script
    sunburst(JSON.parse(#{vizJson}))

Hope that helps!

希望有帮助!

回答by Airswoop1

Oddly enough, for me the solution involved no calls to JSON.parse. I stringified my object on the server and just used the !{vizJson}method and got my object clientside.

奇怪的是,对我来说,解决方案没有调用JSON.parse. 我在服务器上对我的对象进行了字符串化,然后使用了该!{vizJson}方法并获取了我的对象客户端。

Per the docs, unescaped string interpolation: http://jade-lang.com/reference/interpolation/

根据文档,未转义的字符串插值:http: //jade-lang.com/reference/interpolation/

回答by Greg S

On the JS side, you send back

在JS端,你发回

res.render(__dirname + '/pages/viz.jade', {
    vizJson: JSON.stringify(newJson),
});

On the HTML side, I have found that something like:

在 HTML 方面,我发现类似:

JSON.parse( '!{vizJson}' )

works.

作品。