[英]Symfony: How to render a template as a simple txt
我必须将动作模板呈现为一个简单的.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');
我看不出使用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
编写一个监听kernel.response
来修改响应头,但这可能会使事情变得过于复杂。 在此处查看更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.