如何解析Rest Api json响应并将数据插入Jade模板(Node.js + express)?

时间:2015-09-30 22:51:01

标签: javascript json node.js express pug

所以,我需要解析node.js + express中的json响应并将数据插入到jade文件中。我在Sinatra这样做,这很容易,但在这里.. 响应格式如:

{
  "status": "200",
  "name": "",
  "port": "7777",
  "playercount": "4",
  "players": "name, of, player"
}

1 个答案:

答案 0 :(得分:1)

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对象。