Search code examples
meteormeteor-blazespacebarsmeteor-helper

How can I avoid duplicate templates in Meteor?


So I'm building my first app with meteor, and I feel like I'm repeating myself with my templates more than I should be.

I have multiple parent views, an example of which is the user contacts view, and the add group members view. (simplified examples below.)

<template name="GroupMembers">
    {{#each contacts}}
        {{> contact }}
    {{/each}}
</template>

<template name="contacts">
    {{#each contacts}}
        {{> contact }}
    {{/each}}
</template>

<template name="contact">
    //... single contact template stuff
</template>

When the contact is displayed in the contacts list, I want to display a remove from contacts link in the single contact template, but in the group members list I'd like an 'add to group' link in its place. I know I could probably achieve this with either session variables or by invoking the iron-router controller obj, but I'd like to know if there is a simple way to do this in the template helper(s). Or put another way can these template partials become context aware?

Any help would be great.

Thanks.


Solution

  • I would solve it this way:

    <template name="GroupMembers">
        {{#each contacts}}
          {{> contact groupMembers=true}}
        {{/each}}
    </template>
    
    <template name="contacts">
        {{#each contacts}}
            {{> contact }}
        {{/each}}
    </template>
    
    <template name="contact">
        <p>
          {{#if groupMembers}}
            {{../name}} 
            <button>add to group</button>
          {{else}}
            {{name}} 
            <button>delete</button>
          {{/if}}
        </p>
    </template>
    

    Live demo: http://meteorpad.com/pad/LDTvHC787kJ6e9JQA/Leaderboard