在 Symfony 中注册 Twig 扩展

2022-01-22 00:00:00 php symfony twig twig-extension

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

I want to use nochso/html-compress-twig extension to compress all html, inline css and js.But it is the first time that I register a new extension on Twig and I am bit confused about where I should add the following lines in my project:

$twig = new Twig_Environment($loader);
$twig->addExtension(new 
ochsoHtmlCompressTwigExtension());

我正在阅读 Twig 的文档,但对我没有太大帮助,因为他们举了同样的例子,只是添加了以下内容:

I was reading the Twig's documentation but it didn't helped me much as they put the same example and just add the following:

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

I only want enable the extension globally and be able to use {% htmlcompress %}{% endhtmlcompress %} in any twig template

推荐答案

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

You can register your twig extension as a tagged service this way:

services:
    htmlcompress:
        class: '
ochsoHtmlCompressTwigExtension'
        tags:
            - { name: twig.extension }

相关文章