【问题标题】:accessing variable globally in marko template在marko模板中全局访问变量
【发布时间】:2017-02-24 02:33:38
【问题描述】:

我们在 nodejs 应用程序中使用 marko 模板引擎。我们有 3 个 marko 布局

  1. header.marko
  2. layout.marko
  3. footer.marko

页眉和页脚布局呈现在 layout.marko 中

每当我们创建一个新的标记页面(内容页面)时,我们都会使用这样的布局标记

<layout-use template="./../layout.marko">

并像这样加载标记

this.body = marko.load("./views/home.marko").stream(data);

现在我们要全局访问一个变量。即如果我们有一个变量用户名='abc'。我们想在页眉、布局或页脚标记文件中访问和显示这个名称。但是我们不想为每个内容标记页面传递用户名。即,如果我们在网站上有 100 个页面,我们不想为所有 100 个页面传递用户名。每当用户登录时,将用户名保存在全局变量中,并在所有页面中使用此全局变量。

我们如何实现这个全局变量功能。

【问题讨论】:

    标签: layout global-variables koa


    【解决方案1】:

    看起来您可以使用$global 属性来公开数据 适用于所有模板。

    例如:

    router.get('/test', function * () {
      this.type = 'html'
      this.body = marko.load("./views/home.marko")
        .stream({
          color: 'red',
          $global: { 
            currUser: { id: 2, username: 'hansel' }
          }
        })
    })
    

    然后是这些模板:

    // home.marko
    <include('./header.marko') />
    <h1>color is ${data.color}</h1>
    
    // header.marko
    <h2>Header</h2>
    <p if(out.global.currUser)>
      Logged in as ${out.global.currUser.username}
    </p>
    <p else>
      Not logged in
    </p>
    

    这行得通。

    但显然你不想将$global 传递给 每个.stream(),所以一个想法是将它存储在 Koa 上下文中,让 任何中间件将数据附加到它,然后编写一个助手将其传递给 我们的模板。

    // initialize the object early so other middleware can use it
    // and define a helper, this.stream(templatePath, data) that will
    // pass $global in for us
    router.use(function * (next) {
      this.global = {}
      this.stream = function (path, data) {
        data.$global = this.global
        return marko.load(path).stream(data)
      }
      yield next
    })
    
    // here is an example of middleware that might load a current user
    // from the database and attach it for all templates to access
    router.use(function * (next) {
      this.global.currUser = {
        id: 2,
        username: 'hansel'
      }
      yield next
    })
    
    // now in our route we can call the helper we defined,
    // and pass any additional data
    router.get('/test', function * () {
      this.type = 'html'
      this.body = this.stream('./views/home.marko', {
        color: red
      })
    })
    

    该代码适用于我上面定义的模板:${out.global.currUser} 可从 header.marko 访问,但 ${data.color} 可从 home.marko.

    我从未使用过 Marko,但我很好奇,看了之后就阅读了文档 你的问题,因为我不时考虑使用它。我没感觉 想弄清楚&lt;layout-use&gt; 是如何工作的,所以我改用&lt;include&gt;

    【讨论】:

    • 谢谢。它满足我的要求。
    猜你喜欢
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多