1.下载Smarty, 解压缩, 有4个文件夹
templates : 模板存放目录
templates_c : 模板编译目录
configs : 设定文件存放目录
cache : 缓存目录
2.在PHP中加载Smarty
define( 'SMARTY_DIR', '/usr/local/lib/Smarty-2.6.18/libs/' );
require_once( SMARTY_DIR .'Smarty.class.php' );
3.在PHP中使用Smarty
$smarty = new Smarty();
$smarty->template_dir = '/var/www/smarty/templates/';
$smarty->compile_dir = '/var/www/smarty/templates_c/';
$smarty->config_dir = '/var/www/smarty/configs/';
$smarty->cache_dir = '/var/www/smarty/cache/';
$smarty->assign( 'name', '某某人' );
$smarty->display( 'test.tpl' );
模板文件test.tpl如下
{$name},你好!
今天是{$smarty.now|date_format:'%Y年%m月%d日'}。
4.smarty中使用变量
1)在PHP中定义变量
单个变量 : $smarty->assign( 'name', '名字' );
数组 : $smarty->assign( array( 'age' => '18', 'sex' => 'male' ) );
$testArray = array( 'black', 'white', 'blue', 'yellow' );
$smarty->assign( 'testArray', $testArray);
类 : $obj = new TestClass();
$smarty->assign( 'test_obj', $obj );
或者 $smarty->assign_by_ref( 'test_obj', $obj );
assign会复制类,assign_by_ref直接使用该对象
2)直接在tpl模板中定义变量
{assign var="title" value="标题"}
3)在tpl模板中调用变量
{$name}
{$testArray[0]}
{$test_obj->method1()}
5.smarty中使用设定文件
1)configs目录下新建config文件
title = '标题'
content = '内容'
writer= '作者'
2)加载config文件
在PHP中加载 : $smarty->config_load( 'config文件名' );
在tpl中加载 : {config_load file='config文件名'}
3)使用config文件中的设定值
{#title#} {#content#} {#writer#}
6.使用定义值
1)PHP中定义 : define( 'TITLE', '标题' );
2)tpl中使用 : {$smarty.const.TITLE}
7.tpl中可使用的变量
环境变量 : {$smarty.env.PATH}
Form的POST变量 : {$smarty.post.name}
URL中的变量 : {$smarty.get.id}
时间 : {$smarty.now}
8.分歧条件
{if 条件1}...{elseif 条件2}...{else}...{/if}
9.循环
{foreach from=$testarray1 key=k item=f}...{foreachelse}...{/foreach}
{while 条件}...{/while}
{section name=c loop=$testarray1}...{$testarray1[c]}...{$testarray2[c]}...{$testarray3[c]}
...{/section}
10.使用函数
{funcname attr1=$val1 attr2='stri1'}
这里的attr1,attr2是指function中用到的变量,不是固定的attr1,attr2
11.模板文件的嵌套(include)
一个模板文件可以通过include嵌套到另外一个模板文件中
{include file='header.tpl' title='标题' content='内容XXX'}
这里的title,country都是header.tpl中用到的变量
12.模板文件中的 { }
若需要表示{或者},可以使用 {ldelim},{rdelim}
或者用 {literal}不需要{smarty}解析的文本{/literal}
13.模板文件中的修饰子
文字列转大写 : {$str|upper}
文字列转大写并加空格 :{$str|upper|spacify}
时间格式化 : {$smarty.now|date_format:'%Y年%m月%d日'}
解决html语法问题和正确显示问题 : {$title|escape:'html':'UTF-8'}
转换内码 : {$text|mb_convert_encoding:'SJIS':'UTF-8'}
14.php中读取tpl模板内容
$buffer = $smarty->fetch( 'test.tpl' );