symfony4 - Symfony 4,登录(或注销)后如何将用户重定向到上一页?
问题描述
例如,用户转到“关于我”页面。从这个页面,他可以通过导航栏中的按钮登录或注销。
当用户登录或注销时,他会自动重定向到主页。相反,我想将用户重定向到上一页(本例中的“关于我”)
阅读文档后,我找不到/不了解如何为我的目的配置重定向
有人可以解释/给我看:?谢谢你 !
解决方案
我也遇到过这个问题。
我假设你使用 ```Symfony4.4``` 并使用 ```make:auth``` 来创建登录界面。在你的 ``SecurityController```(你有登录路径的那个)中,你使用 ```$request->headers->get('referer')``` 将你来自的 URL 传递给树枝登录页面。
public function login(AuthenticationUtils $authenticationUtils, Request $request): Response
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
'back_to_your_page' => $request->headers->get('referer')
]);
}
然后在 Twig 页面 (login.html.twig) 中使用back_to_your_page
登录表单中的变量。_target_path
变量在这里是必不可少的。
<form>
...
<input type="hidden" name="_target_path" value="{{ back_to_your_page }}"/>
...
</form>
现在是最后一部分。在onAuthenticationSuccess
函数所在的 LoginFormAuthenticator (make:auth) 中,您使用该_target_path
变量。
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return new RedirectResponse($request->get('_target_path'));
}
测试和享受。我知道这是一个迟到的回应,但也许其他人将来会得到帮助。
推荐阅读
- python - 基于 DateTime 功能合并 2 个 DataFrame
- c# - 在大多数其他控件之上添加新控件 - C# Winforms
- javascript - 如何在 JS 中动态创建的表格中添加可点击的文本
- oauth-2.0 - 用户名/密码和不记名令牌之间的区别是什么?
- python - 使用熊猫根据另一个数据框向数据框添加列
- r - ggplot中的中断未显示
- python - CNNLSTM2D 实现
- r - 我正在尝试附加一个返回函数,错误是 FUN(X[[i]], ...) 中的错误:未使用的参数
- ios - 希伯来语的默认 iOS 系统字体是什么?
- express - route.patch 中的 For 循环不起作用。|| Exprees.js