Search code examples
meteorhandlebars.js

Parameter isn't passed into nested template


I'm doing category sidebar template for online shop. I will use that in 2 places - on customer, and admin side. Each one will have own service of clicking on category. I want to pass parameter "redirect" which will decide what action will be done, but the problem is, that parameter isn't visible in nested templates - only in 1st level categories.

HTML :

<template name="categoriesSidebar">
    <ul>
        {{#each mainCategories}}
            <li>
                {{> categoriesSidebarItem redirect=true data=this }}
            </li>
        {{/each}}
    </ul>
</template>

<template name="categoriesSidebarItem">
    <a href="#">
        {{data.name}}
    </a>
    {{#if data.subCategories.length}}
        <ul>
            {{#each subCats }}
                <li>
                    {{> categoriesSidebarItem redirect=redirect data=this }}
                </li>
             {{/each}}
        </ul>
    {{/if}}
</template>

Javascript :

Template.categoriesSidebar.helpers({
    mainCategories:  function() {
    return Categories.find({'categoryLevel' : 1});
  }
});

Template.categoriesSidebarItem.helpers({
    subCats : function(){
        return Categories.find({_id:{$in: this.data.subCategories}});
    }
});

Template.categoriesSidebarItem.events({
    'click a' : function(event){
        if(this.redirect == true){
            Router.go('category',{_id : this.data._id});
            return false;
        }else{
            //categoryId is ReactiveVar used in another template
            categoryId.set(this.category._id);
        }
    }
})

Result :

Women
    Nike
Men
    Nike
    Adidas

Women and Men category work well , after clicking on them, "redirect" is seen as true and Router redirects to desired route, but for nested categories, "redirect" parameter is undefined.

How to pass that parameter to nested template ?


Solution

  • Change the code to this:

    {{#if data.subCategories.length}}
        <ul>
            {{#each subCats }}
                <li>
                    {{> categoriesSidebarItem redirect=../redirect data=this }}
                </li>
             {{/each}}
        </ul>
    {{/if}}
    

    The each block changes the data context, so you need to retrieve redirect from the parent data context. That's what ../ does.