每个来自自定义起点的把手

时间:2015-06-25 12:09:31

标签: javascript jquery loops handlebars.js each

说我有一个对象,

      {
        "empID": "1002729041",
        "empName": "ABHIJIT AUDHYA"
      },
      {
        "empID": "1004563331",
        "empName": "ABDUL MULLA"
      },
      {
        "empID": "1004703190",
        "empName": "ABDUL RAZIC"
      },
      {
        "empID": "1004912437",
        "empName": "ABDUL HAFEEZ"
      }  

我可以使用把手循环整个对象,

{{#each myObj}}
  <li>{{empName}}</li>
{{/each}}  

说,我想从第3个对象开始,忽略第1个和第2个。有没有一种简单的方法来实现这一目标?

1 个答案:

答案 0 :(得分:0)

不,你需要一个帮手: Logical operator in a handlebars.js {{#if}} conditional

所以你可以做if index > 2 then show content之类的事情。

如果我可能会问:在调用模板之前,为什么不在实际的javascript中删除前两个(或者就此而言:任何不需要的元素)?

编辑:你在这里......

&#13;
&#13;
Handlebars.registerHelper('eachFrom', function(context, count, options) {
    var ret = "";
    
    context.slice(count).forEach(function(elem) {
        ret += options.fn(elem);
    });
    
    return ret;
});

var context = {
    myObj: [{
        "empID": "1002729041",
            "empName": "ABHIJIT AUDHYA"
    }, {
        "empID": "1004563331",
            "empName": "ABDUL MULLA"
    }, {
        "empID": "1004703190",
            "empName": "ABDUL RAZIC"
    }, {
        "empID": "1004912437",
            "empName": "ABDUL HAFEEZ"
    }]
};

var source = $("#entry-template").html();
var template = Handlebars.compile(source);
$("#container").append(template(context));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/handlebarsjs/3.0.3/handlebars.min.js"></script>

<script id="entry-template" type="text/x-handlebars-template">
    <ul>
        {{#eachFrom myObj 3}}
          <li>{{empName}}</li>
        {{/eachFrom}}
    </ul>
</script>
<div id="container"></div>
&#13;
&#13;
&#13;