JS模版

jQuery的JS模版 http://plugins.jquery.com/node/3694

 

John Resig的JS模版
http://ejohn.org/blog/javascript-micro-templating/#postcomment

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="http://ejohn.org/blog/javascript-micro-templating/">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
  <script>
function init()
{
 // Simple JavaScript Templating
 // John Resig - http://ejohn.org/ - 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 把模版转换成JS代码
   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 提供给用户基本的
  alert(fn)
  return data ? fn( data ) : fn;
   };
 })();

 var results = document.getElementById("results");
 var dataObject = {i:4,profile_image_url:'http://www.baidu.com/img/baidu_logo.gif',from_user:'xx',id:9,text:'hello'};
 results.innerHTML = tmpl("item_tmpl", dataObject);
}
  </script>

<script type="text/html" id="item_tmpl">
  <div id="<%=id%>" class="? 1 == 2 % <%=(i" even" : "")%>">
    <div class="right alpha grid_1">
      <img class="righted" src="<%=profile_image_url%>"/>
    </div>
    <div class="contents omega grid_6">
      <p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p>
    </div>
  </div>
</script>

</HEAD>
 <BODY onload="init()">
 <form>
  <div id='results'></div>
   </form>
 </BODY>
</HTML>

posted @ 2010-02-23 11:04  xjy  阅读(272)  评论(0编辑  收藏  举报