Skip to content

Instantly share code, notes, and snippets.

@2bbb
Created November 14, 2012 20:17
Show Gist options
  • Save 2bbb/4074491 to your computer and use it in GitHub Desktop.
Save 2bbb/4074491 to your computer and use it in GitHub Desktop.
JavaScript Template Test
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