Search code examples
node.jshandlebars.jsexpress-handlebarshandlebarshelper

Iterating through the array values using handlebars #each loop


I have two arrays named firstnames and lastnames. The values these two arrays hold are as follows:-

firstnames =[ 'A', 'B', 'C','D','E' ]
lastnames =['a','b','c','d','e']

I am rendering these two arrays to my webpage in the following manner:-

res.render('sample',{firstnames:firstnames,lastnames:lastnames})

Using the #each loop-helper in handlebars, I was able to display the names on the webpage in such a way that all the firstnames appear first followed by all the lastnames by making use of this :-

  {{#each firstname}}
  <h1>{{this}}</h1>
    {{/each}}
    
    {{#each lastname}}
   <h1>{{this}}</h1>
    {{/each}}

And the output was some thing like:-

A 
B
C
D
E
a
b
c
d
e

But, how can I able to display the data in such a way that, each firstname must be followed by the each lastname. Like that of below:-

A
a
B
b
C
c
D
d
E
e

Solution

  • Solution

    This can be done using the Handlebar's lookup helper using either the ../ path or @root data variable syntax in combination with the @key data variable. Using either ../ or @root is necessary because #each creates a new context. In other words, each object in firstnames would be the new context, so it is necessary to get back to the root scope, because that is where lastnames is located.

    {{#each firstnames}}
        <h1>{{this}}</h1>
        <h1>{{lookup @root.lastnames @key}}</h1>
        // OR
        <h1>{{lookup ../lastnames @key}}</h1>
    {{/each}}
    

    Snippet/Example

    var data = {
      firstnames: [ 'A', 'B', 'C','D','E' ],
      lastnames: ['a','b','c','d','e']
    };
    
    var source = $('#entry-template').html();
    var template = Handlebars.compile(source)(data);
    
    $('body').html(template)
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.12/handlebars.min.js"></script>
    
    <script id="entry-template" type="text/x-handlebars-template">
    {{#each firstnames}}
        <h1>{{this}}</h1>
        <h1>{{lookup ../lastnames @key}}</h1>
    {{/each}} 
    </script>