开发者

Javascript templating engines? [duplicate]

This question already has answers here: C开发者_如何学运维losed 10 years ago.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜