Created
March 31, 2011 11:16
-
-
Save netroy/896192 to your computer and use it in GitHub Desktop.
A small template rendering engine in JS ... uses Function constructor, unfortunately
This file contains hidden or 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
function(b,c){return b.replace(/{[\w\.\(\)]+}/g,function(a){a=a.replace(/[\{\}]/g,"");try{with(c)return eval(a)}catch(b){return""}})}; |
This file contains hidden or 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
goto http://jsfiddle.net/netroy/HA8es/ for a running example using this renderer |
This file contains hidden or 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
// 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 ""; | |
} | |
}); | |
} |
This file contains hidden or 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
// 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 ""; | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Will have to dig more into this. I got the above snippet from Crockford