I have a huge application built with Backbone, Marionette, Require.js and this is an example of the view that I'm using:
define([
'backbone',
'text!templates/oauth.html'
], function (Backbone, Template) {
var OAuthView = Backbone.View.extend({
template: _.template(Template),
render: function() {
var type = this.options.error;
this.$el.html(this.template({ error: type }));
return this;
}
});
return OAuthView;
});
I would like to have in production (only in production because in development I like that all template files are separated) a single file html and use this https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.templatecache.md to improve the performance.
Any hints/idea? How can you solve this problem?
Thanks.
Not sure what your workflow is, I offer this as a solution that works for me. I use grunt as my automation tool, and the grunt jst plugin to automate the pre-compilation of all my templates.
This creates a single javascript file will all the compiled templates.
Once include this file in your html document you can reference all
templates through the window.JST[...]
object.
I keep all my templates in src/templates/views/*
and src/templates/layouts/*
.
My jst config looks likes this:
jst: {
compile: {
options: {
prettify: false,
amdWrapper: false,
processName: function (filename) {
var key = 'templates/';
// src/templates/views/viewName.js -> views/viewName
return filename.slice(filename.indexOf(key) + key.length, filename.lastIndexOf('.'));
}
},
files: {
"<%= app.src %>/scripts/templates.js": ["<%= app.src %>/**/*.tpl"]
}
}
},
This gives me a src/scripts/templates.js
file looking like this:
this["JST"] = this["JST"] || {};
this["JST"]["views/modal"] = function(obj) {
// compiled template here...
};
...
And finally my views look like this:
var ModalView = Backbone.View.extend({
template: window.JST['views/modal'],
...
});
You can easily wrap window.JST['views/modal']
in a helper, much like Marionette.TemplateCache
. Perhaps this is where you could handle dev/production differences, dynamically requiring the template if in dev, loading the pre-compiled version for production.
Ideally you want to abstract the logic for getting a template into a function.
In development you could have something like this where you require all your templates and based on the input name you return the correct template. You'll have to adjust this depending upon how your app/workflow is designed.
define([
'text!templates/oauth.html',
'text!templates/otherTemplate.html',
...
], function () {
App.getTemplate = function (name) {
return require('text!templates/' + name + '.html');
};
});
Then in production you would include this alternate version of the getTemplate
function that access the precompiled templates
App.getTemplate = function (name) {
return window.JST[name];
};