简体   繁体   中英

Accessing Array from Handlebars

const data = {
 customer:{
  name:[{
         user 1
        },
        {
         user 2
        },
        {
         user 3
        }],
  users : 2
 }
}

Printing data of newest user in a view template using:

{{#each data}}
  {{this.customer.name.[this.customer.users]}}
{{/each}}

The output is

: N/A

Are There any solution to print the newest user data?

Yes, it is possible.

But first, you will need to determine which property of each name object you wish to render. You have included invalid JavaScript for each object in your name array (ex., { user 1 } ), and so, I must guess on how you plan to use these objects. I am going to assume these objects have a shape like { value: "user 1" } .

Since you wish to lookup an object on the customer.name array using another variable, customer.user as the index, you will need to use the built-in Lookup helper. In fact, you will need to use it twice : once to get the object out of customer.name at the customer.user index, and then to get the value of the value property off of the returned object.

Fortunately, Handlebars support Subexpressions to do this kind of lookup nesting. Our template now becomes:

<p>
  Newest username is...
  {{lookup (lookup customer.name customer.users) 'value'}}
</p>

I have created a fiddle for reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM