Calling Helper Within If Block in Handlebars Template

和自甴很熟 提交于 2019-12-02 20:13:55

I don't think this is going to work. If I understand the handlebars documentation correct, the #if is a registered block-helper itself and does not take another registered helper as an argument.

According to the documentation you might implement it like that


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

  if(selected) {
    return block(this);
  }
});

Afterwards you should be able to call it with


{{#ifItemSelected SomeItem}}
    This was selected
{{/ifItemSelected}

but you have to make sure SomeItem has the proper format. I don't see a way to use a registered handler as conditional in an if-statement.

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.

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

If you want to have an else option too, you will need this code:

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

  if (selected) {
    return options.fn(this);
  }
  else {
   return options.inverse(this);
 }
});

Used with:

{{#ifItemSelected SomeItem}}
    This was selected
{{else}}
    This was not selected
{{/ifItemSelected}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!