Last active
December 11, 2015 17:58
-
-
Save nickjacob/4638462 to your computer and use it in GitHub Desktop.
logic-less, compiled client-side templates in 5 lines of javascript
This file contains 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
/** | |
* PicoTemplate | |
* syntax (there is barely any) | |
* | |
* <a href="{{ url }}">{{ movie.title }}</a> | |
* NO LOGIC! | |
**/ | |
function __deep(obj, prop) { | |
var parts = prop.split('.'), i = -1, l = parts.length; | |
while(++i < l) { | |
if (!(obj[parts[i]] !== undefined && (obj = obj[parts[i]]))) { | |
return undefined; | |
} | |
} | |
return (typeof obj === 'function') ? obj() : obj; | |
} | |
function compile (tpl) { | |
var qq = /"/.test(tpl) ? "\'" : "\"", _qq = function(str){ return qq + str + qq; }; | |
return Function(["obj"], "with (obj) { return " + _qq(tpl.replace(/['"]/g,"\$&").replace(/{{\s*([\w\.]+)\s*}}/ig, function (str, m) { | |
return (/\./g.test(m)) ? _qq("+ __deep(obj, " + _qq(m) + ") +") : _qq(" + ((typeof(" + m + ") !== " + _qq("function") +") ? " + m + " : " + m + "()) +"); | |
})) + "; }"); | |
} |
Author
nickjacob
commented
Feb 19, 2013
- fixed problem with escaping quotes in template
- fixed trailing whitespace issue
- added support for functions
- made it quote-agnostic
- added support for nested properties
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment