沃梦达 / 编程问答 / php问题 / 正文

在 Symfony 中注册 Twig 扩展

Register Twig Extension in Symfony(在 Symfony 中注册 Twig 扩展)

本文介绍了在 Symfony 中注册 Twig 扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 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 }

这篇关于在 Symfony 中注册 Twig 扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 Symfony 中注册 Twig 扩展

基础教程推荐