以前在用smarty做模板开发PHP程序的时候,都是给一个全局变量,然后用全局变量加上图片的路径,如{$siteroot}/images/1.jpg。
今天看到smarty预过滤器,可以用正则过滤模板的内容,写个plusing就可以设置图片目录,CSS,JS的目录,小小研究了下。
定义TMP_DIR常量
- define('TMP_DIR','templates/');
在smarty的plusing目录下新建一个文件smarty_prefilter_chpath.php
- <?php
- function smarty_prefilter_chpath($tpl_source,$smarty)
- {
- return preg_replace("/(<(img.*?src|link.*?href)=([/"']))(.*?)(//3.*?>)/is","$1".TMP_DIR."$4$5",$tpl_source);
- }
- ?>
然后设置smarty的时候使用进行预过滤。
- $smarty=new Smarty();
- $smarty->load_filter('pre','chpath');
模板地址就变成TMP_DIR/img/*.jpg了