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 # 入口脚本
title = "Welcome to Smarty!"
cutoff_size = 40
[setup]
bold = true
<html>
<head>
<title>Smarty Test</title>
</head>
<body>
<h1>Hello, {$Name}</h1>
<p>Config title: {#title#}</p>
</body>
</html>
<?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;{php} 标签默认禁用(安全)composer require smarty/smarty 安装最新版Smarty 虽非当下最潮流选择(Twig、Blade 更现代),但在大量存量项目中仍广泛运行,掌握其核心机制有助于维护与重构。