Question

What I am looking is the way to enable/disable {% spaceless %}{% endspaceless %} wrapper for the whole Response object based on current Symfony environment. I think I should listen to kernel.view event and modify response there, but I can't make it.

The reason for this is that it is better to debug with all those spaces, but keep it minified for production usage.

Has anybody done this?

Was it helpful?

Solution

The spaceless is a Twig tag, the response will never know about it.

You can't easily disable it as it's part of the Twig_Extension_Core and there is no option to disable it.

You have to find another way. Maybe directly from your template (using it or not the depending on the environnement).

OTHER TIPS

Implement a ResponseListener in your bundle:

class ResponseListener
{
    private $container;

    public function __construct($container)
    {
        $this->container = $container;
    }

    public function onKernelResponse(FilterResponseEvent $event)
    {
        // Compress HTML on prod environment only
        if($this->container->get('kernel')->getEnvironment() == 'prod')
            $event->getResponse()->setContent(trim(preg_replace('/>\s+</', '><', $event->getResponse()->getContent())));
    }
}

Then declare in services.yml:

services:
    kernel.listener.response_listener:
        class: AppBundle\Listener\ResponseListener
        tags:
            - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }
        arguments: [@service_container]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top