【问题标题】:Symfony & twig minify html with nochso/html-compress-twigSymfony & twig 使用 nochso/html-compress-twig 缩小 html
【发布时间】:2017-11-23 14:43:38
【问题描述】:

正如我在 How can I minify HTML with Twig? 上看到的那样

建议使用https://github.com/nochso/html-compress-twig 来缩小从 Twig 模板生成的 html。

但在文档中显示无法使用 Symfony 加载。你们知道如何在 Symfony 中使用它吗?

正如它所说:

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

但是在 Symfony 上,我怎样才能获得现有的 Twig_Environment 以及将扩展初始化放在哪里?

【问题讨论】:

  • 你为什么要这样做?缩小 html 现在没用了。
  • @Tokeeen.com 为什么缩小 html 没用?
  • 因为服务器响应的 gzip 或 deflate 压缩。

标签: php symfony twig minify symfony-3.3


【解决方案1】:

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

  1. 你应该创建 BaseController
  2. 从控制器扩展它
  3. 重写 Controller 类的渲染方法
  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。

【讨论】:

    【解决方案2】:

    安装后,尝试注册为服务:

    services: 
        nochso\HtmlCompressTwig\Extension
            tags:
                - { name: twig.extension }
    

    【讨论】:

    • 当使用 PHP 7 兼容的 fork github.com/voku/html-compress-twig 时,自动装配会报错。像这样添加扩展名:``` services: voku\helper\HtmlMin: tags: - { name: HtmlMin } voku\twig\MinifyHtmlExtension: tags: - { name: twig.extension } ```
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 2017-07-14
    • 2016-08-10
    相关资源
    最近更新 更多