【问题标题】:Handlebars conditional checked property from Jade template来自 Jade 模板的车把条件检查属性
【发布时间】:2013-05-23 17:19:52
【问题描述】:

我希望提供给客户的车把模板看起来像

<input type='checkbox' checked={{isChecked}}>

<input type='checkbox' {{#if isChecked}}checked{{/if}}>

如何编写一个可以编译成这个的 Jade 模板?从他们的文档中,如果分配的值是真实的但实际上不包含该值,则将包含选中的属性:

input(type="checkbox", checked="{{isChecked}}")

编译成

<input type='checkbox' checked>

我也试过了:

input(type="checkbox", checked={{isChecked}})

input(type="checkbox", {{#if isChecked}}checked{{/if}})

只是编译失败,我理解

【问题讨论】:

    标签: javascript html node.js handlebars.js pug


    【解决方案1】:

    直接在你的翡翠模板中试试吧。

    <input type='checkbox' {{#if isChecked}}checked{{/if}}>
    

    应该保持相同的格式。

    【讨论】:

      【解决方案2】:

      我建议创建一个更通用的帮助器,以便以后轻松重用

      Handlebars.registerHelper("checkedIf", function (condition) {
          return (condition) ? "checked" : "";
      });
      

      然后,您可以在任何模板中使用它:

      <script id="some-template" type="text/x-handlebars-template">
         ...
         <input type="checkbox" {{checkedIf this.someField}} />
         ...
      </script>
      

      这将呈现为

      <input type="checkbox" checked />
      
       or...
      
      <input type="checkbox" />
      

      取决于someField(映射到模板的对象的字段)的值

      【讨论】:

      • 你如何检查一个否定的,比如检查是否为假?
      • @dvidsilva 我已经很久没有使用 Handlebars 了……这行得通吗? {{checkedIf !this.someField}}?
      • 不是真的,我最终不得不写checkedIf和checkedIfNot :O
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-23
      • 1970-01-01
      • 2013-06-19
      • 1970-01-01
      • 2012-11-15
      • 2014-04-03
      • 1970-01-01
      相关资源
      最近更新 更多