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

Smarty 模板引擎 POST 表單處理實戰:從配置到數據回顯

     編輯:PHP 綜合知識

Smarty 實戰:表單提交、後端處理與模板渲染完整流程

Smarty 作為經典 PHP 模板引擎,其核心優勢在於「業務邏輯與展示分離」。本文通過一個完整的 POST 表單提交案例,演示從配置初始化、頁面渲染、表單提交、數據處理到結果回顯的全鏈路實現。

項目目錄結構

project/
├── libs/
│   └── Smarty.class.php
├── templates/          # 模板文件目錄
│   ├── kk.html         # 首頁模板
│   └── m.tpl           # 結果頁模板
├── templates_c/        # 編譯緩存目錄(需寫入權限)
├── configs/            # 配置文件目錄
├── cache/              # 緩存目錄(需寫入權限)
├── conf.php            # Smarty 通用配置
├── index.php           # 首頁控制器
└── submit.php          # 表單處理控制器

核心代碼實現

1. 通用配置文件 conf.php

<?php
// conf.php
header("Content-Type: text/html; charset=UTF-8");
require_once '../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->caching = true; // 生產環境可開啟緩存
?>

2. 首頁控制器 index.php

<?php
// index.php
require_once 'conf.php';

$smarty->assign('content', 'welcome to arrival');
$smarty->assign('mylife', [
    "生活", "吃飯", "夢想", "涼風", 
    "報仇", "fuck someone", "fuck you die"
]);

$smarty->display('kk.html');
?>

3. 首頁模板 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 POST 示例</title>
</head>
<body>
    <h1>{$content}</h1>
    
    <h2>生活片段</h2>
    {section name=truelife loop=$mylife}
        {$mylife[truelife]}<br/>
    {/section}
    
    <p>{html_select_time use_24_hours=true}</p>
    
    <form id="form1" name="form1" method="post" action="submit.php">
        <p>
            <label for="conteng">標題:</label>
            <input type="text" name="conteng" id="conteng" />
        </p>
        <p>
            <label for="ct">內容:</label>
            <textarea name="ct" id="ct" cols="45" rows="5"></textarea>
        </p>
        <input type="submit" name="submit" id="submit" value="提交" />
    </form>
</body>
</html>

4. 表單處理控制器 submit.php

<?php
// submit.php
require_once 'conf.php';

// 接收 POST 數據
$content = $_POST['conteng'] ?? '';
$textarea = $_POST['ct'] ?? '';

$smarty = new Smarty();
$smarty->template_dir = 'templates/';
$smarty->compile_dir  = 'templates_c/';
$smarty->config_dir   = 'configs/';
$smarty->cache_dir    = 'cache/';

// 賦值給模板
$smarty->assign('content', $content);

// 處理多行文本:按換行符分割為數組
$lines = explode("\r\n", $textarea);
// 兼容 Linux/Unix 換行符
if (count($lines) === 1) {
    $lines = explode("\n", $textarea);
}
$smarty->assign('ml', $lines);

$smarty->display('m.tpl');
?>

5. 結果頁模板 templates/m.tpl

<h1>{$content}</h1>
<h2>提交內容逐行顯示:</h2>
{section name=kk loop=$ml}
    {$ml[kk]}<br/>
{/section}

Smarty 關鍵語法解析

語法說明示例
{$var}輸出變量{$content}
{section name=i loop=$arr}遍歷數組見上文 mylife/ml 遍歷
{$arr[i]}訪問數組元素{$mylife[truelife]}
{html_select_time}內置函數:生成時間選擇框{html_select_time use_24_hours=true}

進階優化建議

  1. 配置複用:將 Smarty 實例化邏輯封裝為單例或工廠函數,避免重複配置
  2. 輸入過濾:模板輸出前對用戶輸入進行 htmlspecialchars() 或使用 Smarty 內置 |escape 修飾符防 XSS
  3. 錯誤處理:檢查 $_POST 鍵是否存在,提供友好默認值
  4. 模板繼承:使用 {extends}/{block} 實現佈局復用(需 Smarty 3+)
  5. 緩存策略:生產環境開啟 $smarty->caching = true,設置合理 cache_lifetime

常見問題排查

現象可能原因解決方案
模板變量不顯示assign 變量名與模板不一致檢查大小寫、拼寫;使用 {$smarty.get} 調試
section 不循環數組為空或非索引數組確保傳入數值索引數組;使用 @count 判斷
權限錯誤templates_c/cache 目錄不可寫chmod 777 templates_c cache (Linux)

這個完整案例展示了 Smarty 「PHP 處理邏輯、模板負責展示」的核心思想,是理解 MVC 模式在傳統 PHP 開發中落地的優秀入門實踐。

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