make csrf_token() usable without forms
The Twig function `csrf_token()` is currently only registered when the Form component is installed. However, this function is also useful, for example, when creating simple login forms for which you do not need the full Form component.
This commit is contained in:
parent
22192b16d8
commit
709efa30fc
44
src/Symfony/Bridge/Twig/Extension/CsrfExtension.php
Normal file
44
src/Symfony/Bridge/Twig/Extension/CsrfExtension.php
Normal file
@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Bridge\Twig\Extension;
|
||||
|
||||
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
|
||||
use Twig\Extension\AbstractExtension;
|
||||
use Twig\TwigFunction;
|
||||
|
||||
/**
|
||||
* @author Christian Flothmann <christian.flothmann@sensiolabs.de>
|
||||
*/
|
||||
class CsrfExtension extends AbstractExtension
|
||||
{
|
||||
private $csrfTokenManager;
|
||||
|
||||
public function __construct(CsrfTokenManagerInterface $csrfTokenManager)
|
||||
{
|
||||
$this->csrfTokenManager = $csrfTokenManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFunctions(): array
|
||||
{
|
||||
return array(
|
||||
new TwigFunction('csrf_token', array($this, 'getCsrfToken')),
|
||||
);
|
||||
}
|
||||
|
||||
public function getCsrfToken(string $tokenId): string
|
||||
{
|
||||
return $this->csrfTokenManager->getToken($tokenId)->getValue();
|
||||
}
|
||||
}
|
@ -21,5 +21,10 @@
|
||||
<argument type="service" id="request_stack" on-invalid="ignore" />
|
||||
</service>
|
||||
<service id="Symfony\Component\Security\Csrf\CsrfTokenManagerInterface" alias="security.csrf.token_manager" />
|
||||
|
||||
<service id="twig.extension.security_csrf" class="Symfony\Bridge\Twig\Extension\CsrfExtension">
|
||||
<tag name="twig.extension" />
|
||||
<argument type="service" id="security.csrf.token_manager" />
|
||||
</service>
|
||||
</services>
|
||||
</container>
|
||||
|
Reference in New Issue
Block a user