0

guys. I'm just getting started with Handlebars, as such, my question might seem a tad 'nooby'. I have a two-dimensional array (it is the data in the first line) I'm supposed to loop through and render the information. Under normal circumstances, this is straightforward. However, the problem arises when trying to create the route path inside the second loop. The 'name' in <p><a href="/polls/categories/{{name}}">{{title}}</a></p> is supposed to be the same as the one in <th scope="row">{{name}}</th>. How do I escape the nested array(loop) to get the value corresponding to the 'name' key from the parent, data, array?

Here's a code snippet

{{#each data}}
<tr>
   <th scope="row">{{name}}</th>
   <td>
      {{#each polls}}
      <p><a href="/polls/categories/{{name}}">{{title}}</a></p>
      {{/each}}
   </td>
</tr>
{{/each}}

Here's part of the data array, for illustration purposes.

...,
category: 'Sports',
polls: [
    {
        title: 'Most hated team in the NBA',
        choices: ['Golden State Warriors', 'LA Lakers', 'Cleveland Cavaliers', 'New York Knicks', 'Boston Celtics'],
    },
    {
        title: 'Best (active) boxer pound for pound',
        choices: ['Roman Gonzalez', 'Terence Crawford', 'Andre Ward', 'Gennady Golovkin', 'Vasyl Lomachenko'],
    },
    {
        title: 'Greatest football (soccer) player of all time',
        choices: ['Lionel Messi', 'Diego Maradona', 'Johann Cruyff', 'Pele', 'Alfredo di Stefano'],
    }
],
...

1 Answer 1

1

There is a ../ syntax in Handlebars that allows you to use the parent context. Using that your polls loop should be:

{{#each polls}}
<p><a href="/polls/categories/{{../name}}">{{title}}</a></p>
{{/each}}

They have a similar example in their official page that uses the same syntax:

<h1>Comments</h1>

<div id="comments">
  {{#each comments}}
  <h2><a href="/posts/{{../permalink}}#{{id}}">{{title}}</a></h2>
  <div>{{body}}</div>
  {{/each}}
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, thank you, man! Was just going through the official documentation but was kind of in hurry to get the code working.

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.