簡體   English   中英

把手TypeError:無法讀取未定義的屬性'fn'

[英]Handlebars TypeError: Cannot read property 'fn' of undefined

我創建了一個自定義車把幫助器,但未定義參數值時出現以下錯誤。

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

如果我這樣定義所有三個參數,則此方法有效:

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

如果未定義,則控制台顯示“ Handlebars TypeError:無法讀取未定義的屬性'fn'”。

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

關於我在這里做錯什么的任何想法?

更新:如下所示,也用“ null”檢查,但仍然是相同的錯誤。

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

如果您不想提供任何參數,請使用null 因此,以下代碼應該工作:

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

您不應在函數簽名中聲明可選參數。 把手將哈希對象放入傳遞給函數的提供的options對象中。 通過哈希對象,您可以訪問所有提供的參數。 請參考Block Helpers文檔中的“哈希參數”部分。

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 = '';
...

也許嘗試用null而不是undefined檢查您的屬性?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM