Created
November 14, 2012 20:17
-
-
Save 2bbb/4074491 to your computer and use it in GitHub Desktop.
JavaScript Template Test
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 defaultNeedle = new RegExp(/__(.+?)__/g); | |
return function(template, obj, needle) { | |
needle = needle || defaultNeedle; | |
var evalString = '"' + template.replace(needle, "\"+obj.$1+\"") + '"'; | |
if(obj["length"] && obj["push"]) { | |
var src = obj, dst = []; | |
for(var i = 0; i < src.length; i++) { | |
obj = src[i]; | |
dst.push(eval(evalString)); | |
} | |
return dst; | |
} else { | |
return eval(evalString); | |
} | |
} | |
}()); | |
dom = "<div><h1>__title__</h1><h2>__subtitle__</h2></div>"; | |
res = template( | |
dom, | |
[ | |
{ | |
title : "Demo", | |
subtitle : "Sub Title 1" | |
},{ | |
title : "Demo", | |
subtitle : "Sub Title 2" | |
} | |
] | |
); | |
console.log(res); | |
res = template(dom, { | |
title : "bar", | |
subtitle : "st" | |
} | |
); | |
console.log(res); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment