代码之家  ›  专栏  ›  技术社区  ›  OwenP

如何处理部分车把中的布尔HTML属性?

  •  0
  • OwenP  · 技术社区  · 6 年前

    我正在写一个有趣的小项目来提高我的HTML/JS技能。我在用车把渲染一些形状,我碰到了一些我似乎无法避开的东西。

    我已将此注册为名为“checkbox”的部分模板:

    <label>
    <input 
       type="checkbox" 
       id="{{id}}" 
       name="{{id}}" 
       value="true">
    {{labelText}}
    </label>
    

    当我制作用于添加数据的表单时,这对我很有帮助,但现在我正在制作用于添加数据的表单 编辑 数据,因此如果当前项已被选中,我希望选中复选框。我不知道该怎么做。

    我尝试的第一件事是这样的:

    <label>
    <input 
       type="checkbox" 
       id="{{id}}" 
       name="{{id}}" 
       value="true"
       checked="{{isChecked}}">
    {{labelText}}
    </label>
    

    但如果我像 isChecked=true 我每次都会得到一个复选框,因为我猜HTML中的这种属性在任何情况下都意味着“真”。好啊。

    所以我尝试使用if助手:

    <input 
       type="checkbox" 
       id="{{id}}" 
       name="{{id}}" 
       value="true"
       {{#if isChecked}}checked{{/if}}>
    {{labelText}}
    

    这个 某种程度上 作品。如果我省略了 isChecked 属性完全不选中该框。如果我硬编码A true false 像这样的价值,它起作用:

    {{> checkbox id="test" labelText="test" isChecked=true }}
    

    但我似乎无法得到我想要的价值。例如,如果我尝试:

    {{> checkbox id="test" labelText="test" isChecked="{{someCondition}}" }}
    

    似乎这个条件没有得到正确的解决,因为在这种情况下我总是得到属性。

    我错过了什么?我觉得应该有办法做到这一点,但我已经没有技巧了。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Evolter    6 年前

    不能将表达式放入另一个表达式中:

    {{> checkbox id="test" labelText="test" isChecked="{{someCondition}}" }}
    

    从您编写的示例中,我假设您遇到的问题与您如何传递上下文有关- id labelText 是硬编码的,而 isChecked 应为某种类型的变量。实际上,所有这些都应该是变量。请考虑以下示例-html:

    <div id="content"></div>
    
    <script id="parent-template" type="text/x-handlebars-template">
      {{#each checkboxes}}
        {{> checkbox this }}<br>
      {{/each}}
    </script>
    
    <script id="partial-template" type="text/x-handlebars-template">
      <input 
        type="checkbox" 
        id="{{id}}" 
        name="{{id}}" 
        value="true"
        {{#if isChecked}}checked{{/if}}>
      {{labelText}}
    </script>
    

    JS:

    var parentTemplate = Handlebars.compile($("#parent-template").html());
    
    Handlebars.registerPartial({
      checkbox: Handlebars.compile($("#partial-template").html())
    });
    
    $('#content').html(parentTemplate(
      {checkboxes: [
        {id: 1, labelText: "test 1", isChecked: true},
        {id: 2, labelText: "test 2", isChecked: false},
      ]}
    ));