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

Layout 在marko模板中全局访问变量,layout,global-variables,koa,Layout,Global Variables,Koa,我们正在nodejs应用程序中使用marko模板引擎。我们有3个marko布局 header.marko layout.marko footer.marko 页眉和页脚布局在layout.marko内呈现 当我们创建一个新的marko页面(内容页面)时,我们会像这样使用布局marko <layout-use template="./../layout.marko"> this.body = marko.load("./views/home.marko").stream(data);

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

  • header.marko
  • layout.marko
  • footer.marko
  • 页眉和页脚布局在layout.marko内呈现

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

    <layout-use template="./../layout.marko">
    
    this.body = marko.load("./views/home.marko").stream(data);
    
    现在,我们希望访问一个可变的全局。如果我们有一个变量username='abc'。我们希望在页眉、布局或页脚标记文件中访问和显示此名称。但我们不希望为每个内容标记页面传递用户名。如果我们在网站上有100个页面,我们不想为所有100个页面传递用户名。每当用户登录时,将用户名保存在全局变量中,并在所有页面中使用此全局变量


    如何实现此全局变量功能。

    看起来您可以使用该属性公开数据 适用于所有模板

    例如:

    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>
    
    该代码与我在上面定义的模板一起工作:
    ${out.global.currUser}
    可以从header.marko访问,但是可以从header.marko访问
    ${data.color}
    home.marko

    我从来没有用过Marko,但我很好奇,在看到这些文档后,我读了它们 你的问题,因为我一直想用它不时。我没有感觉
    比如弄清楚
    是如何工作的,所以我用
    来代替。

    谢谢。这符合我的要求。
    // 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
      })
    })