0

Say I have an object,

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

I can use handlebars to loop through the entire object using,

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

Say, I want to start from the 3rd object, ignoring the 1st and 2nd. Is there a simple way to achieve this?

Thomas Sebastian
  • 1,582
  • 5
  • 18
  • 38

1 Answers1

0

No, you need a helper for that: Logical operator in a handlebars.js {{#if}} conditional

So you could do something like if index > 2 then show content.

If I may ask: why not drop the first two (or for that matter: any unneeded elements) in actual javascript before calling the template?

Edit: here you are...

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));
<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>
Community
  • 1
  • 1
boast
  • 269
  • 1
  • 13
  • I have ten list items out of which it should display only two. I have a `see more` button. On clicking `see more`, I should show the remaining list items in a separate pop-up. I can do it using `JS`, but I was curious to know if this was possible in handlebars. It seemed very straight forward to me. Sad it is not there by default. I don't need to show it on an if condition. I am asking if I can display it from the third object straight away without any if block? Is there a helper for that? – Thomas Sebastian Jun 25 '15 at 12:30
  • A simple `array.slice()` can solve this... added it to my answer. – boast Jun 25 '15 at 13:10
  • This looks like a more dynamic solution. I am accepting it. Hope this will work irrespective of my data. – Thomas Sebastian Jun 25 '15 at 13:27
  • Well, it needs to be an array (or an object which returns an array after calling slice ;) ), than this works! – boast Jun 25 '15 at 14:28