Symfony2 internal route in Twig render function

这一生的挚爱 提交于 2019-12-01 08:08:24

问题


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?


回答1:


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 %}


来源:https://stackoverflow.com/questions/21427321/symfony2-internal-route-in-twig-render-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!