最简单的JS模版引擎

出于某些原因,比方说学习JS模版引擎的工作原理,相信下边来自 John Resig 的一个JS function能帮助到我们。

// Simple JavaScript Templating
// John Resig - https://johnresig.com/ - MIT Licensed
(function(){
  var cache = {};

  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :

      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +

        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +

        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");

    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();

使用起来也就三步走。

第一步,将上边的代码粘贴到JS作用域最开始部分。
第二步,随便写一个模版。

<script id="hello_template">
  <h2><%=message%></h2>
  <ul>
    <% for(var userIndex in users) { %>
      <li>#<%=users[userIndex]._id%>: <%=users[userIndex].name%></li>
    <% } %>
  </ul>
</script>

第三布,按照格式 tmpl(TEMPLATE_HTML_ID | TEMPLATE_HTML_TEXT, INPUT_DATA) 调用模版。

TEMPLATE_HTML_TEXT 工作方式

var html = tmpl('<h1><%=message%></h1>', {message: 'hello'});

console.log(html);

TEMPLATE_HTML_ID 工作方式

var html = tmpl('hello_template', {
 message: 'hello, world.',
  users: [
    {_id: 0, name: 'robin'},
    {_id: 1, name: 'alex'}
  ]
});

console.log(html);

慢慢领悟,很有意思。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值