How can I use if condition on the meteor template?
Asked Answered
N

1

8

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

<ul>
    {{#each users}}
        <li {{#if(name==admin)}}class="red"{{/if}}>{{name}}</li>
    {{/each}}
</ul> 
Neogothic answered 23/2, 2015 at 9:25 Comment(0)
W
17

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

Template.foo.helpers({
  isAdmin: function (name) {
    return name === "admin"
  }
});
<ul>
  {{#each users}}
    <li {{#if isAdmin name}}class="red"{{/if}}>{{name}}</li>
  {{/each}}
</ul>
Wow answered 23/2, 2015 at 9:35 Comment(4)
thank you!. but Is it possible to use condition or expression on the template?Neogothic
@Phirum, no all calculations in Spacebars must be done through helpers (or the data context).Parvis
@PeppeL-G why does everything need to be done through a helper, shouldn't spacebars have introduced === !== statements?Quinquagesima
@DavidAnderton, I don't know why spacebars doesn't support that, all I can say is that it doesn't. But it might be because spacebars is responsible for the view, and it's good practice to keep computations (such as equal-expressions) away from the view, so you only need the send the view the model is should render (but if you ask me, not being allowed to use equal expressions in the views is too extreme).Parvis

© 2022 - 2024 — McMap. All rights reserved.