Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get kernel root dir in Twig template with Symfony 2

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)

like image 316
nowiko Avatar asked Mar 05 '15 07:03

nowiko


2 Answers

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.

like image 180
Alain Tiemblo Avatar answered Sep 20 '22 06:09

Alain Tiemblo


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.

like image 27
naitsirch Avatar answered Sep 19 '22 06:09

naitsirch