Ease Template Manual Version:E3
功能清單:
選擇最合適的範本 ET
ET 無與倫比的優勢
ET學習入門實例
深入範本應用:變數
深入範本應用:路徑解析
深入範本應用:邏輯判斷
深入範本應用:迴圈處理
深入範本應用:嵌套迴圈
深入範本應用:特殊迴圈
深入範本應用:彌補函式
深入範本應用:連載執行
深入範本應用:中層編譯
深入範本應用:內部引用
深入範本應用:引用PHP
深入範本應用:多語言篇
深入範本應用:偵錯平臺
下載ET
版本歷史
聯係作者
ET 經典案例
深入範本應用:迴圈處理
每個程式都會涉及到迴圈處理,引入迴圈到範本是範本引擎一個比較有特色的功能。

Ease Template 為了方便應用將在每次迴圈時增加一個遞增變數$_i ,使用者可以使用此變數來制作迴圈無資料等提示。

Ease Template提供了兩種迴圈方式:foreach、while

先來介紹foreach用法(為了方便在Ease Template範本中的應用,對用法進行了一定的最佳化)。

test_4.php
  1. <?php  
  2. include"./template.ease.php";  
  3. $tpl = new template();  
  4. //參與迴圈的陣列  
  5. $user_list = array(  
  6.   array(  
  7.     'name'  => 'md-chinese',  
  8.     'pass'  => '654321',  
  9.   ),  
  10.   array(  
  11.     'name'  => 'test',  
  12.     'pass'  => '123456',  
  13.   )  
  14. );  
  15. $tpl->set_file('test_4');  
  16. $tpl->p();  
  17. ?>

test_4.htm
  1. 迴圈程式碼:  
  2. <!-- $user_list AS $user -->  
  3.   ID:{_i}   
  4.   賬號:{user['name']}  
  5.   密碼:{user['pass']}  
  6. <!-- END -->  
  7. 無法得到迴圈資料程式碼:  
  8. <!-- $user_list1 AS $users -->  
  9.   ID:{_i}   
  10.   賬號:{users['name']}  
  11.   密碼:{users['pass']}  
  12. <!-- END -->  
  13. <!-- 用於判斷提示偵測的方法$_i==0 -->  
  14. <!-- IF[$_i==0] -->  
  15. <font color="#800000">抱歉,沒有得到迴圈資料!</font>  
  16. <!-- END -->


現在我們進入更復雜的迴圈操作:while在範本中對資料庫的操作。如果將資料庫物件引入範本則不用在迴圈後得到陣列再賦值給範本,節省了大量時間以及迴圈次數。

測試資料庫內容:
[text character set utf8]
CREATE TABLE `users` (
`uid` INT( 3 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 64 ) NOT NULL ,
`password` VARCHAR( 32 ) NOT NULL
) TYPE = MyISAM ;

INSERT INTO `users` (`uid`, `username`, `password`) VALUES (1, 'md-chinese', '123456'),
(2, 'ease template', 'systn');
[/text character set utf8]

這裡為了體現資料庫操作效果,我們載入一個簡單的資料庫類,連線本機資料庫,並且連線test庫表。

test_5.php
  1. <?php  
  2. include"./template.ease.php";  
  3. //引入資料庫類  
  4. include"./mysql.php";  
  5. $tpl = new template();  
  6. //宣告資料庫  
  7. $db = new Dirver();  
  8. //連線資料庫  
  9. $db->DBLink('localhost','root','','test');  
  10. //索引資料  
  11. $query $db->query("SELECT * FROM users");  
  12. $tpl->set_file('test_5');  
  13. $tpl->p();  
  14. ?>


此次範本中與foreach迴圈一樣也提供了一個沒有資料的迴圈,將會提示沒有資料效果。

test_5.htm
  1. 迴圈程式碼:  
  2. <!-- while:$user = $db->fetch_array($query) -->  
  3.   ID:{_i}   
  4.   賬號:{user['username']}  
  5.   密碼:{user['password']}  
  6. <!-- END -->  
  7. 無法得到迴圈資料程式碼:  
  8. <!-- while:$users = $db->fetch_array($query1) -->  
  9.   ID:{_i}   
  10.   賬號:{users['username']}  
  11.   密碼:{users['password']}  
  12. <!-- END -->  
  13. <!-- 用於判斷提示偵測的方法$_i==0 -->  
  14. <!-- IF[$_i==0] -->  
  15. <font color="#800000">抱歉,沒有得到迴圈資料!</font>  
  16. <!-- END -->
我要啦免费统计