Skip to content

Instantly share code, notes, and snippets.

@nwb
Forked from anonymous/tinystache.js
Created December 20, 2010 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nwb/748788 to your computer and use it in GitHub Desktop.
Save nwb/748788 to your computer and use it in GitHub Desktop.
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