Created
March 18, 2011 05:53
-
-
Save premasagar/875669 to your computer and use it in GitHub Desktop.
Tim (lite), renamed to timLite, for including in perf tests at http://jsperf.com/dom-vs-innerhtml-based-templating/111
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
var timLite=function(){var e=/{{\s*([a-z0-9_][\\.a-z0-9_]*)\s*}}/gi;return function(f,g){return f.replace(e,function(h,i){for(var c=i.split("."),d=c.length,b=g,a=0;a<d;a++){b=b[c[a]];if(b===void 0)throw"tim: '"+c[a]+"' not found in "+h;if(a===d-1)return b}})}}(); |
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
/*! | |
* Tim (lite) | |
* github.com/premasagar/tim | |
* | |
*//* | |
A tiny, secure JavaScript micro-templating script. | |
*//* | |
by Premasagar Rose | |
dharmafly.com | |
license | |
opensource.org/licenses/mit-license.php | |
** | |
creates global object | |
tim | |
** | |
v0.3.0 | |
*/ | |
var timLite = (function(){ | |
"use strict"; | |
var start = "{{", | |
end = "}}", | |
path = "[a-z0-9_][\\.a-z0-9_]*", // e.g. config.person.name | |
pattern = new RegExp(start + "\\s*("+ path +")\\s*" + end, "gi"), | |
undef; | |
return function(template, data){ | |
// Merge data into the template string | |
return template.replace(pattern, function(tag, token){ | |
var path = token.split("."), | |
len = path.length, | |
lookup = data, | |
i = 0; | |
for (; i < len; i++){ | |
lookup = lookup[path[i]]; | |
// Property not found | |
/* | |
if (lookup === undef){ | |
throw "tim: '" + path[i] + "' not found in " + tag; | |
} | |
*/ | |
// Return the required value | |
if (i === len - 1){ | |
return lookup; | |
} | |
} | |
}); | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment