0

I created a custom handlebars helper and I'm getting the following error when I do not define value for parameters.

module.exports = function(src, color, classatr, options) {

    if (typeof src === 'undefined') src = '';
    if (typeof color === 'undefined') color = '';
    if (typeof classatr === 'undefined') classatr = '';

    var bg = '<table class="'+ classatr +'" cellpadding="0" cellspacing="0" border="0" width="100%">\
      <tr>\
        <td background="'+ src +'" bgcolor="'+ color +'" valign="top">\
          <!--[if gte mso 9]>\
          <v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" style="mso-width-percent:1000;">\
            <v:fill type="tile" src="'+ src +'" color="#'+ color +'" />\
            <v:textbox style="mso-fit-shape-to-text:true" inset="0,0,0,0">\
          <![endif]-->\
          <div>'
          + options.fn(this) +
          '</div>\
          <!--[if gte mso 9]>\
            </v:textbox>\
          </v:rect>\
          <![endif]-->\
        </td>\
      </tr>\
    </table>';

    return bg;
}

This works if I define all three parameters as such:

{{#bg-img 'assets/img/hero-header.jpg' '000000' 'my-class'}}
    <container>
        <row>
            <columns>
            </columns>
        </row>
    </container>
{{/bg-img}}

If I do not define a parameter console shows "Handlebars TypeError: Cannot read property 'fn' of undefined".

{{#bg-img }}
    <container>
        <row>
            <columns>
            </columns>
        </row>
    </container>
{{/bg-img}}

Any ideas as to what I'm doing wrong here?

Update: Also checked with "null" as suggested below but still same error.

if (typeof src === 'undefined' || src === null) src = '';
if (typeof color === 'undefined' || color === null) color = '';
if (typeof classatr === 'undefined' || classatr === null) classatr = '';
4

3 回答 3

2

use null where you don't wanna provide any parameter. so, the following code should work :

{{#bg-img null null null}}
    <container>
        <row>
            <columns>
            </columns>
        </row>
    </container>
{{/bg-img}}
于 2017-02-18T09:38:24.450 回答
1

You shouldn't declare optional parameters in your functions signature. Handlebars puts a hash object in the supplied options object passed to your function. Through the hash object you can access all the supplied parameters. Please refer to the "Hash Arguments" section in the Block Helpers Documentation.

module.exports = function(options) {

var src = options.hash.src;
var color = options.hash.color;
var classatr = options.hash.classatr;
if (typeof src === 'undefined') src = '';
if (typeof color === 'undefined') color = '';
if (typeof classatr === 'undefined') classatr = '';
...
于 2017-02-19T00:28:08.420 回答
0

Maybe try to check your attributes with null, not undefined?

于 2017-02-18T09:33:40.783 回答