Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Helper Within If Block in Handlebars Template

I am working with Handlebars.js template engine and am trying to figure out a way to do something like this (contrived example):

{{#if itemSelected "SomeItem"}}     <div>This was selected</div> {{/if} 

where itemSelected is a registered helper like this:

Handlebars.registerHelper("itemSelected", function(item) {     var selected = false;     // Lots of logic that determines if item is selected     return selected; }); 

I get errors when trying to use this syntax for the template, and I cannot find any example showing this kind of thing. I do see simple #if blocks like this...

{{#if myValueInContext}}     <div>This will show if myValueInContext results in a truthy value.</div> {{/if}} 

But, I can't figure out how to tackle the first example. Maybe I am approaching this wrong.

By the way, I tagged this Mustache as I could not add a Handlebars tag to the question.

like image 736
Kevin Avatar asked Jun 11 '11 23:06

Kevin


People also ask

Is there else if in Handlebars?

Handlebars supports {{else if}} blocks as of 3.0. 0. is the point in not having an elsif (or else if) in handlebars that you are putting too much logic into your template.

How do you call a function in Handlebars?

Here is a simple example that formats a phone number. So long as you register the helper before you call it you should be able to use {{formatPhoneNumber phoneNumber}} anywhere in your code. Handlebars. registerHelper("formatPhoneNumber", function(phoneNumber) { phoneNumber = phoneNumber.

What is the correct syntax to call a Handlebarsjs partial template?

Handlebars. registerPartial('myPartial', '{{prefix}}'); This call will register the myPartial partial. Partials may be precompiled and the precompiled template passed into the second parameter.


2 Answers

With last version (1.0.rc.1) of Handlebars, you have to write sth like:

Handlebars.registerHelper('ifItemSelected', function(item, options) {   var selected = false;   // lots of logic that determines if item is selected    if (selected) {     return options.fn(this);   } }); 

ie. block(this) is replaced by options.fn(this)

http://handlebarsjs.com/block_helpers.html#conditionals

like image 44
jgraglia Avatar answered Sep 22 '22 18:09

jgraglia


You should add parentheses around the embedded helper invocation:

{{#if (itemSelected "SomeItem")}}     <div>This was selected</div> {{/if} 

I did experiments and verified that it just works.

Not sure if it's mentioned in the Handlebars documentation. I learned the trick from the examples of handlebars-layouts.

like image 133
gnowoel Avatar answered Sep 23 '22 18:09

gnowoel