Search code examples
handlebars.js

Looking up a boolean in parent context


I'm trying to display content dependant on whether a property with a value of true exists in the parent context.

So:

js

var products = [ {id: "a", desc: "Product A"}, 
                 {id: "b", desc: "Product B"} ]

var customers = [ {name: "John", a: true, b: true}, 
                  {name: "Mike", a: false, b: true} ]

hbs

{{#each customers}}
   Name: {{name}}
   {{#each ../products}}
     Has product {{desc}}: {{#if // something // }} Yes! {{else}} No. {{/if}}
   {{/each}}
{{/each}}

If that makes sense? In pure js I'd use something like:

for(var c=0; c<customers.length; c++) {
  let customer = customers[c];
  for(var p=0; i<products.length; p++) {
     let product = products[p];
     let hasThisProduct = customer[product] ? 'yes!' : 'no.';
     [....]
  }
}

From what I've read before I think I should be using 'lookup', but I can't figure out quite how it applies to this use case?


Solution

  • Specify this in the parent context: ../this and use id as the lookup key:

    lookup ../this id
    

    You'll want to put the lookup in brackets, so you can test the returned value with if, for your requirement, so:

    {{#if (lookup ../this id) }} Yes! {{else}} No. {{/if}}