How to use the Symfony twig bundle to render templates?

by lindsey.homenick , in category: PHP Frameworks , a year ago

How to use the Symfony twig bundle to render templates?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer


by deron , a year ago


To use the Symfony Twig Bundle to render templates, follow these steps:

  1. Install the Twig Bundle using Composer:composer require symfony/twig-bundle
  2. In your Symfony application, open the config/bundles.php file and add the following line to enable the Twig Bundle:return [ // ... SymfonyBundleTwigBundleTwigBundle::class => ['all' => true], // ... ];
  3. Create a Twig template file in the templates/ directory of your Symfony application. For example, you can create a file called index.html.twig:<!DOCTYPE html> <html> <head> <title>{{ page_title }}</title> </head> <body> <h1>{{ page_title }}</h1> <p>{{ page_content }}</p> </body> </html>
  4. In your controller, create a method that returns a Response object and calls the render method of the Twig_Environment object to render the template. For example:use SymfonyComponentHttpFoundationResponse; use SymfonyComponentRoutingAnnotationRoute; use TwigEnvironment; class MyController { /** * @Route("/my-route") */ public function myAction(Environment $twig) { $page_title = 'My Page Title'; $page_content = 'Welcome to my page!'; $html = $twig->render('index.html.twig', [ 'page_title' => $page_title, 'page_content' => $page_content, ]); return new Response($html); } } Note that you should inject the Twig_Environment object into your controller using the Environment class, which is provided by the Twig Bundle.
  5. Finally, navigate to the URL of your Symfony application that corresponds to the route defined in your controller. For example, if you defined the route as /my-route, navigate to http://localhost/my-route in your web browser to see the rendered Twig template.