我们正在nodejs应用程序中使用marko模板引擎。我们有3个马尔科布局
layout.marko中的页眉和页脚布局呈现
当我们创建一个新的marko页面(内容页面)时,我们使用这样的布局
<layout-use template="./../layout.marko">像这样把马科装上
this.body = marko.load("./views/home.marko").stream(data);现在我们想要在全球范围内实现多样化。如果我们有一个变量用户名=‘abc’。我们想要访问和显示这个名称在页眉,布局或页脚marko文件。但我们不想传递每个内容marko页面的用户名。如果我们在网站上有100页,我们不想传递所有100页的用户名。每当用户登录时,将用户名保存在全局变量中,并在所有页面中使用该全局变量。
我们如何才能实现这个全局变量功能。
发布于 2016-10-17 01:24:41
看起来,您可以使用$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>。
https://stackoverflow.com/questions/40046904
复制相似问题