Reputation: 3097
How can I minify all output HTML templates in Smarty?
like this way:
$smarty->minify = true;
P.S : I found {strip}
function but I should use this function in all of my .tpl
files. I have many .tpl
file and this way is not possible for me.
Upvotes: 6
Views: 8809
Reputation: 14987
You can use trimwhitespace
output filter, which is bundled with Smarty v3.
$smarty->loadFilter('output', 'trimwhitespace');
This filter does not directly minify the output, but it removes a lot of whitespaces that comes with Smarty. In my case the whitespaces are about 80% to 90% of the problem.
Notice that the output
filter runs every time on the compiled template. So this filter takes longer to run than sending the complete file, it is not of much use as long as you don't need to reduce traffic or use caching. But maybe one can write a similar filter that runs as a post
filter.
There also is the {strip}
block. This also removes whitespaces. The difference is that it runs on compile time and not on every call like the output filter.
So if touching every template file is an option, {strip}
would be the better option. If not, just go with the output filter.
Upvotes: 5
Reputation: 503
I used this code:
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);
NOTE: you will need to change // comments
into SCRIPT tags to /* comments */
Upvotes: 5
Reputation: 10188
You could use an output filter for this: Output filters take your HTML output, after all smarty parsing, and run some PHP logic on it, before outputting it to the user. This way, you would register an output filter and minify/compress your output there. Consult the good smarty documentation for output filtering: smartyV2 - smartyV3
As to how to minify code in PHP, you can find several good articles on the net.
Upvotes: 1