Reputation: 555
I am new to things like angular and backbone and am trying to understand the structure better. I built some views but if I leave any spaces in the template chunk it breaks everything.
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();
Is there a way to make this pull from external templates outside of the javascript. What's best practices if the pages are very elaborate?
Here is my jsfiddle link.
https://jsfiddle.net/galnova/k4ox8yap/14/
Upvotes: 0
Views: 743
Reputation: 1448
If you are using a javascript module loader like RequireJs (which you'll probably find yourself doing when the application gets more complicated!) then the templates can be loaded from an external source using the RequireJs text plugin.
For example you might have a file called home.js
which could look like:
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);
}
});
}
);
Then an app.js
file could contain your application logic and require your views:
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
Upvotes: 1
Reputation: 1917
You can specify your template in your html
<script id='CoolViewTpl' type='template'>
<h1>Cool</h1><p>This is the third test. I think this is the way.</p>
</script>
Then in your render func, simply select the template by ID and get the content.
var CoolView = Backbone.View.extend({
template: "#CoolViewTpl",
initialize: function () {
this.render();
},
render: function () {
this.$el.html($(this.template).html());
}
});
Upvotes: 3