沃梦达 / 编程问答 / php问题 / 正文

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

Symfony FOSUserBundle - include login form in layout template(Symfony FOSUserBundle - 在布局模板中包含登录表单)

本文介绍了Symfony FOSUserBundle - 在布局模板中包含登录表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们已经成功配置了 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;

这篇关于Symfony FOSUserBundle - 在布局模板中包含登录表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Symfony FOSUserBundle - 在布局模板中包含登录表单

基础教程推荐