簡體   English   中英

如何在symfony2.X控制器中設置標頭並渲染沒有renderView()方法的樹枝模板

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM