Pass parameter to all views

一个人想着一个人 提交于 2019-12-01 08:34:13

User is accessible as a predefined global variable, take a look at this, and if you want to reuse the same template fragment in all your templates take a look at the include tag.

The simplest solution is to embed controllers from your templates/layout. But beware that subrequests are costly and can affect performance significantly. If at some point you'll notice that the dev version of your app is slow as hell, then know that the reason is probably several subrequests on each request.

The next solution is Twig extensions. In most cases you'll want functions. You could call it like:

{{ user_info(user) }}

I started with embedding controllers first, but my dev version reached the point when most pages on my site were timing out in 30 seconds. I didn't know the reason first, but as soon as I found it out, I replaced all subrequsts with Twig extensions. Since then the performance is back to normal.

I don't know if it was available when this question was posted in 2012, but I'd use Twig Globals.

From http://twig.sensiolabs.org/doc/advanced.html#globals :

Globals

A global variable is like any other template variable, except that it's available in all templates and macros:

$twig = new Twig_Environment($loader);
$twig->addGlobal('text', new Text());

You can then use the text variable anywhere in a template:

{{ text.lipsum(40) }}

I put the code in some place where it will get called each time, like the controller constructor or something like that.

Had this use-case just last month. Turned to render command and it really worked great as called controller action does not have to have @Route defined... not even a @Template but that's up to you ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!