@muriel.schmidt
To create a new Twig template in Symfony, you can follow these steps:
- Create a new file in the templates directory of your Symfony application. You can choose any name for this file, but it should have the .twig extension.
- Write the content of your Twig template in this file. You can use any of the Twig syntax and features to create the desired output.
- Optionally, you can define some variables that will be passed to the template from the controller. For example, you can define a variable called title and set its value to "My Page Title".
- In the controller that will render this template, add a method that will return a new Response object that uses the render() method to render the Twig template. The first argument of the render() method should be the name of the template file you just created, without the .twig extension. If you defined any variables in step 3, you can pass them as the second argument of the render() method.
Here's an example of a controller method that renders a Twig template called my_template.twig
and passes a variable called title
to it:
1
2
3
4
5
6
7
8
|
public function myControllerMethod(): Response
{
$title = "My Page Title";
return $this->render('my_template', [
'title' => $title,
]);
}
|
In this example, the render()
method is called with the argument 'my_template'
, which refers to the file my_template.twig
in the templates
directory. The second argument is an array that defines the variable title
and sets its value to the $title
variable defined in the controller method.