Created
July 24, 2009 13:46
-
-
Save willbailey/154216 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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