2015-06-14 32 views
0

我試圖使用編譯模板建立一些下拉菜單中的把手,但它是不是能夠進入我的變量:引用車把變量在一個循環中

把手:

{{#each options}} 
<div class="control-group consumables-options"> 
    <div class="row-fluid"> 
     <div class="span2"> 
      {{select 'task_services_options' ../bond_service_request_quantities quantity}} 
     </div> 
    </div> 
</div> 
{{/each}} 

JS:

var html = Handlebars.templates.service_request_consumable_options({ 
    bond_service_request_quantities: bond_quantities, 
    options: opts 
}); 

其中bond_quantitiesopts是對象陣列。

選擇幫助程序來自handlebars-form-helpers,但即使在正常的handlebars({{../bond_service_request_quantities.0.text}})中也會出現錯誤。

Uncaught TypeError: Cannot read property '1' of undefined

回答

0

我的回答是我使用了兩個不同版本的把手。該項目有v2.0.0,但npm爲編譯模板的grunt任務安裝了3.0.3。

0

您的Handlebars模板和JavaScript代碼看起來沒問題。從查看錯誤消息,它看起來像變量「bond_quantities」爲空。

這是我用來測試代碼的一個示例html文件。我試圖儘可能簡化它,將預編譯模板直接添加到頁面中,對數據進行硬編碼。

<html> 

<head> 
<script src="http://code.jquery.com/jquery-1.11.3.js"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script> 
<script src="handlebars.form-helpers.min.js"></script> 

<script> 
    (function() { 
    var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {}; 
templates['service_request_consumable_options'] = template({"1":function(depth0,helpers,partials,data,blockParams,depths) { 

    depths = []; 
    depths[1] = data.root; 

    return "<div class=\"control-group consumables-options\">\n <div class=\"row-fluid\">\n  <div class=\"span2\">\n   " 
    + this.escapeExpression((helpers.select || (depth0 && depth0.select) || helpers.helperMissing).call(depth0,"task_services_options",(depths[1] != null ? depths[1].bond_service_request_quantities : depths[1]),(depth0 != null ? depth0.quantity : depth0),{"name":"select","hash":{},"data":data})) 
    + "\n  </div>\n </div>\n</div>\n"; 
},"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data,blockParams,depths) { 
    var stack1; 

    return ((stack1 = helpers.each.call(depth0,(depth0 != null ? depth0.options : depth0),{"name":"each","hash":{},"fn":this.program(1, data, 0, blockParams, depths),"inverse":this.noop,"data":data})) != null ? stack1 : ""); 
},"useData":true,"useDepths":true}); 
})(); 
</script> 

<script> 
    $(function() { 
     HandlebarsFormHelpers.register(Handlebars); 

     var bond_quantities = [ { 
      value : 1, 
      text : 'One' 
     }, { 
      value : 2, 
      text : 'Two' 
     } ]; 

     var opts = [ { 
      quantity : 100 
     }, { 
      quantity : 200 
     } ]; 

     var html = Handlebars.templates.service_request_consumable_options({ 
      bond_service_request_quantities: bond_quantities, 
      options: opts 
     }); 

     $('#target').html(html); 
    }); 
</script> 
</head> 

<body> 
    <div id="target"></div> 
</body> 

</html> 
+0

不,如果我在循環外輸出它工作正常,它就在那裏。 – BeaverusIV

+0

我使用車把v2,這是否重要? – BeaverusIV

+0

它在v2中看起來像深度參數沒有被傳遞給模板。您可以通過手動設置參數來獲取模板。我會更新這個例子。 –