Skip to content

Instantly share code, notes, and snippets.

@Voronenko
Created March 31, 2013 08:06
Show Gist options
  • Save Voronenko/5279944 to your computer and use it in GitHub Desktop.
Save Voronenko/5279944 to your computer and use it in GitHub Desktop.
Simple javascript formatter. Supports tokens {{property}}, {{someobject.property}}, {{anotherobject.nestedobject.property}} Enjoy.
function fmt(tmpl, repls) {
var res = tmpl.replace(
/(?:\{\{|\%7B\%7B)(.*?)(?:\}\}|\%7D\%7D)/g,
function (m) {
return getPropertyFromVar(repls, m);
}
);
return res;
}
function getPropertyFromVar(obj, m, errors) {
var ret;
var localobj = obj;
var props = m.match(/(?:\{\{|%7B%7B)(.*?)(?:\}\}|%7D%7D)/);
if (props) {
var proppath = props[1].split(".");
for (var i = 0; i < proppath.length; i++) {
localobj = localobj[proppath[i]];
if (typeof (localobj[proppath[i]]) != "undefined") break;
}
/* options typed or untyped json:*/
ret = (localobj)
? ((localobj.content) ? localobj.content : localobj)
: ((errors) ? "No value for '" + props[1] + "' (" + m + ")" : "");
} else {
ret = (errors) ? "No key in '" + m + "'" : "";
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment