Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the current URL or route in TWIG?

Tags:

php

twig

symfony

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?

like image 789
MikeGA Avatar asked May 20 '12 18:05

MikeGA


People also ask

What is Twig syntax?

Twig is a template engine for the PHP programming language. Its syntax originates from Jinja and Django templates. It's an open source product licensed under a BSD License and maintained by Fabien Potencier.

What is twig in HTML?

Twig is a templating language for PHP, which is a boring way of saying that it's a tool used to output variables inside HTML. If a project you're working on uses Twig, then you're in luck: it's easy to learn, powerful and a joy to work with.


1 Answers

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 %}
like image 104
Samy Dindane Avatar answered Nov 11 '22 01:11

Samy Dindane