Smarty 是 PHP 經典的模板引擎,能有效分離程式邏輯與畫面呈現。本文將帶你從零建立目錄結構,完成第一個「Hello Smarty」專案。
解壓縮 Smarty 套件後,建議在專案根目錄建立以下資料夾:
project/ ├── libs/ # Smarty 核心程式庫 (Smarty.class.php 等) ├── templates/ # 模板檔 (.tpl) ├── templates_c/ # 編譯後的 PHP 檔 (需可寫入權限) ├── configs/ # 設定檔 └── index.php # 入口程式
configs/test.conftitle = "Welcome to Smarty!" cutoff_size = 40 [setup] bold = true
templates/test.tpl<html>
<head>
<title>Smarty Test</title>
</head>
<body>
<h1>Hello, {$name}</h1>
</body>
</html>
index.php<?php
require_once __DIR__ . '/libs/Smarty.class.php';
$smarty = new Smarty();
// 設定目錄路徑 (若採用預設結構可省略)
$smarty->setTemplateDir(__DIR__ . '/templates');
$smarty->setCompileDir(__DIR__ . '/templates_c');
$smarty->setConfigDir(__DIR__ . '/configs');
$smarty->setCacheDir(__DIR__ . '/cache');
// 指派變數
$smarty->assign('name', 'Simon');
// 輸出模板
$smarty->display('test.tpl');
?>
瀏覽器將顯示:
<html> <head> <title>Smarty Test</title> </head> <body> <h1>Hello, Simon</h1> </body> </html>
首次執行時,Smarty 會在 templates_c/ 產生編譯後的 PHP 檔 (如 %%...%%test.tpl.php),內容類似:
<?php /* Smarty version 3.x, compiled from test.tpl */ ?> <html> <head> <title>Smarty Test</title> </head> <body> <h1>Hello, <?php echo $_smarty_tpl->tpl_vars['name']->value; ?></h1> </body> </html>
後續請求若模板未異動,將直接執行編譯檔,大幅提升效能。這就是 Smarty 「編譯型」與「快取」機制的核心優勢。
templates_c/ 與 cache/ 目錄對 Web 伺服器使用者可寫入 (chmod 775 或 777)。require_once 路徑是否正確指向 Smarty.class.php。完成以上步驟,你已成功跑起第一個 Smarty 專案。後續可探索快取、插件、模板繼承等進階功能,打造更易維護的 PHP 應用。