0

As I have seen on How can I minify HTML with Twig?

Recommends to use the https://github.com/nochso/html-compress-twig to minify the generated html from Twig templates.

But on documentation it shows no way to load with Symfony. Do you fellas know how to use it with Symfony?

As far as it says:

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

But on Symfony how can I get the existing Twig_Environment and where to put the extension initialization?

Stephan Vierkant
  • 9,674
  • 8
  • 61
  • 97
Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164

2 Answers2

1

After install, try to register it as a service:

services: 
    nochso\HtmlCompressTwig\Extension
        tags:
            - { name: twig.extension }
Stephan Vierkant
  • 9,674
  • 8
  • 61
  • 97
  • When using the PHP 7 compatible fork https://github.com/voku/html-compress-twig , autowiring complains. Add the extension like this: ``` services: voku\helper\HtmlMin: tags: - { name: HtmlMin } voku\twig\MinifyHtmlExtension: tags: - { name: twig.extension } ``` – Mondane Jul 26 '18 at 11:55
1

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.