Imran Azad
Imran Azad

Reputation: 1048

Pass object to partial template

I have the following object:

 "hasDevices": {
   "hasLaptops": { "title": "abc" }
   "hasTablets": { "title": "abc" }
 }

Which I'm iterating:

{{#each hasDevices }}
  {{> hasDevicesPartial this}}
{{/each }}

This is what hasDevicesPartial looks like:

 {{#if hasLaptops }}
   {{#each hasLaptops as |hasLaptop| }}
     {{> anotherPartial hasLaptop }}
   {{/each }}
 {{/if }}

 {{#if hasTablets }}
   {{#each hasTablets as |hasTablet| }}
     {{> anotherPartial hasTablet }}
   {{/each }}
 {{/if }}

The problem I'm having is that when I iterate through hasDevices I'm passing the current object however the hasDevicesPartial can't see the property hasLaptops or hasTablets except what's inside i.e. title. How can I iterate through hasDevices such that I'm able to pass the hasLaptops or hasTablets object so that the hasDevicesPartial can access it in the if statement to check if it exists.

Upvotes: 0

Views: 795

Answers (1)

Christophe
Christophe

Reputation: 2200

You shoudn't use {{#each}} on a simple object, this is designed for arrays. If you want an array use a different structure.

{ "shops" : [
     { "Shop1" :
          "hasDevices": {
              "laptops": [ { "HP": "Spectre360" } , { "Microsoft" , "Surface book" } ]
           }
     },
     { "Shop2" :
          "hasDevices": {
              "laptops": [ { "Apple": "Macbook" } ],
              "tablets": [ { "Apple": "Ipad" } ]
           }
     }
}

With such a structure you can iterate over shops and then over your other properties

{{#each shops}}
  {{> shopsPartial this}}
{{/each }}

and your partial

 {{#if laptops }}
   {{#each laptops as |hasLaptop| }}
     {{> anotherPartial hasLaptop }}
   {{/each }}
 {{/if }}

 {{#if tablets }}
   {{#each tablets as |hasTablet| }}
     {{> anotherPartial hasTablet }}
   {{/each }}
 {{/if }}

Upvotes: 1

Related Questions