'How can I minify HTML with Twig?

I'm using Twig and I'd like to be able to minify the HTML output. How do I do this? I tried {% spaceless %}, but that requires adding that to all my templates. Can I add minification within the Twig engine?



Solution 1:[1]

This may help you little.

use html-compress-twig you can compress html,css,js in one package.use composer to install composer require nochso/html-compress-twig and you have to add Extension with twig by using this code.

$app->extend('twig_theme', function($twig_theme, $ojt) {
$twig_theme->addExtension(new nochso\HtmlCompressTwig\Extension());
return $ojt_theme;});

finally go to your template file add this code.

{% htmlcompress %} ....your coding... {% endhtmlcompress %}
{{ htmlcompress('<ul> <li>') }}
{{ '<ul> <li>'|htmlcompress }}

Solution 2:[2]

For example you have the BaseController in your src/Controller directory.

  1. You should create BaseController
  2. Extends it from Controller
  3. Override render method of the Controller class
  4. And use this method in every controller
class BaseController extends Controller {
protected function render($view, array $parameters = array(), Response $response = null)
    {
        if ($this->container->has('templating')) {
            $content = $this->container->get('templating')->render($view, $parameters);
        } elseif ($this->container->has('twig')) {
            $content = $this->container->get('twig')->render($view, $parameters);
        } else {
            throw new \LogicException('You can not use the "render" method if the Templating Component or the Twig Bundle are not available. Try running "composer require symfony/twig-bundle".');
        }

        if (null === $response) {
            $response = new Response();
        }
        $content = preg_replace(array('/<!--(.*)-->/Uis',"/[[:blank:]]+/"),array('',' '),str_replace(array("\n","\r","\t"),'',$content));
        $response->setContent($content);

        return $response;
    }
}

You also can extends BaseController in others controllers.

Solution 3:[3]

Use a Listener on kernel.response event to automatize the process:

In config/services.yaml:

services:
    // ...
    app.listener.compression:
        class: App\Event\CompressionSubscriber
        arguments:
        tags:
            - { name: kernel.event_subscriber }

In src/Event/CompressionSubscriber.php:

<?php

namespace App\Event;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class CompressionSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::RESPONSE => ['onKernelResponse', -256]
        ];
    }

    public function onKernelResponse($event)
    {
        if ($event->getRequestType() != HttpKernelInterface::MAIN_REQUEST) {
            return;
        }
        $response = $event->getResponse();
        $content = preg_replace(
            ['/<!--(.*)-->/Uis',"/[[:blank:]]+/"],
            ['',' '],
            str_replace(["\n","\r","\t"], '', $response->getContent())
        );
        $response->setContent($content);
    }
}

Based on this post

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alagendran Ayyadurai
Solution 2 Дніщенко Денис
Solution 3