PHP : your first views with Twig

Step by step, here is how to build your first pages with the PHP template engine. These pages are taken from the book “Développer avec Symfony2” published by Eyrolles.

This article is based on extracts from the book “Développer avec Symfony2” by Clément Camin published by Eyrolles.

In this chapter, we will create our first real pages using Twig, a very popular component. We will learn how to structure the views of our application using a hierarchical structure. We will create a home page and an About page, which we will link together with a menu to navigate from one to the other. This will reinvest what we’ve learned about routing and controllers. These first pages will be simple; we will expand them in later chapters.

Symfony2, an MVC architecture

All web pages work on the same principle: the server receives an HTTP request to which it must provide a response. To do so, from the input parameters (the URL of the request and its parameters), it must fetch the information to be displayed and return it in the requested form.

Symfony2 is built around an architecture called MVC: Model, View, Controller. This architecture is used in many fields of software engineering, and provides a solution to this problem. It is therefore logical that it is found, in its original form or in a variant, in many web frameworks, in PHP as in other languages.

The idea of this architecture is to clearly separate three elements.

  • The model contains the data that we manipulate, as well as the business logic to manage them.
  • The view contains the logic for presenting this data to the user. For a web page, it is most often in HTML.
  • The controller uses the input parameters to communicate with the model and obtain the data needed by the view to achieve the expected display.

This division of labor results in a physical separation of the code related to each of these aspects. In this chapter, we will mainly talk about Symfony2 views and we will first code simple controllers. As for the model, we will come back to it in a large part of this book.

Even if we don’t have any data to display yet, we will still start to structure our project and take advantage of Symfony2’s assets. In particular, we will take our first steps with Twig, the framework‘s view engine.

We’ll split our first pages into meaningful blocks and we’ll give simple but specific tasks to the dedicated tools (routing system, controllers, view engine). Later, as the project becomes more complex, we will keep in mind these notions of separation of responsibilities and, in turn, we will break our code into simple blocks and tools.

The Twig view engine

Among the various components of a Symfony2 application, one of the most famous is Twig. We will use its syntax instead of PHP, the other way to manage views.

It is a view engine developed by SensioLabs. Like many libraries, it can work independently. However, it is available with Symfony2.


{{ article.title }}

{{ article.content }}
{# Displaying keywords and link to a page listing articles containing these keywords #}
    {% for tag in article.keywords %} {% endfor %}

This code could be in a page displaying a blog post, with its title and content. Below the article is a list of keywords, with a link to a page listing articles containing those keywords.

An overlay that has many advantages

Using one more overlay in a framework that already seems very large may, at first, seem like a bad idea: it’s one more thing to learn, you can’t run PHP directly… In fact, it has many advantages.

  • the usual control structures (conditional tests, loops…) ;
  • automatic escape of variables, to avoid security problems;
  • view inheritance, to separate views in a hierarchical way;
  • filters, which allow to display complex data, for example dates, as you wish;
  • translations.

These numerous features, native to Twig, help to develop business functionality more quickly, without having to deal with low-level issues, such as escaping variables.

Moreover, as we can see in the previous example, Twig’s syntax is simple and concise. These two advantages make it easier to use, while making views easier to read than when they contain many PHP tags.

Three delimiters

Twig’s syntax contains three delimiters, as seen in the previous example.

  • {% … %} means “execute something”. The code between these delimiters is usually used to execute operations, for example loops or tests.
  • {{ … }} means “display something”. The value of the variable or the result of the expression between these two delimiters will be displayed.
  • {# … #} delimits comments. Unlike HTML comments, these will not appear in the generated page.

We’ve talked a lot about HTML generation so far, because it is the most common output format on the web. However, Twig can actually generate any type of file: plain text, JSON… as long as you have a valid view file.

The home page

In terms of routing, nothing changes: it is still associated with the homepageAction in the StaticController. However, for this controller to use a view, changes must be implemented in the action body and a view file must be created.

The controller

Let’s start by modifying the StaticController, to update the code of the homepageAction method.

   return $this->render(

In the body of the action, instead of generating a response on the fly, we return the result of the render method. The render method takes care of using a view and applying the renderer to it. We tell render to use the homepage.html.twig file located in theviews folder of the TechCorpFrontBundle’s Static controller for the display. Physically, this corresponds to src/TechCorp/FrontBundle/Resources/views/Static/homepage.html.twig.

The format of the filename used as a parameter to the render method is not like the ones we are used to. The template name is of the form bundle:controller:template and allows you to refer to bundles from anywhere in the application, or even in another bundle. We will see this later in the chapter. This format for naming view files is a convention, found in many places.

That’s it for this action. We’ll have plenty of time to write more complex ones later!

The view

Now it’s time to create our first view, by placing the following content in the src/TechCorp/FrontBundle/Resources/views/Default/index.html.twig file.

Hello World !

As you can see, the view is very simple. It simply displays “Hello World !”, a classic at the beginning of a project.

First test

  • We created a route for our home page. We gave it a name and associated it with a pattern (/), and an action, i.e. a method in a controller.
  • We created a controller in which the action requests the rendering of a view.
  • We have created the necessary view file.

Now let’s launch the browser at the URL app_dev.php; we should see our home page displayed.

PHP : vos premières vues avec Twig
Figure 7-1 The home page, our first page. Eyrolles

Passing parameters to the view

With Twig, we will often have to pass information to the view. To do so, we just need to add a second parameter to the render method:

class StaticController extends Controller
     public function homepageAction()
          $name = 'World';
          return $this->render(
                array ('name' => $name)

In this example, we provide the view with the name variable, associated with PHP’s $name variable. We can then access it and display its value.

Hello, {{ name }} !

In our example, the result is the same as before: we still display “Hello World!”.

This is a simple example, but we will see many other features of the view engine later in this chapter.

Three-level structure

Now that we know how to display pages, it’s time to properly structure the views. To do this, we’ll set up a three-level hierarchy. This will allow us to separate the content of the views into three distinct levels:

  • the application ;
  • the bundle ;
  • the action.

The idea is that in a view file that is only about a particular page, we don’t need to know everything that is done at the application level. If we just need to display the title of an article, we don’t need to know the precise DOM structure that needs to be respected and we don’t want to include the CSS files ourselves. In fact, at each level, we just display the information we know. This avoids code duplication and standardizes the DOM structure throughout the application. This is a nice side effect, not only is it easier to develop, but also, from an SEO (Search Engine Optimization) point of view, the improvement of the results in search engines will be noticeable. Moreover, by dividing the code in a coherent way, it is easier to find where to make an addition, a modification or a correction, whether it is the original author of the code or another developer.

So let’s create our three levels of views, in three different places.

Leave a Comment