Comparing route with current request in Symfony

For site navigation, I would like to point to the current page. If every page in the navigation has its own route, is there a way to see if the current request matches the route? Sort of:

$request->getRoute() == '@my_route'

Or more generally, is there an idiomatic way to set the active page when creating site navigation in Symfony?

+2


a source to share


3 answers


Or more generally, is there an idiomatic way to set the active page when creating site navigation in Symfony?

Don't use sfContext :: getInstance () for this, route names or internal uris. There are several ways to highlight navigation menu highlighting with Symfony, personnaly I like to set the request attribute (in a controller for example) like:

<?php
// ...
  public function executeFoo(sfWebRequest $request)
  {
    $request->setAttribute('section', 'blah');
  }

      

Then in your template:

<ul>
  <li class="<?php echo 'blah' === $sf_request->getAttribute('section') ? 'active' : '' ?>">
    <a href="<php echo url_for('@my_route') ?>">Blah</a>
  </li>
</ul>

      



You can even add a parameter section

from your routes in the file routing.yml

:

my_route:
  url: /foo
  param: { module: foo, action: bar, section: blah }

      

Then in your template, if you do, be careful to check the request parameter instead of the attribute:

<ul>
  <li class="<?php echo 'blah' === $sf_request->getParameter('section') ? 'active' : '' ?>">
    <a href="<php echo url_for('@my_route') ?>">Blah</a>
  </li>
</ul>

      

Simple but effective, right? But you need more complex navigatioin (especially nested menus), you should consider using more full featured plugins or Symfony CMS based ones like Sympal, Diem or ApostropheCMS.

+5


a source


You can try working with the following:

In template:
$route = $sf_context->getInstance()->getRouting()->getCurrentRouteName();

In action:
$route = sfContext::getInstance()->getRouting()->getCurrentRouteName();

      



Returns the name of the route as you specified in routing. For example, if you have a routing rule called "@search_results", the above method will return "search_results".

There is probably a better way, but I also use this to set the currently active page in my layouts ... by adding the "selected" class to the nav element if the current route name matches "xxx".

+1


a source


I created a helper, added it to standard_helpers, and I create navigation links using this instead of link_to:

function thu_menu($name, $uri, $options = array())
{
  return link_to_unless(strpos(sfContext::getInstance()->getRouting()->getCurrentInternalUri(true), $uri) !== false, $name, $uri, $options);
}

      

I don't like sfContext :: getInstance (), but that was the only way I found.

0


a source







All Articles