19

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?

daviesgeek
  • 819
  • 3
  • 14
  • 30
  • 1
    Well, Twig's key developer clearly [indicated](https://github.com/fabpot/Twig/issues/624) that Twig in general, and `spaceless` in particular, is not designed as a minification tool. How about using Tidy or `mod_strip` instead? – raina77ow Sep 07 '13 at 22:48
  • Kinda noob question, but how do I implement that into the Twig engine? – daviesgeek Sep 07 '13 at 22:50
  • 2
    You can add `{% spaceless %}` in your base templates, surrounding the `` tags. That way it applies to every child template as well. – adamors Feb 25 '14 at 10:38

4 Answers4

5

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 }}
  • In which file/function must the code to add the extension by placed? Does this work with backbone templates (which use <% %> tags for javascript stuff)? What is the average size compression? Does using this bundle affect performance? – WiRa Sep 06 '19 at 09:31
3

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.

0

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

Edouard
  • 363
  • 3
  • 14
-9

Use

{% spaceless %}
YOUR WHOLE PAGE GOES HERE HTML, TWIG, JS EVERYTHING...
{% endspaceless %}

It can be that your twig version does not recognize the tags, just update the latest version of twig.

This will minify the output html generated and page load will go up because it only loads the compiled version of html.

While you can still view the code in a readable situation.

benka
  • 4,732
  • 35
  • 47
  • 58
Michael
  • 23
  • 2
  • 19
    `spaceless` is NOT intended for this purpose. "This tag is not meant to "optimize" the size of the generated HTML content but merely to avoid extra whitespace between HTML tags to avoid browser rendering quirks under some circumstances." http://twig.sensiolabs.org/doc/tags/spaceless.html – tvanc Oct 08 '14 at 00:10
  • 1
    Also, minifing != removing whitespaces. It should also remove all the comments, for example. This is a feature they should add in Twig – the_nuts Jun 04 '16 at 14:48