从 symfony 4 中的树枝模板调用服务

Call a service from twig template in symfony 4

我想知道如何在 Symfony 4 上直接从 twig 模板调用服务。我在每个操作中都使用它,如下所示:

public function indexAction(TranslatorInterface $translator, NavigationGenerator $navigationGenerator)
    {

        return $this->render('index/index.html.twig', [
            'navigationItems'=>$navigationGenerator->getNavigation(self::class)
        ]);
    }

在模板中我称之为:

{% for navigationItem in navigationItems.topNavigation['left'] %}
    <a href="{{ navigationItem.route }}">{{ navigationItem.label }}</a>
{% endfor %}

在早期的 bootstrap 版本中,我可以在 config.yml 中将服务定义为全局对象,并直接从 twig 中使用它,如下所示:

{ NavigationGenerator.getNavigation(ControllerName) }

任何提示如何在 Symfony 4 中执行此操作?没有 config.yml 了。

您仍然可以定义 Twig 全局变量 - 它们将与 config/packages/twig.yaml 中的其余 Twig 配置一起使用。

另一个可能更好的地方是 Twig function。定义函数(或过滤器)的服务与控制器一样是一种服务,因此您可以在构造函数中对 NavigationGenerator 和您需要的任何其他内容进行类型提示,以供在正在调用的函数中使用从 Twig 调用。