Germán Lena Germán Lena - 2 months ago 8x
PHP Question

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

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?


Here is a simple example:


{# base.html.twig #}
  <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>


{# page2.html.twig #}
{% extends 'YourBundle::base.html.twig' %}

{% set menu_selected = 'two' %}

Output from rendering page2.html.twig:

  <li class="selected">Two</li>