在Jade Template中显示中间件值

时间:2016-04-20 01:49:56

标签: node.js express pug

我有以下示例中间件组件,我想在index.jade文件中显示。这可能吗?如何在Jade模板中添加req.requestTime

var requestTime = function (req, res, next) {
  req.requestTime = Date.now();
  next();
};

app.use(requestTime);

2 个答案:

答案 0 :(得分:0)

将属性添加到res.locals,您可以在Pug(以前的Jade)中使用它

var requestTime = function (req, res, next) {
  req.requestTime = Date.now();
  res.locals.requestTime = req.requestTime;
  next();
};

答案 1 :(得分:0)

var requestTime = function (req, res, next) {
    req.requestTime = Date.now();
      res.locals.requestTime = req.requestTime;
      next();
};

//Jade renderer
var jadeRenderer = function(req, res) {
    var jadeFile = 'path/to/jade/template';
    var jadeVars = {
        locals: req.locals,
        queryParams: req.query //if you desire?
    };
    res.render(jadeFile, jadeVars, function(err, html) {
        if(err) {
            //handle error
        }
        res.send(html);
    });
};

//jade template
<p>#{locals.requestTime}</p>