既然主干表单扩展了主干视图,我想使用自定义模板应该以同样的方式完成。
首先:在header
中插入一个模板作为script type="text/html"元素<head>
[ ... ]
<script type="text/html" id="myTemplate">
<h1>This is a template for my view</h1>
</script>
</head>
然后使用模板
的id来设置视图的template属性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'
我是新来的骨干/骨干形式。有人能告诉我我哪里做错了吗?
谢谢!
Try
template: function(attrs) { return _.template($('#myTemplate').html(), attrs)},
使用模板如下:
$('body').append(this.template({fieldsets: 'fieldsets'}));
查看工作示例http://jsbin.com/uzutes/2/