Smarty是一个用PHP编写的模板引擎,它允许将业务逻辑和表示逻辑分离,提供了更好的模板设计和维护。在Smarty框架中,模板文件是纯HTML,其中可以包含一些变量和逻辑控制语句。
使用Smarty框架的步骤如下:
在项目中引入Smarty框架,可以通过Composer安装Smarty:composer require smarty/smarty创建Smarty实例并设置模板目录、编译目录和缓存目录:require_once('vendor/autoload.php');$smarty = new Smarty();$smarty->setTemplateDir('templates/');$smarty->setCompileDir('templates_c/');$smarty->setCacheDir('cache/');将变量赋值给模板:$smarty->assign('title', 'Welcome to My Website');$smarty->assign('content', 'This is the content of my website');在模板文件中使用Smarty标签显示变量:<!DOCTYPE html><html><head> <title>{$title}</title></head><body> <h1>{$content}</h1></body></html>渲染模板并显示:$smarty->display('index.tpl');通过以上步骤,你可以使用Smarty框架来更好地管理和显示你的模板文件。Smarty还提供了很多其他功能,例如循环、条件语句、包含文件等,可以根据具体需求进行灵活运用。


