我希望能够将一个全局对象传递给 Jade 模板,稍后我将使用该全局对象
可以说:
app.get("/", function(req, res){
var options = {
chGlobal : {// this is the object i want to be a global
"property1" : 1,
"property2" : 2,
"property3" : 3,
}
};
jade.renderFile(__dirname +'/tpl/main.jade', options, function (err, html) {
console.log(err, html);
if (err)
{
throw err
}
else
{
res.send(html);
}
});
});
我希望能够在加载的其他脚本中使用“chGlobal”。就像 chGlobal 是在全局范围内定义的一样。
谢谢
最佳答案
如果通过express使用jade作为 View 引擎,像这样:
app.set('views', __dirname); // this will be where your views are located.
app.set('view engine', 'jade');
您可以使用res.locals.variable指定局部变量。
示例)
app.get("/", function(req, res){
res.locals.options = {
chGlobal : {// this is the object i want to be a global
"property1" : 1,
"property2" : 2,
"property3" : 3,
}
};
res.render('main');
});
然后在 Jade 中,您可以访问选项变量。
您可以编写一个中间件来自动附加全局变量,如下所示:
app.get("/", registerGlobals, function(req, res) {
那么中间件功能将是:
function registerGlobals(req, res, next) {
res.locals.options = {
chGlobal : {// this is the object i want to be a global
"property1" : 1,
"property2" : 2,
"property3" : 3,
}
};
next();
}
更多关于如何使用jade的教程在这里:http://runnable.com/UTlPPF-f2W1TAAEe/render-jade-with-express-for-node-js
关于javascript - 我如何将全局变量传递给 Jade 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24317922/