子標題:Smarty 入門 - 5
決定內容是否顯示
要決定是否顯示內容,我們可以使用 if 這個語法來做選擇。例如如果使用者已經登入的話,我們的樣版就可以這樣寫:
![]()
![]()
{if $is_login == true}
顯示使用者操作選單
{else}
顯示輸入帳號和密碼的表單
{/if}
if 語法一般的應用可以參照官方使用說明,所以筆者在這裡就不詳加介紹了。不過筆者發現了一個有趣的應用:常常會看到程式裡要產生這樣的一個表格: (數字代表的是資料集的順序)
| 1 | 2 |
| 3 | 4 |
| 5 | 6 |
| 7 | 8 |
這個筆者稱之為「橫向重覆表格」。它的特色和傳統的縱向重覆不同,前幾節我們看到的重覆表格都是從上而下,一列只有一筆資料。而橫向重覆表格則可以橫向地在一列中產生 n 筆資料後,再換下一列,直到整個迴圈結束。要達到這樣的功能,最簡單的方式只需要 section 和 if 搭配即可。
我們來看看下面這個例子:
test4.php
![]()
![]()
<?php
require "main.php";
$my_array = array(
array("value" => "0"),
array("value" => "1"),
array("value" => "2"),
array("value" => "3"),
array("value" => "4"),
array("value" => "5"),
array("value" => "6"),
array("value" => "7"),
array("value" => "8"),
array("value" => "9"));
$tpl->assign("my_array", $my_array);
$tpl->display('test4.htm');
?>
樣版的寫法如下:
templates/test4.htm
![]()
![]()
<html>
<head>
<title>橫向重覆表格測試</title>
</head>
<body>
<table width="500" border="1" cellspacing="0" cellpadding="3">
<tr>
{section name=sec1 loop=$my_array}
<td> {$my_array[sec1].value} </td>
{if $smarty.section.sec1.rownum is div by 2
&& $smarty.section.sec1.rownum < $smarty.section.sec1.total}
</tr>
<tr>
{/if}
{/section}
</tr>
</table>
</body>
</html>
重點在於 $smarty.section.sec1.rownum 及 $smarty.section.sec1.total 這兩個 Smarty 變數,在 section 迴圈中這個 rownum 變數會取得從 1 開始的 索引值,所以當 rownum 能被 2 除盡時,就輸出 </tr><tr> 使表格換列 (注意!是 </tr> 在前面 <tr> 在後面) ,因此數字 2 就是我們在一列中想要呈現的資料筆數。而 total 這個變數會回傳資料總筆數,所以讓 rownum 在小於 total 這個變數才做輸出 </tr><tr> 的動作,會確保不會出現最後一個空的 </tr><tr> 。
各位可以由此去變化其他不同的呈現方式。 載入外部內容
我們可以在樣版內載入 PHP 程式碼或是另一個子樣版,分別是使用 include_php 及 include 這兩個 Smarty 樣版語法; include_php 筆者較少用,使用方式可以查詢官方手冊,這裡不再敘述。
在使用 include 時,我們可以預先載入子樣版,或是動態載入子樣版。預先載入通常使用在有共同的文件標頭及版權宣告;而動態載入則可以用在統一的框架頁,而進一步達到如 Winamp 般可換 Skin 。當然這兩種我們也可以混用,視狀況而定。
我們來看看下面這個例子:
test5.php
![]()
![]()
<?php
require "main.php";
$tpl->assign("title", "Include 測試");
$tpl->assign("content", "這是樣版 2 中的變數");
$tpl->assign("dyn_page", "test5_3.htm");
$tpl->display('test5_1.htm');
?>
樣版 1 的寫法如下:
templates/test5_1.htm
![]()
![]()
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title> {$title} </title>
</head>
<body>
{include file="test5_2.htm"}
{include file=$dyn_page}
{include file="test5_4.htm" custom_var="自訂變數的內容"}
</body>
</html>
樣版 2 的寫法如下:
templates/test5_2.htm
![]()
![]()
<p>{$content}</p>
樣版 3 的寫法如下:
templates/test5_3.htm
![]()
![]()
<p>這是樣版 3 的內容</p>
樣版 4 的寫法如下:
templates/test5_4.htm
![]()
![]()
<p>{$custom_var}</p>
這裡注意幾個重點:
- 樣版的位置都是以先前定義的 template_dir 為基準。
- 所有 include 進來的子樣版中,其變數也會被解譯。
- include 中可以用「變數名稱=變數內容」來指定引含進來的樣版中所包含的變數,如同上面樣版 4 的做法。