【问题标题】:how can i pass a variable as global to a jade template如何将变量作为全局变量传递给玉模板
【发布时间】:2014-06-19 23:43:28
【问题描述】:

我希望能够将一个全局对象传递给玉模板

让我们说:

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 是在全局范围内定义的一样。

谢谢

【问题讨论】:

  • 你有什么理由要手动编译jade吗?
  • 手动编译jade是什么意思?我刚开始使用玉,这是我知道如何使用它的唯一方法。

标签: javascript node.js express pug


【解决方案1】:

如果通过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

【讨论】:

  • 是的,我确实这样使用它,但我不需要本地变量,我需要全局变量。假设我有一个模板 - 在该模板中我加载了另一个 JS 标头,其中包含该页面的所有功能我希望能够使用我从该文件中的服务器“加载”的变量。
  • 我有点糊涂了,如果你在jade中使用include语句(引用另一个模板),你可以访问变量。全局变量,您希望它们可以在您的翡翠模板中访问,对吧?
  • 不使用包括使用 script(src="/js/utilFunctions.js" type="text/javascript")link(href="/css/style.css" rel="stylesheet" type="text/css") 用于 css,我希望能够使用 utilFunction.js 中的变量
  • 如果您想在客户端脚本上公开变量,您必须手动执行(明确说明 var options = '#{options}';)或创建一个名为 /js/utilFunctions 的端点.js 是一个显式的快速端点来渲染你的 JS 文件。
  • 是的,没有解析工作得很好,我把它放在了正确的地方:-) 谢谢你坚持我。
猜你喜欢
  • 2015-08-24
  • 1970-01-01
  • 2012-09-20
  • 2013-09-05
  • 1970-01-01
  • 2014-05-14
  • 1970-01-01
  • 2017-11-10
  • 2012-09-01
相关资源
最近更新 更多