Search code examples
handlebars.js

Handlebars - Not each but some


I am using handlebars for a project and I have a data file with 10 items in it. I am using the 'each' command to show them all on one page (which works fine) but for another page i would like to show only the first 4 items. How can I do this? Thanks in advance!


Solution

  • You can do that with the @index variable within a {{#each}} loop and a custom helper that will test the value of @index. Look at the snippet code below to suit your needs.

    $(document).ready(function () {
      var context = {
        "items" : [{"name":"item1"},{"name":"item2"},{"name":"item3"},{"name":"item4"},{"name":"item5"},{"name":"item6"},{"name":"item7"},{"name":"item8"},{"name":"item9"},{"name":"item10"},{"name":"item11"},{"name":"item12"},{"name":"item13"}]
      };
      Handlebars.registerHelper('test', function(lvalue, operator, rvalue, options) {
    	var doDisplay = false;
    	var items = (""+rvalue).split("|");
    	var arrayLength = items.length;
    	for (var i = 0; (i < arrayLength); i++) {
    		if (operator == "eq") {
    	    	if (lvalue == items[i]) {
    	    		doDisplay = true;
    	    	}
    	    } else if (operator == "ne") {
    	    	if (lvalue != items[i]) {
    	    		doDisplay = true;
    	    	}
    	    } else if (operator == "gt") {
    	    	if (parseFloat(lvalue) > parseFloat(items[i])) {
    	    		doDisplay = true;
    	    	}
    	    } else if (operator == "lt") {
    	    	if (parseFloat(lvalue) < parseFloat(items[i])) {
    	    		doDisplay = true;
    	    	}
    	    }else if (operator == "le") {
    	    	if (parseFloat(lvalue) <= parseFloat(items[i])) {
    	    		doDisplay = true;
    	    	}
    	    }else if (operator == "ge") {
    	    	if (parseFloat(lvalue) >= parseFloat(items[i])) {
    	    		doDisplay = true;
    	    	}
    	    }
    	}
        if (doDisplay) {
        	return options.fn(this);
        } else {
        	return "";
        }
    });
      var source = $("#sourceTemplate").html();
      var template = Handlebars.compile(source);
      var html = template(context);
      $("#resultPlaceholder").html(html);
    
    
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script id="sourceTemplate" type="text/x-handlebars-template">
      Complete list<br/>
      <ul>
        {{#each items}}
        <li>
          {{@index}} {{name}}
        </li>
        {{/each}}
      </ul>
      Partial list<br/>
      <ul>
        {{#each items}}
          {{#test @index 'lt' 4}} 
          <li>
            {{@index}} {{name}}
          </li>
          {{/test}}
        {{/each}}
      </ul>
    </script>
    
    <div id="resultPlaceholder">
    </div>