Smarty是一個PHP下的網頁模板系統。Smarty基本上是一種為了將不同考量的事情分離而推出的工具,這對某些應用程式是一種共通性設計策略。
簡介
Smarty以在文件中放置特殊的「Smarty標籤」來產生網頁內容。這些標籤會被處理並替換成其他的內容。
標籤是給Smarty的指令符,以模板定界符包住。這些指令符可以是變數,以$符號代表函數、邏輯或 流程控制語法。Smarty允許PHP程式設計師以Smarty標籤去定義可存取的函數。
Smarty意圖簡化區域化,允許PHP網頁後端邏輯與表現層(即使用者介面)分離。理想的情況下,這將降低軟體維護費用和人力。在這個研發策略之下,設計師可專注於實現表現層而不用撰寫PHP程式碼,並允許PHP程式設計師抽離出表現層並專注實現後端邏輯。
Smarty支援幾個高階模板程式的特性,包含:
- 正規表示法
- 流程控制語法,如foreach、while。
- if,elseif,else
- 可修改的變數 - 例如{$variable|nl2br}
- 使用者自訂的函數
- 在模板內的數學計算
以及其他特性。一些其他的模板引擎也支援這類特性。
程式碼範例
因為 Smarty將 HTML碼與PHP程式碼分離,所以會有兩個檔案:
{$title_text}
{ This is a little comment that won't be visible in the HTML source }
{$body_text}
在企業邏輯程式碼中,設計者能配置Smarty去使用這個模板:
define('SMARTY_DIR', 'smarty-2.6.9/' );
require_once(SMARTY_DIR . 'Smarty.class.php');
$smarty = new Smarty();
$smarty->template_dir = './templates/';
$smarty->compile_dir = './templates/compile/';
$smarty->cache_dir = './templates/cache/';
$smarty->caching = false;
$smarty->error_reporting = E_ALL; // LEAVE E_ALL DURING DEVELOPMENT
$smarty->debugging = true;
$smarty->assign('title_text', 'TITLE: This is the Smarty basic example ...');
$smarty->assign('body_text', 'BODY: This is the message set using assign()');
$smarty->display('index.tpl');
並且能將PHP包涵在Smarty模板裡,像是下面這樣:
{ We can use PHP syntax in smarty template inside {php} ..{/php} }
{php}
$contentType = strpos($_SERVER['HTTP_ACCEPT'],'application/xhtml+xml') === false ? 'text/html' : 'application/xhtml+xml';
header("Content-Type: $contentType; charset=utf-8");
{/php}
{$page_title}
{$body_text}
參照
參見
- 內容管理系統
外部連結
英文
- [http://www.smarty.net/ Official site]
- [https://web.archive.org/web/20061207024654/http://www.zend.com/zend/tut/tutorial-cezar.php PHP Templating with Smarty] by Cezar Floroiu - Smarty tutorial
- [http://www.devpapers.com/article/18 Smarty vs. XML/XSLT] - from DevPapers.com by Sergey Makogon
- [http://hasin.wordpress.com/2006/06/10/smarty-cheat-sheet-version-20/ Smarty Cheat Sheet] Smarty Cheat Sheet for Templates Designers and Programmers
- [https://web.archive.org/web/20070627161639/http://www.timestretch.com/php_intro/?page=smarty Timestretch: PHP, MySQL, and Smarty Programming] - Also see the PHP2 page for more.
- [http://www.nusphere.com/products/php_smarty.htm PHP Smarty Tools] - Using Smarty in PhpED
中文
评论 (0)