不能传递一个嵌套的对象res.render()?

我想访问一个variables在客户端JavaScript, 通过玉 ,传递forms的服务器(节点) 。

所以我做了一个嵌套的对象:

var clientData = {clientData:{ title: 'Title', body: "body", appadress: 'localhost' || req.host, socketport: socketport, } } 

然后将这个对象传递给玉( 通过res.render )..

 app.get('/', function(req, res){ clientData.clientData.appadress = req.host; res.render('index.jade', clientData)}); 

这在玉是接收…(我相信)

 clientData:{ title: 'Title', body: "body", appadress: 'localhost' || req.host, socketport: socketport, } 

然后我可以把它作为一个单独的对象传递给客户端的JavaScript。

 script. var clientData = #{clientData} 

但是这不起作用。

res.render()不是像这样或那样的其他东西的嵌套对象的问题?

你不能使用#{...}来渲染对象,因为它把对象string化(类似于: {}.toString() ,这会产生[object Object] )。

相反,您需要首先将该variables转换为JSON,并确保Jade不会转义输出:

 var clientData = !{ JSON.stringify(clientData) }; 

编辑 :这是一个简单的独立testing(但同样的原则将适用于通过Express使用翡翠):

 // app.jade var jade = require('jade'); jade.renderFile('test.jade', { filename : 'test.jade', // These two properties are only for `renderFile`, pretty : true, // you don't need to include them with`res.render` clientData:{ title : 'Title', body : 'body', appadress : 'localhost', socketport: 8888, } }, function(err, html) { if (err) throw err; console.log(html); }); // test.jade !!! html head script. var clientData = !{ JSON.stringify(clientData) }; body h1 Hello World // Output: <!DOCTYPE html> <html> <head> <script>var clientData = {"title":"Title","body":"body","appadress":"localhost","socketport":1234};</script> </head> <body> <h1>Hello World</h1> </body> </html> 

而我只注意到你似乎在使用clientData作为共享variables,并且只能从每个请求中设置clientData.clientData.appadress 。 这将导致问题,因为clientDatavariables是在所有请求之间共享的,一个请求可能会覆盖appaddress属性,就像另一个请求将渲染模板(显示被覆盖的属性)一样。