How to pass data from a controller to a Twig template in Symfony?

In Symfony, you can pass data from a controller to a Twig template by using the render method of the Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait class. The render method renders a Twig template and passes data to it.

Here is an example of how to pass data from a controller to a Twig template:

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; class MyController extends AbstractController { public function myAction() { $data = [ 'name' => 'John Doe', 'age' => 30 ]; return $this->render('my_template.html.twig', $data); } }

In this example, the myAction method retrieves some data and then passes it to the my_template.html.twig Twig template using the render method. The data is passed as an associative array where the keys are the variable names in the template and the values are the actual data.

In your Twig template, you can then access the data like this:

<h1>Hello, {{ name }}!</h1> <p>You are {{ age }} years old.</p>

When the my_template.html.twig template is rendered, the name and age variables will be replaced by the values passed from the controller.

This is how you can pass data from a controller to a Twig template in Symfony.