【问题标题】:Macros in Handlebars车把中的宏
【发布时间】:2013-07-29 20:37:21
【问题描述】:

Handlebars.js 有部分,您可以使用 <script> 模板 sn-p 和对 registerPartial 的 Javascript 调用单独定义和注册。我觉得这很麻烦,我更喜欢 Jinja 风格的宏定义,你可以使用相同的模板语言。

有没有帮手可以让我做这样的事情:

{{#macro macro-name}}
  This is {{ bar }} and this is {{ foo }}
{{/macro}}

{{macro-name bar="BAR"}} {{! foo would be searched in the outer context}}

我没有运气搜索过。

【问题讨论】:

  • 您可以使用其他方法在页面上查找代码并将其作为函数提供给车把。

标签: javascript templates reusability handlebars.js


【解决方案1】:

好的,在阅读了几个小时的部分内容并摸不着头脑后,我想到了这个:

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));
    });
});

你可以像这样定义一个宏:

{{#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}}

然后像这样调用它:

{{macro-name param1="foo" param2=some_array_in_context}}

定义的第一个参数是宏名。所有其他参数必须采用 param=value 格式。

我已经用了几个小时了。我发现了一些错误,但修复了它们,我发现它很有用。令我惊讶的是最终代码的结果是如此之少。真正神奇的部分是您可以使用帮助器而不是返回字符串,而是定义一个新的帮助器。

它需要 jQuery,但是,嘿,什么不需要 :-)

【讨论】:

    【解决方案2】:

    目前的方法是使用inline partials。您可以通过编程方式或在模板中使用内联部分定义这些:

    {{#*inline "myPartial"}}
      {{param1}}
    {{/inline}}
    
    {{> myPartial param1="foo" }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 2012-04-23
      相关资源
      最近更新 更多