[英]Symfony2 internal route in Twig render function
My layout.html.twig
: 我的
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. Page
控制器从该学说中检索所有页面,并使用一组页面呈现mainmenu.html.twig
。
My mainmenu.html.twig
: 我的
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. 但是不会显示任何
active
课程。 As far as I understand the problem is in internal routing. 据我了解,问题出在内部路由。 How to fix that?
如何解决?
Better do not use {{ render(controller('AcmeDemoBundle:Page:mainmenu')) }}
. 最好不要使用
{{ 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. 在使用中,您可以轻松访问当前
_route
以添加active
类。
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')) }}
,那么您需要将当前请求传递给他们,例如:
{{ 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 %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.