Skip to content

Instantly share code, notes, and snippets.

@willbailey
Created July 24, 2009 13:46
Show Gist options
  • Save willbailey/154216 to your computer and use it in GitHub Desktop.
Save willbailey/154216 to your computer and use it in GitHub Desktop.
(function() {
// Class for template value placeholder objects
var _Value = Class.create({
toString: function() {
// "x==null" is true for catches null and undefined
return this.value == null ? '' : this.value.toString();
}
});
/**
* @class ZenTemplate
*/
window.ZenTemplate = Class.create({
/**
* @constructor
*/
initialize: function(s) {
this.klass = 'ZenTemplate';
var parts = this.parts = [];
var vals = this.values = {};
// Compile the template
var RE = /^(.*?)#\{(.+?)\}(.*)/;
while (s) {
var m = RE.exec(s);
if (!m) break;
if (m[1]) parts.push(m[1]);
var k = m[2];
if (k) parts.push(vals[k] = (vals[k] || new _Value()));
s = m[3];
}
if (s) parts.push(s);
},
/**
* @function ?
*/
evaluate: function(o) {
var vals = this.values;
for (var k in vals) vals[k].value = o[k];
return this.parts.join('');
}
});
// The "store"
var _instances = {};
/**
* Factory method for getting a template object. Templates are compiled and
* cached
* @function {static} ?
*/
window.ZenTemplate.get = function(s) {
if (s.klass && s.klass == 'ZenTemplate') return s;
return _instances[s] || (_instances[s] = new ZenTemplate(s));
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment