Possible Duplicate:
How do templating engines in JavaScript work?
I've started learning Javascript and have been reading various different articles on the web, one thing I'm not really sure of is what are javascript templating engines? and what are their purposes? If someone could explain this that would be great!
Thanks Kyle
There are different kinds of templating. Basically the idea is to have some string containing placeholders for values as input, and use some function to replace those placeholders with real values. Like:
var str = 'Hello $1';
Now you could write a javascript function to replace $1
:
function printFromTemplate(){
var args = Array.prototype.slice.call(arguments),
str = args[0],
repl = args.slice(1);
function replacer(a){
var aa = parseInt(a.substr(1),10)-1;
return repl[aa];
}
return str.replace(/(\$\d+)/g,replacer) );
}
and use it like this:
printFromTemplate(str,'world'); //=> Hello world
printFromTemplate('Hello $1, it\'s a really $2 day today','world','sunny');
//|=> Hello world, it's a really sunny day today
[edit] anonymous replacer function to named external function after reading this blog article of a well known SO-visitor
精彩评论