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

This simple example {{#if}} inside {{#each}} leads to 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]
});

Conclusion:

Yes

  • no
  • no
  • no

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

What is wrong with this code?

+4
source share
1 answer

The data context inside each helper is an array of testItems, but you are trying to access the parent context variable (test template data context). Thus, it is natural that it is undefined, which leads to the fact that the if statement evaluates to false. If you are referring to 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>
+5
source

All Articles