I discovered some days ago a secret Symfony 2's helper. I call it secret because I can't find it anywhere on the documentation.
Edit: Here it is on the Symfony2 book: Embedding Controllers
{% render %} is used to show an action's response in a Twig template. It's very useful when wanting to show a dynamic content in all the app's pages.
Example: Displaying online users' counter.
- First of all we have to create a onlineUsersAction() function that fetches, processes the result and returns the counter of the online users.
- Then we gotta create a Twig template that displays the response returned by the action. The syntax is the following:
{% render "LiveGeekBundle:Default:onlineUsers" %}Knowing that onlineUsersAction() is an action of DefaultController which is a controller from the Live\GeekBundle bundle.
- Finally we must include that template in our application's default layout, and thus display the online users' counter in all the app's pages.
Passing arguments:
You can pass arguments to the action this way:
- In the Twig template:
{% render "LiveGeekBundle:Default:onlineUsers" with { 'arg1' : 'value1', 'arg2' : 'value2' } %} - In the controller:
helloAction($arg1, $arg2)
Or
helloAction($arg2, $arg1)
The arguments' order doesn't matter.
Enjoy. ;)
niko says:
Very good solution, thanks!
Is there any way to send additional arguments to the function?
22 November 2011 at 20:17