Skip to content

Instantly share code, notes, and snippets.

@DimitarChristoff
Created February 8, 2012 12:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DimitarChristoff/1768949 to your computer and use it in GitHub Desktop.
Save DimitarChristoff/1768949 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link
Author

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

@DimitarChristoff
Copy link
Author

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