7

I want to use nochso/html-compress-twig extension to compress all html, inline css and js.But it is the first time that I register a new extension on Twig and I am bit confused about where I should add the following lines in my project:

$twig = new Twig_Environment($loader);
$twig->addExtension(new \nochso\HtmlCompressTwig\Extension());

I was reading the Twig's documentation but it didn't helped me much as they put the same example and just add the following:

Twig does not care where you save your extension on the filesystem, as all extensions must be registered explicitly to be available in your templates.

You can register an extension by using the addExtension() method on your main Environment object:

I only want enable the extension globally and be able to use {% htmlcompress %}{% endhtmlcompress %} in any twig template

Kevin Gravell
  • 499
  • 2
  • 7
  • 20
  • 2
    You better follow the Symfony specific documentation here: http://symfony.com/doc/current/templating/twig_extension.html – Frank B Oct 14 '17 at 07:12
  • 1
    do not forget to choose the right symfony version that you are using too – Frank B Oct 14 '17 at 07:13

2 Answers2

15

You can register your twig extension as a tagged service this way:

services:
    htmlcompress:
        class: '\nochso\HtmlCompressTwig\Extension'
        tags:
            - { name: twig.extension }
Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153
0

To enable a Twig extension, add it as a regular service... http://symfony.com/doc/current/reference/dic_tags.html#twig-extension

  • Thaks for your reply! In this case after install the bundle how should I enable it in services.yml? I tried this: ` app.compress: class: \nochso\HtmlCompressTwig\Extension tags: [twig.extension]` But I guess that I should change "twig.extension" for another name... – Kevin Gravell Oct 14 '17 at 08:15
  • 1
    no, you should not change 'twig.extension' for another name. That's not a name. That is a flag that tells symfony that your service is a Twig extension. Have you try to pass 'true' as an argument as per the documention ? Compression is disabled by Twig's debug setting. This is to make development easier, however you can always override it. The constructor of this extension takes a boolean parameter $forceCompression. When true, this will force compression regardless of Twig's debug setting. It defaults to false when omitted. – Frédéric Clausset Oct 14 '17 at 08:43
  • 1
    I tried both options, leaving "twig.extension" raises an exception telling me `A "tags" entry must be an array for service "app.compress"`. I also tried to pass true as an argument but I need to configure it in the right way first – Kevin Gravell Oct 14 '17 at 09:38
  • Please add some more explanation to your answer instead of linking to external ressources – Nico Haase Jun 17 '20 at 06:23