Community for developers to learn, share their programming knowledge. Register!
Twig Templates and Templating in Symfony

Creating First Twig Template in Symfony


You can gain valuable insights and practical skills from this article as we explore the intricacies of creating your first Twig template in Symfony. Twig is a powerful templating engine that enables developers to write cleaner and more maintainable code, making it an excellent choice for Symfony projects. In this article, we'll cover the essentials of Twig templates, including writing your first template, rendering them in controllers, and using variables effectively.

Writing Your First Twig Template

Creating a Twig template begins with understanding its syntax and structure. Twig templates are written in files with the .twig extension, and they can contain a mix of HTML and Twig syntax. To get started, you'll want to create a new Twig file in your Symfony project.

Step 1: Setting Up Your Environment

Ensure that you have Symfony installed and set up. You can create a new Symfony project using Composer:

composer create-project symfony/skeleton my_project_name

Once your project is set up, navigate to the templates directory, which is where Twig templates are stored by default.

Step 2: Creating Your First Template

Create a new file named welcome.twig in the templates directory. Open this file in your code editor and add the following content:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Welcome to Symfony</title>
</head>
<body>
    <h1>Welcome to Symfony with Twig!</h1>
    <p>This is your first Twig template.</p>
</body>
</html>

This template is a simple HTML structure that serves as a starting point. You can expand upon this by adding more content or utilizing Twig features like loops and conditionals.

Rendering Twig Templates in Controllers

Once you have your template ready, the next step is to render it from a controller. Symfony uses controllers to handle requests and responses, and rendering a Twig template is straightforward.

Step 1: Creating a Controller

Create a new controller in the src/Controller directory. For instance, create a file named WelcomeController.php:

<?php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class WelcomeController extends AbstractController
{
    /**
     * @Route("/welcome", name="welcome")
     */
    public function index(): Response
    {
        return $this->render('welcome.twig');
    }
}

In this controller, we define a route /welcome that, when accessed, will render the welcome.twig template. The render method takes care of locating the template and returning a response.

Step 2: Accessing the Route

To see your template in action, start the Symfony server:

symfony server:start

Now, visit http://localhost:8000/welcome in your browser. You should see the content from your welcome.twig template displayed.

Using Variables in Twig Templates

One of the most powerful features of Twig is its ability to handle variables. This allows for dynamic content rendering based on data passed from the controller.

Step 1: Passing Variables from the Controller

Let's modify our controller to pass a variable to the Twig template. Update the index method in WelcomeController.php:

public function index(): Response
{
    $name = 'Developer';
    return $this->render('welcome.twig', [
        'name' => $name,
    ]);
}

Here, we define a variable $name and pass it to the template as an associative array.

Step 2: Using Variables in the Template

Next, update your welcome.twig file to include the variable:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Welcome to Symfony</title>
</head>
<body>
    <h1>Welcome to Symfony with Twig, {{ name }}!</h1>
    <p>This is your first Twig template.</p>
</body>
</html>

The {{ name }} syntax is used to embed the variable into the HTML output. Now, when you access the /welcome route, you should see "Welcome to Symfony with Twig, Developer!".

Leveraging Twig Filters and Functions

Twig offers a variety of filters and functions to manipulate data. For instance, if you want to convert the name to uppercase, you can modify the template like this:

<h1>Welcome to Symfony with Twig, {{ name|upper }}!</h1>

This will render the name in uppercase letters.

Summary

In this article, we explored the process of creating your first Twig template in Symfony. Starting from writing a basic template, we moved on to rendering it through a controller and utilizing variables to make the content dynamic. Twig's syntax and capabilities allow for clean and efficient templating, which is essential for maintaining professional-grade applications.

As you continue working with Symfony and Twig, consider diving deeper into advanced features such as custom filters, template inheritance, and using Twig extensions to enhance your development process. With these tools at your disposal, you can create robust, maintainable, and efficient web applications. For further reading, refer to the official Symfony documentation and Twig documentation.

Last Update: 22 Jan, 2025

Topics:
Symfony