Reputation: 4429
I've seen a few long winded answers to how to load templates for rendering in respect of the _underscore templates utility and the like. What I've got below works:
$.ajax({
url: 'template.tmp',
type: 'get',
success: function(data) {
$('html').append(data);
}
});
The code sits after jquery is loaded but before any scripts using the templates. Would this be ok or is there a reason why it wouldn't be a good idea to load templates like this? The templates.tmp file has templates within
<script type="text/template" id="tmpId"></script>
tags. They seem to get loaded into the DOM pretty much instantly. I'm prepared to be criticised for this implementation, but I'd just like to know why. The only thing I can think of is perhaps some processing if "error:" gets called instead of "success:". Thx.
Upvotes: 2
Views: 130
Reputation: 4429
I decided to produce my own OO based solution. This is the constructor:
var TemplateLoader = function(templatePath) {
this.template = templatePath;
this.loaded = false;
this.error = false;
}
And these are the methods:
TemplateLoader.prototype.setReady = function (state) {
this.loaded = state;
}
TemplateLoader.prototype.setError = function (state) {
this.error = state;
}
TemplateLoader.prototype.isReady = function () {
return this.loaded;
}
TemplateLoader.prototype.isError = function () {
return this.error;
}
TemplateLoader.prototype.loadTemplate = function() {
templateLoader = this;
$.ajax({
url: this.template,
type: 'get',
success: function(data) {
$('html').append(data);
templateLoader.setReady(true);
},
error: function() {
templateLoader.setError(true);
}
});
}
And this is how to use it:
templateLoader = new TemplateLoader('template.tmpl');
templateLoader.loadTemplate();
And to check the template has loaded:
templateLoader.isReady() //true for loaded
templateLoader.isError() //true for error loading template, eg. template doesn't exist
Again, I'd appreciate any feedback on issues anyone could see with this code. How about checking for the DOM object appended to the HTML. Worthwhile?
Upvotes: 2