在marko模板中全局访问变量

穆罕默德·哈比卜

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

  1. 标头
  2. layout.marko
  3. 页脚标记

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

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

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

并像这样加载marko

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

现在,我们要全局访问一个变量。即,如果我们有一个变量username ='abc'。我们要访问此名称并将其显示在header,layout或footer marko文件中。但是我们不想为每个内容标记页面传递用户名。也就是说,如果我们网站上有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给every .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>改用了。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章