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

Smarty 模板引擎入門:配置、顯示與變數輸出完整範例

     編輯:PHP 相關知識

Smarty 模板引擎入門:配置、顯示與變數輸出完整範例

Smarty 是經典的 PHP 模板引擎,核心優勢在於「業務邏輯與表現層分離」。本文通過一個最簡單的範例,展示 Smarty 目錄結構、配置初始化、變數指派、模板語法 (輸出、迴圈) 等核心用法。

目錄結構規劃

project/
├── libs/           # Smarty 核心庫 (Smarty.class.php 等)
├── templates/      # 模板檔 (*.html, *.tpl)
├── templates_c/    # 編譯後的 PHP 檔案 (需寫入權限)
├── configs/        # 設定檔 (可選)
├── cache/          # 快取檔 (需寫入權限)
└── index.php       # 入口腳本

PHP 入口腳本 index.php

<?php
// 1. 載入 Smarty 核心類別
require_once __DIR__ . '/libs/Smarty.class.php';

// 2. 實例化
$smarty = new Smarty();

// 3. 設定目錄路徑 (建議使用絕對路徑)
$smarty->template_dir = __DIR__ . '/templates/';
$smarty->compile_dir  = __DIR__ . '/templates_c/';
$smarty->config_dir   = __DIR__ . '/configs/';
$smarty->cache_dir    = __DIR__ . '/cache/';

// 4. 指派變數
$smarty->assign('content', 'Welcome to Smarty!');
$smarty->assign('mylife', ['生活', '吃飯', '夢想', '涼風']);

// 5. 顯示模板
$smarty->display('kk.html');
?>

模板檔 templates/kk.html

<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Smarty 入門範例</title>
</head>
<body>
    <h1>{$content}</h1>
    
    <h2>我的生活關鍵字:</h2>
    <ul>
    {section name=truelife loop=$mylife}
        <li>{$mylife[truelife]}</li>
    {/section}
    </ul>
</body>
</html>

關鍵語法解析

語法說明
{$var}輸出變數 (自動轉義取決於設定)
{section name=foo loop=$arr}...{/section}迴圈陣列,$arr 可為索引或關聯陣列
{$arr[foo]}在 section 中存取當前元素
{$smarty.get.id}直接存取 $_GET['id'] (亦有 post, cookies, server, env, session, request)
{if $cond}...{elseif}...{else}...{/if}條件判斷
{include file="header.tpl"}引入子模板

常見進階設定

<?php
// 開啟快取
$smarty->caching = true;
$smarty->cache_lifetime = 3600; // 秒

// 強制重新編譯 (開發環境)
$smarty->force_compile = true;

// 開啟錯誤報告 (開發環境)
$smarty->debugging = true;

// 變數修飾符範例 (模板中使用)
// {$name|upper}          -> 大寫
// {$text|truncate:30}    -> 截斷 30 字
// {$date|date_format:"%Y-%m-%d"} -> 格式化日期
// {$html|escape}         -> HTML 轉義 (防 XSS)
?>

最佳實踐建議

  • 目錄權限: templates_c/ 與 cache/ 必須可由 Web 服務器使用者 (www-data, nginx 等) 寫入。
  • 安全性: 模板目錄建議放在 Web 根目錄外部,防止直接訪問 .tpl 檔案洩露邏輯。
  • 版本選擇: Smarty 3.x/4.x 支援 PHP 5.3+、命名空間、繼承、區塊等現代特性,新專案請使用最新穩定版。
  • 替代方案: 現代框架 (Laravel Blade, Twig, Latte) 提供更優雅的語法與更好的 IDE 支援,新專案可優先評估。

掌握 Smarty 基礎用法,能快速構建結構清晰、易於維護的 PHP 應用,也是理解現代模板引擎設計思想的良好起點。

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