php smarty变量调节器,smarty配置以及变量调节器详解

最近没事儿做,就研究研究smarty模版引擎,越来越觉得smarty的强大了,smarty的教程在网上好像都比较乱。

2.把下载下来的smarty改名为smarty然后复制到新建好的文件夹里

3.新建一个smarty.inc.php(也可以是别的)<?php

require_once 'smarty/Smarty.class.php';

$smarty=new Smarty();

$smarty->template_dir='templates/';

$smarty->compile_dir='templates_c/';

$smarty->cache_dir='temp/';

$smarty->config_dir='configs/';

$smarty->caching=0;          //缓存

$smarty->cache_lifetime=60;

if (!defined('SITE_URL')){

$url=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'];

define('SITE_URL', $url);

}

if (!defined('__ROOT__')){

define('__ROOT__', rtrim(dirname(__FILE__),'\\').'\\');

}

//去除反斜杠

if (get_magic_quotes_gpc()){

function stripcslashes_arr($array){

is_array($array)?array_map('srtipcslashes_arr', $array):stripcslashes($array);

}

$_POST=stripcslashes_arr($_POST);

$_GET=stripcslashes_arr($_GET);

$_REQUEST=stripcslashes_arr($_REQUEST);

$_COOKIE=stripcslashes_arr($_COOKIE);

$_SESSION=stripcslashes_arr($_SESSION);

}

//时区设置

date_default_timezone_set('PRC');

//加载function

if (file_exists('common/common.php')){

require_once 'common/common.php';

}

并且手动建立相应的目录,调试的时候建议把缓存关了。

然后新建一个index.php,<?php

require_once 'smarty.inc.php';

$title='第一个标题';

$smarty->assign('title',$title);

$people=array(

array('name'=>'张三','sex'=>'男','age'=>'20'),

array('name'=>'李四','sex'=>'男','age'=>'40'),

array('name'=>'王五','sex'=>'女','age'=>'32'),

);

$smarty->assign('people',$people);

$smarty->display('index.tpl');

在templates这个文件夹里新建一个index.tpl,调用方式为{$title},然后访问index.php是不是ok了?

数组的访问方式,比如$people这个二维数组,就是{$people.0.name}输出的就是张三

对象的访问方式,{$对象名->属性(方法)}

接下来就是变量调节器,其实日常用到的并不多,所以我就练习了几个常用的

1.capitalize首字母大写{$title|captalize}

2.count_characters统计字符数    {$title|count_characters},新版的smarty统计中文也没问题,统计的时候会过滤掉空格(默认),{$title|count_character:true},就不会过滤空格了

3.cat连接字符串{$title|cat:"..."}    output:第一个标题...

4.date_format        格式化时间{$smarty.now|date_format:"%T-%m-%d %H:%M:%S"}    输出目前格式化的时间,第二个参数为格式化失败以后默认显示{$smarty.now|date_format:"%T-%m-%d %H:%M:%S":"0000-00-00"}

5.default    变量为空的时候要输出什么,或者变量没有定义,都可以指定默认输出{$title|dafault:"暂时没有数据"}

6.escape        编码,最常用的就是url,html编码了,把html代码转换为实体保存到数据库等作用,默认为html编码

7.indent        缩进,发布文章的时候会需要这个。第一个参数指定要缩进的字符数,第二个参数指定要用什么字符代替{$title|indent:4:"..."}        output:............第一个标题

8.lower        所有字符转换为小写

9.nl2br        等同php的nl2br函数

10.regex_replace    正则替换,第一个为正则表达式,第二个为要替换成的文本

11.replace        简单替换,用法等同regex_replace

12.strip            去掉多余的空格

13.strip_tags        去掉html标签,

14.truncate        截取字符数,{$title|truncate:10}截取10个字符,{$title|truncate:10:"..."}截取以后在后面显示...{$title|truncate:10:"..."|true}截取到词的边界(false)的时候,为true的时候是截取到字符边界

15.upper    转换为大写

16.wordwrap    行宽约束{$title|wordwrap:10}到了第10个字符就自动换行{$title|wordwrap:10:"
"}用什么字符约束,如果没有这个,他是不换行的。第三个如果为true,{$title|wordwrap:10:"
",true}约束到到词的边界(false)的时候,为true的时候是约束到字符边界

这些变量调节器也可以根据需要去组合在一起的。