繁体   English   中英

如何将全局变量传递给Jade模板

[英]how can i pass a variable as global to a jade template

我希望能够传递一个全局对象,以后将其用于玉模板

可以说:

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用作视图引擎,则如下所示:

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中,您可以访问options变量。

您可以编写一个中间件来自动添加全局变量,如下所示:

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();
}

有关如何使用玉器的更多教程,请参见: http : //runnable.com/UTlPPF-f2W1TAAEe/render-jade-with-express-for-node-js

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM