I'm starting with marionette.js and was searching for ways to use external templates instead of script ones. I have read Derick's post about how it is a bad idea to load templates in async way. I have also checked BBCloneMail to see how templates are loaded there. It turned out that those are included into the index.html page when the web application loads. I wonder if this is a good idea for some big applications that might have 30+ templates and 10+ screens (sub-applications). Am I mistaken?
I was thinking that, instead of loading all templates at once I would load them when I load some specific sub-application. Is it a good way or is there a better way of dealing with external underscore templates?
If it may help in providing the answer, I've planned to use module system provided by marionette, not RequireJS.
Thank you in advance.
Best Regards.
I ran into the same issue. I found an example online, I modified it to make it work for what I was doing it for (they were pulling html files and I wanted to pull ASP.net pages) but I can't find the example online again to give that person the credit. However, here is my modified code.
The first is the template loader:
if (!window.JackTemplateLoader) {
function JackTemplateLoader(params) {
if (typeof params === 'undefined') params = {};
var TEMPLATE_DIR = params.dir || '';
var file_cache = {};
function get_filename(name) {
if (name.indexOf('-') > -1) name = name.substring(0, name.indexOf('-'));
return TEMPLATE_DIR + name;
}
this.get_template = function (name) {
var template;
var file = get_filename(name);
var file_content;
var result;
if (!(file_content = file_cache[name])) {
$.ajax({
url: file,
async: false,
success: function (data) {
file_content = data;
file_cache[name] = file_content;
}
});
}
return file_content;
}
this.clear_cache = function () {
template_cache = {};
};
}
}
Then inside my Marionette App, I created an addInitilizer that over writes Marionettes template loader.
app.addInitializer(function (options) {
app.JackTemplateLoader = new JackTemplateLoader({ dir: "/api/ApplicationScreens/", ext: '' });
Backbone.Marionette.TemplateCache.prototype.loadTemplate = function (name) {
if (name == undefined) {
return "";
} else {
var template = app.JackTemplateLoader.get_template(name);
return template;
}
};
The best part is the template loader will cache my templates so they are only loaded once. I am working on making a change to this code to send a flag that will indicate whether or not I want to cache the template.