本文介绍了Symfony-在控制器中使用参数生成URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想直接在我的控制器中生成一个Url.我想使用在我的routing.yml文件中定义的需要参数的网址.

I want to generate a Url directly in my controller. I want to user a url defined in my routing.yml file that needs a parameter.

我已经在Cookbook(Routage部分)中找到了该代码:

I've found that code in the Cookbook (Routage section) :

$params = $router->match('/blog/my-blog-post');
// array('slug' => 'my-blog-post', '_controller' => 'AcmeBlogBundle:Blog:show')

$uri = $router->generate('blog_show', array('slug' => 'my-blog-post'));
// /blog/my-blog-post

但是我不明白$ router是指什么.显然,它不起作用.有没有一种简单的方法可以在控制器中使用参数生成路由网址?

But I don't understand to what is refering the $router. Obviously, it doesn't work.Is there a simple way to generate a routing url with a paramter in a controller ?

推荐答案

这很简单:

public function myAction()
{
    $url = $this->generateUrl('blog_show', array('slug' => 'my-blog-post'));
}

在一个动作中,$ this-> generateUrl是一个别名,它将使用路由器来获取所需的路由,您也可以这样做:

Inside an action, $this->generateUrl is an alias that will use the router to get the wanted route, also you could do this that is the same :

$this->get('router')->generate('blog_show', array('slug' => 'my-blog-post'));

这篇关于Symfony-在控制器中使用参数生成URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 00:59