Search code examples
handlebars.jshandlebarshelper

Accessing previous index value while looping with #each in handlebars


In my handlebars app, I'm trying to loop through a collection of posts. I'm trying to access the id for each post. I'm getting the id for current post correctly. But or each image, I need to provide Previous and Next id. I used the math helper to increment/decrement the index by 1 and it is working fine.

My idea was that I'll use handlebars subexpression to calculate the desired index and then I'll use the lookup helper to access the value at that index. But my code is not working as expected. Could someone please help me out with the correct code for this?

{{#each posts}}
    <div class="lb-overlay" id="image-{{id}}">
        <a href="#image-{{lookup id (math @index '-' 1)}}" class="lb-prev">Prev</a>
        <a href="#image-{{lookup id (math @index '+' 1)}}" class="lb-next">Next</a>
    </div> 
{{/each}}

UPDATE: I figured it out on my own. Implemented my own handlebar helper.

{{#each posts}}     
    <div class="lb-overlay" id="image-{{id}}">       
        <a href="#image-{{getIdByIndex ../posts (math @index '-' 1)}}" class="lb-prev">Prev</a>       
        a href="#image-{{getIdByIndex ../posts (math @index '+' 1)}}" class="lb-next">Next   
    </div> 
{{/each}}

Solution

  •     {{#each posts}}     
            <div class="lb-overlay" id="image-{{id}}">       
                <a href="#image-{{getIdByIndex ../posts (math @index '-' 1)}}" class="lb-prev">Prev</a>       
                a href="#image-{{getIdByIndex ../posts (math @index '+' 1)}}" class="lb-next">Next   
            </div> 
        {{/each}}
    
        getIdByIndex: function(posts, index) {
            return posts[index].id;
        }