Pass JavaScript object/hash to Handlebars helper?

前端 未结 2 1015
感情败类
感情败类 2021-01-02 03:27

Is it possible to pass a JavaScript object/hash into a Handlebars helper call? I\'d like to do something like this:


{{#         


        
相关标签:
2条回答
  • 2021-01-02 04:06

    I found another best way to pass objects.

    Template:

    {{textField dataAttribs='{"text":"Hello", "class": "text-field"}'}}
    

    Helper:

    Handlebars.registerHelper('textField', function(options) {
        var attribs;
    
        attribs = JSON.parse(options.hash.dataAttribs);
        console.log(attribs.text + " -- " + attribs.class);
        ......
        ........
    });
    

    JSFiddle for this

    0 讨论(0)
  • 2021-01-02 04:13

    Solved. I did this:

    Helper:

    Handlebars.registerHelper('textField', function(options) {
        var attributes = [];
    
        for (var attributeName in options.hash) {
          attributes.push(attributeName + '="' + options.hash[attributeName] + '"');
        }
    
        return new Handlebars.SafeString('<input type="text" ' + attributes.join(' ') + ' />');
    });
    

    And the template:

    <label>Label here</label>
    {{textField id="text_field_1" class="some-class" size="30" data-something="data value"}}
    <p>Help text here.</p>
    

    Per the documentation (bottom of the page), you can pass in a variable number of parameters to a helper method, and they will be available in options.hash (assuming "options" is a parameter to your helper method). And what's also nice about this is that you can use named parameters, and parameter order doesn't matter.

    0 讨论(0)
提交回复
热议问题