Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars condition based on lookup

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?

like image 694
Jivan Avatar asked Oct 20 '25 04:10

Jivan


1 Answers

You can indeed do just what you're trying to do, using subexpressions:

{{#if (lookup ../owners @index)}}

works like a charm. (source: Handlebars website)

like image 96
Gratien Avatar answered Oct 24 '25 05:10

Gratien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!