posts - 7,  comments - 58,  trackbacks - 0

    自编 jtle(javascript template language engine) javascript模板语言引擎, 轻松处理json数据! jtle是个简单的javascript板模解析器,可以轻松操作json数据,基于json数据的ajax应用可以很方便的实现数据显示逻辑!

修改了在firefox下不能正确运行问题!

一、测试例子(testJtle.html)

<html>
<head>
 <script src="jtle.js"></script>
 <script>
   window.onload = function() {
     var menus = new jtle({el:"source"});
      menus.parse({menus:[{url:"http://www.163.com",subject: "163.com"}, {url:"http://www.baidu.com",subject: "百度"}]});
      var books = new jtle({el:"bookList"});
      books.parse({books:[
                        {name:"hibernate实战教程", author:"李永胜", plsh:"李永胜出版社", price: "50.00"},
                        {name:"ajax and jtle文档", author:"李永胜", plsh:"李永胜出版社", price: "0.00"},
                        {name:"spring webflow教程", author:"李永胜", plsh:"李永胜出版社", price: "60.00"},
                        {name:"dwr应用", author:"李永胜", plsh:"李永胜出版社", price: "30.00"}
                       ]});
   };
 </script>
</head>
<body>
  <div id="source">
   <%
      for(var i = 0; i < menus.length; i++) {
        var menu = menus[i];
   %>
   <a href="${menu.url}">${menu.subject}</a>
   <% } %>
 </div>
 <div id="bookList">
   <table width="80%">
     <tr bgcolor="#DEB887"><td>书籍名称</td><td>作者</td><td>出版社</td><td>价格</td></tr>
     <% for(var n = 0; n < books.length; n++) {
          var book = books[n];
          if(n % 2 != 0) {
      %>
      <tr bgcolor="#DCDCDC"><td>${book.name}</td><td>${book.author}</td><td>${book.plsh}</td><td>${book.price}</td></tr>
     <% }else{   %>
       <tr bgcolor="#FFFFE0"><td>${book.name}</td><td>${book.author}</td><td>${book.plsh}</td><td>${book.price}</td></tr>
     <% } }  %>
   </table>
 </div>
</body>
</html>

二、jtle.js 实现代码

  String.prototype.xsplit = function(regex) {
  var item = this; //this指传过来的字符串
  var result = regex.exec(item);
  var retArr = new Array();
  while(result != null){
    var first_idx = result.index;
    if(first_idx != 0) {
      var first_bit = item.substring(0, first_idx);
      retArr.push(first_bit);
    }
    retArr.push(result[0]);
    item = item.slice(first_idx+result[0].length);
    result = regex.exec(item);
  }
  if(item != '' && item != null){
   retArr.push(item);
  }
  return retArr;
 };
 function _toString(val){
   if(val == null || val === undefined){
       return "";
   }
   if(val instanceof Date){
     return val.toDateString();
   }
  if(val.toString) {
     return val.toString();
   }
   return "";
 }
 /*
  * 说明:js脚本模板引擎
  * 作者:lys
  * @param options {el: "elId", _target:"编译后输出容器div id"}
  */
 function jtle(options) {
   this.source = " "; //待编译的模板代码
   this.element; //板模源容器
   this.script = "var _html = \"\";";
   this._htmlVar = "_html += ";
   this.buffer = "";
   this._target = document.getElementById(options._target);
   this.split_source = [];
   this.left_delimiter = "<js>";
   this.right_delimiter = "</js>";
   this.left_writer = "$j{";
   this.right_writer = "}";
   this.startTag = null;
   this.options = options;
    
   this.compile = function() {
     if(this._target == null) {
       alert("请指定输出目标DIV id");
       return;
     }
     if(!this.options || !this.options.el) {
       alert("new jtle(options)参数有误");
       return;
     }
     this.element = document.getElementById(this.options.el);
     if(!this.element) {
       alert("指定的板模源不合法");
       return;
     }
     this.source = this.element.value.toLowerCase();
     this.format();
     this.scan();
   };
   this.parse = function(data) {
     this.compile();
     this.script = "(function(){ with(data) {" + this.script + "} return _html;})();";
     var out = eval(this.script);
     this._target.innerHTML = out;
   };
   this.scan = function() {
     this.split_source = this.source.xsplit(/\n/);
     var len = this.split_source.length;
     for(var i = 0; i < len; i++) {
       var item = this.split_source[i];
       this.scanline(item);
     }
   };
   this.scanline = function(item) {
     var regex = /(<js>)|(<\/js>)|(\$j\{(\w*\.\w*)\})|(\n)/;
     var line_split = item.xsplit(regex);
     var len = line_split.length;
     for(var i = 0; i < len; i++) {
       var token = line_split[i];
        if(token != null) {
        this.appendBuffer(token);
       }
     }
   };
   this.appendBuffer = function(token) {
      if(token) {
       var rst = token;
       if(token.indexOf("$j{") > -1) {
         if(this.buffer != "") {
           this.buffer = this._htmlVar + "\"" + this.clean(this.buffer) + "\";";
           this.fush();
         }
         rst = rst.replace(/(\$j\{)/g, "");
         rst = rst.replace(/\}/g, "");
         this.buffer = this._htmlVar + "_toString(" + rst + ");";
         this.fush();
         return;
       }
      }
      if(this.startTag == null) {
        switch(token) {
        case "\n":
         this.buffer = this.buffer + "\n";
         this.buffer = this._htmlVar + "\"" + this.clean(this.buffer) + "\";";
         this.fush();
         break;
        case this.left_delimiter:
          if(this.buffer != "") {
          this.buffer = this._htmlVar + "\"" + this.clean(this.buffer) + "\";";
          this.fush();
         }
         this.startTag = this.left_delimiter;
         break;
        case this.right_delimiter:
          if(this.buffer != "") {
            this.fush();
          }
          break;
        default:
          this.buffer = token;
         break;
       }
      }else{
        switch(token) {
       case this.right_delimiter:
       case "\n":
         if(this.buffer != "") {
           this.fush();
         }
        break;
       default:
         this.buffer = token;
        break;
       }
       if(token == this.right_delimiter) {
         this.startTag = null;
       }
    }
    
  };  
   this.fush = function() {
     this.script = this.script + this.buffer + "\n";
     this.buffer = "";
   };
   this.format = function() {
     this.source = this.source.replace(/(\r\n)/g, "\n");
     this.source = this.source.replace(/\r/g, "\n");
     this.source = this.source.replace(/(\n\r)/g, "\n");
   };
   this.clean = function(txt) {
     txt = txt.replace(/\n/g, "\\n");
     txt = txt.replace(/"/g,  "\\\"");
     return txt;
   };
  
 }

三、效果图


备注: 当前实现只是初稿,  欢迎讨论交流. 原创文章,如需转载,请注明出处!

posted on 2008-05-25 10:24 Sonny Li 阅读(2267) 评论(4)  编辑  收藏 所属分类: javascript编程语言

FeedBack:
# re: 自编 jtle(javascript template language engine) javascript模板语言引擎, 轻松处理json数据!
2008-05-25 23:29 | 陈小稳
看了下,在需要ajax动态变更数据内容,而数据呈现样式比较复杂的时候比较适用,只是在jsp里面有点冲突了,因为 <% %>是用来包裹java语句的。  回复  更多评论
  
# re: 自编 jtle(javascript template language engine) javascript模板语言引擎, 轻松处理json数据!
2008-05-25 23:43 | 无羽苍鹰
在ajax应用中,个人认为,.jsp文件只写java代码,不包括任何的html和javascript。应用javascript template的地方应该是.html而不是.jsp  回复  更多评论
  
# re: 自编 jtle(javascript template language engine) javascript模板语言引擎, 轻松处理json数据!
2008-05-26 00:16 |
<%%>,$ 等最好要参考标准,最好不要和现在有的标准冲突。。不过8 错,8错。。主要是有这个思想。。  回复  更多评论
  
# re: 自编 jtle(javascript template language engine) javascript模板语言引擎, 轻松处理json数据![未登录]
2012-04-13 17:00 | Sonny Li
离技术越来越远了  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 
<2008年5月>
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

常用链接

留言簿(3)

随笔分类

随笔档案

文章分类

相册

收藏夹

博客好友

搜索

  •  

最新评论

阅读排行榜

评论排行榜