We hope you find this tutorial helpful. In addition to guides like this one, we provide simple cloud infrastructure for developers. Learn more →

How To Design Template Pages with Twig on a VPS

Posted Sep 12, 2013 12.2k views PHP Frameworks PHP

About Twig

Twig is a modern template engine designed for PHP that is both designer and developer friendly. It is a very good alternative to the PHPTemplate way of building the presentation logic of a web application as it is represents a much cleaner templating experience. In this respect, it comes with a very easy to understand syntax and restricts you from performing dynamic PHP operations in template files.

In the previous tutorial, we’ve seen how to set up Twig with Composer and get started using it at its most basic level. In this tutorial, we will dive a bit deeper into its syntax and how you can use it to build up your template files.


The first thing you need to know is how to add comments to your page. There is a simple syntax for it: {# #}. Everything you put inside this block will not be parsed. And it can be on multiple lines too:

  This is a comment that won’t be parsed. 


We’ve already seen how to pass a variable to the template file and how to print it out (in between the double curly braces). The one we saw was a very simple string PHP variable. However, you can pass through the render() method also arrays or objects.

Let’s say we have the following PHP class in our application:

class Box

    public $shape = 'square';

    public function displayShape() {
        return $this->shape;

If we instantiate a new object based on this class (let’s call it myBox) and pass it through to the Twig template, we can work with it in the following way. If we want to print out the $shape attribute we do this:

{{ myBox.shape }}

If we want the return of the displayShape() method, we do this:

{{ myBox.displayShape() }}

With an array, it’s very similar. Suppose myBox is an array with one element with the key shape. We print it out with the same syntax as the object attribute:

{{ myBox.shape }}

Additionally, you can set new variables in the template file by using the other Twig delimiter {%%}:

{% set shape = 'square' %}


A cool thing about Twig are the availability of a number of very useful and easy to use filters. What are filters you ask? Easiest way to explain is with an example:

{{ shape|upper }}

This will output the value of the shape variable in all uppercase letters. And you can even combine multiple filters if you want:

{{ shape|upper|trim }}

This one also trims the empty spaces at the beginning and end of the variable value. Additionally, you can apply filters to an entire block:

{% filter upper %}
  This box is {{ shape }}.
{% endfilter %}

?The above statement will turn everything within the filter block into uppercase letters.

You have a good number of handy filters you can check out on the Twig documentation website. Some even take arguments, like the date filter in which you specify a format you want a date variable to be displayed in. If you are learning Twig, you’ll find you’ll often go there to check for stuff.

Control Structures

Since no template files can go without loop or if/else statements, Twig also let’s you use various control structures for your data. For instance, this is how you’d do a regular foreach iteration:

{% for shape in shapes %}
  {{ shape }} 
{% endfor %}

This will loop through the shapes array and print out each shape. An if/else statement looks something like this:

{% if shape is defined %}
  {{ shape }}
{% endif %}

This will print out the shape variable only if it is set. More information about control structures you can find on the Twig documentation page.

Including and Inheriting Templates

Twig has a very powerful feature that allows you to include templates inside each other. Let's illustrate:

{% include 'header.html' %}

This statement will load the header.html file and render it within the current context of the template that is including it. This means that it has access to all the variables available to the including template. This is a great feature that allows you to keep multiple but much cleaner files.

Additionally, inheritance is another and even more powerful feature in Twig. It allows you to create templates into which you define blocks and then have them extended by other templates that can either override the default content in these blocks or add new content to them. A quick example:

Template A (layout.html) contains the following (keep in mind that this is just an example):

<div class=”eight columns”>{% block mainContent %}{% endblock %}</div>
<div class=”four columns”>{% block rightSidebar %}{% endblock %}</div>

As you can see, there is no content within the defined blocks. We could add some if we wanted to. But also template B can extend this template and add content into those blocks:

{% extends "layout.html" %}

{% block mainContent %}Some page text{% endblock %}
{% block rightSidebar %}Some sidebar content{% endblock %}

What happens here is that template B extends template A (basically gets template A loaded and rendered onto the page) but also populates it’s defined blocks which are currently empty. If the blocks in template A have content, template B would overwrite that content in the example above. To add to the existing content instead of overwriting, it would have to be something like this:

{% block mainContent %}
  {{ parent() }}
  Some page text
{% endblock %}

So the mainContent block now loads what is in the parent it extends, prints it out and adds below some more content.

Some key points to mention. The extends block should be the first thing on your page if you want to extend a template. Also, if you do this, you cannot have content outside of the blocks defined in the template you are extending. Therefore in template B, all content you add must go into one of the blocks defined in template A.

More information about inheriting via the extend tag, you can read on the Twig documentation page.


In this article, we’ve gotten a bit deeper into using Twig to build up template pages. We’ve seen how to use the commenting system, print out variables (both simple and complex such as arrays and objects), use control structures for more dynamic results and how to include and extend templates. There is a bunch more you can do in the twig files and I encourage you to check them out.

And if you like using PHP frameworks, Twig is the default templating engine for Symfony2, so keep that in mind. Also, the upcoming major Drupal 8 release will use Twig for the templating as well.

Article Submitted by: Danny


Creative Commons License