在marko模板中全局访问变量

accessing variable globally in marko template

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

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

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

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

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

并像这样加载 marko

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

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

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

看起来您可以使用 $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,但是看了文档之后很好奇 你的问题,因为我不时想过使用它。我没觉得 就像弄清楚 <layout-use> 是如何工作的,所以我改用 <include>