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

标签 javascript node.js express pug

我希望能够将一个全局对象传递给 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/

相关文章:

javascript - 使用 mongoose 在 Mongo DB 中搜索和过滤数据

node.js - Express Node.js 在实时服务器上没有响应

javascript - 使用 npm 作为构建工具无法完成的事情?

javascript - Node Js Express 遍历数组

javascript - 如何从 Node 表达渲染 Angular 组件

javascript - 如何在 Angular 中使用ng-template?

javascript - 正则表达式适用于 JavaScript,但不适用于 PHP

javascript - 与 npm install 集成

javascript - 如何在 JavaScript 中使用 'MMMM Do YYYY, h:mm:ss a' 对日期进行排序

javascript - Node/Express 未将更新的公司信息保存到数据库