首页 > 代码库 > 迷你template

迷你template

JavaScript Micro-Templating
http://ejohn.org/blog/javascript-micro-templating/


 
//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     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;};})();

You would use it against templates written like this (it doesn’t have to be in this particular manner – but it’s a style that I enjoy):

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

 

You can also inline script:

<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>

 

来个完整的

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">  <meta name="format-detection" content="telephone=no" />   <title>news</title><link rel="stylesheet" type="text/css" href="./css/css.css" media="screen" /></head><body>  <div id="container">  <section class="news layout" id="newsList">    <figure class="clr big-img">      <a href="http://www.baidu.com">        <figcaption>疯狂世界杯,挖财社区邀您High!</figcaption>        <span class="img"><img src="./image/0.jpg" alt="" width="100%"></span>        <span class="time">15分钟前</span>      </a>    </figure>    <figure class="clr small-img hot">      <a href="http://www.baidu.com">        <img src="./image/1.jpg" class="fr mgl15" alt="" width="80">        <figcaption>什么叫拿奖拿到手抽筋,你造吗?</figcaption>        <span class="time">30分钟前</span>      </a>    </figure>    <figure class="clr small-img">      <a href="#">        <img src="./image/2.jpg" class="fr mgl15" alt="" width="80">        <figcaption>问题来了:半年结余了11万存款该怎么用</figcaption>        <span class="time">41分钟前</span>      </a>    </figure>    <figure class="clr">      <a href="#">        <figcaption>版主倾囊相授:行业从业者教你认清保险背后的事情 </figcaption>        <span class="time">1小时前</span>      </a>    </figure>  </section></div><script>// 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        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><script type="text/html" id="big_img">  <figure class="clr big-img [%=(recommend ? "hot" : "")%]">    <a href="[%=url%]">      <figcaption>[%=content%]</figcaption>      <span class="img" data-url="[%=imgSrc%]">点击加载图片</span>      <span class="time">[%=time%]</span>    </a>  </figure></script><script type="text/html" id="small_img">  <figure class="clr small-img [%=(recommend ? "hot" : "")%]">    <a href="[%=url%]">      <img src="[%=imgSrc%]" class="fr mgl15" alt="" width="80" height="60">      <figcaption>[%=content%]</figcaption>      <span class="time">[%=time%]</span>    </a>  </figure></script><script type="text/html" id="no_img">  <figure class="clr [%=(recommend ? "hot" : "")%]">    <a href="[%=url%]">      <figcaption>[%=content%]</figcaption>      <span class="time">[%=time%]</span>    </a>  </figure></script><script>var list = [{    recommend: 1,    content: "我来测试测试",    url: "http://www.baidu.com",    imgSrc: "http://h.hiphotos.baidu.com/image/pic/item/b17eca8065380cd7ce039fe4a344ad345982819d.jpg",    time: "15分钟前"  }, {    recommend: 0,    content: "我来测试测试",    url: "http://www.baidu.com",    imgSrc: "http://h.hiphotos.baidu.com/image/pic/item/b17eca8065380cd7ce039fe4a344ad345982819d.jpg",    time: "20分钟前"  }];var oDiv = document.getElementById("newsList"),  len = list.length,  i = 0,  html = "";for(; i < len; i++) {  html += tmpl("small_img", list[i]);}oDiv.innerHTML = html;</script></body></html>