Search code examples
meteorspacebars

Meteor Spacebars: {{#if}} inside {{#each}} produces unexpected results


This simple example of {{#if}} inside {{#each}} produces an unexpected (for me) result:

HTML:

<head>
    <title>test</title>
</head>

<body>
    {{> test yes=true}}
</body>

template name="test">
    {{#if yes}}
        <span>yes</span>
    {{else}}
        <span>no</span>
    {{/if}}
    <ul>
        {{#each testItems}}
            {{#if yes}}
                <li>yes</li>
            {{else}}
                <li>no</li>
            {{/if}}
        {{/each}}
    </ul>
</template>

JS:

Template.test.helpers({
    testItems: [1,2,3]
});

Output:

yes

  • no
  • no
  • no

I was expecting a list with 3 x yes...

What is wrong with this code?


Solution

  • The data context within the each helper is testItems array, but you're trying to access a variable of the parent context (the test template's data context). So naturally yes is undefined, thus leading to the if statement evaluating to false. If you access the parent context, you should get the expected results.

    <head>
        <title>test</title>
    </head>
    
    <body>
        {{> test yes=true}}
    </body>
    
    template name="test">
        {{#if yes}}
            <span>yes</span>
        {{else}}
            <span>no</span>
        {{/if}}
        <ul>
            {{#each testItems}}
                {{#if ../yes}}
                    <li>yes</li>
                {{else}}
                    <li>no</li>
                {{/if}}
            {{/each}}
        </ul>
    </template>