将路由与 Symfony 中的当前请求进行比较 [英] Comparing route to current request in Symfony

查看:34
本文介绍了将路由与 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'

或者,更一般地说,在 Symfony 中创建站点导航时,是否有一种惯用的方式来设置活动页面?

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

推荐答案

或者,更一般地说,在 Symfony 中创建站点导航时,是否有一种惯用的方式来设置活动页面?

不要为此使用 sfContext::getInstance()、路由名称或内部 uri.有几种方法可以使用 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');
  }

然后在你的模板中:

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

您甚至可以从 routing.yml 文件中的路由中添加 section 参数:

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>

简单而高效,对吧?但是如果您需要更复杂的导航(尤其是嵌套菜单),您应该考虑使用一些功能更全的插件或基于 symfony 的 CMS,例如 Sympal、Diem 或 ApostropheCMS.

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.

这篇关于将路由与 Symfony 中的当前请求进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆