【问题标题】:Symfony: How to render a template as a simple txtSymfony:如何将模板呈现为简单的 txt
【发布时间】:2017-02-01 13:45:54
【问题描述】:

我必须将动作模板呈现为一个简单的.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');

【问题讨论】:

  • 不,这是不对的,因为此响应将标头设置为application/json,而我需要将标头设置为text/plainsymfony.com/doc/current/components/…
  • 我很确定在我发布的答案中有如何进行文本和 json 响应的示例。阅读您链接到的示例和文档,并尝试理解它,而不是等待准备就绪。
  • 我只是要求一种更简单的方法,我知道如何“手动”执行此操作:)

标签: php symfony twig


【解决方案1】:

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

如果您想呈现来自许多控制器操作的文本响应并且您不想重复很多次,您可以定义一些为您构建响应的服务类,例如:

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

    // 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 renderResponse(string $template, array $parameters): Response 
    {
        $content = $this->engine->render($template, $parameters);

        $textResponse = new Response($content , 200);
        $textResponse->headers->set('Content-Type', 'text/plain');

        return $textResponse;
    }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 2017-01-31
    • 2015-07-20
    • 2012-12-11
    • 2011-04-28
    • 2018-08-30
    • 1970-01-01
    相关资源
    最近更新 更多