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等腳本,必定要嚴格輸寫,要花括號的地方必定要加、要分號的地方必定要加。
否則全變成一行會出錯的~