Smarty技巧

2008-4-24  14:14

安装:
可以通过继承来实现安装的,看代码

PHP代码
  1. //setup.php   
  2. <?php   
  3. require("libs/Smarty.class.php");   
  4. class Smarty_C extends Smarty{   
  5.     function Smarty_C(){   
  6.         $this->smarty();   
  7.         $this->template_dir = ‘templates’;   
  8.         $this->compile_dir = ‘templates_c’;   
  9.         $this->cache_dir = ‘cache’;   
  10.         $this->left_delimiter = ‘<{’;   
  11.         $this->right_delimiter = ‘}>’;   
  12.         $this->caching = 1;   
  13.         $this->cache_lifetime = 1800;   
  14.         $this->config_dir = ‘config’;    
  15.   
  16.         //regist functions   
  17.         $this->register_block(‘dynamic’,’smarty_block_dynamic’,false);   
  18.     }   
  19. }   
  20.   
  21. function smarty_block_dynamic($param$content$smarty) {   
  22.     return $content;   
  23. }   

这样更方便管理,可以在类里面完成插件的注册,而不用实例化一个对象后再注册,使用方法还是类似

PHP代码
  1. <?php   
  2. require(’setup.php’);   
  3. $smarty = new Smarty_C();   
  4. //$smarty->assign(’title’,'hello lzyy’);   
  5. $smarty->display(‘test.tpl’);   
  6. ……….   
  7. ?>  

 config文件的设置:
除了建立常规的templates,templates_c,cache文件夹外,我觉得config文件夹也很必要,可以在里面建立config文件,然后在模板里载入

比如config文件夹下面,有一个test.conf文件

# global variables
bgcolor = ‘#cc0000′
title = ‘hello world’

# customer variables
[customer]
title = ‘hello lzyy’
 

然后就可以在模板里载入,并使用其中的变量了

<{ config_load file=’test.conf’ section=’customer’ }>
<{ include file=’header.tpl’ title=#title# }>
<body style=’background:<{ #bgcolor# }>’>

config里面的变量通过#varname#来获取,同时如果在config里面,指定了section,比如上面的customer,并且在载入config文件的时候指定了相应的section,那么就可以使用该section里面的变量(全局变量自动载入,如果section里面的变量名跟全局变量的变量名一样,那么前者将覆盖后者)

关于缓存:
拿动态内容作为例子,如果涉及到根据传递的参数查询数据库,比如user_id,那么有两种缓存策略

1、使用display($filename,$user_id)
这样就能为不同的user_id产生不同的缓存文件,但是问题也来了,如果用户数很多的话,那么会在缓存文件夹里生成很多的类似文件,无论是从磁盘占用,还是查询速度都会受到影响。

2、对动态内容不执行缓存
可以通过两种方法来解决。一个是smarty内置的insert方法,我感觉这个不够灵活和方便;第二个方法就是我们在安装的时候注册的一个函数dynamic,使用方法

<{ dynamic }>
<{ ‘0′|date_format:’%D %H:%M:%S’ }>
<{ /dynamic }>
 
插件:
插件默认都放在plugins文件夹下面,如果自己想写一个插件,只要把写完的插件按照smarty的方式命名,并放到这个文件夹下面就可以使用了。

插件的使用方法

function usage:{funcname data=’hello baby’}(function.name.php)
modifiler usage:{$data|upper}(modifiler.name.php)
block usage:{func} … {/func}(block.name.php)

具体的参数可以参考smarty手册,后者直接打开相应的php文件查看。

小提示:
如果一个smarty变量为空(”),并且要输出一个默认值时,可以使用default(eg:$text|default:’ ‘)
smarty很方便的一个特性是支持include,并且php里assign的变量可以在include进来的file里显示
如果要显示时间的话,最好传递给smarty一个时间戳,这样就能方便地控制时间的显示格式
smarty内置了对全局变量的引用,比如{$smarty.get.page},{$smarty.cookie.name}
使用section代替foreach

Tags:

发表评论