看起来您可以使用$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>。