简体   繁体   中英

How to loop over array objects and template with Handlebars

I'm having trouble templating out some object data using Handlebars, objects look like this:

[{
    slug: "slug-q",
    videoBanner: true,
    videoId: "e_pBdaN5nEY",
    videoPoster: {
        "small": "630x630_partner.jpg",
        "medium": "853x863_partner.jpg",
        "large": "1306x653_partner.jpg",
        "xlarge": "1832x704_partner.jpg"
    }
},
{
    slug: "slug-w",
    videoBanner: true,
    videoId: "e_fewf5nEY",
    videoPoster: {
        "small": "630x630_partnerY.jpg",
        "medium": "853x863_partnerY.jpg",
        "large": "1306x653_partnerY.jpg",
        "xlarge": "1832x704_partnerY.jpg"
    }
}]

And my template:

<a href="http://youtu.be/{{videoId}}" class="hero-content js-vid" target="_blank">

    {{#if videoBanner}}
        <img class="hero-img preload-image js-preload-image js-poster" alt="" sizes="100%" srcset="
            /static/img/partners/{{slug}}/{{videoPoster.small}} 320w,
            /static/img/partners/{{slug}}/{{videoPoster.medium}} 640w,
            /static/img/partners/{{slug}}/{{videoPoster.large}} 1024w,
            /static/img/partners/{{slug}}/{{videoPoster.xlarge}} 1280w">
    {{else}}
        <img class="hero-img preload-image js-preload-image" alt="" sizes="100%" srcset="
            /static/img/partners/{{slug}}/{{videoPoster.small}} 320w,
            /static/img/partners/{{slug}}/{{videoPoster.medium}} 640w">
    {{/if}}
</a>

Right now the only thing that gets set is the videoId , I'm not sure where I need to add {{#each}} in order to loop through the data out and template. I initially tried adding {{#each this}} around the whole template block but this was incorrect.

Add a key to your payload, and use it in the {{#each}} :

http://jsbin.com/loveci/1/edit?html,js,output

Try writing {{#.}} {{/.}} around the template block, this loops an array in Mustache.js which handlebars is built on. (Not sure but I remember me solving something similar this way, so worth a quick try)

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