2
votes

I have 3 people, each with unique answer to the same question.

1 template shows the name and question. Another different template holds the answer. (4 total templates. 1 for names/question, 3 other - 1 for each unique answer).

<template name="people">

  {{#each profile }}

    <h2>{{ name }}</h2>
    <p>{{ question }}</p>    

    <p>{{> answer }}</p> 

  {{/each }}

</template>

I want to set up a helper, so that when each profile loop is running, I can insert the correct named template (instead of {{> answer }}, 3 distinct templates identified by their name {{> nameAnswers }}, aka {{> fooAnswers }}.

Tried this, which displays all 3, in each profile, instead of 1 per profile.

<template name="people">

  {{#each profile }}

    <h2>{{ name }}</h2>
    <p>{{ question }}</p>              

            {{#if nameHelper=Fred }}  
              {{> fredAnswers }}
            {{/if }}

            {{#if nameHelper=Ringo }}  
              {{> ringoAnswers }}
            {{/if }}  

            {{#if nameHelper=Jackson }}  
              {{> jacksonAnswers  }}
            {{/if }} 
  {{/each }}

</template>

Note: the {{> nameAnswers }} templates are already defined as static html, need to insert them is all.

3

3 Answers

5
votes

You cannot test equality with = operator like that. You need to define a helper to do so, for example:

UI.registerHelper('equals', function(a, b) {
  return a == b; // == intentional
};

And then you can use it:

{{#if equals nameHelper 'Ringo'}}  
  {{> ringoAnswers}}
{{/if}}
5
votes

you can to do this...

Using Blaze

https://github.com/meteor/meteor/wiki/Using-Blaze

<template name="people">

  {{#each profile }}

    <h2>{{ name }}</h2>
    <p>{{ question }}</p>              

            {{#if isName Fred }}  
              {{> fredAnswers }}
            {{/if }}

            {{#if isName Ringo }}  
              {{> ringoAnswers }}
            {{/if }}  

            {{#if isName Jackson }}  
              {{> jacksonAnswers  }}
            {{/if }} 
  {{/each }}

</template>


Template.people.helpers({
    isName:function(name){
       return //true or false;
    }
})
3
votes

{{#if nameHelper=Fred }} tests whether Spacebars.kw({nameHelper: view.lookup("Fred")}) is true, which it is, because it's an object. That's why all three are showing up.

It looks like you have a helper, nameHelper, that returns a string. You could use a helper that returns a template instead. Suppose it's like this:

Template.people.nameHelper = function () {
    // return 'Fred', 'Ringo', or 'Jackson'
};

Template.people.chooseAnswerTemplate = function () {
    return {
        'Fred': Template.fredAnswers,
        'Ringo': Template.ringoAnswers,
        'Jackson': Template.jacksonAnswers
    }[Template.people.nameHelper.call(this)];
};

and in your people template,

<template name="people">
    {{#each profile }}
        ...
        {{> chooseAnswerTemplate}}
    {{/each }}
</template>