conditional on last item in array using handlebars.js template

前端 未结 6 2029
我在风中等你
我在风中等你 2020-12-04 15:17

I am leveraging handlebars.js for my templating engine and am looking to make a conditional segment display only if it is the last item in array contained in the templates c

6条回答
  •  北海茫月
    2020-12-04 16:08

    Solution:

    Leveraging helpers from the following blog and gist...

    https://gist.github.com/2889952

    http://doginthehat.com.au/2012/02/comparison-block-helper-for-handlebars-templates/

    // {{#each_with_index records}}
    //  
  • {{Name}}
  • // {{/each_with_index}} Handlebars.registerHelper("each_with_index", function(array, fn) { var total = array.length; var buffer = ""; //Better performance: http://jsperf.com/for-vs-foreach/2 for (var i = 0, j = total; i < j; i++) { var item = array[i]; // stick an index property onto the item, starting with 1, may make configurable later item.index = i+1; item.total = total; // show the inside of the block buffer += fn(item); } // return the finished buffer return buffer; }); Handlebars.registerHelper('compare', function(lvalue, rvalue, options) { if (arguments.length < 3) throw new Error("Handlerbars Helper 'compare' needs 2 parameters"); operator = options.hash.operator || "=="; var operators = { '==': function(l,r) { return l == r; }, '===': function(l,r) { return l === r; }, '!=': function(l,r) { return l != r; }, '<': function(l,r) { return l < r; }, '>': function(l,r) { return l > r; }, '<=': function(l,r) { return l <= r; }, '>=': function(l,r) { return l >= r; }, 'typeof': function(l,r) { return typeof l == r; } } if (!operators[operator]) throw new Error("Handlerbars Helper 'compare' doesn't know the operator "+operator); var result = operators[operator](lvalue,rvalue); if( result ) { return options.fn(this); } else { return options.inverse(this); } });

    Notice the starting index is correctly 1.

提交回复
热议问题