首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在marko模板中全局访问变量

在marko模板中全局访问变量
EN

Stack Overflow用户
提问于 2016-10-14 15:30:34
回答 1查看 350关注 0票数 2

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

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

layout.marko中的页眉和页脚布局呈现

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

代码语言:javascript
复制
<layout-use template="./../layout.marko">

像这样把马科装上

代码语言:javascript
复制
this.body = marko.load("./views/home.marko").stream(data);

现在我们想要在全球范围内实现多样化。如果我们有一个变量用户名=‘abc’。我们想要访问和显示这个名称在页眉,布局或页脚marko文件。但我们不想传递每个内容marko页面的用户名。如果我们在网站上有100页,我们不想传递所有100页的用户名。每当用户登录时,将用户名保存在全局变量中,并在所有页面中使用该全局变量。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-17 01:24:41

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

例如:

代码语言:javascript
复制
router.get('/test', function * () {
  this.type = 'html'
  this.body = marko.load("./views/home.marko")
    .stream({
      color: 'red',
      $global: { 
        currUser: { id: 2, username: 'hansel' }
      }
    })
})

然后是这些模板:

代码语言:javascript
复制
// 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上下文中,让任何中间件将数据附加到它上,然后编写一个帮助程序将它传递给模板。

代码语言:javascript
复制
// 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>

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40046904

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档