Skip to content

Commit 1ad8976

Browse files
committed
feature #25197 [FrameworkBundle][TwigBridge] make csrf_token() usable without forms (xabbuh)
This PR was merged into the 4.1-dev branch. Discussion ---------- [FrameworkBundle][TwigBridge] make csrf_token() usable without forms | Q | A | ------------- | --- | Branch? | master | Bug fix? | no | New feature? | yes | BC breaks? | no | Deprecations? | no | Tests pass? | yes | Fixed tickets | | License | MIT | Doc PR | 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. Commits ------- 709efa30fc make csrf_token() usable without forms
2 parents ddd248a + ea8d5e1 commit 1ad8976

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Extension/CsrfExtension.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Bridge\Twig\Extension;
13+
14+
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
15+
use Twig\Extension\AbstractExtension;
16+
use Twig\TwigFunction;
17+
18+
/**
19+
* @author Christian Flothmann <[email protected]>
20+
*/
21+
class CsrfExtension extends AbstractExtension
22+
{
23+
private $csrfTokenManager;
24+
25+
public function __construct(CsrfTokenManagerInterface $csrfTokenManager)
26+
{
27+
$this->csrfTokenManager = $csrfTokenManager;
28+
}
29+
30+
/**
31+
* {@inheritdoc}
32+
*/
33+
public function getFunctions(): array
34+
{
35+
return array(
36+
new TwigFunction('csrf_token', array($this, 'getCsrfToken')),
37+
);
38+
}
39+
40+
public function getCsrfToken(string $tokenId): string
41+
{
42+
return $this->csrfTokenManager->getToken($tokenId)->getValue();
43+
}
44+
}

0 commit comments

Comments
 (0)