Tuesday, December 28, 2021

[FIXED] Symfony: How to render a template as a simple txt

Issue

I have to render a template of an action as a simple .txt file.

How can I do this? Is there a way other than using the Response object?

Using a Response object:

    $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');

Solution

I can't see what's wrong with using the Response object - it's pretty simple!

If you want to render text responses from many controller actions and you don't want to repeat yourself a lot, you can define some service class that builds up the response for you, like:

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;
    }
}

Other option may be writing a listener for the kernel.response that modifies the response headers, but this might be over-complicating things. See more info here.



Answered By - MikO

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.