Create a gist now

Instantly share code, notes, and snippets.

Loading a bunch of external templates through mootools
(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");
}
});
@afoeder
afoeder commented Feb 16, 2012

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>
@DimitarChristoff
Owner

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

@DimitarChristoff
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment