To use Twig templates in Symfony, follow these steps:
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
.
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');
}
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.
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);
}
{{ }}
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>
config/packages/twig.yaml
file.That's it! You have successfully used Twig templates in your Symfony project.