Originally, this was meant to be released as something for String.Extras in mootools-more as an idea by Oskar, coined by myself with input from csuwldcat – but it seems that the pull request is not going anywhere so I will release it here instead.
The idea is to extend the behaviour of String.substitute to be able to work with deep properties of the object that is being passed on, which means easier templating without having to flatten objects beforehand so the properties of interest are on the same level.
View on github as per pull request
String.implement({ substitutePath: function(object, regexp) { return String(this).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name) { if (match.charAt(0) == '\\') return match.slice(1); if (object[name] != null) return object[name]; var retStr = "", path = name.split('.'), length = path.length, sub = object; if (length <= 1) return retStr; for (var i = 0; i < length; i++) { if((sub = sub[path[i]]) == null) return retStr; } return sub; }); } });
The use goes like this:
var foo = "this is a bar called \"{lame.bar.name.here}\""; var objOK = { lame: { bar: { name: { here: 0 } } } }; var objFail = { lame: { bar: { lame: { here: "hello" } } } }; console.log(foo.substitutePath(objOK)); // works console.log(foo.substitutePath(objFail)); // should fail console.log(foo.substitutePath({foo:"bar"})); // should fail console.log("this is a {bar}".substitutePath({bar:"success"})); // should work (legacy as .substitute);
Here's the jsfiddle you can play with: http://jsfiddle.net/dimitar/RtBMm/
Please note that the above will only deal with non-primitives (numbers, strings) and will fail if the key matches a function or an object. To address that, I have made a change in the jsfiddle (still being tested) that deals with it in a reasonable way here: http://jsfiddle.net/dimitar/RtBMm/6/ - though calling the function with the scope of the object and w/o parameters may not be ideal, it should cover a large percentage of cases. For any other types, I guess it will do a .toString() anyway.
GitHub flavoured markdown enabled.