|
深入範本應用:迴圈處理 |
每個程式都會涉及到迴圈處理,引入迴圈到範本是範本引擎一個比較有特色的功能。
Ease Template 為了方便應用將在每次迴圈時增加一個遞增變數$_i ,使用者可以使用此變數來制作迴圈無資料等提示。
Ease Template提供了兩種迴圈方式:foreach、while
先來介紹foreach用法(為了方便在Ease Template範本中的應用,對用法進行了一定的最佳化)。
test_4.php
-
<?php
- include"./template.ease.php";
- $tpl = new template();
- //參與迴圈的陣列
- $user_list = array(
- array(
- 'name' => 'md-chinese',
- 'pass' => '654321',
- ),
- array(
- 'name' => 'test',
- 'pass' => '123456',
- )
- );
- $tpl->set_file('test_4');
- $tpl->p();
- ?>
test_4.htm
-
迴圈程式碼:
- <!-- $user_list AS $user -->
- ID:{_i}
- 賬號:{user['name']}
- 密碼:{user['pass']}
- <!-- END -->
- 無法得到迴圈資料程式碼:
- <!-- $user_list1 AS $users -->
- ID:{_i}
- 賬號:{users['name']}
- 密碼:{users['pass']}
- <!-- END -->
- <!-- 用於判斷提示偵測的方法$_i==0 -->
- <!-- IF[$_i==0] -->
- <font color="#800000">抱歉,沒有得到迴圈資料!</font>
- <!-- 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
-
<?php
- include"./template.ease.php";
- //引入資料庫類
- include"./mysql.php";
- $tpl = new template();
- //宣告資料庫
- $db = new Dirver();
- //連線資料庫
- $db->DBLink('localhost','root','','test');
- //索引資料
- $query = $db->query("SELECT * FROM users");
- $tpl->set_file('test_5');
- $tpl->p();
- ?>
此次範本中與foreach迴圈一樣也提供了一個沒有資料的迴圈,將會提示沒有資料效果。
test_5.htm
-
迴圈程式碼:
- <!-- while:$user = $db->fetch_array($query) -->
- ID:{_i}
- 賬號:{user['username']}
- 密碼:{user['password']}
- <!-- END -->
- 無法得到迴圈資料程式碼:
- <!-- while:$users = $db->fetch_array($query1) -->
- ID:{_i}
- 賬號:{users['username']}
- 密碼:{users['password']}
- <!-- END -->
- <!-- 用於判斷提示偵測的方法$_i==0 -->
- <!-- IF[$_i==0] -->
- <font color="#800000">抱歉,沒有得到迴圈資料!</font>
- <!-- END -->
|
|