技术头条 - 一个快速在微博传播文章的方式     搜索本站
您现在的位置首页 --> PHP --> 两个smarty小插件,以及如何自定义smarty插件目录

两个smarty小插件,以及如何自定义smarty插件目录

浏览:2192次  出处信息
smarty中文截取,其实网上那些并不是太好。。翻了翻手册,发现个现成的代码,挺好用
<?php
function smarty_modifier_truncate_cn($string$length 80$etc '...'$code 'utf-8'
) {
    if (
$length == 0
)
        return 
''
;
    return 
mb_strimwidth($string0$length'...''utf-8'
);
}
?>

保存为modifier.truncate_cn.php放在smarty的plugins目录下即可,怎么用就不用说了吧。。

第二个是类似腾讯微博的发表时间的
<?php
function smarty_modifier_cntime($old_time
) {
    
$res    null
;
    
$old    strtotime($old_time
);
    
$now    $_SERVER['REQUEST_TIME'
];
    
$ex    $now $old
;
    switch (
$ex
) {
        case 
$ex 60 
:
            
$res    '刚才'
;
            break;
        case 
$ex 3600 
:
            
$res    intval($ex/60).'分钟前'
;
            break;
        case 
$ex 86400 
:
            
$res    intval($ex/3600).'小时前'
;
            break;
        case 
$ex 604800 
:
            
$res    intval($ex/86400).'天前'
;
            break;
        default :
            
$res    date("Y-m-d H:s",$old
);
    }
    return 
$res
;
}
?>

保存为modifier.cntime.php放在smarty的plugins目录下即可,想增加也很方便,再写几个判断就行


下面来说说怎么在不更改原有plugins目录的情况下,自定义添加一个plugins的目录。
由于有时候我们会自定义几个插件,而在作为框架使用的情况下,smarty是会被公用的,那么各自的项目需要各自的plugins,如果混在一起,都放在smarty默认的plugins里面肯定是不行的,于是我看了看smarty的源码,发现在core.assemble_plugin_filepath.php这个文件中有这么一段
<?php
    
foreach ((array)$smarty->plugins_dir as $_plugin_dir
) {

        
$_plugin_filepath $_plugin_dir DIRECTORY_SEPARATOR $_plugin_filename
;

        
// see if path is relative
        
if (!preg_match("/^([/\\]|[a-zA-Z]:[/\\])/"$_plugin_dir
)) {
            
$_relative_paths[] = $_plugin_dir
;
            
// relative path, see if it is in the SMARTY_DIR
            
if (@is_readable(SMARTY_DIR $_plugin_filepath
)) {
                
$_return SMARTY_DIR $_plugin_filepath
;
                break;
            }
        }
        
// try relative to cwd (or absolute)
        
if (@is_readable($_plugin_filepath
)) {
            
$_return $_plugin_filepath
;
            break;
        }
    }
?>

我们可以看到,在smarty的实例中,plugins_dir是以一个数组形式存在的,并且可以有多个,这样一来就简单了,直接给这个数组再塞进去一个地址就ok了。
<?php
.......
array_push($this->tpl->plugins_dirROOT_PATH '/smarty_plugins/'
);
.......
?>

这是我的框架中的一个应用。。这样一来,针对这个项目的plugins我就可以放在本项目的目录下了,而不需要放在核心框架的smarty的plugins目录下,以免造成混乱

建议继续学习:

  1. Smarty之缓存操作    (阅读:2628)
  2. smarty的date_format中不能有中文的解决方案    (阅读:2472)
  3. Smarty截取中文乱码的解决办法    (阅读:2390)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
© 2009 - 2024 by blogread.cn 微博:@IT技术博客大学习

京ICP备15002552号-1