0

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

1 Answer 1

4

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.