Skip to content

Instantly share code, notes, and snippets.

@netroy
Created March 31, 2011 11:16
Show Gist options
  • Save netroy/896192 to your computer and use it in GitHub Desktop.
Save netroy/896192 to your computer and use it in GitHub Desktop.
A small template rendering engine in JS ... uses Function constructor, unfortunately
function(b,c){return b.replace(/{[\w\.\(\)]+}/g,function(a){a=a.replace(/[\{\}]/g,"");try{with(c)return eval(a)}catch(b){return""}})};
goto http://jsfiddle.net/netroy/HA8es/ for a running example using this renderer
// Similar to the older version, without eval & with (sort-of)
function render(template, data) {
return template.replace(/\{[\w\.\-\(\)]+\}/g, function(match){
var token = match.replace(/[\{\}]/g,"");
try {
return (new Function("data", "return data." + token))(data);
} catch(e) {
return "";
}
});
}
// templates support object & function ... like "{abcd}" or "xyz.pqr" or "GL.package.class.init(arguments.toString())"
// data is an object with values that would be used for rendering .... like {abcd:"something",xyz:{pqr:123},arguments:[]}
function render(template, data){
return template.replace(/{[\w\.\-\(\)]+}/g, function(match){
var token = match.replace(/[\{\}]/g,"");
try {
with(data) {
return eval(token);
}
} catch(e) {
return "";
}
});
}
@netroy
Copy link
Author

netroy commented Oct 30, 2011

As of ES5, eval executes in a private scope, so its okay to use it if needed.
More important thing to remove is the with statement, but without that, i haven't figured out how to have function calls in templates.
for just namespaced objects, with can be replaced by a eval("data."+token)

@jaseemabid
Copy link

Will have to dig more into this. I got the above snippet from Crockford

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment