将路由与 Symfony 中的当前请求进行比较
对于我的网站导航,我想指示当前页面。如果导航中的每个页面都有自己的路线,是否有办法查看当前请求是否与该路线匹配?类似于:
$request->getRoute() == '@my_route'
或者,更一般地说,在 Symfony 中创建站点导航时是否有一种惯用的方法来设置活动页面?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要为此使用 sfContext::getInstance()、路由名称或内部 uri。有几种方法可以使用 Symfony 实现导航菜单突出显示,我个人喜欢设置请求属性(例如在控制器中),如下所示:
然后在模板中:
您甚至可以添加
section
参数routing.yml
文件中的路由:然后在模板中,如果这样做,请小心检查请求参数而不是属性:
简单而高效,对吧?但如果您需要更复杂的导航(尤其是嵌套菜单),您应该考虑使用一些功能更齐全的插件或基于 symfony 的 CMS,例如 Sympal、Diem 或 ApostropeCMS。
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:
Then in your template:
You can even add the
section
parameter from your routes in therouting.yml
file:Then in your template if you do so, be careful to check for a request parameter nstead of an attribute:
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.
您可以尝试使用以下内容:
它返回的是您在路由中定义的路由名称。例如,如果您有一个名为“@search_results”的路由规则,则上述方法将返回“search_results”。
也许有更好的方法,但我也使用它来设置布局中的当前活动页面...如果当前路线名称与“xxx”匹配,则通过向导航元素添加“选定”类。
You could try work with the following:
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".
我创建了一个助手,将其添加到 standard_helpers 中,并使用它而不是 link_to 创建导航链接:
我不喜欢 sfContext::getInstance(),但这是我找到的唯一方法。
I've created a helper, added it to the standard_helpers and I create navigations links using this instead of link_to:
I don't like sfContext::getInstance(), but this was the only way that I found.