# Hooks

There are several places where you can hook into Handlebars function calls.

# helperMissing

This hook is called when a mustache or a block-statement

  • a simple mustache-expression is not a registered helper AND
  • is not a property of the current evaluation context.

you can add custom handling for those situations by registering the helper helperMissing:

template
{{foo}}
{{foo true}}
{{foo 2 true}}
{{#foo true}}{{/foo}}
{{#foo}}{{/foo}}
preparationScript
Handlebars.registerHelper('helperMissing', function( /* dynamic arguments */) {
  var options = arguments[arguments.length-1];
  var args = Array.prototype.slice.call(arguments, 0,arguments.length-1)
  return new Handlebars.SafeString("Missing: "+options.name+"("+args+")")
})
output
Missing: foo()
Missing: foo(true)
Missing: foo(2,true)
Missing: foo(true)

The helper receives the same arguments and options (hash, name etc) as any custom helper or block-helper. The options.name is the name of the helper being called.

# Default behavior

If no parameters are passed to the mustache, the default behaviour is to do nothing and ignore the whole mustache expression or the whole block:

template
some_{{foo}}mustache
some_{{#foo}}abc{{/foo}}block
output
some_mustache
some_block

If parameter is passed to the mustache, Handlebars with throw an exception:

template
{{foo bar}}
{{#foo bar}}abc{{/foo}}
error
Missing helper: "foo"

# blockHelperMissing

This hook is called, when a

  • block-expression calls a helper that is not registered,
  • but the name matches a property in the current evaluation context.

You can handle this situation by registering a helper named blockHelperMissing.

template
{{#person}}
  {{firstname}} {{lastname}}
{{/person}}
preparationScript
Handlebars.registerHelper('blockHelperMissing', function(context, options) {
    return "Helper '"+options.name+"' not found. " 
      + "Printing block: " + options.fn(context); 
});
output
Helper 'person' not found. Printing block:   Yehuda Katz

# Default behavior

The hook will be called with the resolved property value on the current context and the options.name field set to the name of the property.

If the hook is not overridden, then the default implementation will mimic the behavior of Mustache and just call the block.

template
{{#person}}
  {{firstname}} {{lastname}}
{{/person}}
output
  Yehuda Katz