Aerendir Aerendir - 6 months ago 53
Twig Question

Symfony: How to render a template as a simple txt

I have to render a template of an action as a simple


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

Using a

$content = $this->get('templating')->render(
'invoice' => 'This is the invoice'
$response = new Response($content , 200);
$response->headers->set('Content-Type', 'text/plain');


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

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.