smarty—牛刀小试
###smarty 初识
- 官网 http://www.smarty.net/
- Smarty is a template engine for PHP(PHP模板引擎)
smarty使用:
index.php
<?php
date_default_timezone_set("PRC");//PRC为“*”
require ('../smarty/Smarty.class.php');
$smarty = new Smarty();
/*Smarty配置(五配置两方法)2.0版本*/
// $smarty->left_delimiter = "{"; //左定界符
// $smarty->right_delimiter = "}"; //右定界符
// $smarty->template_dir = "tpl"; //html模板地址
// $smarty->compile_dir = "template_c"; //模板编生成的文件
// $smarty->cache_dir = "cache"; //缓存
//以下是开启缓存的另外两个配置。因为一般不用smarty的配置,这里作为了解
$smarty->caching = true; //开启缓存
$smarty->cache_lifetime = 120; //缓存时间
/*smarty3.0版本后的五配置*/
$smarty->setLeftDelimiter('{');//左定界符
$smarty->setRightDelimiter('}');//右定界符
$smarty->setTemplateDir('tpl/');//模板地址
$smarty->setCompileDir('template_c/');//编译文件
$smarty->setCacheDir('cache/');//缓存地址
$smarty->assign('articalTitle','奔波霸');
$smarty->display('test.tpl');
?>
test.tpl
{$articalTitle};
smarty 输出数组
$arr = array("title"=>"lol","name"=>"德玛西亚");
$smarty->assign("arr", $arr);
$brr = array("artical"=>array("title"=>"lol","name"=>"德玛西亚"));
$smarty->assign("brr", $brr);
{$arr['title']}{$arr['name']}; {*一维数组*}{*注释*}
{$brr["artical"]["title"]}{$brr["artical"]["name"]} {*二维数组*}
smarty 注释
{* XXX *}
smarty 变量调节器
####capitalize,cat,upper,lower
$scale = "hello";
$smarty->assign("scale", $scale);
{$scale|capitalize}; {*首字母大写*}
{$scale|cat:" kity"} {*连接字符串*}
{$scale|upper}; {*大写变量调节器*}
{$scale|lower|upper}; {*小写变量调节器*}
date_format
$time = time();
$smarty->assign("time", $time);
{$time|date_format:"%B %e,%y %H:%M:%S"}; {*日期格式化*}
default
$lol = "";
$smarty->assign("lol", $lol);
{$lol|default:"诺克萨斯之手"} {*默认输出*}
escape
$url = "https://www.baidu.com";
$smarty->assign("url", $url);
{$url|escape:"url"} {*url转码*}
nl2br
$str = "我有一只小毛驴\n从来也不骑";
$smarty->assign("str", $str);
{$str|nl2br} {*换行符转换为br,html不识别\n,其中2(two)是to的谐音*}
smarty 对象赋值
class Cool {
function dd(){
echo "pilipala";
}
}
$obj = new Cool();
$smarty->assign("obj",$obj);
{$obj->dd()}
smarty 函数使用
function add ($params){ //$params为模板传递过来的数组变量
$p1 = $params["p1"];
$p2 = $params["p2"];
echo $p1."已经".$p2;
}
$smarty->registerPlugin("function", "f_test", "add"); //f_test为函数名字便于模板调用,add为函数本身
{f_test p1="苹果" p2="熟了"} {*将后面的键值对组合为数组,作为参数传递给函数本身*}
smarty 使用php的变量调节器
smarty->assign("time", time());
$str = "我有一只小毛驴\n从来也不骑";
$smarty->assign("str", $str);
{"Y-m-d"|date:$time} {*此处$time对应前面time,date调节器第一个参数为格式,第二个参数为日期*}
{"小"|str_replace:"大":$str} {*str_replace调节器,第一个参数为替换谁,第二个参数为替换为什么,第三个参数为被替换的字符串*}
smarty 编写插件
####function插件
plugins目录下新建function.插件名.php
如:function.test.php
function.test.php
<?php
function smarty_function_test($params){
$p1 = $params["p1"];
$p2 = $params["p2"];
echo $p1."已经".$p2;
}
?>
test.tpl
{test p1="苹果" p2="熟了"}
modeifier插件(变量调节器插件)
block插件(区块函数插件)
smarty 循环
$crr = array(array("title"=>"lol","name"=>"德玛西亚"));
$smarty->assign("crr", $crr);
{foreach $crr as $value}
{$value.title}
{$value.name}
{foreachelse}
没有
{/foreach}