我必须将一个动作的模板呈现为一个简单的.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');
Run Code Online (Sandbox Code Playgroud)
我看不出使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
其他选项可能是为kernel.response
修改响应标头的编写侦听器,但这可能会使事情变得过于复杂。在此处查看更多信息。
归档时间: |
|
查看次数: |
4485 次 |
最近记录: |