I want to set following Headers for TWIG Template from within my DefaultController:
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Origin: http://www.mywebsite.com');
header('Access-Control-Allow-Headers: Content-Type, *');
Any suggestions how to do that?
from this article:
CorsListener.php
<?php
namespace MyCorp\MyBundle\Listener;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
class CorsListener
{
public function onKernelResponse(FilterResponseEvent $event)
{
$responseHeaders = $event->getResponse()->headers;
$responseHeaders->set('Access-Control-Allow-Headers', 'origin, content-type, accept');
$responseHeaders->set('Access-Control-Allow-Origin', '*');
$responseHeaders->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, PATCH, OPTIONS');
}
}
services.yml
app.cors_listener:
class: MyCorp\MyBundle\Listener\CorsListener
tags:
- { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }
Using the response class:
use Symfony\Component\HttpFoundation\Response;
$response = new Response();
$response->headers->set('Content-Type', 'text/html');
$response->send();
Source/Documentation
If its inside controller then use this:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class DefaultController extends Controller
{
public function indexAction()
{
...
$response = new Response($xmlContent);
$response->headers->set('Content-Type', 'xml');
$response->headers->set('Another-Header', 'header-value');
return $response;
}
}
Just replace Content-Type with your header key and xml with value ... etc
If you are using the render()
method of the controller, then you can add the necessary headers like below because render()
method returns a Response object:
$response = $this->render('AppBundle:Post:index.html.twig', array('someArgs' => $someArgs));
$response->headers->set('Content-Type', 'text/html');
return $response;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With