5

I need to get kernel.root_dir in my twig template, I found solutions here, but it does not work. I get error about non existing method Kernel in this class. Realy in GlobalVariables class method getKernel() not exists. So how I can get root_dir in twig template.

(P.S. No I cant get it form controller, and no I cant get it as container parameters)

Stephan Vierkant
  • 9,674
  • 8
  • 61
  • 97
nowiko
  • 2,507
  • 6
  • 38
  • 82

2 Answers2

16

I suggest you to add a global variable in your config.yml:

# app/config/config.yml
twig:
    # ...
    globals:
        kernelRootDir: "%kernel.root_dir%"

Then, use {{ kernelRootDir }} in your views.

Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153
2

In newer Symfony versions the solution is similar, but the parameter kernel.root_dir has been removed in version 5.0 and the config file for twig is located elsewhere.

Now you can use the kernel.project_dir parameter, which resolves to the projct's root dir (not the kernel's root dir). This is usually the directory where your composer.json is located.

twig:
    globals:
        kernelProjectDir: '%kernel.project_dir%'

Then use {{ kernelProjectDir }} in your templates.

stollr
  • 6,534
  • 4
  • 43
  • 59