Smarty是PHP模板引擎,实现前后端分离,通过assign赋值、display渲染模板,支持变量、循环、条件判断等语法,可配置缓存提升性能,便于维护与开发。

模板引擎,简单说,就是把PHP代码和HTML代码分离,让前端专注于HTML,后端专注于PHP逻辑。Smarty,是PHP界的老牌劲旅,用它能让你的代码更清晰,维护起来也更方便。
下载和安装Smarty
去Smarty官网下载最新版本,解压后,把
libs
引入Smarty类
立即学习“PHP免费学习笔记(深入)”;
在你的PHP代码里,引入Smarty类:
require_once 'libs/Smarty.class.php'; $smarty = new Smarty();
设置模板目录和编译目录
$smarty->setTemplateDir('templates/');
$smarty->setCompileDir('templates_c/');
$smarty->setConfigDir('configs/');
$smarty->setCacheDir('cache/');templates/
.tpl
templates_c/
configs/
cache/
创建模板文件(.tpl)
比如,
templates/index.tpl
<!DOCTYPE html>
<html>
<head>
<title>{$title}</title>
</head>
<body>
<h1>{$heading}</h1>
<p>{$content}</p>
</body>
</html>注意:
{$title}{$heading}{$content}PHP代码赋值并显示模板
require_once 'libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->setTemplateDir('templates/');
$smarty->setCompileDir('templates_c/');
$smarty->setConfigDir('configs/');
$smarty->setCacheDir('cache/');
$smarty->assign('title', 'Smarty Demo');
$smarty->assign('heading', 'Welcome to Smarty!');
$smarty->assign('content', 'This is a simple example.');
$smarty->display('index.tpl');assign()
display()
Smarty的语法挺丰富的,但掌握几个常用的就够用了。
变量:
{$variable}循环:
{foreach}<ul>
{foreach $items as $item}
<li>{$item.name} - {$item.price}</li>
{/foreach}
</ul>条件判断:
{if}{if $user.is_logged_in}
<p>Welcome, {$user.name}!</p>
{else}
<p>Please log in.</p>
{/if}函数:Smarty内置了一些函数,比如
{html_options}注释:
{* This is a comment *}配置文件可以让你把一些全局性的配置,比如网站名称、数据库连接信息等,放在一个单独的文件里,方便管理。
创建配置文件
比如,
configs/config.conf
title = "My Awesome Website" db_host = "localhost" db_user = "root" db_pass = "password"
在PHP代码中加载配置文件
$smarty->configLoad('config.conf');在模板中使用配置变量
<h1>{$smarty.config.title}</h1>Smarty的缓存机制可以大大提高网站的性能,尤其是在访问量大的时候。它会将编译后的模板缓存起来,下次访问时直接读取缓存,而不用重新编译模板。
开启缓存
$smarty->caching = true; $smarty->cache_lifetime = 3600; // 缓存有效期,单位秒
判断是否使用缓存
if (!$smarty->isCached('index.tpl')) {
// 如果没有缓存,则进行赋值操作
$smarty->assign('title', 'Smarty Demo');
$smarty->assign('heading', 'Welcome to Smarty!');
$smarty->assign('content', 'This is a simple example.');
}
$smarty->display('index.tpl');清除缓存
你可以手动清除缓存:
$smarty->clearCache('index.tpl'); // 清除单个模板的缓存
$smarty->clearAllCache(); // 清除所有缓存或者设置缓存的生命周期,让Smarty自动清除过期缓存。
使用Smarty,刚开始可能会觉得有点麻烦,但熟练之后,你会发现它确实能提高你的开发效率,让你的代码更清晰易懂。而且,它也是很多PHP框架的基础,学会Smarty,对你学习其他框架也有帮助。
以上就是PHP如何使用模板引擎_模板引擎Smarty使用教程的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号