49

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

torbatamas
  • 1,236
  • 1
  • 11
  • 21

2 Answers2

123

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

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

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

{{ your_service.someMethod(twig_variable) }}

See here.

k0pernikus
  • 60,309
  • 67
  • 216
  • 347
Mun Mun Das
  • 14,992
  • 2
  • 44
  • 43
  • 4
    or just get the whole container by doing "@service_container" – Gigala Apr 15 '13 at 11:52
  • 5
    @Gigala Only inject what you really need, much cleaner. – Marcel Burkhard Oct 07 '14 at 09:06
  • 1
    just saying, some may want the whole thing – Gigala Oct 16 '14 at 14:04
  • 16
    I may prefer to insert the service in the controllerAction instead as a global variable o.O – Mateo Tibaquira Oct 28 '14 at 21:01
  • 1
    in my service i have some arguments like @request so i have this error : The definition "twig" references the service "my_service" which belongs to a narrower scope. How can i do ? – altore Sep 16 '15 at 08:46
  • Seconding the comment by @altore. My service needs to be scoped to `request` so when I try to define it as a global twig variable as above I get a `ScopeWideningInjectionException` Exception...any way around this? – Andy Oct 04 '15 at 12:06
0

To get this done in Symfony 5, first you must declare the service in services.yaml, for example:

        App\Service\NavigationHelper:
        arguments:
            foo: bar

Then you can declare the service for its use in Twig. To achieve this, you must add it as a variable in the "globals" section of the Yaml file located in packages/twig.yaml:

  globals:
    navHelper: '@App\Service\NavigationHelper'

Now you can use your service methods from the templates as Mun Mun Das suggested in his last code snippet.