Register Twig Extension in Symfony

假装没事ソ 提交于 2020-06-23 05:07:06

问题


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 \nochso\HtmlCompressTwig\Extension());

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:

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


回答1:


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

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



回答2:


To enable a Twig extension, add it as a regular service... http://symfony.com/doc/current/reference/dic_tags.html#twig-extension



来源:https://stackoverflow.com/questions/46741728/register-twig-extension-in-symfony

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