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

人盡茶涼 提交于 2020-01-03 10:46:10

问题


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


回答1:


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(...);




回答2:


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;
}


来源:https://stackoverflow.com/questions/23618962/how-to-set-a-header-and-render-a-twig-template-without-renderview-method-in-sy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!