论坛首页 入门技术论坛

在前端开发中应用JS模板引擎 -- 事半功倍!

浏览 25056 次
精华帖 (0) :: 良好帖 (6) :: 新手帖 (7) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-08-18   最后修改:2010-08-24
我们在使用JavaScript进行前端开发的时候,做的最多的事情,除了dealing with dom以外,就是围绕json数据的操作了。而数据操作最麻烦的就是用json生成dom对象了,通常我们会写一堆for, switch, if之类的代码来支持data向view的转化, 这样的代码一般会像:

var data = [{name: ‘Claire’, sex: ‘female’, age: 18, flag: true},
   {name: ‘Mark’, sex: ‘male’, age: 25, flag: true},
   {name: ‘Dennis’, sex: ‘male’, age: 32, flag: false},
   {name: ‘Tracy’, sex: ‘female’, age: 23, flag: true},
   {name: ‘Wane’, sex: ‘male’, age: 18, flag: true}],    
    html = [‘<ul>’], item; 
 
for (var i = 0, l = data.length; i < l; i++) { 
   item = data[i]; 
   if (item.flag) {
      html.push(‘<li>’);
      switch (item.sex) {
        case ‘male’:
          html.push(‘<span style=”color: blue”>’);
          break;
        case ‘female’:
        default:
           html.push(‘<span style=”color: red”>’);
           break;
      }
      html.push(‘name: ‘ + item.name + ‘,  age: ‘ + item.age);
      html.push(‘</span></li>’);
   }
} 
html = html.push(‘</ul>’).join(‘’); 


最终生成的html如下:
<ul> 
 <li><span color=”red”>name: Claire,  age: 18</span></li> 
 <li><span color=”blue”>name: Mark,  age: 25</span></li> 
 <li><span color=”red”>name: Tracy,  age: 23</span></li> 
 <li><span color=”blue”>name: Wane,  age: 18</span></li> 
</ul> 

这样做,随着数据结构越来越复杂很快你就会发现代码越来越臃肿,而且html完全嵌入代码,几乎不可维护。实际上,将展现逻辑同数据分开在服务器端脚本中是很容易的事情,因为服务器端脚本一般都支持模板技术。相信大家对<% %>之类的标记已经熟悉到烦了。模板语言的好处是能用一种灵活、易扩展的方式来将展现标记(如 html)、数据(如json)和控制代码(如javascript)解耦。
现在也有不少浏览器端用javascript实现的模板引擎,如extjs的xtemplate,,jTemplate,TrimPath等。实现的思路都一样:将一段定义好的模板代码(像 <% do something %>之类的)compile为js代码;然后将json data作为这段js代码的输入,最终产生一段需要的文本(如html)。

我在项目里使用过不少js模板引擎,下面列一下他们的优缺点,其中会用到两个性能指标,compile speed(从一段模板代码生成js代码的速度) 和 apply speed(应用json data产生最终输出文本的速度)



Extjs:

Xtemplate是extjs的基础组件,extjs中不少控件都是靠xtemplate来生成html。当然,就为了用个模板引擎就把1m多的extjs include进来显然不是什么明智之举。所以我用的时候将其剥离了出来,大概也就10k吧。这个引擎的使用感觉是速度快,小,语法简单,没什么学习曲线。但是在模板语句中很难调用外部代码,难以扩展,而且,每compile一次都得n次eval,一不小心就会造成内存泄露。

Compile speed: 中等    apply speed:快



jTemplate:

这是一个开源的小程序,目前版本1.1(好像1.1很久了),32k。定义了一套完整的模板语法,然而这也正是问题所在,要想用这个程序还必须学一套没什么大用的语法。分析了它的代码后我发现它并没有什么compile过程,大部分工作都放到apply data阶段了,导致它转换数据的速度很慢。

Compile speed: 快      apply speed: 慢



TrimPath template:

Trimpath本来是一个js框架,也和extjs一样基于一个模板引擎,只不过作者直接将模板引擎拿出来作为了一个可以单独调用的组件,20k左右。有一套简单的语法,功能一般,性能也不突出。

Compile speed: 慢     apply speed: 中等



把这几个引擎都用了一遍以后,感觉都不太顺手,不过也总结出了一个优秀的模板引擎应该具有的特点:

1.     使用javascript的流程控制语句,并做适当增强

2.     在模板代码中可自由引用任何global对象,模板代码中的scope(即this对象)可任意扩展

3.     性能优良(compile speed和apply speed)



于是<script type="text/javascript" src="http://www.iteye.com/javascripts/tinymce/themes/advanced/langs/zh.js"></script><script type="text/javascript" src="http://www.iteye.com/javascripts/tinymce/plugins/javaeye/langs/zh.js"></script>,按照这三条标准,我自己写了一个很轻量的模板引擎,使用这个引擎,上面那段替换代码就可以换成:


var html = (new Sweet('<ul><[foreach($data as people) { if (people.flag) {]>'
+ '<li>'
+ '<span style=”color: <[=people.sex == "female" ? "red" : "blue"]>”>'
+ 'name: <[=name]>, age: <[=age]>'
+ '</li>'
+ '<[}}]></ul>')).applyData(data);


附件是带jquery插件的代码,欢迎下载试用~
开源地址:
http://code.google.com/p/sweet-template/

应几位朋友的要求,放两个测试文件。
详细介绍请到:
开源地址:
http://code.google.com/p/sweet-template/

   发表时间:2010-08-18  
这个插件很好,不知道是否有性能测试数据?
1 请登录后投票
   发表时间:2010-08-18  
这是compile和apply一段数据1000次的测试数据


  • 大小: 21.8 KB
1 请登录后投票
   发表时间:2010-08-18  
对了,第一个名叫Sweet的就是我的引擎,名字是取
Simple WEb front-End Template 中的大写字母。。。
1 请登录后投票
   发表时间:2010-08-18  
不错,这个可能用得上
0 请登录后投票
   发表时间:2010-08-19  
贴一段jquery作者写的,非常的简洁
(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;
  };
})();

<script type="text/html" id="user_tmpl">
  <% for ( var i = 0; i < users.length; i++ ) { %>
    <li><a href="<%=users[i].url%>"><%=users[i].name%></a></li>
  <% } %>
</script>

var results = document.getElementById("results");
results.innerHTML = tmpl("item_tmpl", dataObject);

1 请登录后投票
   发表时间:2010-08-19  
呵呵。有点意思啊。
0 请登录后投票
   发表时间:2010-08-19  
嗯,John Resig 写的这段代码我也是后来才看到的,确实非常简洁,而一般的应用也足够了,但是用到较复杂的上下文中可能就不够用了
ps: 俺的代码其实也很简洁,
请查看http://code.google.com/p/sweet-template/,里面有详细文档

tapestry1122 写道
贴一段jquery作者写的,非常的简洁
(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;
  };
})();

<script type="text/html" id="user_tmpl">
  <% for ( var i = 0; i < users.length; i++ ) { %>
    <li><a href="<%=users[i].url%>"><%=users[i].name%></a></li>
  <% } %>
</script>

var results = document.getElementById("results");
results.innerHTML = tmpl("item_tmpl", dataObject);


0 请登录后投票
   发表时间:2010-08-19  
这个可以研究,提高效率。哈哈啊
0 请登录后投票
   发表时间:2010-08-20  
不错。可以看看。
0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics