alt
alt

Reputation: 2606

Handlebars - #if based on parent property within #each

Say I have the following data:

[
  {
    id: 1,
    someFoo: true,
    things: [
      { blah: "bang" },
      { blah: "bing" }
    ]
  },
  {
    id: 2,
    someFoo: false,
    things: [
      { blah: "boop" },
      { blah: "barp" }
    ]
  }
]

Within Handlebars, how can I check if someFoo is true within an {{#each things}}?

I've tried:

{{#each things}}
<p>{{blah}}</p>
{{#if ../someFoo}}<p>Yay!</p>{{/if}}
{{/each}}

with no luck.

EDIT, sorry it looks like my array is a bit misleading. The actual use-case is I have an invoice that might include tax. So, data is like this:

{
    tax: 0, // <-- this could be non-0, in which case should be "truthy"
    orders: [
        {words: 2, text: "some text", pay: 5.4},
        {words: 3, text: "some more text", pay: 7.8}
    ]
}

and the template is like this:

<table class="clear">
  <thead>
    <tr>
      <th>Description</th>
      <th>Quantity</th>
      {{#if tax}}<th>PU HT</th>{{else}}<th>PU</th>{{/if}}
      {{#if tax}}<th>TVA</th>{{/if}}
      {{#if tax}}<th>Total HT</th>{{else}}<th>Total</th>{{/if}}
    </tr>
  </thead>
  <tbody>
    {{#each orders}}
    <tr>
      <td>Start of text: {{substring text}}...</td>
      <td align="right">1.00 U</td>
      <td align="right">{{accounting pay}}</td>
      {{#if ../tax}}<td align="right">20.00%</td>{{/if}}
      <td align="right">{{accounting pay}}</td>
   </tr>
   {{/each}}
  </tbody>
</table>

My problem is the {{#if}} outside the {{#each}} works, but not the one inside.

Upvotes: 0

Views: 518

Answers (2)

Vaibhav Nigam
Vaibhav Nigam

Reputation: 1467

There is nothing wrong in your code snippet, other than another loop over data.

{{#each this}}
  {{#each things}}
    <p>{{blah}}</p>
    {{#if ../someFoo}}<p>Yay!</p>{{/if}}
  {{/each}}
{{/each}}

You access variables 1 level up of current each block using ../

Upvotes: 2

Mohd Hassan
Mohd Hassan

Reputation: 184

this is how I would write it, you will find you someFoo property with in this as it refer to each things

{{#each things}}
<p>{{blah}}</p>
{{#if this.someFoo}}<p>Yay!</p>{{/if}}
{{/each}}

Upvotes: 0

Related Questions