萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP Smarty 模板引擎入门:目录结构、配置、变量赋值与模板编译全流程

Smarty 简介

Smarty 是经典的 PHP 模板引擎,实现“业务逻辑与展示分离”。模板文件含占位符,PHP 分配数据后由 Smarty 编译为 PHP 文件并缓存,后续访问直接执行编译后文件,性能优于原生 PHP 混写 HTML。

目录结构规范

project/
├── libs/
│   └── Smarty.class.php        # 核心类库
├── configs/                    # 配置文件目录
│   └── test.conf
├── templates/                  # 模板源文件目录
│   └── test.htm
├── templates_c/                # 编译缓存目录(需可写)
│   └── test.htm.php            # 自动生成
└── index.php                   # 入口脚本

配置文件 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>
    <p>Config title: {#title#}</p>
</body>
</html>

PHP 入口脚本 index.php

<?php
require_once __DIR__ . '/libs/Smarty.class.php';

$smarty = new Smarty();

// 目录配置(可选,默认即以上结构)
$smarty->template_dir = __DIR__ . '/templates';
$smarty->compile_dir  = __DIR__ . '/templates_c';
$smarty->config_dir   = __DIR__ . '/configs';

// 分配模板变量
$smarty->assign('Name', 'Simon');

// 可选:加载配置文件变量
$smarty->config_load('test.conf');

// 显示模板(编译+执行+输出)
$smarty->display('test.htm');
?>

运行结果

<html>
<head>
    <title>Smarty Test</title>
</head>
<body>
    <h1>Hello, Simon</h1>
    <p>Config title: Welcome to Smarty!</p>
</body>
</html>

编译缓存机制

首次访问时,Smarty 将 test.htm 编译为 templates_c/test.htm.php:

<?php
/* Smarty version 3.1.x, created on 2024-05-18 10:00:00 compiled from test.htm */ ?>
<html>
<head>
    <title>Smarty Test</title>
</head>
<body>
    <h1>Hello, <?php echo $this->getVariable('Name'); ?></h1>
    <p>Config title: <?php echo $this->getConfigVariable('title'); ?></p>
</body>
</html>

后续请求直接执行该 PHP 文件,跳过编译步骤。模板修改后自动重新编译(对比时间戳)。

常用进阶功能速查

功能模板语法PHP 代码
变量输出{$var}$smarty->assign('var', $val)
配置变量{#var#}$smarty->config_load('file.conf')
修饰器{$var|upper|truncate:20}管道链式调用 PHP 函数
条件判断{if $x}{else}{/if}支持 eq, neq, gt, lt, is [not] div by
循环{foreach $arr as $k => $v}$smarty->assign('arr', $data)
引入子模板{include file="header.tpl"}支持传参 {include file="x.tpl" title=$title}
字面量{literal}JS代码{/literal}禁用 Smarty 解析,原样输出

调试技巧

  • 开启调试控制台:$smarty->debugging = true; 页面底部弹出变量面板
  • 查看编译文件:templates_c/ 下对应 .php 文件
  • 强制重新编译:$smarty->force_compile = true;(开发环境)
  • 缓存模板输出:$smarty->caching = true; $smarty->cache_lifetime = 3600;

从 Smarty 2 迁移到 Smarty 3/4 注意点

  • 类名不变,但内部重构,性能大幅提升
  • 模板语法基本兼容,{php} 标签默认禁用(安全)
  • 插件机制改用命名空间自动加载
  • 建议直接 composer require smarty/smarty 安装最新版

Smarty 虽非当下最潮流选择(Twig、Blade 更现代),但在大量存量项目中仍广泛运行,掌握其核心机制有助于维护与重构。

copyright © 萬盛學電腦網 all rights reserved