钩子
有几个地方可以挂载 Handlebars 函数调用。
helperMissing
当胡子或块语句时调用此钩子
- 简单的胡子表达式不是注册的助手并且
- 不是当前评估上下文的属性。
你可以通过注册助手 helperMissing
来添加针对这些情况的自定义处理:
template {{foo}}
{{foo true}}
{{foo 2 true}}
{{#foo true}}{{/foo}}
{{#foo}}{{/foo}}
preparationScript Handlebars.registerHelper('helperMissing', function( ) {
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)
辅助程序接收与任何自定义辅助程序或块辅助程序相同的参数和选项(hash
、name
等)。 options.name
是被调用的帮助者的名字。
默认行为
如果没有参数传递给 Mustache,则默认行为是不执行任何操作并忽略整个 Mustache 表达式或整个块:
template some_{{foo}}mustache
some_{{#foo}}abc{{/foo}}block
output some_mustache
some_block
如果参数传递给小胡子,Handlebars 会抛出异常:
template {{foo bar}}
{{#foo bar}}abc{{/foo}}
error Missing helper: "foo"
blockHelperMissing
当一个
- 块表达式调用未注册的助手,
- 但名称与当前评估上下文中的属性匹配。
你可以通过注册一个名为 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
默认行为
将使用当前上下文中已解析的属性值和设置为属性名称的 options.name
字段来调用该钩子。
如果钩子没有被覆盖,那么默认实现将模仿 Mustache 的行为并只调用该块。
template {{#person}}
{{firstname}} {{lastname}}
{{/person}}