17

I am trying to write a conditional if statement helper for Handlebars.js. Essentially, I want to put an "active" class on a link if it is the Apply Now page.

Helper:

  Handlebars.registerHelper('isApplyNow', function(block) {
    if(this.title == "Apply Now") {
      return block(this);
    } else {
      return block.inverse(this);
    }
  });

And Template:

  <ul>
    {{#each pages}}
      <li>
        {{#isApplyNow}}
          <a href="{{url}}" class ='active'>{{this.title}}</a>
        {{else}}
          <a href="{{url}}">{{this.title}}</a>
        {{/if}}
      </li>
    {{/each}}  
  </ul>

But, I am getting a very bare-bones javascript error:

Uncaught [object Object] in handlebars-1.0.0.beta.2.js:595

Can anyone see if I am writing this improperly?

Thanks!

Referenced articles:

Calling Helper Within If Block in Handlebars Template

http://thinkvitamin.com/code/handlebars-js-part-2-partials-and-helpers/

Community
  • 1
  • 1
wart
  • 610
  • 1
  • 6
  • 10

2 Answers2

22

I do see one minor syntax mistake which I believe could be the issue. If you are going to use a helper that takes a block, then you have to close it with the helper name. See how I've replaced your {{/if}} with {{/isApplyNow}}, like so:

    {{#isApplyNow}}
      <a href="{{url}}" class ='active'>{{this.title}}</a>
    {{else}}
      <a href="{{url}}">{{this.title}}</a>
    {{/isApplyNow}}
kaptron
  • 477
  • 5
  • 12
  • Ahh duh, I'll try this in a little bit when I get back to that side of the app. Thanks! – wart Mar 14 '12 at 18:19
2

NOTE: block(this) in the helper will not work anymore. Instead, use block.fn(this)

e.g.

 Handlebars.registerHelper('isApplyNow', function(block) {
    if (this.title === "Apply Now") 
      return block.fn(this);
    else 
      return block.inverse(this);
 });
Rohit Suthar
  • 3,528
  • 1
  • 42
  • 48
digiwand
  • 1,258
  • 1
  • 12
  • 18