Last active
August 30, 2016 05:59
-
-
Save talbergs/e2ce00ea06eaaa6e94bddbcf36b57158 to your computer and use it in GitHub Desktop.
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
String.prototype.template = function(obj) { | |
// dot notation path getter for array and obj | |
function objPath(obj, path){ | |
var arr = path.split('.'); | |
while (arr.length && obj) { | |
obj = obj[arr.shift()] | |
if(obj === undefined) return '{undefined '+path+'}'; | |
} | |
return ~[Number, String].indexOf(obj.constructor) ? obj : JSON.stringify(obj); | |
} | |
// parser | |
var outstr = '', | |
start = -1, | |
end = 0; | |
while((end = this.indexOf('{', ++start)) > -1) { | |
outstr += this.slice(start, end); | |
start = end; | |
if ((end = this.indexOf('}', start)) > -1) { | |
outstr += objPath(obj, this.slice(start + 1, end)); | |
start = end; | |
} | |
} | |
return outstr + this.slice(start); | |
} | |
fill = {a:{b:{c:'y'},a:['x', 0, 2]}} | |
'<div> {not} {a.not} </div> {a.b} <p> {a.b.c} Today at: {a.a.1} </p> {a.a.0}'.template(fill) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment