javascriptmeteorspacebarsmeteor-collections

meteor.js & spacebars - passing variables in nested loop


Context

I’m trying to use Handlebars to loop through events and then nested loop through images. I need to select only the images that correspond to the event that the event loop is currently on.


Problem

I can’t pass the _id of the event inside the image nested. Is there a work-around for this? I realize I can pass variables through a helper but it would be good to know if there is a simpler way.


The following is meta-code for what is not working so far:

//attach venue image to each venue
{{#each myVenues}}
   {{#each myImages}}
      {{#if myVenues._id == myImages._id}}
         <img src="{{this.url}}>
      {{/if}}
   {{/each}}
{{/each}}

Any help would be appreciated!


Solution

  • More recent versions of spacebars supports referencing the parent. Try:

    {{#each myVenues}}
        {{#each myImages}}
            {{#if ../_id == myImages._id}}
                <img src="{{this.url}}>
            {{/if}}
        {{/each}}
    {{/each}}
    

    EDIT:

    Christian Fritz pointed out that your conditional logic in the if statement won't work with spacebars. If you set up a helper to evaluate the conditional logic, you can still get this working:

    {{#each myVenues}}
        {{#each myImages}}
            {{ifequals ../_id myImages._id}}
                <img src="{{this.url}}>
            {{/if}}
        {{/each}}
    {{/each}}
    

    Then in a helper:

    Template.registerHelper('ifequals', function(a,b) {
        return a === b;
    });