smarty是一款优秀的模板引擎,不仅可以自定义方法,还要以进行页面编译缓存,功能相当完美。
之前同事,问我smarty里模板文件可不可以把模板源文件去除一些没必要的空格和回车了。
请看下面的说明,这里用的是smarty2和smarty3
1、首先加个方法 striphtml方法
在smarty.class.php里添加一个去除多余空格回车的方法
/**
* strip Html
*
* @param string $html
* @return string
*/
function striphtml($html)
{
//return $html;
//strip php inline comment
$html = preg_replace(':\s+//.*?\n:', '', $html);
//strip html comments(消去html注释内容)
$html = preg_replace('/<!--\s*[^[][^!][^<].*?-->/s', '', $html);
//strip javascript comments(消去javascript注释内容)
$html = preg_replace('/\/\*.*?\*\//s', '', $html);
//strip blank between tags(消去相邻标记间空白)
$html = preg_replace('/>\s*</s', '><', $html);
//strip blank line(消去空行)
$html = preg_replace('/(\s)+/s', ' ', $html);
return trim($html);
}
2、找到编译模板的方法smarty2中,_compile_resource
在文件smarty.class.php,方法是_compile_resource添加striphmtl
大约在文件的1432行,方法名是:_compile_resource
function _compile_resource($resource_name, $compile_path)
{
$_params = array('resource_name' => $resource_name);
if (!$this->_fetch_resource_info($_params)) {
return false;
}
$_source_content = $this->striphtml($_params['source_content']);
....省略
}
3、找到编译模板的方法smarty3中,/smarty3/libs/sysplugins/smarty_template_source.php
在这个文件里,同样添加striphtml方法,然后再找到getContent()方法即可~
/**
* Get source content
*
* @return string
*/
public function getContent()
{
return isset($this->content) ? $this->striphtml($this->content) : $this->striphtml($this->handler->getContent($this));
}
用浏览器访问站点的URL,查看查看源文件看看。
注意:
如果模板文件里有js等脚本,一定要严格输写,要花括号的地方一定要加、要分号的地方一定要加。
不然全变成一行会出错的~