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

Smartty 入門指南:配置、模板分離與變量輸出基礎實例

     編輯:PHP 綜合知識

Smarty 模板引擎零基礎入門:從安裝配置到第一個 Hello World

Smarty 是 PHP 歷史上最流行的模板引擎之一,其核心理念是「強制分離業務邏輯(PHP)與展示邏輯(HTML)」。本文通過最簡潔的代碼演示 Smarty 核心工作流:配置初始化 → 變量賦值 → 模板渲染。

環境準備

  1. 下載 Smarty:官網下載頁
  2. 解壓後將 libs/Smarty.class.php 放入項目可訪問路徑
  3. 創建可寫目錄:templates/、templates_c/、configs/、cache/

核心代碼:index.php

<?php
// index.php
header("Content-Type: text/html; charset=UTF-8");

// 1. 載入核心類
require_once '../libs/Smarty.class.php';

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

// 3. 目錄配置(關鍵步驟)
$smarty->template_dir = 'templates/';   // 模板文件目錄
$smarty->compile_dir  = 'templates_c/'; // 編譯緩存目錄(需寫入權限)
$smarty->config_dir   = 'configs/';     // 配置文件目錄
$smarty->cache_dir    = 'cache/';       // 緩存目錄(需寫入權限)

// 4. 賦值變量
$smarty->assign('content', 'welcome to arrival');
$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>
    
    <ul>
    {section name=truelife loop=$mylife}
        <li>{$mylife[truelife]}</li>
    {/section}
    </ul>
</body>
</html>

運行效果

welcome to arrival

• 生活
• 吃飯
• 夢想
• 涼風

核心概念速查

概念說明對應代碼
template_dir存放 .html/.tpl 模板文件templates/
compile_dir存放編譯後的 PHP 文件(自動生成)templates_c/
config_dir存放 .conf 配置文件(可選)configs/
cache_dir存放緩存文件(開啟 caching 後使用)cache/
assign()PHP 向模板傳遞變量$smarty->assign('key', $val)
display()渲染並輸出模板$smarty->display('file.html')

模板基本語法

  • 變量輸出:{$var}、{$arr.key}、{$obj->prop}
  • 遍歷數組:{section name=i loop=$arr}{$arr[i]}{/section}
  • 條件判斷:{if $cond}...{elseif $cond}...{else}...{/if}
  • 修飾符:{$var|upper}、{$var|escape}、{$var|truncate:20}
  • 內置函數:{html_options}、{html_select_date}、{counter}

開發與生產環境配置差異

配置項開發環境生產環境
$smarty->force_compiletrue (每次重新編譯)false
$smarty->cachingfalsetrue
$smarty->cache_lifetime03600 (秒,視業務而定)
$smarty->compile_checktruefalse

下一步學習路徑

  1. 掌握 模板繼承:{extends 'layout.tpl'} + {block name='content'}{/block} (Smarty 3+)
  2. 學習 自定義插件:修飾符、函數、塊函數開發
  3. 了解 緩存機制:靜態緩存、局部緩存、緩存組
  4. 探索 Smarty 3 新特性:命名空間、繼承、語法簡化

Smarty 雖非現代框架首選(如 Laravel Blade、Twig),但在維護老項目、快速原型、非框架項目中仍具極高實用價值。掌握其核心工作流,能快速上手各類基於 Smarty 的歷史項目。

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