Created
March 31, 2013 08:06
-
-
Save Voronenko/5279944 to your computer and use it in GitHub Desktop.
Simple javascript formatter. Supports tokens {{property}}, {{someobject.property}}, {{anotherobject.nestedobject.property}} Enjoy.
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
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