【问题标题】:Conditional class in Marko JS TemplateMarko JS模板中的条件类
【发布时间】:2016-01-10 14:52:43
【问题描述】:

我正在使用layout taglib 将页面扩展到其模板,但我不知道如何将变量传递给主布局并应用条件类。

考虑到这是我的main-layout.marko

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body class="#### (TITLE === 'REGISTER')?'ACTIVE':'INACTIVE' ####">
    <layout-placeholder name="title"/>
    <layout-placeholder name="body"/>
  </body>
</html>

这是我的registration.marko

<layout-use template="./layout.marko">
    <layout-put into="title">
      $data.title
    </layout-put>
    <layout-put into="body">
      some content
    </layout-put>
</layout-use>

最后这是我用来渲染页面并传递标题数据的代码

router.get('/register', function(req, res, next) {
  registration.render({
    title: 'register'
  }, res);
});

如何在 main-layout.marko 文件上创建一个条件类,根据页面标题在 active 或 inactive 之间切换?

谢谢

【问题讨论】:

    标签: node.js template-engine marko


    【解决方案1】:

    您可以通过向 &lt;layout-use&gt; 标记添加其他属性来将数据传递到布局。见:marko-layout » Layout Data

    对于您的示例,以下内容将起作用:

    在main-layout.marko:

    <!DOCTYPE html>
    <html lang="en">
      <head>
      </head>
      <body class="#### ${data.title === 'REGISTER' ? 'ACTIVE' : 'INACTIVE' } ####">
        <layout-placeholder name="title">
          ${data.title}
        </layout-placeholder>
        <layout-placeholder name="body"/>
      </body>
    </html>
    

    在registration.marko:

    <layout-use template="./layout.marko" title="${data.title}">
        <layout-put into="body">
          some content
        </layout-put>
    </layout-use>
    

    这应该可以解决您的问题,但如果您仍然卡住,请告诉我。

    【讨论】:

    • 它确实有效,谢谢!你写的三元条件和这个{?data.title === 'register';active;inactive}有什么区别?
    • 好问题,@crash。它们编译成相同的东西,所以只是语法不同。请参阅:markojs.com/try-online/#Conditionals_Shorthand_Conditionals 当使用 {? ... } 语法时,替代子句是可选的,与 JavaScript 三元条件不同。在 Marko 的下一个主要版本中,我们计划放弃对自定义 Marko {? ... } 语法的支持,以简化语言并更接近 JavaScript。在 Marko v3 中,属性值始终是有效的 JavaScript 表达式。见:github.com/marko-js/marko/issues/90
    【解决方案2】:

    还有另一种向其所有模板传递数据的方法,即使用 $global 来传递数据。

    在使用 global 之后,您不需要将属性添加到任何标签。您可以使用 like 访问它 out.global.username

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-21
      • 2018-03-31
      • 2018-06-10
      • 2017-02-24
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多