php symfony2:如何从模板访问服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13243638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:02:06  来源:igfitidea点击:

symfony2: how to access service from template

phpsymfony

提问by torbatamas

If I created a service is there a way to access it from twig, without creating a twig.extension?

如果我创建了一个服务,有没有办法从 twig 访问它,而无需创建 twig.extension?

回答by Mun Mun Das

You can set the service a twig global variable in config.yml, e.g

您可以将服务设置为 twig 全局变量config.yml,例如

#app/config/config.yml
twig:
    globals:
        your_service: "@your_service"

And in your template.html.twigfile you can invoke your service this way:

在您的template.html.twig文件中,您可以通过以下方式调用您的服务:

{{ your_service.someMethod(twig_variable) }}

See here.

这里