【问题标题】:Passing variables through handlebars blockhelper通过把手blockhelper传递变量
【发布时间】:2016-07-27 20:10:34
【问题描述】:

我想在我的自定义块助手中传递和编译参数。我发现参数在哈希对象中,但是如何将它们编译成部分?

我希望将参数 flyoutClass 编译到我的部分中。一切正常,但我的参数输出应该是空的地方......

车把助手

module.exports.register = function (Handlebars, context)  { 
    Handlebars.registerHelper('injectHtml', function(name, options) {
        console.log(options.hash); //yeah my param
        var partial = Handlebars.partials[name];
        var template = Handlebars.compile(partial);
        //var template = Handlebars.compile(partial)(options.hash); *
        var output = template({"body":  options.fn(this)});     
        return new Handlebars.SafeString(output); 
        //return new Handlebars.SafeString(output(options.hash)); *
        //return new Handlebars.SafeString(partial(output)); *
    }) 
};

我已经尝试了一些东西,但我总是得到那个警告......

警告:字符串不是函数

.hbs 文件

<div class="flyout {{flyoutClass}}">
    <button>flyout-button</button>
    <div class="flyout__content">
        {{{body}}}
    </div> 
</div>

调用我的blockhelper

{{#injectHtml "flyout" flyoutClass='navigation__item'}}
    <div class="wrapper">
        <h3>Headline</h3>
        <p>some copy</p>
        <button>CTA</button>
    </div
    <div class="wrapper">
        <h3>Headline</h3>
        <p>some copy</p>
        <button>CTA</button>
    </div>
{{/injectHtml}}

升级

是否可以从我的 blockhelper 传递一个参数到另一个部分?

var output = template({
    "addClass": options.hash.addClass,
    "id": options.hash.id,
    "body": options.fn(this)
});

我喜欢用“id”扩展这个部分

{{#injectHtml "flyout" flyoutClass='navigation__item'id='myUniqueID'}}

并在我的部分按钮中使用它

<div class="flyout {{flyoutClass}}">
    {{>button btn="icon-text" id="{{id}}"/*[1]*/ icon="arrow-down"label="klick me"}}
    <div class="flyout__content" aria-labelledby="{{id}}"/*[2]*/> 
        {{{body}}}
    </div> 
</div>

但在 [1] 处,参数未编译,[2] 工作正常。

<div class="flyout navigation__item">
    <a href="#" id="{{id}}"/*[1]*/ aria-expanded="false">
    <div class="flyout__content" aria-labelledby="myUniqueID"/*[2]*/> 
        //html content
    </div> 
</div>

【问题讨论】:

    标签: handlebars.js partials


    【解决方案1】:

    您不能将flyoutClass 参数“编译”到部分模板中,因为您希望此参数是动态的。这意味着它实际上只是模板数据的另一个参数:

    var output = template({
        "flyoutClass": options.hash.flyoutClass,
        "body": options.fn(this)
    });
    

    更新

    ...但是没有办法动态添加参数??[原文]

    如果您希望将所有参数传递给您的助手,您可以简单地使用options.hash 在您的助手中扩展一个模板数据对象:

    var data = Handlebars.Utils.extend({ body: options.fn(this) }, options.hash);
    var output = template(data); 
    

    【讨论】:

    • 哇,谢谢 ;) 可以,但是没有办法动态添加参数?因为我还想将此块助手用作其他部分的通用助手,例如我的 fakescroller、下拉列表、..
    猜你喜欢
    • 2012-07-16
    • 2014-09-25
    • 1970-01-01
    • 2018-10-11
    • 2011-10-19
    • 2014-12-25
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多