【问题标题】:Simplest way to add one class or another添加一个或另一个类的最简单方法
【发布时间】:2014-10-18 02:10:33
【问题描述】:

使用 Handlebars,向 {{#each ...}} 助手渲染的每个元素添加一个或另一个类的最简单方法是什么?我必须与网站的现有 CSS 设置集成,这需要将一个或另一个类添加到列表中的交替元素。

示例助手:

{{#each items}}
<div class="{{what here?}}">...</div>
{{/each}

...我们希望 evenodd 作为类名。 (是的,我知道这可以通过 CSS 完成;我正在与 现有 网站的 CSS 集成,它使用交替类。)

【问题讨论】:

    标签: handlebars.js


    【解决方案1】:

    作为 Handlebars 的新手,我没有看到任何内置的东西,但是 API 可以很容易地添加一个帮助程序,让您可以从任意长度的项目列表中进行选择,如下所示:

    Handlebars.registerHelper('cycle', function(index) {
        index = index % (arguments.length - 2); // -2 to leave out `index` and the final argument HB adds
        return arguments[index + 1];
    });
    

    使用它会是:

    {{#each items}}
    <div class="{{cycle @index 'even' 'odd'}}">...</div>
    {{/each}
    

    Handlebars.registerHelper('cycle', function(index) {
      index = index % (arguments.length - 2); // -2 to leave out `index` and the final argument HB adds
      return arguments[index + 1];
    });
    
    var items = [
      "one", "two", "three", "four", "five"
    ];
    
    var template = Handlebars.compile(
      document.getElementById("template").innerHTML
    );
    
    var html = template({items: items});
    
    document.body.insertAdjacentHTML(
      "beforeend",
      html
    );
    .even {
      color: blue;
    }
    .odd {
      color: green;
    }
    <script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min.js"></script>
    <script id="template" type="text/x-handlebars-template">
    {{#each items}}
    <div class="{{cycle @index 'even' 'odd'}}">{{this}}</div>
    {{/each}}
    </script>

    或者如果我想要三个班轮流:

    {{#each items}}
    <div class="{{cycle @index 'one' 'two' 'three'}}">...</div>
    {{/each}
    

    Handlebars.registerHelper('cycle', function(index) {
      index = index % (arguments.length - 2); // -2 to leave out `index` and the final argument HB adds
      return arguments[index + 1];
    });
    
    var items = [
      "one", "two", "three", "four", "five"
    ];
    
    var template = Handlebars.compile(
      document.getElementById("template").innerHTML
    );
    
    var html = template({items: items});
    
    document.body.insertAdjacentHTML(
      "beforeend",
      html
    );
    .one {
      color: blue;
    }
    .two {
      color: green;
    }
    .three {
      color: red;
    }
    <script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min.js"></script>
    <script id="template" type="text/x-handlebars-template">
    {{#each items}}
    <div class="{{cycle @index 'one' 'two' 'three'}}">{{this}}</div>
    {{/each}}
    </script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 2017-06-25
      相关资源
      最近更新 更多