在Symfony中注册Twig Extension

时间:2017-10-14 06:46:38

标签: php symfony twig twig-extension

我想用nochso/html-compress-twig extension来压缩所有的html,内联css和js.But这是我第一次在Twig上注册一个新的扩展,我有点困惑我应该在哪里添加以下几行我的项目:

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

我正在阅读Twig的文档,但它没有帮助我,因为他们使用相同的示例并添加以下内容:

Twig does not care where you save your extension on the filesystem, as all extensions must be registered explicitly to be available in your templates.

You can register an extension by using the addExtension() method on your main Environment object:

我只想全局启用扩展程序,并且能够在任何树枝模板中使用{% htmlcompress %}{% endhtmlcompress %}

2 个答案:

答案 0 :(得分:3)

您可以通过以下方式将twig扩展名注册为已标记的服务:

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

答案 1 :(得分:1)

要启用Twig扩展程序,请将其添加为常规服务... http://symfony.com/doc/current/reference/dic_tags.html#twig-extension