{{#each}} 中 {{#if}} 的这个简单示例产生了意想不到的(对我而言)结果:
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]
});
输出:
是的
我期待一个 3 x 是的列表...
这段代码有什么问题?
最佳答案
每个助手中的数据上下文是 testItems 数组,但您正在尝试访问父上下文的变量(测试模板的数据上下文)。所以自然是未定义,从而导致 if 语句评估为 false。如果您访问父上下文,您应该得到预期的结果。
<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>
关于 meteor 空格键 : {{#if}} inside {{#each}} produces unexpected results,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26532200/