How to adjust the title and display the branch template without the renderView () method in the symfony2.X controller

How to set header setting (Content Type) and branch template visualization without renderView () method in symfony2.X controller?

+4
source share
2 answers

You can do this by returning the answer as a visualized 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 answer has specific header information, you can easily set $response->header->set(...);

+2
source

I am not sure if the accepted answer is true or has ever been. Anyway, there are several ways to do this. I have XML and a 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;
}
+8
source

Source: https://habr.com/ru/post/1540290/


All Articles