快遞的res.render()
方法可以讓你在本地模板傳遞變量,且模板中使用它們。例如:
app.route('/', function (req, res) {
// Your code to get the response, and for example's sake, I'll say it's assigned to 'view_data'.
if (typeof view_data === 'string') {
// If you know for sure if your data is going to be an object or a string,
// you can leave the if statement out, and instead just parse it (or not if
// it's already an object.
view_data = JSON.parse(view_data);
}
res.render('template', view_data);
});
並在template.jade
h1 This is #{name}
pre= status
p #{playercount} players online
的數據可以是任何JSON對象,所以如果你有響應返回文本,你可以使用JSON.parse()
把它變成一個JSON對象。
var obj ='JSON.parse(json_str)'? –
你好,歡迎來到StackOverflow!我建議你應該在網站上搜索類似的問題。解析JSON是一個已經被問及多次回答的問題[例如](http://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object)。我也發現[這個問題](http://stackoverflow.com/questions/32021147/output-a-server-generated-json-object-in-jade-without-json-parse)這似乎是非常類似於你的。 –