问题
For my site navigation I'd like to indicate the current page. If each page in the navigation has its own route is there a way to see if the current request matches the route? Something like:
$request->getRoute() == '@my_route'
Or, more generally, is there an idiomatic way of setting the active page when creating site navigation in Symfony?
回答1:
Or, more generally, is there an idiomatic way of setting the active page when creating site navigation in Symfony?
Don't use sfContext::getInstance(), route names or internal uris for this. There are several ways to achieve navigation menu highlighting with Symfony, personnaly I like setting a request attribute (eg. in a controller), like this:
<?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 the section
parameter from your routes in the routing.yml
file:
my_route:
url: /foo
param: { module: foo, action: bar, section: blah }
Then in your template if you do so, be careful to check for a request parameter nstead of an 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 yet efficient, right? But f you need more complex navigatioin (especially nested menus), you should be thinking using some more full-featured plugins or symfony-based CMSes like Sympal, Diem or ApostropheCMS.
回答2:
You could try work with the following:
In template:
$route = $sf_context->getInstance()->getRouting()->getCurrentRouteName();
In action:
$route = sfContext::getInstance()->getRouting()->getCurrentRouteName();
What it returns is the route name as you've defined in routing. So for example if you've got a routing rule called "@search_results", the above method would return "search_results".
Maybe there's a better way, but I'm also using this to set the current active page in my layouts... by adding a "selected" class to a navigation element if the current route name matches "xxx".
回答3:
I've created a helper, added it to the standard_helpers and I create navigations 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 this was the only way that I found.
来源:https://stackoverflow.com/questions/2739923/comparing-route-to-current-request-in-symfony