How to set a header and render a twig template without renderView() method in symfony2.X controller

StackOverflow https://stackoverflow.com/questions/23618962

  •  21-07-2023
  •  | 
  •  

Pergunta

How would one go about setting a header (Content Type) and rendering a twig template without renderView() method in symfony2.X controller?

Foi útil?

Solução 2

You can do it returning the response as rendered view (check this sample)

public function indexAction()
{
   // a parameter which needs to be set in twig
   $variable = 'This is sample assignment';
   $current_user = $this->user; // assume you defined a private variable in your class which contains the current user object

   $response = new Response(
      'AcmeMyBundle:Default:myTemplate.html.twig',
      ['parameter1' => $variable],
      ['user' => $current_user]
   );

   return $response;
}

If your response has a specific header info you can easily set by $response->header->set(...);

Outras dicas

I'm not sure if the accepted answer is valid anymore, or if ever was. Anyhow, here's a couple ways of doing it. I've got an XML, and JSON sample for you here.

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;

class DefaultController extends Controller{
  public function indexAction($x = 0)
  {
    $response = new Response(
      $this->renderView('AcmeMyBundle:Default:index.html.twig', array('x'=>$x)),
      200
    );
    $response->headers->set('Content-Type', 'text/xml');

    return $response;
  }

  //...

or for JSON response

//...

public function indexAction( $x = 0 )
{
  $response = new JsonResponse(
    array('x'=>$x)
  );

  return $response;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top