我是角度和骨干之类的新手,我试图更好地理解结构。我构建了一些视图,但如果我在模板块中留下任何空格,它会破坏所有内容。
var HomeView = Backbone.View.extend({
template: '<h1>Home</h1><p>This is the first test. I think this is the way.</p>',
initialize: function () {
this.render();
},
render: function () {
this.$el.html(this.template);
}
});
var AboutView = Backbone.View.extend({
template: '<h1>About</h1><p>This is the second test. I think this is the way.</p>',
initialize: function () {
this.render();
},
render: function () {
this.$el.html(this.template);
}
});
var CoolView = Backbone.View.extend({
template: '<h1>Cool</h1><p>This is the third test. I think this is the way.</p>',
initialize: function () {
this.render();
},
render: function () {
this.$el.html(this.template);
}
});
var AppRouter = Backbone.Router.extend({
routes: {
'': 'homeRoute',
'home': 'homeRoute',
'about': 'aboutRoute',
'cool': 'coolRoute',
},
homeRoute: function () {
var homeView = new HomeView();
$("#content").html(homeView.el);
},
aboutRoute: function () {
var aboutView = new AboutView();
$("#content").html(aboutView.el);
},
coolRoute: function () {
var coolView = new CoolView();
$("#content").html(coolView.el);
}
});
var appRouter = new AppRouter();
Backbone.history.start();
有没有办法从javascript之外的外部模板中获取。如果页面非常精细,最佳做法是什么?
这是我的jsfiddle链接。
答案 0 :(得分:2)
您可以在html中指定模板
<script id='CoolViewTpl' type='template'>
<h1>Cool</h1><p>This is the third test. I think this is the way.</p>
</script>
然后在你的渲染功能中,只需按ID选择模板并获取内容。
var CoolView = Backbone.View.extend({
template: "#CoolViewTpl",
initialize: function () {
this.render();
},
render: function () {
this.$el.html($(this.template).html());
}
});
答案 1 :(得分:1)
如果您正在使用像RequireJs这样的javascript模块加载器(当应用程序变得更复杂时,您可能会发现自己正在做的那样!)那么可以使用{{3}从外部源加载模板}。
例如,您可能有一个名为home.js
的文件,如下所示:
require([ "backbone", "underscore", "text!templates/template.html" ],
function( Backbone, _, template ) {
return Backbone.View.extend({
template: _.template( template ),
initialize: function () {
this.render();
},
render: function () {
this.$el.html(this.template);
}
});
}
);
然后app.js
文件可能包含您的应用程序逻辑并需要您的观点:
require([ "backbone", "jquery", "home.js" ],
function( Backbone, $, HomeView ) {
var AppRouter = Backbone.Router.extend({
routes: {
'': 'homeRoute',
'home': 'homeRoute',
// etc
},
homeRoute: function () {
var homeView = new HomeView();
$("#content").html(homeView.el);
}, // etc