Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 - Twig - How can I send parameters to the parent template?

Tags:

php

twig

symfony

I am working on a PHP project using Symfony2 with Twig templating, and I can't find a solution for this problem.

I have an admin bundle and all the templates extend from admin base which has a master template with a menu.

I need to set the current tab of the menu in the base template of the page to selected when the user is on that page.

Is there any way to pass parameter to the base template through extends?

like image 695
Germán Lena Avatar asked Jun 21 '13 20:06

Germán Lena


People also ask

How do you pass variables to Twig?

to print variable in twig file just use {{ my_variable }}.

How do I get the current URL in Twig?

You can get the current URL in Twig/Silex 2 like this: global. request. attributes. get('_route') .

Is Twig a template engine?

Twig is a template engine for the PHP programming language.


2 Answers

Here is a simple example:

base.html.twig:

{# base.html.twig #} ... <ul>   <li{% if menu_selected|default('one') == 'one' %} class="selected"{% endif %}>One</li>   <li{% if menu_selected == 'two' %} class="selected"{% endif %}>Two</li>   <li{% if menu_selected == 'three' %} class="selected"{% endif %}>Three</li> </ul> ... 

page2.html.twig:

{# page2.html.twig #} {% extends 'YourBundle::base.html.twig' %}  {% set menu_selected = 'two' %} 

Output from rendering page2.html.twig:

<ul>   <li>One</li>   <li class="selected">Two</li>   <li>Three</li> </ul> 
like image 76
Paul Avatar answered Oct 04 '22 09:10

Paul


A better way that I just discovered is the basic approach by checking the route for the shortcut route name:

<li class="{% if app.request.attributes.get('_route') == 'homepage' %}active{% endif %}">Home</li> 

Or another way is to name all your route shortcut names according to the group it belongs to. For example all the routes from your products controller start with "product_...." and then in the template you can do this:

<li class="{% if app.request.attributes.get('_route') starts with 'product' %}active{% endif %}"> 
like image 22
pogeybait Avatar answered Oct 04 '22 09:10

pogeybait