【问题标题】:Add class to element with Handlebars based on property使用基于属性的 Handlebars 向元素添加类
【发布时间】:2017-05-18 20:10:59
【问题描述】:

我使用把手#each 循环通过具有给定布尔属性的对象,例如:

elements: [
  {
    text: "a"
    active: true
  },
  {
    text: "b"
    active: false
  }
]

根据该属性将类添加到 html 元素的最简单方法是什么?像这样的:

{{#each elements}}
  <article class={{if active 'active-class'}}>
  ...
{{/each}}

我正在使用车把 4.0.6

【问题讨论】:

    标签: handlebars.js


    【解决方案1】:

    你需要先打开一个helper block

    {{#if}}
    

    然后,添加要检查的参数(在本例中为布尔值):

    {{#if active}}
    

    然后,你像这样关闭它:

    {{#if active}}{{/if}}
    

    然后,如果满足条件,您要呈现的内容将放在花括号之间:

    {{#if active}}text{{/if}}>
    

    所以,你的 HTML 应该是这样的:

    {{#each elements}}
        <article {{#if active}}class="active"{{/if}}>
        ...
    {{/each}}
    

    或者,如果您还想在该元素中添加一个静态类,您可以这样做:

    {{#each elements}}
        <article class="example {{#if active}}active{{/if}}">
        ...
    {{/each}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      • 2022-08-18
      相关资源
      最近更新 更多