在marko模板中全局访问变量

Muh*_*bib 2 layout global-variables koa

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

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

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

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

<layout-use template="./../layout.marko">
Run Code Online (Sandbox Code Playgroud)

并像这样加载marko

this.body = marko.load("./views/home.marko").stream(data);
Run Code Online (Sandbox Code Playgroud)

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

我们如何实现这种全局变量功能.

dan*_*neu 5

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

例如:

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

然后是这些模板:

// 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>
Run Code Online (Sandbox Code Playgroud)

这样可行.

但显然你不想传递$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
  })
})
Run Code Online (Sandbox Code Playgroud)

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

我从来没有使用过Marko,但是在看到你的问题之后我很好奇地阅读了文档,因为我已经想过不时地使用它.我不想弄清楚它是如何<layout-use>工作的,所以我用了它<include>.