Transcript Document

Smarty – 樣版引擎教學
Anjeng
套件的使用觀念
• Smarty及ezSQL皆為套件
– Smarty – 樣版引擎套件
– ezSQL – 資料庫存取套件
• 什麼是套件
– 函式集合而形成特定功能的工具
– 用於解決特定領域的問題
• 為何要使用套件
– 避免重覆造輪子
– 專注於核心開發
Smarty介紹
• 網頁樣版工具
– 將PHP(程式邏輯)和HTML(使用者介面)分離
– Programmer與Web Designer平行開發
• 在TPL樣版中插入特殊標籤, 這些標籤會被
並替換成其他內容
樣版引擎運作
PHP程式
<?php
$hello_smarty = “Smarty!!”
$tpl->assign(
“hello_smarty”, $hello_smarty);
$tpl->display(“hello_smarty.tpl);
?>
樣版(hello_smarty.tpl)
<html>
<body>
<{$hello_smarty}>
</body>
</html>
樣版輸出
<html>
<body>
Smarty!!
</body>
</html>
使用Smarty – 安裝
• 下載Smarty
– http://www.smarty.net/download
• 安裝Smarty至專案目錄
– 在Linux底下, 將templates_c 權限變更為 777
使用Smarty – PHP程式撰寫
• PHP程式撰寫
– 載入Smarty class file
• Require_once(“/smarty_path/Smarty.class.php”);
– 建立Smarty物件
• $tpl = new Smarty();
– 設定Smarty左右標籤
• $tpl->left_delmiter = “<{“;
• $tpl->right_delmiter = “}>“;
– 設定樣版檔案路徑
• $tpl->template_dir = “/your_tpl_path/”;
– 設定樣版變數
• $tpl->assign(“title”, “Hello Smarty Title”);
– 套用並輸出樣版
• $tpl->display(‘assign.tpl’);
使用Smarty – 樣版撰寫
• 樣版撰寫
– 在template_dir下新增一個assign.tpl樣版檔案
– 撰寫HTML畫面
– 使用樣版變數
• <{title}>
• <{content}>
使用Smarty – 套用結果
• assign.php
• assign.tpl
使用一般變數
• PHP檔案, 透過assign()進行樣版變數替換
– $title = “Hello Smarty Title”;
– $tpl->assign(“title”, $title);
• 最後用display() 載入tpl檔案並輸出畫面
– $tpl->display(“assign.tpl”);
• 在樣版檔案裡(*.tpl), 如果使用樣版變數
– 使用特殊標籤<{}>
– <title><{$title}></title>
使用陣列變數
• PHP檔案
– $product_list = array(
'index_key_1' => "ASUS WIN8 NB",
'index_key_2' => "ACER UT NB" );
– $tpl->assign('product_list', $product_list);
– $tpl->display('array.tpl');
• 樣版檔案
– <{$product_list.index_key_1}>
– <{$product_list.index_key_2}>
使用物件變數
• PHP檔案
– 撰寫自訂物件
• class product { … }
– assgin物件變數
• tpl->assign(“objProduct”, $objProduct);
– 套用並輸出樣版
• 樣版檔案
– <{$objProduct->pd_price}>
– <{$objProduct->getName()}>
條件式樣版
• PHP檔案
• 樣版檔案
– <{ if 判斷語法 }>
• 執行內容
– <{ elseif 判斷語法 }>
• 執行內容
– <{ else }>
• 執行內容
– <{/if}>
重覆樣版區塊
• PHP檔案
• 樣版檔案
– <{ foreach key=key item=item from=$variable }>
• 執行內容
– <{ foreachelse }>
• 沒有內容時執行
– <{/foreach}>
子母樣版
•
•
•
•
不同區塊套用不同樣版
樣版結構清楚
彈性佳
可重覆利用
子母樣版
• 切割並規劃各子樣版內容
– header.tpl, content.tpl, footer.tpl
• 整合並規劃主樣版內容
– main_tpl.tpl
multi_tpl.tpl
子母樣版
• 設定子樣版的樣版變數
– $tpl->assign('header_content', "這裡是頁首樣版" );
• 透過fetch()函數, 將套用後的子樣版結果暫存
– $header = $tpl->fetch('header.tpl');
• 整合各子版套用後結果
– $tpl->assign(array('header' => $header, 'content' => $content, 'footer' => $footer));
• 輸出整合結果
– $tpl->display('multi_tpl.tpl');
子母樣版
• PHP檔案
$tpl->assign('header_content', "這裡是頁首樣版" );
$header = $tpl->fetch('header.tpl');
$tpl->assign('main_content', "這裡是主內容樣版" );
$content = $tpl->fetch('content.tpl');
$tpl->assign('footer_content', "這裡是頁尾樣版" );
$footer = $tpl->fetch('footer.tpl');
$tpl->assign(array('header' => $header, 'content' =>
$content, 'footer' => $footer));
$tpl->display('multi_tpl.tpl');
Netbeans 安裝 Smarty Plugins