道框架(framework)那么必須要提到smarty模板,在面試時你可以不會任何的框架,但是如果不會smarty模板,那么面試官會認為你在說謊,因為幾乎所有的框架都是基于或借鑒smarty。
smarty模板介紹
基于面向對象編程思想封裝的類,實現前后臺代碼分離,降低耦合度,并且為后續的分工合作開發做準備。Smarty(輕量,微小)是編譯性模板框架,體積小、速度快,支持緩存、全局站點配置等功能,是“旅行居家”開發必備神器!
使用步驟
1、在官網www.smarty.net 下載最新版,解壓,復制libs文件夾到項目目錄;
2、在對應的項目目錄下創建4個文件夾分別為模板文件夾(保存前臺頁面,必須,一般命名為templates)、編譯(自動整理前后臺頁面,從第二次訪問開始不需要重新重新整合,一般命名為templates_c,compile必須)、配置文件夾(應用于整個站點的配置)、緩存文件夾
3、測試
新建一個后臺頁面index.php
<?php
//引入核心類庫文件
include_once('libs/Smarty.class.php');
//實例化類
$smarty=new Smarty();
//定義配置
//用戶訪問的后臺頁面所有的路徑都是應該以訪問后臺頁面作為參照物!!!
$smarty->setTemplateDir('templates');//定義模板路徑
//定義編譯路徑
$smarty->setCompileDir('templates_c');
//定義配置文件路徑
$smarty->setConfigDir('config');
//定義緩存路徑
$smarty->setCacheDir('cache');
//修改默認定界符避免和JS沖突?。。?/p>
$smarty->left_delimiter='<{';
$smarty->right_delimiter='}>';
$test='我是test變量';
$smarty->assign("test",$test);//建議注冊的變量名和鍵保持一致
//注冊一個索引數組
$smarty->assign("arr1",array('a','b','c'));
//注冊一個引用數組,section無法用于引用數組
$smarty->assign("arr2",array("a"=>1,"b"=>2,"c"=>3));
//開啟調測
//$smarty->debugging=true;
//自動整理前后臺頁面
$smarty->display('index.tpl');
$smarty->assign('test1','test1');//這個變量無法使用,想一想為什么?
?>
在templates文件加新建index.tpl文件
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
</head>
<body>
我是網站根目錄下index.php的前臺index.tpl頁面<br />
輸出后臺變量test的值:<font color="red" style="font-weight:bold;"><{$test}></font>XXXX<br />
該變量無法輸出:<{$test1}><br />
遍歷輸出索引數組:
<{section name=i loop=$arr1}>
索引:<{$smarty.section.i.index}>值:<{$arr1[i]}>
<{sectionelse}>
沒有符合的記錄
<{/section}>
<br />
遍歷引用數組(用foeach,foreach也可以用于索引數組):
<{foreach from=$arr2 item=v key=k}>
鍵:<{$k}>值:<{$v}>
<{foreachelse}>
沒有符合的記錄集
<{/foreach}>
<br />
新版本寫法:
<{foreach $arr2 as $k=>$v}>
鍵:<{$k}>值:<{$v}>
<{/foreach}>
</body>
</html>
訪問后臺頁面?。。。。y試結果
變量解析
后臺注冊,語法 $smarty對象->assign(‘鍵’,mixed 值);
前臺在需要的位置顯示,語法 {$鍵}
開啟調測
$smarty->debugging=true;
編譯原理
smarty模板調用display函數自動整合前后臺頁面,是從templates文件夾下查找前臺地址自動把訪問的后臺php頁面和該前臺頁面替換成內嵌PHP代碼,生成編譯文件,文件名XXX.前臺模板名.tpl.php,第二次訪問自動把這個頁面相應給用戶,加快速度,只要PHP后臺代碼不改變,這個編譯頁面就不會再次生成。
篇文章主要介紹了JavaScript模板引擎原理與用法,結合實例形式詳細分析了javascript模版引擎相關概念、原理、定義及使用方法,寫的十分的全面細致,具有一定的參考價值,對此有需要的朋友可以參考學習下。如有不足之處,歡迎批評指正。
一、前言
什么是模板引擎,說的簡單點,就是一個字符串中有幾個變量待定。比如:
var tpl='Hei, my name is <%name%>, and I\'m <%age%> years old.';
通過模板引擎函數把數據塞進去,
var data={ "name": "Barret Lee", "age": "20" }; var result=tplEngine(tpl, data); //Hei, my name is Barret Lee, and I'm 20 years old.
那這玩意兒有什么作用呢?其實他就是一個預處理器(preprocessor),搞php開發的童鞋對Smarty必然是十分熟悉,Smarty是一個php模板引擎,tpl中待處理的字符通過數據匹配然后輸出相應的html代碼,加之比較給力的緩存技術,其速度和易用性是非常給力的!JS Template也是一樣的,我們的數據庫里保存著數以千萬計的數據,而每一條數據都是通過同一種方式輸入,就拿上面的例子來說,我們不可能在數據庫里存幾千條"Hei, my name...",而是只保存對應的name和age,通過模板輸出結果。
JS模板引擎應該做哪些事情?看看下面一串代碼:
var tpl='<% for(var i=0; i < this.posts.length; i++) {' + 'var post=posts[i]; %>' + '<% if(!post.expert){ %>' + '<span>post is null</span>' + '<% } else { %>' + '<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><% post.expert %> at <% post.time %></a>' + '<% } %>' +
一個基本的模板引擎至少可以保證上面的代碼可以正常解析。如送入的數據是:
var data={ "posts": [{ "expert": "content 1", "time": "yesterday" },{ "expert": "content 2", "time": "today" },{ "expert": "content 3", "time": "tomorrow" },{ "expert": "", "time": "eee" }] };
可以輸出
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >content 1 at yesterday</a> <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >content 2 at today</a> <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >content 3 at tomorrow</a> <span>post is null</span>
下面就具體說說這個模板引擎的原理是啥樣的。
二、JS模板引擎的實現原理
1.正則摳出要匹配的內容 針對這一串代碼,通過正則獲取內容
var tpl='Hei, my name is <%name%>, and I\'m <%age%> years old.'; var data={ "name": "Barret Lee", "age": "20" };
最簡單的方式就是通過replace函數了:
var result=tpl.replace(/<%([^%>]+)?%>/g, function(s0, s1){ return data[s1]; });
通過正則替換,我們很輕松的拿到了result,你可以去試一試,他正是我們想要的結果。但是這里又有了一個問題,改一下data和tpl,
var tpl='Hei, my name is <%name%>, and I\'m <%info.age%> years old.'; var data={ "name": "Barret Lee", "info": { age": "20"} };
再用上面的方式去獲取結果,呵呵,不行了吧~ 這里data["info.age"]本身就是undefined,所以我們需要換一種方式來處理這個問題,那就是將它轉換成真正的JS代碼。如:
return 'Hei, my name is ' + data.name + ', and I\'m ' + data.info.age' + ' years old.'
但是接著又有一個問題來了,當我們的代碼中出現for循環和if的時候,上面的轉換明顯是不起作用的,如:
var tpl='Posts: ' + '<% for(var i=0; i < post.length; i++) {'+ '<a href="#"
如果繼續采用上面的方式,得到的結果便是:
return 'Posts: ' + for(var i=0; i < post.length; i++) { + '<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >' + post[i].exper + '</a>' + }
這顯然不是我們愿意看到的,稍微觀察一下上面的結構,如果可以返回一個這樣的結果也挺不錯哦:
'Posts: ' for(var i=0; i < post.length; i++) { '<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >' + post[i].exper + '</a>' }
但是我們需要得到的是一個字符串,而不是上面這樣零散的片段,因此可以把這些東西裝入數組中。
2.裝入數組
var r=[]; r.push('Posts: ' ); r.push(for(var i=0; i < post.length; i++) {); r.push('<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >'); r.push(post[i].exper); r.push('</a>'); r.push(});
有人看到上面的代碼就要笑了,第三行和最后一行代碼的邏輯明顯是不正確的嘛,那腫么辦呢?呵呵,很簡單,不放進去就行了唄,
var r=[]; r.push('Posts: ' ); for(var i=0; i < post.length; i++) { r.push('<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >'); r.push(post[i].exper); r.p
這樣的邏輯就十分完善了,不存在太多的漏洞,但是這個轉化的過程是如何實現的?我們必須還是要寫一個解析的模板函數出來。 3.分辨js邏輯部分
var r=[]; tpl.replace(/<%([^%>]+)?%>/g, function(s0, s1){ //完蛋了,這里貌似又要回到上面那可笑的邏輯有錯誤的一步啦... 該怎么處理比較好? });
完蛋了,這里貌似又要回到上面那可笑的邏輯有錯誤的一步啦... 該怎么處理比較好?我們知道,JS給我們提供了構造函數的“類”,
var fn=new Function("data", "var r=[]; for(var i in data){ r.push(data[i]); } return r.join(' ')"); fn({"name": "barretlee", "age": "20"}); // barretlee 20
道了這個就好辦了,我們可以把邏輯部分和非邏輯部分的代碼鏈接成一個字符串,然后利用類似fn的函數直接編譯代碼。而/<%([^%>]+)?%>/g,這一個正則只能把邏輯部分匹配出來,要想把所有的代碼都組合到一起,必須還得匹配非邏輯部分代碼。replace函數雖然很強大,他也可以完成這個任務,但是實現的邏輯比較晦澀,所以我們換另外一種方式
var reg=/<%([^%>]+)?%>/g; var tpl='Hei, my name is <%name%>, and I\'m <%age%> years old.'; var match=reg.exec(tpl); console.log(match);
看到的是:
[ 0: "<%name%>", 1: name, index: 16, input: "Hei, my name is <%name%>, and I'm <%age%> years old." length: 2 ]
這。。。我們可是想得到所有的匹配啊,他竟然只獲取了name而忽略了后面的age,好吧,對正則稍微熟悉點的童鞋一定會知道應該這樣處理:
var reg=/<%([^%>]+)?%>/g; while(match=reg.exec(tpl)) { console.log(match); }
關于正則表達式的內容就不在這里細說了,有興趣的同學可以多去了解下match,exec,search等正則的相關函數。這里主要是靠match的index屬性來定位遍歷位置,然后利用while循環獲取所有的內容。
4.引擎函數
所以我們的引擎函數雛形差不多就出來了:
var tplEngine=function(tpl, data){ var reg=/<%([^%>]+)?%>/g, code='var r=[];\n', cursor=0; //主要的作用是定位代碼最后一截 var add=function(line) { code +='r.push("' + line.replace(/"/g, '\\"') + '");\n'; }; while(match=reg.exec(tpl)) { add(tpl.slice(cursor, match.index)); //添加非邏輯部分 add(match[1]); //添加邏輯部分 match[0]="<%" + match[1] + "%>"; cursor=match.index + match[0].length; } add(tpl.substr(cursor, tpl.length - cursor)); //代碼的最后一截 如:" years old." code +='return r.join("");'; // 返回結果,在這里我們就拿到了裝入數組后的代碼 console.log(code); return tpl; };
這樣一來,測試一個小demo:
var tpl='<% for(var i=0; i < this.posts.length; i++) {' + 'var post=posts[i]; %>' + '<% if(!post.expert){ %>' + '<span>post is null</span>' + '<% } else { %>' + '<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><% post.expert %> at <% post.time %></a>' + '<% } %>' + '<% } %>'; tplEngine(tpl, data);
返回的結果讓人很滿意:
var r=[]; r.push(""); r.push(" for(var i=0; i < this.posts.length; i++) {var post=posts[i]; "); r.push(""); r.push(" if(!post.expert){ "); r.push("<span>post is null</span>"); r.push(" } else { "); r.push("<a href=\"#\">"); r.push(" post.expert "); r.push(" at "); r.push(" post.time "); r.push("</a>"); r.push(" } "); r.push(""); r.push(" } "); r.push("");
不過我們并需要for,if,switch等這些東西也push到r數組中去,所以呢,還得改善下上面的代碼,如果在line中發現了包含js邏輯的代碼,我們就不應該讓他進門:
regOut=/(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g; var add=function(line, js) { js? code +=line.match(regOut) ? line + '\n' : 'r.push(' + line + ');\n' : c
所以我們只剩下最后一步工作了,把data扔進去!
5.把data扔進去
沒有比完成這東西更簡單的事情啦,通過上面對Function這個函數的講解,大家應該也知道怎么做了。
return new Function(code).apply(data);
使用apply的作用就是讓code中的一些變量作用域綁定到data上,不然作用域就會跑到global上,這樣得到的數據索引就會出問題啦~ 當然我們可以再優化一下:
return new Function(code.replace(/[\r\t\n]/g, '')).apply(data);
把回車換行以及tab鍵都給匹配掉,讓代碼更加干凈一點。那么最終的代碼就是:
var tplEngine=function(tpl, data) { var reg=/<%([^%>]+)?%>/g, regOut=/(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, code='var r=[];\n', cursor=0; var add=function(line, js) { js? (code +=line.match(regOut) ? line + '\n' : 'r.push(' + line + ');\n') : (code +=line !='' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : ''); return add; } add(tpl.slice(cursor, match.index))(match[1], true); cursor=match.index + match[0].length; } add(tpl.substr(cursor, tpl.length - cursor)); code +='return r.join("");'; return new Function(code.replace(/[\r\t\n]/g, '')).apply(data); };
三、應用場景
畢竟是前端代碼,所以寫出來是要為前端服務的,平時我們處理的一般是一個html的模板,通常的情況下,模板代碼是放在script標簽或者textarea中,所以首先是要獲取到這里頭的東西,然后再來做解析。
var barretTpl=function(str, data) { //獲取元素 var element=document.getElementById(str); if (element) { //textarea或input則取value,其它情況取innerHTML var html=/^(textarea|input)$/i.test(element.nodeName) ? element.value : element.innerHTML; return tplEngine(html, data); } else { //是模板字符串,則生成一個函數 //如果直接傳入字符串作為模板,則可能變化過多,因此不考慮緩存 return tplEngine(str, data); } var tplEngine=function(tpl, data) { // content above }; };
這樣一來就更加簡單了,使用方式就是 barretTpl(str, data), 這里的str可以是模板代碼,也可以是一個DOM元素的id~
四、優化以及功能拓展
總共就三四十行代碼,完成的東西肯定是一個簡潔版的,不過對于一個簡單的頁面而言,這幾行代碼已經足夠使用了,如果還想對他做優化,可以從這幾個方面考慮:
結語
感謝您的觀看,如有不足之處,歡迎批評指正。
Smarty的兼容性非常好,多數情況下Smarty高版本都能夠兼容低版本。但有一點必須呀注意,Smarty之所以功能強大,是由于支持眾多模版插件,這些插件并非都具備良好兼容性,所以在使用前或升級前需要開發人自行測試,以確保適用新的Smarty版本。接下來將以Smarty3.1.12為例,詳細介紹Smarty的安裝及使用。
在傳統的PHP中使用Smarty是主要的開發方式,也是最簡單的使用方式。下面示例詳細介紹Smarty在PHP中的導入及使用,步驟如下
首先去官方下載Smarty,將下載后的Smarty文件夾復制到網站相應的目錄,例如Smarty目錄。完成后可以通過Http://localhoso/smarty網址訪問到該目錄。然后在該目錄中分別創建cache、compiles、conf、tpl目錄,用于存放緩存、編譯文件、配置文件、模版文件等。完成后,創建index.php網站入口文件,在該文件中包含Smarty.class.php入口文件,并初始化相關配置信息,如下代碼所示
我們相信對上述代碼并不陌生,無論是分配變量還是分配模版,這些操作都與ThinkPHP相類似,事實上這是類Smarty模版引擎所具有的特性。保存上述代碼,然后在tpl目錄中創建index.html模版文件,代碼如下
注:加有{}內容即為PHP變量
*請認真填寫需求信息,我們會在24小時內與您取得聯系。