javascript - Custom handlebars each helper with index -


i wrote helper loops on array, i'm stuck @ getting index available each iteration. wish in view print index of current item.

helpers: {     each_min: function(ary, min, options) {       if(!ary || ary.length == 0)           return options.inverse(this);        var result = [];       for(var = 0; < min; ++i)           result.push(options.fn(ary[i]));       return result.join('');     } } 

my template

{{#each_min p.name 4}} {{#if this}} {{index}} {{this}} {{else}} <p>-</p> {{/if}} {{/each_min}} 

looking through handlebars docs found relevant info in block helpers section.

block helpers can inject private variables child templates. can useful add information not in original context data. ... make sure create new data frame in each helper assigns own data. otherwise, downstream helpers might unexpectedly mutate upstream variables.

based on made these changes:

template:

{{#each_min p.name 4}}     {{#if this}}         {{@index}} {{this}}     {{else}}         <p>-</p>     {{/if}} {{/each_min}} 

helper:

function(ary, min, options) {     if(!ary || ary.length === 0) {         return options.inverse(this);     }     var data;     if (options.data) {         data = handlebars.createframe(options.data);     }      var result = [];     for(var = 0; < min; ++i) {         if (data) {             data.index = i;         }         result.push(options.fn(ary[i], {data: data}));     }      return result.join(''); } 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -