smarty压缩html代码
发布于 作者:苏南大叔 来源:程序如此灵动~

苏南大叔为大家带来了smarty的进阶版的使用教程,去除smarty输出的html中的所有的html中的回车换行空白注释等。这种做法,在现在是个流行的趋势,即代码压缩。
js和css都被压缩了,那么html有什么理由不被压缩呢?对吧?
- 苏南大叔最喜欢的css和js的压缩工具是:koala,见这里:https://newsn.net/say/koala-release.html 。
- smarty的基础使用,见这里:https://newsn.net/say/composer-install-smarty.html 。
苏南大叔的答案:
$smarty = new \Smarty;
//......
function compress_html($html) {
$html = preg_replace(':\s+//.*?\n:', '', $html);
$html = preg_replace('/<!--\s*[^[][^!][^<].*?-->/s', '', $html);
$html = preg_replace('/\/\*.*?\*\//s', '', $html);
$html = preg_replace('/>\s*</s', '><', $html);
$html = preg_replace('/(\s)+/s', ' ', $html);
return trim($html);
}
$smarty->registerFilter("output", "compress_html");
网上流行的说法:
在smarty.class.php里添加一个去除多余空格回车的方法。
function striphtml($html)
{
$html = preg_replace(':\s+//.*?\n:', '', $html);
$html = preg_replace('/<!--\s*[^[][^!][^<].*?-->/s', '', $html);
$html = preg_replace('/\/\*.*?\*\//s', '', $html);
$html = preg_replace('/>\s*</s', '><', $html);
$html = preg_replace('/(\s)+/s', ' ', $html);
return trim($html);
}
然后修改,/smarty3/libs/sysplugins/smarty_template_source.php 这个文件中的getContent()方法。
public function getContent()
{
return isset($this->content) ? $this->striphtml($this->content) : $this->striphtml($this->handler->getContent($this));
}
对比说明
苏南大叔个人觉得,我写的这种比网上流传的更好些,因为毕竟没有破坏smarty3的完整性。您觉得呢?
效果截图
最后再贴出压缩完的效果截图。
就苏南大叔个人来说,不是太喜欢这种压缩效果,更喜欢tidy后的代码完美输出。不过,既然,这个是个趋势,那么大家就学习学习吧~


