使用 yaml 路由描述时,如何在运行时获取 Symfony2 中的路由名称? [英] How to get at runtime the route name in Symfony2 when using the yaml routes description?

查看:16
本文介绍了使用 yaml 路由描述时,如何在运行时获取 Symfony2 中的路由名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里你可以找到我关于 Symfony2 的第 n 个问题.

Here you can find my n-th question on Symfony2.

我正在使用 分页包,它使用 routing.yml<中提供的路由名称/代码>文件.从我的角度来看,这种方法不灵活并且导致代码脏,因为如果我更改路由的名称,那么我必须查看所有 Twig 模板或 PHP 文件来更新路由名称.这对于小型 Web 应用程序来说是可以的,但是对于较大的应用程序会提供这样的 bug,并且对开发人员来说也需要很大的负担.

I'm working with a pagination bundle that uses the route name provided in the routing.yml file. From my perspective, this approach is not flexible and lead to a dirty code, since if I change the name of the route, then I have to look at all the Twig templates or PHP files to update the route name. This is ok for small Web applications, but will provide such a bug for larger applications and also need an high burden for the developer.

所以,我想将字符串变量 x 传递给上述包提供的 Pager 对象.字符串 x 应该在控制器中初始化,并且必须提供在 routing.yml 文件中给出的所需路由名称.

So, I was wondering to pass a string variable x to the Pager object provided by the above mentioned bundle. The string x should be initialized within the controller and has to provide the desired route name as given in the routing.yml file.

让我举个例子.路由文件如下:

Let me give an example. The routing file is the following:

//routing.yml
 AcmeTestBundle_listall:
pattern:  /test/page/{page}
defaults: { _controller: AcmeTestBundle:List:listall, page: 1 }
requirements:
    page:  d+   

那么相关的控制器是:

//use something....
class ListController extends Controller
{

  public function exampleAction($page)
  {
    $array = range(1, 100);
    $adapter = new ArrayAdapter($array);
    $pager = new Pager($adapter, array('page' => $page, 'limit' => 25));

    return array('pager' => $pager);  
  }
}

然后,在 twig 模板中,$pager 接收引用上述捆绑包的路由名称

Then, in the twig template, the $pager receives the route name that refer to the above bundle

{% if pager.isPaginable %}
   {{ paginate(pager, 'AcmeTestBundle_listall') }}
{% endif %}
{% for item in pager.getResults %}
   <p>{{ item }}</p>
{% endfor %}

知道如何在控制器内部的运行时获取AcmeTestBundle_listall"字符串值吗?

Any idea of how to get the 'AcmeTestBundle_listall' string value at runtime just inside the controller?

推荐答案

您可以使用 twig 中可用的 app 全局变量从请求中获取当前路由.

You can use the app global variable that is available in twig to get the current route from the request.

{% if pager.isPaginable %}
   {{ paginate(pager, app.request.get('_route') }}
{% endif %}

更多关于app 这里这里.

这篇关于使用 yaml 路由描述时,如何在运行时获取 Symfony2 中的路由名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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