smarty是一款优秀的模板引擎,不只能够自定义方法,还要以进行页面编译缓存,功能至关完美。javascript
以前同事,问我smarty里模板文件可不能够把模板源文件去除一些不必的空格和回车了。php
请看下面的说明,这里用的是smarty2和smarty3html
一、首先加个方法 striphtml方法java
在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); }
二、找到编译模板的方法smarty2中,_compile_resource缓存
在文件smarty.class.php,方法是_compile_resource添加striphmtlfetch
大约在文件的1432行,方法名是:_compile_resourcethis
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']); ....省略 }
三、找到编译模板的方法smarty3中,/smarty3/libs/sysplugins/smarty_template_source.phpcode
在这个文件里,一样添加striphtml方法,而后再找到getContent()方法便可~htm
/** * Get source content * * @return string */ public function getContent() { return isset($this->content) ? $this->striphtml($this->content) : $this->striphtml($this->handler->getContent($this)); }
用浏览器访问站点的URL,查看查看源文件看看。
注意:
若是模板文件里有js等脚本,必定要严格输写,要花括号的地方必定要加、要分号的地方必定要加。
否则全变成一行会出错的~