Skip to content

Commit 8db2848

Browse files
committed
[FrameworkBundle] Add support for setting headers with TemplateController
1 parent 3d93e08 commit 8db2848

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
CHANGELOG
22
=========
33

4+
7.2
5+
---
6+
7+
* Add support for setting `headers` with `Symfony\Bundle\FrameworkBundle\Controller\TemplateController`
8+
49
7.1
510
---
611

Controller/TemplateController.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,9 @@ public function __construct(
3737
* @param bool|null $private Whether or not caching should apply for client caches only
3838
* @param array $context The context (arguments) of the template
3939
* @param int $statusCode The HTTP status code to return with the response (200 "OK" by default)
40+
* @param array $headers The HTTP headers to add to the response
4041
*/
41-
public function templateAction(string $template, ?int $maxAge = null, ?int $sharedAge = null, ?bool $private = null, array $context = [], int $statusCode = 200): Response
42+
public function templateAction(string $template, ?int $maxAge = null, ?int $sharedAge = null, ?bool $private = null, array $context = [], int $statusCode = 200, array $headers = []): Response
4243
{
4344
if (null === $this->twig) {
4445
throw new \LogicException('You cannot use the TemplateController if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
@@ -60,6 +61,10 @@ public function templateAction(string $template, ?int $maxAge = null, ?int $shar
6061
$response->setPublic();
6162
}
6263

64+
foreach ($headers as $key => $value) {
65+
$response->headers->set($key, $value);
66+
}
67+
6368
return $response;
6469
}
6570

Tests/Controller/TemplateControllerTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,4 +84,18 @@ public function testStatusCode()
8484
$this->assertSame(201, $controller->templateAction($templateName, null, null, null, [], $statusCode)->getStatusCode());
8585
$this->assertSame(200, $controller->templateAction($templateName)->getStatusCode());
8686
}
87+
88+
public function testHeaders()
89+
{
90+
$templateName = 'image.svg.twig';
91+
92+
$loader = new ArrayLoader();
93+
$loader->setTemplate($templateName, '<svg></svg>');
94+
95+
$twig = new Environment($loader);
96+
$controller = new TemplateController($twig);
97+
98+
$this->assertSame('image/svg+xml', $controller->templateAction($templateName, headers: ['Content-Type' => 'image/svg+xml'])->headers->get('Content-Type'));
99+
$this->assertNull($controller->templateAction($templateName)->headers->get('Content-Type'));
100+
}
87101
}

0 commit comments

Comments
 (0)