【问题标题】:Global variable in Marko JS Template and ExpressMarko JS 模板和 Express 中的全局变量
【发布时间】:2016-01-13 07:54:48
【问题描述】:

一旦我在 Express 中设置了一个全局变量,使用

app.use(function(req, res, next){
  res.locals.isAuthenticated = true;
  next();
});

如何从任何视图(*.marko 模板)中获取该变量?

我知道在 Jade 中您应该能够像访问任何其他变量一样直接访问它,而无需将其从子模板传递给父模板。 Marko JS 中的等价物是什么?

谢谢

【问题讨论】:

    标签: node.js marko


    【解决方案1】:

    使用 Marko,您通常希望 bypass the Express view engine 并将模板直接渲染到可写的 res 流:

    var template = require('./template.marko');
    
    app.use(function(req, res){
      var templateData = { ... };
      template.render(templateData, res);
    });
    

    通过这种方法,您可以完全控制将哪些数据传递给您的模板。从技术上讲,您可以通过执行以下操作访问模板中的res.locals

    <div if="out.stream.locals.isAuthenticated">
    

    注意:out.stream 只是对正在写入的可写流的引用(在本例中为 res

    您还有其他一些选择:

    使用res.locals作为模板数据

    var template = require('./template.marko');
    
    app.use(function(req, res){
      var templateData = res.locals;
      template.render(templateData, res);
    });
    

    res.locals构建模板数据

    var template = require('./template.marko');
    
    app.use(function(req, res){
      var templateData = {
        isAuthenticated: res.locals.isAuthenticated
      };
      template.render(templateData, res);
    });
    

    Marko 还支持使用out.global 访问的“全局”数据。见:http://markojs.com/docs/marko/language-guide/#global-properties

    如果您还有疑问,请分享!

    【讨论】:

    • 谢谢@Patrick Steele-Idem,除了我在帖子中写的代码之外,我唯一要做的就是用if="out.stream.locals.isAuthenticated" 检查变量,就像你说的那样。而已!这样我就不必像您建议的其他示例那样将变量直接传递给模板。 app.locals 呢?我怎样才能接触到这些?
    • 嘿@crash,app 实例挂断resreq 分别为res.appreq.app,因此您可以访问app.localsout.stream.app.locals
    • 对于像我这样到达这里并发现死链接的人:我们可以通过 out.global 在任何视图中使用 res 自动访问 req、res、app、app.locals 和 res.locals。 marko 而不是 template.render 与 express。见markojs.com/docs/express/#usage
    猜你喜欢
    • 2017-02-24
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    相关资源
    最近更新 更多