[英]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.我需要在我的树枝模板中获取 kernel.root_dir,我在这里找到了解决方案,但它不起作用。 I get error about non existing method Kernel in this class .
我收到有关此类中不存在的方法 Kernel 的错误。 Realy in GlobalVariables class method getKernel() not exists.
确实在 GlobalVariables 类方法中 getKernel() 不存在。 So how I can get root_dir in twig template.
那么我如何在树枝模板中获得 root_dir 。
(PS No I cant get it form controller, and no I cant get it as container parameters) (PS 不,我无法从控制器中获取它,也不能将其作为容器参数获取)
I suggest you to add a global variable in your config.yml:我建议您在 config.yml 中添加一个全局变量:
# app/config/config.yml
twig:
# ...
globals:
kernelRootDir: "%kernel.root_dir%"
Then, use {{ kernelRootDir }}
in your views.然后,在您的视图中使用
{{ kernelRootDir }}
。
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.在较新的 Symfony 版本中,解决方案类似,但参数
kernel.root_dir
已在版本5.0 中删除,并且kernel.root_dir
的配置文件位于其他位置。
Now you can use the kernel.project_dir
parameter, which resolves to the projct's root dir (not the kernel's root dir).现在您可以使用
kernel.project_dir
参数,该参数解析为项目的根目录(不是内核的根目录)。 This is usually the directory where your composer.json
is located.这通常是您的
composer.json
所在的目录。
twig:
globals:
kernelProjectDir: '%kernel.project_dir%'
Then use {{ kernelProjectDir }}
in your templates.然后在模板中使用
{{ kernelProjectDir }}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.