如何在 Smarty 中缩小所有输出 HTML 模板?
像这样:
$smarty->minify = true;
PS:我找到了{strip}
函数,但我应该在我的所有.tpl
文件中使用这个函数。我有很多.tpl
文件,这种方式对我来说是不可能的。
如何在 Smarty 中缩小所有输出 HTML 模板?
像这样:
$smarty->minify = true;
PS:我找到了{strip}
函数,但我应该在我的所有.tpl
文件中使用这个函数。我有很多.tpl
文件,这种方式对我来说是不可能的。
我使用了这段代码:
function minify_html($tpl_output, Smarty_Internal_Template $template) {
$tpl_output = preg_replace('![\t ]*[\r\n]+[\t ]*!', '', $tpl_output);
return $tpl_output;
}
// register the outputfilter
$smarty->registerFilter("output", "minify_html");
$smarty->display($template);
注意:您需要更改// comments
为 SCRIPT 标签/* comments */
您可以使用与 Smarty v3 捆绑的trimwhitespace
输出过滤器。
$smarty->loadFilter('output', 'trimwhitespace');
此过滤器不会直接缩小输出,但会删除 Smarty 附带的大量空格。在我的情况下,空格大约是问题的 80% 到 90%。
请注意,output
过滤器每次都在编译的模板上运行。所以这个过滤器的运行时间比发送完整文件要长,只要你不需要减少流量或使用缓存,它就没有多大用处。但也许可以编写一个类似的过滤器作为post
过滤器运行。
还有{strip}
块。这也删除了空格。不同之处在于它在编译时运行,而不是像输出过滤器那样在每次调用时运行。
因此,如果可以选择触摸每个模板文件,{strip}
那将是更好的选择。如果没有,只需使用输出过滤器。