PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, December 28, 2021

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

 December 28, 2021     php, symfony, twig     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing