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

PHP Smarty 入門完整範例:從安裝到第一個模板

     編輯:PHP 綜合知識

目錄結構

/var/www/
├── index.php
├── libs/
│   └── Smarty.class.php
├── templates/
│   └── test.htm
├── templates_c/     # 編譯快取 (chmod 777)
├── configs/
│   └── test.conf
└── cache/           # 快取目錄 (chmod 777)

配置檔

configs/test.conf

title = "Welcome to Smarty!"
cutoff_size = 40

[setup]
bold = true

模板檔

templates/test.htm

<html>
<head><title>Smarty Test</title></head>
<body>
<H1>Hello, {$Name}</H1>
</body>
</html>

PHP 入口

<?php
require 'libs/Smarty.class.php';

$smarty = new Smarty();
// 目錄設定 (可選,符合慣例可省略)
$smarty->template_dir = 'templates/';
$smarty->compile_dir  = 'templates_c/';
$smarty->config_dir   = 'configs/';
$smarty->cache_dir    = 'cache/';

// 指派變數
$smarty->assign("Name", "Simon");

// 顯示模板
$smarty->display('test.htm');
?>

瀏覽器輸出

<html>
<head><title>Smarty Test</title></head>
<body>
<H1>Hello, Simon</H1>
</body>
</html>

編譯快取檔

templates_c/%%...test.htm.php

<?php
/* Smarty version 2.6.22, created on 2009-03-19 13:20:00
   compiled from test.htm */
?>
<html>
<head><title>Smarty Test</title></head>
<body>
<H1>Hello, <?php echo $this->_tpl_vars['Name']; ?></H1>
</body>
</html>

核心流程解析

  1. 實例化:new Smarty() 建立模板引擎
  2. 指派:assign() 將 PHP 變數傳遞給模板
  3. 編譯:首次執行將 .htm 編譯為 PHP 檔存入 templates_c/
  4. 執行:載入編譯後 PHP 執行輸出 HTML
  5. 快取:啟用 $smarty->caching = true 可快取輸出 HTML

進階功能快速導覽

配置檔讀取

$smarty->config_load('test.conf');
echo $smarty->get_config_vars('title'); // Welcome to Smarty!

快取機制

$smarty->caching = true;
$smarty->cache_lifetime = 3600; // 1小時
if (!$smarty->is_cached('test.htm')) {
    // 只有未快取時才做昂貴操作
    $data = expensive_query();
    $smarty->assign('data', $data);
}
$smarty->display('test.htm');

模板函式

{* 內建函式 *}
{$name|upper}
{$date|date_format:"%Y-%m-%d"}
{$arr|@count}

{* 自訂函式 *}
{html_options values=$ids output=$names selected=$selected}

模板繼承

{* layouts/main.htm *}
<html><body>{block name="content"}{/block}</body></html>

{* page.htm *}
{extends file="layouts/main.htm"}
{block name="content"}<h1>頁面內容</h1>{/block}

常見問題排查

問題原因解決
空白頁/500錯誤 templates_c/ 權限不足 chmod 777 templates_c/ cache/
修改模板不生效 編譯快取未更新 刪除 templates_c/ 對應檔案或 $smarty->force_compile = true
變數顯示為 Array 陣列直接輸出 用 {$arr|@count} 或 {foreach}
中文亂碼 編碼不一致 確保 PHP、模板、資料庫皆 UTF-8

Smarty 3/4 升級重點

  • 命名空間支援:Smarty\Smarty
  • Composer 安裝:composer require smarty/smarty
  • 模板繼承 {extends}/{block} 取代 {include} 重構
  • 資料綁定 {$var} 自動跳脫 (需關閉 $smarty->auto_escape = false 相容舊版)
  • 效能大幅提升,編譯器重寫

Smarty 是 PHP 經典模板引擎,掌握「指派→編譯→執行」核心流程,即可快速上手專案開發。

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