public
Last active

Loading a bunch of external templates through mootools

  • Download Gist
Asset.templates.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
(function() {
// sequential loading of handlebars / other templates from static sources into script els
// Exports: Asset.templates. Use as a constructor with 'new'
 
Asset = Asset || {};
Asset.templates = function(sources, options) {
if (!(this instanceof arguments.callee))
return new Asset.templates(sources, options);
 
// load an array of templates and fire an onComplete
options = Object.merge({
path: "",
type: "text/x-handlebars",
property: "data-template-name",
onComplete: Function.from,
onProgress: Function.from
}, options);
 
var counter = 0, todo = sources.length, self = this, obj = {};
 
var loadNext = function() {
if (sources[0])
var source = sources[0];
 
new Request.HTML({
url: [options.path, source.file].join(""),
onComplete: function() {
var obj = {
"type": options.type,
html: this.response.text
};
 
obj[options.property] = source.name;
 
new Element("script", obj).inject(document.head);
counter++;
 
options.onProgress.call(self, source, counter);
 
if (counter == todo)
options.onComplete.call(self, counter);
else
loadNext();
}
}).get();
};
 
loadNext();
};
})();
 
// example use - load and make 2 templates available to handlebars or backbone.js or whatever
new Asset.templates([{
name: "user-edit",
file: "user-edit.html"
},
{
name: "user-view",
file: "user-view.html"
}], {
path: "static/templates/",
onProgress: function(template, count) {
console.log(template.file + " loaded...");
},
onComplete: function() {
window.fireEvent("templatesLoaded");
}
});

so, during runtime, am I right it would/could be

<script type="text/javascript" data-template-name="user-edit">
<h1>Demo</h1>
<span>This would be any html, propably with {specialSyntax} etc?</span>
</script>

this is what will/could be get injected into the dom, yes.

updated now, due to IE affecting HTML as it injects it into the DOM and reads it back, sometimes causing parser errors in .js `.template()`, I have moved the templates behind a private closure with a getter and a setter. Faster access this way anyway.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.