# 钩子

¥Hooks

有几个地方可以挂载 Handlebars 函数调用。

¥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.

你可以通过注册助手 helperMissing 来添加针对这些情况的自定义处理:

¥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)

辅助程序接收与任何自定义辅助程序或块辅助程序相同的参数和选项(hashname 等)。options.name 是被调用的帮助者的名字。

¥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

如果没有参数传递给 Mustache,则默认行为是不执行任何操作并忽略整个 Mustache 表达式或整个块:

¥If no parameters are passed to the mustache, the default behavior 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

如果参数传递给小胡子,Handlebars 会抛出异常:

¥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.

你可以通过注册一个名为 blockHelperMissing 的助手来处理这种情况。

¥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

将使用当前上下文中已解析的属性值和设置为属性名称的 options.name 字段来调用该钩子。

¥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.

如果钩子没有被覆盖,那么默认实现将模仿 Mustache 的行为并只调用该块。

¥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
Last Updated: 2024/4/16 21:37:19