How can I minify HTML with Twig?

。_饼干妹妹 提交于 2019-12-22 01:41:57

问题


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?


回答1:


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 }}



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/18678522/how-can-i-minify-html-with-twig

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!