6

I'm very new to Symfony2 and I need to be able to test the current route in TWIG so I can display sub-menus in a template that's rendered like:

{% render "CPAdminBundle:Messages:sidebarMenu" %}
{% render "CPAdminBundle:Readings:sidebarMenu" %}

Within the sidebar templates I tried using the following but it throws an error:

path(app.request.attributes.get('_route')) 

What's the correct way of doing what I'm trying to accomplish?

1
  • You should check out KnpMenuBundle, it solves a lot of your menu-related problems. Commented May 21, 2012 at 8:37

1 Answer 1

25

The check you want to do doesn't belong to a view. Views should only take care of displaying, not doing any kind of logic.

Do the check in your controller and store it in a variable, pass this variable to your views, and the check the value of this variable in there.
If you want to do this on every action, give the kernel.controller event a look.

If you want to do it in the view anyway, simply compare app.request.attributes.get('_route') to the route you want. I don't understand why you put in path().

{% if app.request.attributes.get('_route') == 'my_route' %}
{% endif %}
Sign up to request clarification or add additional context in comments.

4 Comments

the path was something that I got off of google but even If I try to print {{ app.request.attributes.get('_route') }} the output says _internal and I can't seem to get the route name in the view which is what I need since I have like 10 twig templates that will go in my sidebar and display submenus according to the current route
What's the output of $this->getRequest()->attributes->get('_route') in the controller?
It gives me the name of the current route just like I expect BUT I don't think I should do this in every controller I will have around 20, don't you think it should be checked in my sidebar template?
I know it's easier, but I find it really nasty. I've done some research and found out about the kernel.controller event, it might be what you need: symfony.com/doc/current/book/internals.html. Use it to check the route before each action. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.