[solved] Conditional CSS class applied to element in template. Can this be simplified?

{{#if note.favorited}}
  <a class="toggle-icon toggled" href="">
    <i class="fa fa-star"></i>
  <a class="toggle-icon" href="">
    <i class="fa fa-star"></i>

As you can see, the only thing that changes is the toggled css class. Can this code be shortened?

  <a class="toggle-icon {{#if note.favorited}}toggled{{/if}}" href="">
    <i class="fa fa-star"></i>


@copleykj’s solution works and is standard for simple, one variable true check. (Note this doesn’t work if you want to check the inverse (!note.favourite) or two variables or anything more complicated than the above example.

If you require anything remotely more than a check for truth of one variable, you’d have get helper functions involved

<a class="toggle-icon {{classFavouriteToggle arg1 arg2}}" href="">
    <i class="fa fa-star"></i>
    classFavouriteToggle: function () {
        // logic based on arguments
        return 'toggled';

I’ve started to write my own templating logic:

Template.registerHelper('none', function () {
    var args = Array.prototype.slice.call(arguments, 0 , -1);
    return !_.some(args);

so I can use it like this:

<a class="toggle-icon {{#if none arg1 arg2}}toggled{{/if}}" href="">
    <i class="fa fa-star"></i>

This way you don’t have to write a helper for every UI element that needs boolean logic.

How to evaluate this condition?

@mordrax, this is a great snippet. thanks for sharing!


Yeah, glad you like it, I was pretty excited when I found it (http://stackoverflow.com/questions/26745185/multiple-spacebar-conditional-operators) and realised I could do if not, if any, if all… Coming from angular, spacebars is a mile backwards…


There’s also a nice helper I use for comparing equality(CS):

Template.registerHelper 'eq', (v1,v2,v3)->
  if v1==v2 or v1==v3
    return true


{{#if eq truth absoluteTruth}}
  <p>At last!</p>