17

我正在使用Twig,我希望能够缩小 HTML 输出。我该怎么做呢?我试过{% spaceless %}了,但这需要将它添加到我的所有模板中。我可以在 Twig 引擎中添加缩小吗?

4

3 回答 3

5

这可能对你帮助不大。

使用 html-compress-twig 您可以在一个包中压缩 html、css、js。使用 composer 安装composer require nochso/html-compress-twig,您必须使用此代码添加带有 twig 的扩展。

$app->extend('twig_theme', function($twig_theme, $ojt) {
$twig_theme->addExtension(new nochso\HtmlCompressTwig\Extension());
return $ojt_theme;});

最后去你的模板文件添加这个代码。

{% htmlcompress %} ....your coding... {% endhtmlcompress %}
{{ htmlcompress('<ul> <li>') }}
{{ '<ul> <li>'|htmlcompress }}
于 2017-02-16T10:44:12.650 回答
2

例如,您的src/Controller目录中有 BaseController。

  1. 您应该创建 BaseController
  2. 从控制器扩展它
  3. 重写Controller类的render方法
  4. 并在每个控制器中使用此方法
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;
    }
}

您还可以在其他控制器中扩展 BaseController。

于 2018-04-19T11:03:32.267 回答
-7

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.

于 2014-04-12T12:16:02.947 回答