How to create a new twig template in Symfony?

by , in category: PHP Frameworks , a year ago

How to create a new twig template in Symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , a year ago 

To create a new Twig template in Symfony, you can follow these steps:

  1. 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.
  2. 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.
  3. 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".
  4. 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:

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.