Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I minify HTML with Twig?

Tags:

twig

minify

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?

like image 230
daviesgeek Avatar asked Sep 07 '13 22:09

daviesgeek


People also ask

How do I minify PHP HTML output?

Use the ob_start() Function With a Callback to Minify HTML Output of the PHP Page. You can use the ob_start() function with a callback to remove whitespaces before and after the tags, comments, and whitespace sequences.

What is HTML Minification?

Minification is the process of minimizing code and markup in your web pages and script files. It's one of the main methods used to reduce load times and bandwidth usage on websites. Minification dramatically improves site speed and accessibility, directly translating into a better user experience.


2 Answers

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 }}
like image 112
Alagendran Ayyadurai Avatar answered Oct 17 '22 11:10

Alagendran Ayyadurai


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.

like image 3
Дніщенко Денис Avatar answered Oct 17 '22 10:10

Дніщенко Денис