akankov / twig-compress-html
Twig 3 extension wrapping akankov/html-min: provides an html_min filter and a {% htmlmin %}...{% endhtmlmin %} block tag, plus an optional Symfony bundle.
Fund package maintenance!
Requires
- php: 8.3.* || 8.4.* || 8.5.*
- akankov/html-min: ^2.0
- twig/twig: ^3.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.65
- phan/phan: ^6.0
- phpstan/extension-installer: ^1.4
- phpstan/phpstan: ^2.1
- phpstan/phpstan-phpunit: ^2.0
- phpstan/phpstan-symfony: ^2.0
- phpunit/phpunit: ^12.0
- rector/rector: ^2.0
- symfony/config: ^7.0
- symfony/dependency-injection: ^7.0
- symfony/filesystem: ^7.0
- symfony/framework-bundle: ^7.0
- symfony/http-kernel: ^7.0
- symfony/twig-bundle: ^7.0
- symfony/yaml: ^7.0
Suggests
- symfony/framework-bundle: Required to use AkankovTwigCompressHtmlBundle for auto-registration in Symfony applications.
README
A Twig 3 extension wrapping akankov/html-min — exposes an html_min filter and an {% htmlmin %}...{% endhtmlmin %} block tag, with an optional Symfony bundle for auto-registration.
Requirements
- PHP
^8.3 twig/twig^3.0akankov/html-min^1.0
Install
composer require akankov/twig-compress-html
Plain Twig usage
use Akankov\HtmlMin\HtmlMin; use Akankov\TwigCompressHtml\HtmlMinExtension; use Akankov\TwigCompressHtml\HtmlMinRuntime; use Twig\Environment; use Twig\Loader\FilesystemLoader; use Twig\RuntimeLoader\FactoryRuntimeLoader; $twig = new Environment(new FilesystemLoader(__DIR__.'/templates')); $twig->addExtension(new HtmlMinExtension()); $twig->addRuntimeLoader(new FactoryRuntimeLoader([ HtmlMinRuntime::class => static fn () => new HtmlMinRuntime(new HtmlMin()), ]));
Filter
{{ rawHtml|html_min }}
Block tag
{% htmlmin %}
<html>
<body>
{{ content }}
</body>
</html>
{% endhtmlmin %}
The tag captures rendered output (variables are escaped first by Twig's autoescape, then minified), so it's safe to interpolate user data inside.
Symfony usage
Register the bundle in config/bundles.php:
return [ // ... Akankov\TwigCompressHtml\Bundle\AkankovTwigCompressHtmlBundle::class => ['all' => true], ];
Optionally tune HtmlMin via config/packages/akankov_twig_compress_html.yaml:
akankov_twig_compress_html: remove_comments: true sum_up_whitespace: true optimize_attributes: true sort_html_attributes: true remove_omitted_quotes: false
Any key you omit leaves the upstream HtmlMin default in place — the bundle only calls a setter when you set the corresponding key.
The filter and tag become available in all templates automatically.
Tests
composer install vendor/bin/phpunit
License
MIT