设为首页收藏本站

Scripts 学盟

 找回密码
 加入学盟

QQ登录

只需一步,快速开始

查看: 1528|回复: 0

像ASP一样的javascript模板函数 [复制链接]

管理员

超级大菜鸟

Rank: 9Rank: 9Rank: 9

混混@普宁.中国 实名认证  发表于 2012-6-27 23:07:56 |显示全部楼层
  1. <script id="myTmpl" type="text/tmpl">
  2. <% for (var i=0; i<10; i++) { %>
  3.         <ul>
  4.                 <li class="li1"><span><%=name%></span></li>
  5.                 <li>电话:<%=tel%></li>
  6.                 <li>QQ:<a target="_blank" href="http://<%=qq%>.qzone.qq.com/"><%=qq%></a></li>
  7.                 <li><%=addr%></li>
  8.         </ul>
  9. <% } %>
  10. </script>

  11. <script type="text/javascript">
  12. var context = {
  13.           "qq"  : '78423497'
  14.         , "addr": '中国·普宁'
  15.         , "name": '混混'
  16.         , "tel" : '186812345678'
  17. };

  18. var html = tmpl(document.getElementById('myTmpl').text, context);
  19. document.write(html);
  20. </script>
复制代码
上面是一个使用例子。 看到那模板了么,写过 asp 的人一定不会陌生。

呵呵, 这是如何实现的呢, tmpl 是怎样一个函数呢
  1. !function() {
  2.         var cache = {};
  3.         window.tmpl = function(strTmpl, args) {
  4.                 var __argNames = [];
  5.                 var __argValues = [];
  6.                 for (var a in args) {
  7.                         __argNames.push(a);
  8.                         __argValues.push(args[a]);
  9.                 }
  10.                 var funcs = cache[strTmpl] || function() {
  11.                         var f = [ 'var __out__ = [];' ];
  12.                         strTmpl.replace(/<%=([\d\D]*?)%>|<%([\d\D]*?)%>|([\d\D]+?)(?=<\%|$)/g, function($0, $1, $2,

  13. $3) {
  14.                                 if ($3) {
  15.                                         f.push('__out__.push(unescape("', escape($3), '"));');
  16.                                 } else if ($1) {
  17.                                         f.push('__out__.push(', $1, ');');
  18.                                 } else if ($2) {
  19.                                         f.push($2, ';');
  20.                                 }
  21.                         });
  22.                         f.push('return __out__.join("")');
  23.                         return new Function(__argNames.join(', '), f.join(''));
  24.                 }();
  25.                 cache[strTmpl] = funcs;
  26.                 return funcs.apply(args||{}, __argValues);
  27.         };
  28. }();
复制代码
您需要登录后才可以回帖 登录 | 加入学盟

手机版|Scripts 学盟   |

GMT+8, 2024-3-29 01:06 , Processed in 1.107699 second(s), 14 queries .

Powered by Discuz! X2

© 2001-2011 Comsenz Inc.

回顶部