[英]How to parse Rest Api json response and insert data to Jade template (Node.js + express)?
所以,我需要在node.js + express中解析json響應並將數據插入到jade文件中。 我在Sinatra這樣做,這很容易,但在這里..響應格式如:
{
"status": "200",
"name": "",
"port": "7777",
"playercount": "4",
"players": "name, of, player"
}
Express的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對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.