简体   繁体   中英

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.

(PS No I cant get it form controller, and no I cant get it as container parameters)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM