Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Loading a bunch of external templates through mootools
/*
---
name: Asset.templates
description: lazy-loading templates via Request.HTML and storing them for later under a key
authors: Dimitar Christoff
license: MIT-style license.
version: 1.1
requires:
- Core/Request
- Core/Obect
- Core/Array
provides:
- Asset.templates
- Asset.templates.get
- Asset.templates.set
...
*/
(function() {
var Templates = {};
var Asset = this.Asset = this.Asset || {};
Asset.templates = function(sources, options) {
if (!(this instanceof arguments.callee))
return new Asset.templates(sources, options);
// load an array of templates as js script elements and fire an onComplete
this.options = Object.merge({
path: "",
onComplete: Function.from,
onProgress: Function.from,
onFailure: Function.from
}, options);
this.counter = 0;
this.todo = sources.length;
var self = this;
var loadTemplate = function(source) {
var options = self.options;
new Request({
url: [options.path, source.file].join(""),
onSuccess: function() {
Asset.templates.set(source.name, this.response.text);
self.counter++;
options.onProgress.call(self, source, self.counter);
if (self.counter == self.todo)
options.onComplete.call(self, self.counter);
},
onFailure: function() {
options.onFailure.call(self, source, self.counter);
}
}).get();
};
Array.each(sources, loadTemplate);
};
Asset.templates.get = function(name) {
return Templates[name] || "";
};
Asset.templates.set = function(name, body) {
return Templates[name] = body || "";
};
})();
/* example use */
new Asset.templates([{
name: "user-edit",
file: "user-edit.html"
}, {
name: "user-create",
file: "user-create.html"
}], {
path: "static/templates/",
onProgress: function(template, count) {
console.log(template.file + " loaded...");
},
onComplete: function() {
window.fireEvent("templatesready");
}
});
@afoeder

This comment has been minimized.

Copy link

@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

This comment has been minimized.

Copy link
Owner Author

@DimitarChristoff DimitarChristoff commented Feb 16, 2012

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

@DimitarChristoff

This comment has been minimized.

Copy link
Owner Author

@DimitarChristoff DimitarChristoff commented Feb 24, 2012

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