I have the following data structure:
{
things: [
"desk",
"chair",
"pen",
"book",
"lamp"
],
owners: [
"Julia",
"Sandra",
"John",
"Paul"
]
}
What's working:
This handleblars template:
{{#each things}}
<p>This {{this}} belongs to {{lookup ../owners @index}}</p>
{{/each}}
Correctly outputs:
This desk belongs to Julia
This chair belongs to Sandra
This pen belongs to John
This book belongs to Paul
This lamp belongs to
What's not working:
Now, I'd like to add a condition because the last thing might not have an owner. The template would then look something like:
{{#each things}}
{{#if lookup ../owners @index}}
<p>This {{this}} belongs to {{lookup ../owners @index}}</p>
{{else}}
<p>...But this {{this}} belongs to nobody</p>
{{/if}}
{{/each}}
And the ouput:
This desk belongs to Julia
This chair belongs to Sandra
This pen belongs to John
This book belongs to Paul
...But this lamp belongs to nobody
Unfortunately, this {{#if lookup ../owners @index}} thing doesn't work.
My question: is it possible to achieve this with built-in Handlebars helpers, or do I have to write a custom helper?
You can indeed do just what you're trying to do, using subexpressions:
{{#if (lookup ../owners @index)}}
works like a charm. (source: Handlebars website)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With