【发布时间】:2017-09-25 13:38:36
【问题描述】:
我想同时发送 URL 中的一些参数(使用 redirectToRoute)和一些不在 URL 中的参数(使用渲染)。我该怎么办?
举个例子:我有两个 var:A 和 B
A 需要在 URL 中:http://website.com?A=smth 需要发送 B 以完成 TWIG(但不是通过 URL)
你能给我看一个代码示例吗?
谢谢
【问题讨论】:
我想同时发送 URL 中的一些参数(使用 redirectToRoute)和一些不在 URL 中的参数(使用渲染)。我该怎么办?
举个例子:我有两个 var:A 和 B
A 需要在 URL 中:http://website.com?A=smth 需要发送 B 以完成 TWIG(但不是通过 URL)
你能给我看一个代码示例吗?
谢谢
【问题讨论】:
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');
// ...
}
【讨论】:
简单易用,只需将一组键/值传递给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
【讨论】:
redirectToRoute。