【问题标题】:Symfony - Send parameters with and without the URL at the same timeSymfony - 同时发送带有和不带有 URL 的参数
【发布时间】:2017-09-25 13:38:36
【问题描述】:

我想同时发送 URL 中的一些参数(使用 redirectToRoute)和一些不在 URL 中的参数(使用渲染)。我该怎么办?

举个例子:我有两个 var:A 和 B

A 需要在 URL 中:http://website.com?A=smth 需要发送 B 以完成 TWIG(但不是通过 URL)

你能给我看一个代码示例吗?

谢谢

【问题讨论】:

标签: php symfony get


【解决方案1】:

HTTP 3xx 重定向确实有正文,因此您不能通过render 包含数据并同时使用redirectToRoute('redirect_target_route', array('A' => 'smth'})

您需要将数据保存在 session flashbag 中,然后在 redirect_target_route 的控制器操作中从那里获取数据。

public function redirectingAction(Request $request)
{
    // ...
    // store the variable in the flashbag named 'parameters' with key 'B'
    $request->getSession()->getFlashBag('parameters')->add('B', 'smth_else');

    // redirect to uri?A=smth
    return $this->redirectToRoute('redirect_target_route', array('A' => 'smth'});
}

public function redirectTargetAction(Request $request)
{
    $parameterB = $request->getSession()->getFlashBag('parameters')->get('B');
    // ...
}

【讨论】:

    【解决方案2】:

    简单易用,只需将一组键/值传递给render() 方法:

    $template = $twig->load('index.html');
    echo $template->render(array('the' => 'variables', 'go' => 'here'));
    

    https://twig.symfony.com/doc/2.x/api.html#rendering-templates

    【讨论】:

    • 我不认为@Destunk 想要传递变量来渲染,而是通过重定向存储/检索它们,因为问题中提到了redirectToRoute
    猜你喜欢
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    相关资源
    最近更新 更多