如何在Symfony中的URL query_string中发送参数? [英] How to send params in url query_string in Symfony?

查看:93
本文介绍了如何在Symfony中的URL query_string中发送参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Twig页面的query_string URL中发送参数,并在控制器中获取它.

I want to send parameters in query_string URL from Twig page and get it in the controller.

例如:index.html.twig

<a href="/newcont/add/{{ id }}">New</a>

controller:

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class Newcont extends Controller
{
    /**
     * @Route("/newcont/add/{id}", requirements={"id": "\d+"})
     */
    public function addAction(Request $request){

        $params = $request->request->all();
        //$id = $request->query->get();
        var_dump($params);
        die;
    }
}

我希望在树枝中有一个包含变量的url,该变量将被发送到控制器操作.

I want to have an url with a variable in twig that is sent to the controller action.

推荐答案

从不对路线进行硬编码!在模板中使用路由助手.首先为您的路线命名,在这种情况下,我将其命名为"myroute",当然您应该使用更有意义的名称:

Never hard code the routes! Use the routing helpers in your templates. First give a name to your route, in this case I have named it "myroute", of course you should use something more meaningful:

class Newcont extends Controller
{
    /**
     * @Route("/newcont/add/{id}", name="myroute", requirements={"id": "\d+"})
     */

然后在Twig文件中,使用path帮助器将为您生成正确的路径:

Then in your Twig file, use the path helper that will generate the correct path for you:

<a href="{{ path('myroute', {'id': 7}) }}">New</a>

您当然可以用一个变量替换7.

<a href="{{ path('myroute', {'id': myTwigVar}) }}">New</a>

在您的控制器中,您可以直接获取id参数,因此您不必使用请求服务:

In your controller you can get the id parameter directly so you don't have to use the request service:

public function addAction(Request $request, $id) { 

之所以可以这样做,是因为您已经在路由中明确命名了此参数,并且该参数是强制性的,因此在所有情况下都将对其进行定义.它使代码更简洁易读.它还允许删除无用的代码.

You can do this because you have explicitly named this parameter in your route and it is mandatory, so in all cases it will be defined. It makes the code much cleaner and easy to read. It also allow to remove useless code.

请注意,在这种情况下,您不想修改查询字符串,而是修改路径.查询字符串是?foo=bar之类的路径之后的内容.

Note that is this case you don't want to modify the query string, you modify the path. The query string is what is after the path like ?foo=bar.

这篇关于如何在Symfony中的URL query_string中发送参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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