js模板引擎template.js的使用

js模板引擎template.js的使用

template.js源码

/*!art-template - Template Engine | http://aui.github.com/artTemplate/*/
!function(){function a(a){return a.replace(t,"").replace(u,",").replace(v,"").replace(w,"").replace(x,"").split(y)}function b(a){return"'"+a.replace(/('|\\)/g,"\\$1").replace(/\r/g,"\\r").replace(/\n/g,"\\n")+"'"}function c(c,d){function e(a){return m+=a.split(/\n/).length-1,k&&(a=a.replace(/\s+/g," ").replace(//g,"")),a&&(a=s[1]+b(a)+s[2]+"\n"),a}function f(b){var c=m;if(j?b=j(b,d):g&&(b=b.replace(/\n/g,function(){return m++,"$line="+m+";"})),0===b.indexOf("=")){var e=l&&!/^=[=#]/.test(b);if(b=b.replace(/^=[=#]?|[\s;]*$/g,""),e){var f=b.replace(/\s*\([^\)]+\)/,"");n[f]||/^(include|print)$/.test(f)||(b="$escape("+b+")")}else b="$string("+b+")";b=s[1]+b+s[2]}return g&&(b="$line="+c+";"+b),r(a(b),function(a){if(a&&!p[a]){var b;b="print"===a?u:"include"===a?v:n[a]?"$utils."+a:o[a]?"$helpers."+a:"$data."+a,w+=a+"="+b+",",p[a]=!0}}),b+"\n"}var g=d.debug,h=d.openTag,i=d.closeTag,j=d.parser,k=d.compress,l=d.escape,m=1,p={$data:1,$filename:1,$utils:1,$helpers:1,$out:1,$line:1},q="".trim,s=q?["$out='';","$out+=",";","$out"]:["$out=[];","$out.push(",");","$out.join('')"],t=q?"$out+=text;return $out;":"$out.push(text);",u="function(){var text=''.concat.apply('',arguments);"+t+"}",v="function(filename,data){data=data||$data;var text=$utils.$include(filename,data,$filename);"+t+"}",w="'use strict';var $utils=this,$helpers=$utils.$helpers,"+(g?"$line=0,":""),x=s[0],y="return new String("+s[3]+");";r(c.split(h),function(a){a=a.split(i);var b=a[0],c=a[1];1===a.length?x+=e(b):(x+=f(b),c&&(x+=e(c)))});var z=w+x+y;g&&(z="try{"+z+"}catch(e){throw {filename:$filename,name:'Render Error',message:e.message,line:$line,source:"+b(c)+".split(/\\n/)[$line-1].replace(/^\\s+/,'')};}");try{var A=new Function("$data","$filename",z);return A.prototype=n,A}catch(B){throw B.temp="function anonymous($data,$filename) {"+z+"}",B}}var d=function(a,b){return"string"==typeof b?q(b,{filename:a}):g(a,b)};d.version="3.0.0",d.config=function(a,b){e[a]=b};var e=d.defaults={openTag:"<%",closeTag:"%>",escape:!0,cache:!0,compress:!1,parser:null},f=d.cache={};d.render=function(a,b){return q(a,b)};var g=d.renderFile=function(a,b){var c=d.get(a)||p({filename:a,name:"Render Error",message:"Template not found"});return b?c(b):c};d.get=function(a){var b;if(f[a])b=f[a];else if("object"==typeof document){var c=document.getElementById(a);if(c){var d=(c.value||c.innerHTML).replace(/^\s*|\s*$/g,"");b=q(d,{filename:a})}}return b};var h=function(a,b){return"string"!=typeof a&&(b=typeof a,"number"===b?a+="":a="function"===b?h(a.call(a)):""),a},i={"<":"<",">":">",'"':""","'":"'","&":"&"},j=function(a){return i[a]},k=function(a){return h(a).replace(/&(?![\w#]+;)|[<>"']/g,j)},l=Array.isArray||function(a){return"[object Array]"==={}.toString.call(a)},m=function(a,b){var c,d;if(l(a))for(c=0,d=a.length;d>c;c++)b.call(a,a[c],c,a);else for(c in a)b.call(a,a[c],c)},n=d.utils={$helpers:{},$include:g,$string:h,$escape:k,$each:m};d.helper=function(a,b){o[a]=b};var o=d.helpers=n.$helpers;d.onerror=function(a){var b="Template Error\n\n";for(var c in a)b+="<"+c+">\n"+a[c]+"\n\n";"object"==typeof console&&console.error(b)};var p=function(a){return d.onerror(a),function(){return"{Template Error}"}},q=d.compile=function(a,b){function d(c){try{return new i(c,h)+""}catch(d){return b.debug?p(d)():(b.debug=!0,q(a,b)(c))}}b=b||{};for(var g in e)void 0===b[g]&&(b[g]=e[g]);var h=b.filename;try{var i=c(a,b)}catch(j){return j.filename=h||"anonymous",j.name="Syntax Error",p(j)}return d.prototype=i.prototype,d.toString=function(){return i.toString()},h&&b.cache&&(f[h]=d),d},r=n.$each,s="break,case,catch,continue,debugger,default,delete,do,else,false,finally,for,function,if,in,instanceof,new,null,return,switch,this,throw,true,try,typeof,var,void,while,with,abstract,boolean,byte,char,class,const,double,enum,export,extends,final,float,goto,implements,import,int,interface,long,native,package,private,protected,public,short,static,super,synchronized,throws,transient,volatile,arguments,let,yield,undefined",t=/\/\*[\w\W]*?\*\/|\/\/[^\n]*\n|\/\/[^\n]*$|"(?:[^"\\]|\\[\w\W])*"|'(?:[^'\\]|\\[\w\W])*'|\s*\.\s*[$\w\.]+/g,u=/[^\w$]+/g,v=new RegExp(["\\b"+s.replace(/,/g,"\\b|\\b")+"\\b"].join("|"),"g"),w=/^\d[^,]*|,\d[^,]*/g,x=/^,+|,+$/g,y=/^$|,+/;e.openTag="{{",e.closeTag="}}";var z=function(a,b){var c=b.split(":"),d=c.shift(),e=c.join(":")||"";return e&&(e=", "+e),"$helpers."+d+"("+a+e+")"};e.parser=function(a){a=a.replace(/^\s/,"");var b=a.split(" "),c=b.shift(),e=b.join(" ");switch(c){case"if":a="if("+e+"){";break;case"else":b="if"===b.shift()?" if("+b.join(" ")+")":"",a="}else"+b+"{";break;case"/if":a="}";break;case"each":var f=b[0]||"$data",g=b[1]||"as",h=b[2]||"$value",i=b[3]||"$index",j=h+","+i;"as"!==g&&(f="[]"),a="$each("+f+",function("+j+"){";break;case"/each":a="});";break;case"echo":a="print("+e+");";break;case"print":case"include":a=c+"("+b.join(",")+");";break;default:if(/^\s*\|\s*[\w\$]/.test(e)){var k=!0;0===a.indexOf("#")&&(a=a.substr(1),k=!1);for(var l=0,m=a.split("|"),n=m.length,o=m[l++];n>l;l++)o=z(o,m[l]);a=(k?"=":"=#")+o}else a=d.helpers[c]?"=#"+c+"("+b.join(",")+");":"="+a}return a},"function"==typeof define?define(function(){return d}):"undefined"!=typeof exports?module.exports=d:this.template=d}();

使用方法

html代码

  <table class="table table-hover table-striped table-bordered">
                            <thead>
                            <tr>
                                <th style="text-align: center; vertical-align: middle;">父订单号th>
                                <th style="text-align: center; vertical-align: middle; ">订单状态th>
                                <th style="text-align: center; vertical-align: middle; ">订单编号th>
                                <th style="text-align: center; vertical-align: middle; ">物流状态th>
                                <th style="text-align: center; vertical-align: middle; ">订单确认状态th>
                                <th style="text-align: center; vertical-align: middle; ">订单类型th>
                                <th style="text-align: center; vertical-align: middle; ">商品总金额th>
                                <th style="text-align: center; vertical-align: middle; ">未含税金额th>
                                <th style="text-align: center; vertical-align: middle; ">订单税额th>
                                <th style="text-align: center; vertical-align: middle; ">运费th>
                                <th style="text-align: center; vertical-align: middle; ">订单创建时间th>
                                <th style="text-align: center; vertical-align: middle; ">订单完成时间th>
                            tr>
                            thead>
                            <tbody id="OrderInfo">
                               
                         
                            tbody>
                        table>
                        <div class="page" style="display:none;">
            			div>

js代码


 <script id="datatmpl" type="text/html">
            {{each list as item  index }}
            <tr>
               {{if item.parentType==1}}
                <td style='text - align: center; vertical - align: middle;'> {{ item.parentJdOrderId }} </td>
                {{/if}}
                <td style='text - align: center; vertical - align: middle;'> {{ item.parentJdOrderId }} </td>
                <td style='text - align: center; vertical - align: middle;'> {{ item.orderState }} </td>
                <td style='text - align: center; vertical - align: middle;'> {{ item.jdOrderId }} </td>
                <td style='text - align: center; vertical - align: middle;'> {{ item.orderState..deliveryState }} </td>
                <td style='text - align: center; vertical - align: middle;'> {{ item.orderState.confirmState }} </td>
                <td style='text - align: center; vertical - align: middle;'> {{ item.orderType }} </td>
                <td style='text - align: center; vertical - align: middle;'> {{ item.orderPrice.orderTotalPrice }} </td>
                <td style='text - align: center; vertical - align: middle;'> {{ item.orderPrice.orderNakedPrice }} </td>
                <td style='text - align: center; vertical - align: middle;'> {{ item.orderPrice.orderTaxPrice }} </td>
                <td style='text - align: center; vertical - align: middle;'> {{ item.orderPrice.orderTotalFreight }} </td>
                <td style='text - align: center; vertical - align: middle;'> {{ item.orderPrice.orderCreateTime }} </td>
                <td style='text - align: center; vertical - align: middle;'> {{ item.orderPrice.orderFinishTime }} </td>
            </tr>
            {{/each}} 
             
 </script>
<script id="datatmp2" type="text/html">

</script>
 <script>
			 $.ajax({
                type: "Post",
                url: dataurl,
                data: urldata,
                dataType: "json",
                success: function (datas) {
                    if (datas && datas.code == 0) {
                        $("#OrderInfo").html(template('datatmpl', datas.data));
                        //OrderInfo是容器ID
                        //datatmpl是模板ID
                        //datas.data是对象数组
                         }
                }, error: function () {
                }
            });

		  $.ajax({
                type: "get",
                url: dataurl,
                data: pdata,
                dataType: "json",
                success: function (data) {
                    try {
                        loading.close();
                    } catch (e) { }
                    if (data.code == -1) {
                        ShowMsg(data.msg, false);
                    }
                    else {
                        $(".page").show();
                        var order = JSON.parse(data.msg);
                        orderdata = order;
                        $(".page").html(template('datatmp2', order));
							//order是一个对象
                        var detailaddress = order.ShippingRegion + "," + order.Address;

                        //加载完成后,验证地址参数
                        getaddress(detailaddress, order.Address);
                    }
                },
                error: function () {
                    try {
                        loading.close();
                    } catch (e) { }
                }
            });
 </script>

拓展用法

<script id="datatmp3" type="text/html">
{{if isAdmin}} 
<h1>{{title}}</h1> 
<ul> 
 {{each list as value i}} 
  <li>索引 {{i + 1}}{{value}}</li> 
 {{/each}} 
</ul> 

</script>

<script>
var data = { 
 title: '基本例子', 
 isAdmin: true, 
 list: ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他'] 
}; 
 $(".page").html(template('datatmp3', data));


//模板中使用函数
 template.helper("totime", function (timestamp) {
                    var date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
                    Y = date.getFullYear() + '-';
                    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
                    D = date.getDate() + ' ';
                    h = date.getHours() + ':';
                    m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':';
                    s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
                    return Y + M + D + h + m + s;
                });

//使用方法
   <label>{{item.msgTime | totime}}</label>



 </script>

你可能感兴趣的:(javascript,html,前端)