Passing a parameter to all types

I want to display the username / last connection date and other information about all of my Twig views (which extend the overall Twig layout).

How can I achieve this without having to explicitly pass these parameters from each controller to each view?

Should I create a Twig extension or make a controller / action call that will retrieve the username / connection / other information from the layout using rendering ?

I would like a simpler solution if possible.

+2
parameter-passing symfony twig controller
source share
4 answers

The user is available as a predefined global variable, look at this one , and if you want to reuse the same template fragment in all your templates, look at the include tag.

+2
source share

The simplest solution is to embed the controllers from your templates / layouts. But be careful that subqueries are expensive and can significantly affect performance. If at some point you notice that the version of your application is slow as hell, then know that the reason is probably several subqueries for each request.

The next solution is Twig extensions . In most cases, you will need functions . You can call it like this:

{{ user_info(user) }} 

At first I started by embedding the controllers, but my version of dev reached the point where most of the pages on my timing site in 30 seconds. At first I did not know the reason, but as soon as I found out, I replaced all the subtasks with Twig extensions. Since then, productivity has returned to normal.

+8
source share

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

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

Globals

A global variable is similar to any other template variable, except that it is available in all templates and macros:

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

Then you can use the text variable anywhere in the template:

 {{ text.lipsum(40) }} 

I put the code in the place where it will be called every time, for example, the constructor of the controller or something like that.

+1
source share

Had this precedent only last month. Turned to the render command, and it really worked fine, since the controller action called up doesn't have to have @Route ... not even @Template , but it's up to you;)

0
source share

All Articles