Javascript模板引擎? [英] Javascript templating engines?

查看:103
本文介绍了Javascript模板引擎?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

JavaScript中的模板引擎如何工作?





<我已经开始学习Javascript,并且已经在网上阅读各种不同的文章,有一点我不确定是什么是javascript模板引擎?他们的目的是什么?如果有人可以解释这个会很棒!

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!

谢谢
Kyle

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';

现在你可以编写一个javascript函数来替换 $ 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) );
}

并像这样使用:

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

[编辑]匿名替换者在阅读此博客文章之后,将函数命名为外部函数href =https://stackoverflow.com/users/157247/tj-crowder>众所周知的SO-visitor

[edit] anonymous replacer function to named external function after reading this blog article of a well known SO-visitor

这篇关于Javascript模板引擎?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆