index.php 入口文件修改:
define('APP_PATH', 'myapp'); // 項目文件獨立目錄
index.html<html>
<head><title>{$title}</title></head>
<body>
{$content}<br>
<ul>
<volist name="list" id="news">
<li>{$news.title}</li>
</volist>
</ul>
</body>
</html>
<?php
class IndexAction extends Action {
public function index() {
header("Content-Type:text/html; charset=utf-8");
$this->assign('title', '循環標簽示例');
$this->assign('content', 'volist 循環演示');
// 構建測試數據(二維數組)
$news = array(
array('title' => 'Title1'),
array('title' => 'Title2')
);
array_push($news, array('title' => 'Title3'));
// 關鍵:模板 volist name="list" 對應此處 assign 'list'
$this->assign('list', $news);
$this->display();
}
}
?>
<html>
<head><title>循環標簽示例</title></head>
<body>
volist 循環演示<br>
<ul>
<li>Title1</li><li>Title2</li><li>Title3</li>
</ul>
</body>
</html>
| 屬性 | 說明 | 示例 |
|---|---|---|
name | 數據源變量名(對應 assign 的鍵) | name="list" |
id | 循環變量別名(模板內引用) | id="news" → {$news.title} |
offset | 起始偏移(可選) | offset="0" |
length | 循環長度(可選) | length="10" |
key | 鍵名變量(可選) | key="k" → {$k} |
mod | 取模數(用於斑馬紋等) | mod="2" |
empty | 空數據時顯示內容 | empty="暫無數據" |
{* 斑馬紋 *}
<volist name="list" id="vo" mod="2">
<li class="<if condition='$i%2'>odd<else/>even</if>">{$vo.name}</li>
{/volist}
{* 巢狀循環 *}
<volist name="categories" id="cat">
<h3>{$cat.name}</h3>
<volist name="cat.items" id="item">
<p>{$item.title}</p>
</volist>
{/volist}
volist 以聲明式語法替代 PHP foreach,模板更純粹、設計師更友好。