最近在想如何为express的模板的变量提前赋值。 减少多个路由设定同一个变量的问题。
以下就是我目前想到的赋值办法:
1.全局赋值
var app = express();
app.locals['username'] = 'xxx';
2.局部赋值
app.use('/', function (req, res) {
res.render('index.ejs',{
username: 'xxx'
});
});
问题: 有没有可能在中间件里面赋值, 如:
app.use(function (req, res, next) {
// 给 res 进行赋值
next();
});
最近了解到 ,
可以 使用
res.locals
进行保存局部变量