Render Twig Template in Symfony 8

Render Twig Template in Symfony 8

Symfony uses the Twig templating engine to generate HTML views. Templates are usually rendered from controllers, but Symfony also allows rendering them in different ways depending on the application's needs. This tutorial shows how to render Twig template in Symfony 8 application.

Let's say we have the following Twig template:

templates/test/index.html.twig

Hello {{ name }}

Controller - Method 1

When controller extends AbstractController, the simplest and most common approach is to use the render helper method. This method renders the template and automatically creates a Response object.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController extends AbstractController
{
    #[Route('/')]
    public function index(): Response
    {
        return $this->render('test/index.html.twig', ['name' => 'John']);
    }
}

Controller - Method 2

If we need more control over the response, we can render the template into a string first and then create the Response manually. For this purpose, the AbstractController provides the renderView method.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController extends AbstractController
{
    #[Route('/')]
    public function index(): Response
    {
        $content = $this->renderView('test/index.html.twig', ['name' => 'John']);

        return new Response($content);
    }
}

Controller - Method 3

Symfony also supports rendering templates using attributes. By applying the Template attribute, the controller method can simply return an array of variables, and Symfony will handle rendering the template. This method doesn't require to extend the AbstractController.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Bridge\Twig\Attribute\Template;
use Symfony\Component\Routing\Attribute\Route;

class TestController
{
    #[Template('test/index.html.twig')]
    #[Route('/')]
    public function index(): array
    {
        return ['name' => 'John'];
    }
}

Service

We can also render Twig templates outside of controllers. To do this, we can inject the Twig Environment service into our own service and call its render method.

src/Service/TestService.php

<?php

namespace App\Service;

use Twig\Environment;

class TestService
{
    public function __construct(private Environment $twig)
    {
    }

    public function render(): string
    {
        return $this->twig->render('test/index.html.twig', ['name' => 'John']);
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.