Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 631
sjt003 Avatar asked May 12 '14 21:05

sjt003


People also ask

What is raw in Twig?

raw. By default, everything in Twig gets escaped when automatic escaping is enabled. If you don't want to escape a variable you'll have to explicitly mark it as safe which you can do by using the raw filter. This only works if the raw filter is the last filter that is applied to the filter.

What is macro Twig?

Macros are comparable with functions in regular programming languages. They are useful to reuse template fragments to not repeat yourself. Macros are defined in regular templates. Imagine having a generic helper template that define how to render HTML forms via macros (called forms.html ):


1 Answers

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;
}
like image 193
Justin Fortier Avatar answered Sep 19 '22 22:09

Justin Fortier