Skip to content

Instantly share code, notes, and snippets.

@nickjacob
Last active December 11, 2015 17:58
Show Gist options
  • Save nickjacob/4638462 to your computer and use it in GitHub Desktop.
Save nickjacob/4638462 to your computer and use it in GitHub Desktop.
logic-less, compiled client-side templates in 5 lines of javascript
/**
* 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 + "()) +");
})) + "; }");
}
@nickjacob
Copy link
Author

  • fixed problem with escaping quotes in template
  • fixed trailing whitespace issue
  • added support for functions

@nickjacob
Copy link
Author

  • 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