[英]How to use renderView and twig templating in a Symfony 4 Service
[英]How to set a header and render a twig template without renderView() method in symfony2.X controller
如何在symfony2.X控制器中设置标题(内容类型)和渲染没有renderView()方法的树枝模板?
我不确定接受的答案是否有效,或者如果有的话。 无论如何,这里有几种方法。 我在这里有一个XML和JSON示例。
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;
}
//...
或者用于JSON响应
//...
public function indexAction( $x = 0 )
{
$response = new JsonResponse(
array('x'=>$x)
);
return $response;
}
您可以将响应作为渲染视图返回(请查看此示例)
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;
}
如果您的回复有特定的标题信息,您可以通过$response->header->set(...);
轻松设置$response->header->set(...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.