如何在symfony2.X控制器中设置标题(内容类型)和渲染没有renderView()方法的树枝模板?
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;
}
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(...);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.