php<=>smarty语法结构
php:
include_once 'smarty/libs/Smarty.class.php';//包含SMARTY类文件
$tpl=new Smarty();//创建一个模板类对象
$tpl->templets_default="default";//默认模板风格
$tpl->template_dir = "templates/".$tpl->templets_default."/";
$tpl->compile_dir = "templates_c/";//模板编译目录
$tpl->config_dir = "include/";//函数及类库等系统重要文件目录
$tpl->cache_dir = "cache/";//模板缓存目录
$tpl->caching=false;//控制是否缓存
$tpl->cache_lifetime = 60 * 60 * 24;//秒为单位进行计算缓存有效的时间
$tpl->left_delimiter="<{";//左标记 为防止和js冲突 尽量不要使用{...} 区别JS可用{literal}JS代码{/literal}
$tpl->right_delimiter="}>";//右标记 模板使用标记<{...}>
$tpl->assign("cfg",$cfg_array);//初始化基本参数 对应模板中引用语法 <{$cfg.varname}>
$tpl->display("index.tpl");//解析对应模板
smarty:【以下书写的左右标记使用默认的{...}】
{* include the header file here *} //注释方式
{php}...{/php}//在模板中直接嵌入php脚本 取决于$php_handling的设置
{include_php file="/path/to/load_nav.php"} //用于在模板中包含php脚本.如果设置安全模式,被包含脚本必须位于$trusted_dir路径下
{include file="header.tpl"} //包含其他文件
{capture name="foo"}...{/capture}//捕获模板输出的数据并将其存储到一个变量里,而不输出到页面.通过$smarty.capture.foo访问该变量
{config_load file="colors.conf"}//装载配置文件colors.conf
文件内容colors.conf:
pageTitle = "This is mine"
bodyBgColor = "#eeeeee"
tableBorderSize = "3"
tableBgColor = "#bbbbbb"
rowBgColor = "#cccccc"
调用方式:
第一种:{$smarty.config.pageTitle}
第二种:{#pageTitle#}
获取相关变量参数:
{$smarty.get.page} //获取浏览器变量page
{$smarty.post.page} //获取表单POST方式变量
{$smarty.cookies.username} //获取username的cookies值
{$smarty.server.SERVER_NAME} //获取服务器端相关参数
{$smarty.env.PATH} //获取系统路径
{$smarty.session.id} //获取session的ID值
{$smarty.request.username} //获取传递过来的username值 方式有:get/post/cookies/server/env
{$smarty.const._MY_CONST_VAL} //获取系统常量
{$smarty.config}//获取系统配置常量
常用小函数:
{$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"} //时间格式化 %Y 年 %m 月 %d 日 %H 时 %M 分 %S 秒 %a 星期缩写 %A 星期全称 %b月缩写 %B 月全称
{$str|capitalize} //将变量str首字母大写
{$str|lower}//将变量str全部字母转换为小写
{$str|upper}//将变量str全部字母转换为大写
{$str|cat:...}//字符串追加...
{$str|count_characters}//统计变量str字符总数 {$str|count_characters:true} true标识表示字符总数要加上空格
{$str|count_paragraphs}//计算段数 {$str|count_sentences} //计算句数 {$articleTitle|count_words} //计算词数 这三种中文不常用
{$str|default:"..."}//当变量str为空则默认显示...
{$str|escape:"html"} //用于html转码,url转码.. 默认html 可选html,htmlall,url,quotes,hex,hexentity,javascript;
{$str|indent:1:"\t"}//在每行缩进字符串,默认是4个字符 第二个可选参数,你可以指定缩进用什么字符代替
{$str|nl2br}//所有的换行符将被替换成 <br />.功能同PHP中的nl2br()函数一样.
{$str|replace:"1":"2"}//将变量str中的1替换为2
{$str|regex_replace:"/[\r\t\n]/":" "}//使用空格替换每个回车,tab,和换行符 正则替换
{$number|string_format:"%.2f"}//格式化字符串 sprintf语法格式
{$str|strip_tags}//去除Html标签.
{$str|truncate:30:"...":true}//从字符串开始处截取某长度的字符.默认是80个.第二个参数作为追加在截取字符串后面的文本字串
{$str|wordwrap:30:"\n":true}//可以指定段落的宽度(也就是多少个字符一行,超过这个字符数换行).默认80.
{assign var="name" value="Bob"}//用于在模板被执行时为模板变量赋值$name
{counter start=0 skip=2 print=false}//输出一个记数过程. counter 保存了每次记数时的当前记数值.
循环语法
第一种 if/else/else if/end if
{if $tbColor == "#D4D0C8"}
<tr bgcolor="{$tbColor}">
{assign var="tbColor" value="#EEEEEE"}
{else $tbColor == "#EEEEEE"}
<tr bgcolor = "{$tbColor}">
{assign var="tbColor" value="#D4D0C8"}
{/if}
第二种 section
{section name=rows loop=$data}
<tr bgcolor="{cycle values="#D4D0C8,#EEEEEE"}">//Cycle用于轮转使用一组值. 该特性使得在表格中交替输出颜色或轮转使用数组中的值变得很容易.
<td>{$data[rows]}</td>
</tr>
{/section}
第三种 foreach/foreach else/end foreach
<{foreach from=$newsArray item=newsID}>
ID:<{$newsID.newsID}><br>
title:<{$newsID.newsTitle}><br><hr>
<{foreachelse}>
no data!
<{/foreach}>
混编循环:
{section name=loop loop=$News step=1}
{if $smarty.section.loop.index % 4==0}
</tr>
<tr>
{/if}
<td>{$News[loop].newsID}</td>
<td>{$News[loop].newsTitle}</td>
{/section}
section语法参数
{section name = name loop = $varName[, start = $start, step = $step, max = $max, show = true]} name: section的名称,不用加$
$loop: 要循环的变量,在程序中要使用assign对这个变量进行操作。
$start: 开始循环的下标,循环下标默认由0开始
$step: 每次循环时下标的增数
$max: 最大循环下标
$show: boolean类型,决定是否对这个块进行显示,默认为true
这里有个名词需要说明:
循环下标:实际它的英文名称为index,是索引的意思,这里我将它译成"下标",主要是为了好理解。它表示在显示这个循环块时当前的循环索引,默认从0开始,受$start的影响,如果将$start设为5,它也将从5开始计数,在模板设计部分我们使用过它,这是当前{section}的一个属性,调用方式为Smarty.section.sectionName.index,这里的sectionName指的是函数原型中的name属性。
{section}块具有的属性值,分别为:
1. index: 上边我们介绍的"循环下标",默认为0
2. index_prev: 当前下标的前一个值,默认为-1
3. index_next: 当前下标的下一个值,默认为1
4. first: 是否为第一下循环
5. last: 是否为最后一个循环
6. iteration: 循环次数
7. rownum: 当前的行号,iteration的另一个别名
8. loop: 最后一个循环号,可用在section块后统计section的循环次数
9. total: 循环次数,可用在section块后统计循环次数
10. show: 在函数的声明中有它,用于判断section是否显示
一、使用缓存
要开启smarty的缓存,只需将caching设为true,并指定cache_dir即可.
使用cache_lefetime指定缓存生存时间,单位为秒
要对相同页面生成多个不同的缓存,在display或fetch中加入第二参数cache_id,如$smarty->display('index.tpl',$my_cache_id);此特性可用于对不同的$_GET进行不同的缓存
二、清除缓存
clear_all_cache();//清除所有缓存
clear_cache('index.tpl');//清除index.tpl的缓存
clear_cache('index.tpl',cache_id);//清除指定id的缓存
三、使用自定义缓存方式
设置cache_handler_func使用自定义的函数处理缓存
如:
$smarty->cache_handler_func = "myCache";
function myCache($action, &$smarty_obj, &$cache_content, $tpl_file=null, $cache_id=null, $compile_id=null){
}
该函数的一般是根椐$action来判断缓存当前操作:
switch($action){
case "read"://读取缓存内容
case "write"://写入缓存
case "clear"://清空
}
一般使用md5($tpl_file.$cache_id.$compile_id)作为唯一的cache_id
如果需要,可使用gzcompress和gzuncompress来压缩和解压
四、局部关闭缓存
要在某些区域使缓存失效(只对需要的缓存),有几种方法:
inser:
定义一个inser标签要使用的处理函数,函数名格式为:insert_xx(array $params, object &$smarty)其中的xx是insert的name,也就是说,如果你定义的函数为insert_abc,则模板中使用方法为{insert name='abc'}
参数通过$params传入
也可以做成insert插件,文件名命名为:insert.xx.php,函数命名为:smarty_insert_aa($params,&$smarty),xx定义同上
register_block:
定义一个block:smarty_block_name($params,$content, &$smarty){return $content;} //name表示区域名
注册block:$smarty->register_block('name', 'smarty_block_name', false); //第三参数false表示该区域不被缓存
模板写法:{name}内容{/name}
写成block插件:
1)定义一件插件函数:block.cacheless.php,放在smarty的plugins目录
block.cacheless.php的内容如下:
<?php
function smarty_block_cacheless($param, $content, &$smarty) {
return $content;
}
?>
2) 编写程序及模板
示例程序:testCacheLess.php
<?php
include('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching=true;
$smarty->cache_lifetime = 6;
$smarty->display('cache.tpl');
?>
所用的模板:cache.tpl
已经缓存的:{$smarty.now}<br>
{cacheless}
没有缓存的:{$smarty.now}
{/cacheless}
就是在缓存页面的时候像这样:
$smarty->display('basic.tpl',"groupxxx|".$cache_id);
然后要清这个groupxxx组下的所有缓存,则像这样:
$smarty->clear_cache(null,"groupxxx");
//检查缓存
if(!$smarty->is_cached('index.tpl')) {
// No cache available, do variable assignments here
}
web2.0网站速度优化的最好方案是减少数据库访问.
缓存是减少数据库访问的最佳方案.
有两种最基本缓存的方式
1.页面缓存
1.1 如果你用的是smarty做为ui模板的话.页面缓存十分的方便
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = 1;
if(!$smarty->is_cached('index.tpl')) {
// No cache available, do variable assignments here.
$contents = get_database_contents();
$smarty->assign($contents);
}
$smarty->display('index.tpl');
以上为最基本的缓存方案,对于同一个tpl,根据不同的参数可以缓存多个.
$smarty->is_cached('index.tpl',params); //根据参数判断
$smarty->display('index.tpl' ,params);//根据参数显示
以上实现了整个页面的缓存
很多时候为了优化用户的体验,需要对局部即时显示.最方便的方案是对即时显示的部分做一下块标记.每次刷新时重新显示些块就可
index.php:
<?php
$smarty->caching = 1;
function smarty_block_dynamic($param, $content, &$smarty) {
return $content;
}
$smarty->register_block('dynamic', 'smarty_block_dynamic', false);
$smarty->display('index.tpl');
?>
index.tpl is://即显示模板
Page created: {'0'|date_format:'%D %H:%M:%S'}
{dynamic}
Now is: {'0'|date_format:'%D %H:%M:%S'}
... do other stuff ...
{/dynamic}
官方介绍
1.2: 当然上面的smarty缓存只是把文件生成好的模板文件缓存在文件系统.更加高级的缓存方案是把文件静态化缓存到内存中.现在有很多此类工具.这里先不介绍.
2.数据缓存.
最流行的是memcache.