Created
March 18, 2011 05:53
-
-
Save premasagar/875670 to your computer and use it in GitHub Desktop.
Tim (lite, cached), renamed to timLiteCached, 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 timLiteCached=function(){function i(b,e){return b.replace(m,function(g,c){for(var j=c.split("."),k=j.length,h=e,f=0;f<k;f++){h=h[j[f]];if(f===k-1)return h}})}var m=RegExp("{{\\s*([a-z0-9_][\\.a-z0-9_]*)\\s*}}","gi"),d={},l=window.JSON;return l?function(b,e){var g=l.stringify(e),c=d[b]&&d[b][g];if(c)return c;d[b]||(d[b]={});return c=d[b][g]=i(b,e)}:i}(); |
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.1 | |
*/ | |
var timLiteCached = (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"), | |
cache = {}, | |
JSON = window.JSON, | |
undef; | |
function tim(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; | |
} | |
} | |
}); | |
} | |
return JSON ? | |
function(template, data){ | |
var stringified = JSON.stringify(data), // NOTE: requires stringifiable data | |
cachedResult = cache[template] && cache[template][stringified]; | |
if (cachedResult){ | |
return cachedResult; | |
} | |
if (!cache[template]){ | |
cache[template] = {}; | |
} | |
cachedResult = cache[template][stringified] = tim(template, data); | |
return cachedResult; | |
} : tim; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment