ate*_*elo 2 javascript templates reusability handlebars.js
Handlebars.js有部分,您可以使用<script>模板片段和Javascript调用来单独定义和注册registerPartial.我发现这很麻烦,我更喜欢Jinja风格的定义宏,你用相同的模板语言.
那里有帮手可以让我这样做:
{{#macro macro-name}}
This is {{ bar }} and this is {{ foo }}
{{/macro}}
{{macro-name bar="BAR"}} {{! foo would be searched in the outer context}}
Run Code Online (Sandbox Code Playgroud)
我没有运气就搜索过.
好吧,经过几个小时的阅读部分和抓挠我的头后,我想出了这个:
Handlebars.registerHelper('macro', function (name, defaults) {
// The following helper will be registered with the name
// given as the first parameter of the macro helper.
// Upon invocation, variables will be looked up in the
// following order: invocation arguments, default values
// given in the macro definition (stored in defaults.hash),
// and finally in the invocation context.
Handlebars.registerHelper(name, function (options) {
// options.hash has the parameters passed to
// the defined helper in invocation, who
// override the default parameters and the current context.
var e = $.extend(this, defaults.hash, options.hash);
// and here's where all the magic happens:
return new Handlebars.SafeString(defaults.fn(e));
});
});
Run Code Online (Sandbox Code Playgroud)
您可以像这样定义一个宏:
{{#macro "macro-name" param1="bar" param2="" param3="egg"}}
{{ param1 }}
{{#each param2 }}
{{ param3 }}
{{ some_value }} {{! this one is looked up in the current context }}
{{/each}}
{{/macro}}
Run Code Online (Sandbox Code Playgroud)
并像这样调用它:
{{macro-name param1="foo" param2=some_array_in_context}}
Run Code Online (Sandbox Code Playgroud)
定义的第一个参数是宏名称.所有其他参数必须采用param = value格式.
我现在已经用了几个小时了.我发现了一些错误,但修复了它们,我发现它很有用.令我惊讶的是最终代码的结果有多少.真正神奇的部分是,您可以使用帮助程序不返回字符串,而是定义新的帮助程序.
它需要jQuery,但是嘿,什么不是:-)