Search code examples
javascriptarraysnode.jshandlebars.jsexpress-handlebars

Handlebars return an array element with certain index if the length is unknown


Using Handlebars and Node, I have an array with changing length and I need always to get the one before last element of it each time it changes.

So if you want to get the last element, you can do:

{{#each array}}
  {{#if @last}}
    {{this}}
  {{/if}}
{{/each}}

and it will return you the last element. I have Math helper, that can perform basic mathematical operations. For example I can get with it the needed index number

{{math array.length '-' 1}}

but I cant use it with another block helper, for example:

{{#each array}}
  {{#if math @last '-' 1}}
    {{this}}
  {{/if}}
{{/each}}

How could this be done? Thank you.


Solution

  • You can register your own helper for that:

    Handlebars.registerHelper('isSecondLastArrayItem', function(array, index, options) {
    
      if((array.length - 2) === index)
        return options.fn(this);
    
      return;
    
    });
    

    And use it like this:

    {{#each array}}
      {{#isSecondLastArrayItem @root.array @index}}
        {{title}}
      {{/isSecondLastArrayItem}}
    {{/each}}
    

    Example data:

    { 
      array: [{ title: 'aa' }, { title: 'vv' }]
    }
    

    Try it out in the sandbox.

    EDIT: case for any index

    Handlebars.registerHelper('isNthLastArrayItem', function(array, index, offset, options) {
    
      if(((array.length >= offset) && (array.length - offset) === index)
        return options.fn(this);
    
      return;
    
    });
    

    usage (for 2nd item from the end):

    {{#each array}}
      {{#isNthLastArrayItem @root.array @index 2}}
        {{title}}
      {{/isNthLastArrayItem}}
    {{/each}}