Symfony FOSUserBundle - 在布局模板中包含登录表单表单、布局、模板、Symfony

2023-09-06 23:47:06 作者:?我会一直站在你的身后,等你再次发现我的身影。

我们已经成功配置了 FOSUserBundle;登录、注册、重置密码等一切正常.

We've successfully configured the FOSUserBundle; login, register, reset password, etc, are all working just fine.

现在我们想将登录表单合并到我们的一般站点布局中,特别是将表单放入布局标题的右上角.如果我们只处理用户名和密码字段,这样做会很容易.但是我们似乎无法弄清楚如何获取 FOSUserBundle 服务生成的 CSRF 令牌:

Now we want to incorporate the login form into our general site layout, notably placing the form into the top-right section of the layout header. Doing this would be easy enough if we were just dealing with the username and password fields. However we can't seem to figure out how to obtain the CSRF token which is generated by the FOSUserBundle service:

$this->container->get('form.csrf_provider')->generateCsrfToken('authenticate');

我尝试在 Twig 扩展程序中调用上述内容,否则可以正常工作,但显然扩展程序无法正确引用容器.

I tried calling the above within a Twig extension which otherwise works fine however apparently the extension can't properly reference the container.

肯定有一些简单的方法可以全局获取 FOSUserBundle CSRF 令牌吗?

Surely there is some easy way to obtain the FOSUserBundle CSRF token globally?

谢谢!杰森

推荐答案

您可以在其中一个控制器中定义这样的函数

You can define a function like this in one of your controllers

public function getTokenAction()
{
    return new Response($this->container->get('form.csrf_provider')
                            ->generateCsrfToken('authenticate'));
}

然后通过

<input type="hidden" name="_csrf_token" value="{% render('YourBundle:YourController:getToken') %}" />

您还需要在控制器顶部包含以下内容:

You also need to include the following at the top of your controller:

use SymfonyComponentHttpFoundationResponse;