2016-09-23 33 views
-3

我必须将操作的模板呈现为简单的.txt文件。Symfony:如何将模板呈现为简单的txt

我该怎么做?除了使用Response对象之外,还有其他方法吗?

使用Response对象:

$content = $this->get('templating')->render(
     'AppBundle:Company:accountBillingInvoice.txt.twig', 
     [ 
      'invoice' => 'This is the invoice' 
     ] 
    ); 
    $response = new Response($content , 200); 
    $response->headers->set('Content-Type', 'text/plain'); 
+0

检查此答案,http://stackoverflow.com/a/27693540/1857533 – Gustek

+0

不,这是不正确的,因为此响应将头设置为'application/json',而我需要将头设置为'text/plain' 。 http://symfony.com/doc/current/components/http_foundation.html#creating-a-json-response – Aerendir

+0

我非常肯定,在我发布的答案中,有如何做文本和json响应的例子。阅读您链接的示例和文档,并尝试理解它,而不是等待准备就绪。 – Gustek

回答

3

我看不出有什么不对使用Response对象 - 这是很简单的!

如果你想呈现许多控制器操作短信回复,你不想重复自己很多,你可以定义建立起对你的反应,像一些服务类:

class TextResponseRenderer 
{ 
    /** @var EngineInterface */ 
    private $templating; 

    // constructor... 

    /** 
    * @param string $template The name of the twig template to be rendered. 
    * @param array $parameters The view parameters for the template. 
    * return Response The text response object with the content and headers set. 
    */ 
    public function renderTextResponse($template, array $parameters) 
    { 
     $content = $this->templating->render($template, $parameters); 
     $textResponse = new Response($content , 200); 
     $textResponse->headers->set('Content-Type', 'text/plain'); 
     return $textResponse; 
    } 
} 

其他选项可能会为修改响应标头的kernel.response编写一个监听器,但这可能是过于复杂的事情。查看更多信息here