How to use Twig templates in Symfony?

To use Twig templates in Symfony, follow these steps:

  1. Create a new Twig template file in the templates directory of your Symfony project. You can name the file with a .html.twig extension, for example home.html.twig.

  2. In your Symfony controller, return a new Response object that renders the Twig template file. Below is an example code snippet to render the home.html.twig template:

use Symfony\Component\HttpFoundation\Response; public function homePage() { return $this->render('home.html.twig'); }
  1. Make sure to inject the Symfony\Component\Templating\EngineInterface service in your controller to render the Twig template. This service allows you to render templates using the render method.

  2. You can pass variables to the Twig template by passing an array of data as a second argument to the render method. For example:

public function homePage() { $data = [ 'title' => 'Welcome to Symfony', 'content' => 'This is the homepage of the Symfony project.' ]; return $this->render('home.html.twig', $data); }
  1. In your Twig template file, you can access the passed variables using the {{ }} syntax. For example, to display the title and content variables, you can use the following code in your home.html.twig file:
<!DOCTYPE html> <html> <head> <title>{{ title }}</title> </head> <body> <h1>{{ title }}</h1> <p>{{ content }}</p> </body> </html>
  1. Finally, make sure that your Symfony project is properly configured to use Twig as the default template engine. This is typically done in the config/packages/twig.yaml file.

That's it! You have successfully used Twig templates in your Symfony project.