-
-
Save nwb/748788 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
var template = function(){ | |
var args = Array.prototype.slice.call(arguments), | |
res = ""; | |
console.log (args.length); | |
if (args.length > 1) { | |
data = args[ args.length - 1 ] | |
for ( var i = 0, l = args.length - 1; i < l; i++ ){ | |
temp = args[i]; | |
if (temp.constructor.toString().indexOf("Array") != -1) { | |
temp[temp.length] = data | |
res += template.apply( this, temp ); | |
} else { | |
res += args[i].replace( /\{{2}([^{]*)\}{2}/g, function(string, parens) { return data[parens]; } ) | |
}; | |
}; | |
return res | |
} else { | |
throw "Need 1 or more template files and one data hash" | |
} | |
} | |
var exampleTemplate = [ | |
"<html>", | |
" <title>{{title}}</title>", | |
" Hi {{name}}, it's {{day}}", | |
"</html>" | |
]; | |
var exampleData = {title: "Some Web Page", name: "Giles", day: "Monday"}; | |
console.log(template( exampleTemplate, exampleData )); | |
console.log(template( "<html>"," <title>{{title}}</title>"," Hi {{name}}, it's {{day}}","</html>", exampleData )); | |
console.log(template( ["<html>"," <title>{{title}}</title>"], " Hi {{name}}, it's {{day}}","</html>", exampleData )); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment