Smarty系统是基于使用一个模板文件(.tpl),它包含了展示代码,并且在里面这个展示层开发者获取数据是从PHP 开发者提供的,这样两者可以隔离开来。
图片.png
Smarty语法
Smarty拥有自己的语法,这样才能从PHP代码和展示层代码中区分出来,用于smarty引擎去处理。我们开发一个PHP应用,需要提供出应用的目录结构templates(模板),templates_c(编译后的模板),configs(模板的配置文件)。
Smarty变量
Smarty变量提供了接口给PHP代码。
1.单个值或者数组。
2.Smarty的临时变量:
{assign var="username" value "Sarah Conner"}POST, cookie, SESSION数据
Smarty系统提供了许多内建方法去获取POST,cookie, SESSION数据。
$smarty.cookies.$smarty.session. $smarty.request. $smarty.post.
内建变量修饰
1.改变大小写
{$variable|capitalize}
{$variable|lower}2.缩进
{$variable|indent:<#ofspaces>}3.使用HTML的
替代换行符
{$variable|nl2br}4.其余的
{section}用于循环
{section name= loop=$array}
{$array[].}
{/section} Smarty使用
目录结构
图片.png
/libs/中是我们下载的整个Smarty文件夹。
我们要建立一个.php文件和相对应的.tpl文件(保存在templates文件夹下)。
smartyHeader.php:
caching = true; $smarty->cache_lifetime = 120; // 我们设置了编译后的模板文件存储时间120s$smarty->template_dir = './templates'; // 配置模板目录$smarty->compile_dir = './templates_c'; // 配置编译后的模板目录
test.php:
assign('title', $title); // 我们可以将这个`title`称作doorway$smarty->assign('message', $msg);
$smarty->display('test.tpl'); // 会将这个模板发送给smarty引擎1)引进创建smarty的变量。
3)我们要指明关联的.tpl文件。
test.tpl:
{$title} {$message}
for循环
{foreach from = $movie_arr key=title item=dir} // key指定为title item指定为dir,注意不是value指定为
{$title} {$dir}
{/foreach}circle
{circle values='gray, sliver'}
| {$title} | {$dir} |
使用smartyBC可以用{php}标签
{php} echo sha1('hellow');
{/php}
作者:廖马儿
链接:https://www.jianshu.com/p/af8673834f62



