smarty模板自定义变量调节器

在smarty里有一些已经定义好的变量调节器,如关于时间的:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
 
<body>
 
 
<!--显示当前时间戳-->
<{$smarty.now}>
     
<!--调用调节器显示想要的时间格式-->
<{$smarty.now|date_format:"%Y-%m-%d %H-%M-%S"}>
 
</body>
</html>

但是这些调节器并不是很好用,每次都要从手册中找,很麻烦。鉴于此,smarty支持自定义的变量调节器,所以我们随时可以自定义一些常用的调节器,以后用到时直接调用就可以了。

1、时间变量调节器 modifier.time.php:

<?php
    //用来格式化时间日期
function smarty_modifier_time($str){
    return date("Y-m-d H:i:s",$str);
}
?>

test.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
 
<body>
 
    <!--调用自定义的变量调节器-->
    <{$smarty.now|time}>
 
</body>
</html>

2、截取字符串的变量调节器 modifier.jiequ.php:

<?php
 
function smarty_modifier_jiequ($str,$cd,$sl){
//  第一个参数:是传过来的变量,必须有
//  第二个参数:是截取多长
//  第三个参数:是要代替后面的省略符号
     
    $str = substr($str,0,$cd);
    return $str.$sl;
}
?>

str.php:

<?php
    header("content-type:text/html;charset=utf-8");
    //引入smarty类
require "../init.inc.php";
 
//数组类型
$arr =array("one"=>"1111","two"=>"2222");
 
 
//注册变量
$smarty->assign("ceshi","大家好啊你是谁啊"); 
 
 
$smarty->assign("haha","12345678901234567890");
 
 
$smarty->assign("nnn","abcdefghijklmnopqrstuvwxyz");
//显示
$smarty->display("test.html");
?>

test.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
 
<body>
     
        <{$ceshi|jiequ:"12":"..."}>
             
        <{$haha|jiequ:"10":"..."}>
             
        <{$nnn|jiequ:"10":"..."}>
         
 
</body>
</html>

 

posted @ 2017-07-03 14:54  梦深深处  阅读(466)  评论(0编辑  收藏  举报