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/
You can use the if helper to conditionally render a block. If its argument returns false , undefined , null , "" , 0 , or [] , Handlebars will not render the block. When using a block expression, you can specify a template section to run if the expression returns a falsy value.
Handlebars. registerHelper("if", function(conditional, options) { if (conditional) { return options. fn(this); } }); When writing a conditional, you will often want to make it possible for templates to provide a block of HTML that your helper should insert if the conditional evaluates to false.
Handlebars compiles templates into JavaScript functions. This makes the template execution faster than most other template engines.
{{if}} is used to check whether a field has a value or not, whereas {{compare}} is used to check whether a field has one value or another value. Check out our Handlebars helper reference for more information on handlebars {{compare}}, {{if}}, and other handlebars expressions!
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}}
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With