5

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.

MajAfy
  • 3,007
  • 10
  • 47
  • 83

3 Answers3

5

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 */

  • or use this to strip single line comments too : http://stackoverflow.com/questions/643113/regex-to-strip-comments-and-multi-line-comments-and-empty-lines – Meloman May 22 '16 at 15:19
  • 1
    This will break elements that need new lines (textarea, for example) and break scripts that use new lines or white spaces inside quotes ("blah / blah"), etc. Instead I threw together this filter which uses a popular HTML Minify function https://github.com/MarkehMe/HTMLMinify-Smarty – Mark Hughes Feb 07 '17 at 01:31
5

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.

AbcAeffchen
  • 14,400
  • 15
  • 47
  • 66
1

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.

periklis
  • 10,102
  • 6
  • 60
  • 68