Sling Academy
Home/PHP/Symfony: How to directly render a Twig template from a route

Symfony: How to directly render a Twig template from a route

Last updated: January 13, 2024

Overview

Twig is the default templating engine for Symfony, providing a syntax designed to be approachable and intuitive. This enables you to separate your application’s logic from its presentation by creating reusable template files. Symfony, being a framework focused on flexibility, provides several ways to work with Twig, including rendering templates from within controllers.

When building web applications with Symfony, one common task you come across is the rendering of templates. Symfony’s templating engine, Twig, is a flexible, fast, and secure template engine that allows you to create complex layouts and front-ends with ease. One powerful feature of Symfony combined with Twig is the ability to render templates directly from a route. In this tutorial, we will walk through how to set this up and provide multiple examples ranging from basic to advanced use cases.

Setting Up Your Environment

To follow along with the code examples provided in this tutorial, you’ll need to have a Symfony project already set up. If you have not yet created a Symfony project, you can create one using Composer:

composer create-project symfony/skeleton my_project_name

Once you have your Symfony project, make sure you have Twig installed. If not, Symfony Flex makes it easy to add Twig to your project:

composer require template

Basics: Rendering a Twig Template from a Route

Let’s start with the most basic example of rendering a Twig template directly from a route. In Symfony, you can create a route in two ways: through annotations in a controller or by using YAML, XML, or PHP files in the config/routes/ directory. For the sake of simplicity, we will use annotations in this example.

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

class HomeController extends AbstractController
{
    /**
     * @Route("/home", name="home")
     */
    public function show()
    {
        return $this->render('home/index.html.twig');
    }
}

Handling Dynamic Content

Twig is powerful in handling dynamic content. You can pass variables to the Twig template from your route to alter the content shown to the user. Let’s expand our previous example to pass data to our Twig template.

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

class HomeController extends AbstractController
{
    /**
     * @Route("/home", name="home")
     */
    public function show()
    {
        // Dynamic content
        $greeting = "Hello, Symfony and Twig lovers!";

        return $this->render('home/index.html.twig', [
            'message' => $greeting,
        ]);
    }
}

Advanced: Rendering a Twig Template from a Custom Service

Moving beyond the basics, Symfony’s service container allows you to define services that your application can use anywhere. You can create a custom service that renders a Twig template upon calling. First, define your service in config/services.yaml:

# config/services.yaml
services:
    App\Service\TemplateRenderer:
        arguments:
            $twig: '@twig'

And then you can create a service like so:

<?php

namespace App\Service;

use Twig\Environment;

class TemplateRenderer
{
    private $twig;

    public function __construct(Environment $twig)
    {
        $this->twig = $twig;
    }

    public function renderTemplate(string $templatePath, array $parameters = []): string
    {
        return $this->twig->render($templatePath, $parameters);
    }
}

Now, whenever you need to render a template using this service, you inject it and call the renderTemplate method.

<?php

namespace App\Controller;

use App\Service\TemplateRenderer;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

class RenderServiceController extends AbstractController
{
    private $renderer;

    public function __construct(TemplateRenderer $renderer)
    {
        $this->renderer = $renderer;
    }

    /**
     * @Route("/render-service", name="render_service")
     */
    public function show()
    {
        $html = $this->renderer->renderTemplate('home/service_render.html.twig', [
            'data' => ['message' => 'Rendered via service!'],
        ]);

        // You can now return a Response with the rendered html
        return new Response($html);
    }
}

Conclusion

In this tutorial, we’ve demonstrated the essentials of rendering Twig templates directly from routes in Symfony. Starting with simple route configuration to service-based rendering, these techniques allow you to keep your application clean and maintain a clear separation of concerns. By utilizing Symfony’s powerful features alongside Twig, you can build dynamic, data-driven web applications with ease.

Next Article: How to upgrade a Symfony project to the latest version

Previous Article: Symfony: How to Escape Output in Twig Templates (with Examples)

Series: Symfony & Doctrine Tutotirlas

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array