Smarty

维基百科,自由的百科全书
Smarty Templates
開發者Monte Ohrt, Messju Mohr
当前版本
  • 4.3.4 (2023年10月1日;穩定版本)[1]
編輯維基數據鏈接
源代码库 編輯維基數據鏈接
类型網頁模板引擎
许可协议LGPL
网站smarty.net

Smarty是一個PHP下的網頁模板系統。Smarty基本上是一種為了將不同考量的事情分離而推出的工具,這對某些應用程式是一種共通性設計策略。[3][4]

簡介[编辑]

Smarty以在文件中放置特殊的「Smarty標籤」來產生網頁內容。這些標籤會被處理並替換成其他的內容。

標籤是給Smarty的指令符,以模板定界符包住。這些指令符可以是變數,以$符號代表函數、邏輯流程控制語法。Smarty允許PHP程式設計師以Smarty標籤去定義可存取的函數。

Smarty意圖簡化區域化,允許PHP網頁後端邏輯與表現層(即使用者介面)分離。理想的情況下,這將降低軟體維護費用和人力。在這個研發策略之下,設計師可專注於實現表現層而不用撰寫PHP程式碼,並允許PHP程式設計師抽離出表現層並專注實現後端邏輯。

Smarty支援幾個高階模板程式的特性,包含:

  • 正規表示法
  • 流程控制語法,如foreach、while。
  • if,elseif,else
  • 可修改的變數 - 例如{$variable|nl2br}
  • 使用者自訂的函數
  • 在模板內的數學計算

以及其他特性。一些其他的模板引擎也支援這類特性。

程式碼範例[编辑]

因為 Smarty將 HTML碼與PHP程式碼分離,所以會有兩個檔案:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
   <title>{$title_text}</title>
   <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>

<body> {* This is a little comment that won't be visible in the HTML source *}

<p>{$body_text}</p>

</body><!-- this is a little comment that will be seen in the HTML source -->
</html>

在企業邏輯程式碼中,設計者能配置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}
<html>
<head>
<title>{$page_title}</title>
</head>
<body>
   {$body_text}
</body>
</html>

參照[编辑]

  1. ^ Release 4.3.4. 2023年10月1日 [2023年10月20日]. 
  2. ^ 存档副本. [2015-08-07]. (原始内容存档于2019-02-17). 
  3. ^ Smarty將PHP碼(事務邏輯英语Business logic)與 HTML碼分開(通常代表表現邏輯英语Presentation logic).
  4. ^ Parr, Terence John. Enforcing strict model-view separation in template engines. Proceedings of the 13th international conference on World Wide Web. 2004. 1-58113-844-X. 

參見[编辑]

外部連結[编辑]

英文[编辑]

中文[编辑]