首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Smarty 模板引擎入門實戰:從目錄結構到第一個範例

     編輯:PHP 相關知識

Smarty 模板引擎入門實戰:從目錄結構到第一個範例

Smarty 是 PHP 經典的模板引擎,能有效分離程式邏輯與畫面呈現。本文將帶你從零建立目錄結構,完成第一個「Hello Smarty」專案。

一、標準目錄結構

解壓縮 Smarty 套件後,建議在專案根目錄建立以下資料夾:

project/
├── libs/           # Smarty 核心程式庫 (Smarty.class.php 等)
├── templates/      # 模板檔 (.tpl)
├── templates_c/    # 編譯後的 PHP 檔 (需可寫入權限)
├── configs/        # 設定檔
└── index.php       # 入口程式

二、設定檔範例 configs/test.conf

title = "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>

四、PHP 入口程式 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。
  • 變數未顯示:模板變數區分大小寫,{$Name} 與 {$name} 不同。

完成以上步驟,你已成功跑起第一個 Smarty 專案。後續可探索快取、插件、模板繼承等進階功能,打造更易維護的 PHP 應用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved