2013-05-09 21 views
1

由於骨幹形式擴展了骨幹視圖,我猜想使用自定義模板可以以同樣的方式完成。骨幹形式:如何使用自定義模板渲染表單

首先:插入一個模板作爲腳本類型= 「text/html的」元件在

<head> 
    [ ... ] 
    <script type="text/html" id="myTemplate"> 
     <h1>This is a template for my view</h1> 
    </script> 
</head> 

然後,使用該模板的ID設置的視圖的模板屬性首標

var myView= new Backbone.View.extend({ 
    template: '#myTemplate', 
    [...] 
}); 

對於主幹形式,模板不起作用:

<head> 
    [...] 
    <script type="text/javascript" src="scripts/jquery.js"></script> 
    <script type="text/javascript" src="scripts/underscore.js"></script> 
    <script type="text/javascript" src="scripts/backbone.js"></script> 
    <script type="text/javascript" src="scripts/backbone-forms.js"></script> 
    <script type="text/html" id="myTemplate"> 
     <h2>This is my custom form template!</h2> 
     <form><%= fieldsets %></form> 
    </script> 
</head> 
<body> 
    <div id="myform"></div> 
    <script type="text/javascript"> 
     $(document).ready(function(){ 
      MyModel = Backbone.Model.extend({ 
       schema: { 
        id : {type : "Number", validators : ["required"]}, 
        first_name: {type : "Text", validators : ["required"]}, 
        last_name: {type : "Text", validators : ["required"]}, 
        screen_name: {type : "Text"} 
       } 
      }); 
      var myModel = new MyModel(); 
      var myForm = new Backbone.Form({ 
       template: '#myTemplate', 
       model : myModel 
      }); 
      $('#myform').html(myForm.render().el); 
     }); 
    </script> 
</body> 
</html> 

此代碼將出現以下錯誤:

Uncaught TypeError: Property 'template' of object [object Object] is not a function 

然後我嘗試設置模板屬性時使用下劃線。它不工作,要麼

var myForm = new Backbone.Form({ 
    template: _.template($('#myTemplate')), 
    model : myModel 
}); 

另外一個得到一個不同的錯誤與上面的代碼:

Uncaught TypeError: Object [object Object] has no method 'replace' 

我是新來的骨幹網/骨幹網的形式。有人可以告訴我我做錯了什麼?

謝謝!

回答

1

嘗試

template: function(attrs) { return _.template($('#myTemplate').html(), attrs)}, 

使用模板是這樣的:

$('body').append(this.template({fieldsets: 'fieldsets'})); 

看到一個工作示例http://jsbin.com/uzutes/2/