javascript 如何在流星模板上使用 if 条件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28670444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:20:47  来源:igfitidea点击:

How can I use if condition on the meteor template?

javascriptmeteorspacebars

提问by Phirum

I want to use an ifcondition in a Meteor Blaze template. Let's say you have a helper userson the Users collection you want to iterate through tasks and if the username is admin, use a "red" style:

我想if在 Meteor Blaze 模板中使用条件。假设您users在 Users 集合上有一个要遍历任务的助手,如果用户名是 admin,请使用“红色”样式:

<ul>
    {{#each users}}
        <li {{#if(name==admin)}}class="red"{{/if}}>{{name}}</li>
    {{/each}}
</ul> 

回答by Dan Dascalescu

Meteor uses Spacebars, a variant of Handlebars, which are "logicless" templates. You need to define a Template helper, then use it in the {{#if}}.

Meteor 使用Spacebars,一种Handlebars的变体,它是“无逻辑”的模板。您需要定义一个模板助手,然后在{{#if}}.

Template.foo.helpers({
  isAdmin: function (name) {
    return name === "admin"
  }
});
<ul>
  {{#each users}}
    <li {{#if isAdmin name}}class="red"{{/if}}>{{name}}</li>
  {{/each}}
</ul>