Symfony2 internal route in Twig render function

doctrine-orm, php, routes, symfony, twig

Solution

Better do not use `{{ render(controller('AcmeDemoBundle:Page:mainmenu')) }}`. It work more fast and comfortable when you use services instead. You can create a service which will show menu on any page where you include them. And in service you can easy get access to current `_route` for add `active` class.

But if you really need to use `{{ render(controller('AcmeDemoBundle:Page:mainmenu')) }}`, so you need pass to them a current request like:

{{ render(controller('AcmeDemoBundle:Page:mainmenu', {'request': app.request})) }}

and then in action pass request to twig:

public function mainmenuAction($request) {

    return $this->render('AcmeDemoBundle:Page:mainmenu.html.twig', array('request' => $request));
}

and in twig use this request:

{% if menu_pages is defined %}
    {% for page in menu_pages %}
        <li class="{% if request.get('_route') == '_page_show' and request.get('id') == page.id %}active{% endif %}"><a href="{{ path('_page_show', {id: page.id}) }}">{{ page.title|e }}</a></li>
    {% endfor %}
{% endif %}

Problem

My `layout.html.twig`: ``` {{ render(controller('AcmeDemoBundle:Page:mainmenu')) }} ``` The `Page` controller retrieves all pages from the Doctrine and renders `mainmenu.html.twig` with a set of pages. My `mainmenu.html.twig`: ``` {% if menu_pages is defined %} {% for page in menu_pages %} <li class="{% if app.request.attributes.get('_internal') == '_page_show' and app.request.get('id') == page.id %}active{% endif %}"><a href="{{ path('_page_show', {id: page.id}) }}">{{ page.title|e }}</a></li> {% endfor %} {% endif %} ``` But no `active` class is displayed. As far as I understand the problem is in internal routing. How to fix that?

Original source