symfony Controllers Rendering a Twig template


Most of the time, you will want to render HTML responses from a template instead of hard-coding the HTML in your controller. Also, your templates will not be static but will contain placeholders for application data. By default Symfony comes with Twig, a powerful templating language.

In order to use Twig in your controller, extend Symfony's base Controller class:

// src/AppBundle/Controller/HelloWorldController.php
namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class HelloWorldController extends Controller
    public function helloWorldAction()
        $text = 'Hello World!';

        return $this->render('hello-world.html.twig', ['text' => $text]);

Create the Twig template (located in app/Resources/views/hello-world.html.twig):

<html><body>{{ text }}</body></html>

Twig will automatically replace the {{ text }} placeholder with the value of the text parameter, passed by the controller. This will render the following HTML output:

<html><body>Hello World!</body></html>