TWIG: Integrating Markup Languages and PHP for Web Development

TWIG is a modern, fast, secure and flexible templating engine for PHP. With PHP, mixing and matching the scripting in a single file is quite easy but leads to cumbersome code, which makes debugging a nightmare. TWIG is a one-stop solution to coding problems in markup languages.

With the current fast pace of technological enhancements, object oriented programming (OOP) plays a crucial role due to its unique features such as polymorphism, inheritance and encapsulation. Most modern languages have developed support for these concepts. But the markup languages that we use today (HTML, XML, etc) lack such features, though they are versatile and important.

Some problems with todays markup languages are:
1. Code redundancy
2. Their static nature
3. Inability to embed other markups
4. Fragmented integrity with the backend
5. Lack of arithmetic, logical and programmatic operations
With PHP, it is easy to mix and match the markup and scripting in a single file. We use it quite often to get whats missing. This solves almost all the problems from the above list, but makes the code hard to read, understand and thus undermines the troubleshooting and debugging process that will follow. Also, enhancing the software becomes more difficult. More important, no one likes to work on ugly looking code!

In order to attain an optimum solution to all the above mentioned problems, programmers have come up with templating engines. TWIG is one such engine created by Sensio Labs. It is an extremely fast and lightweight framework that delivers excellent performance along with a neat coding structure. It includes several features such as inheritance and logical operations that are embedded or built right out-of-the-box. In this article, we will explore all the features that come pre-built with TWIG and learn how they benefit you.

TWIG is a modern template engine for PHP
If you have any exposure to other text-based template languages, such as Smarty, Django or Jinja, you should feel right at home with TWIG. Its both designer- and developer-friendly, because it sticks to PHPs principles and adds functionality useful for templating environments.

Its key features are listed here.

Fast: TWIG compiles templates down to plain optimised PHP code. The overhead compared to regular PHP code has been reduced to the very minimum.

Secure: TWIG has a sandbox mode to evaluate untrusted template code. This allows TWIG to be used as a template language for applications where users may modify the template design.

Flexible: TWIG is powered by a flexible lexer and parser. This allows the developer to define custom tags and filters, and create a custom DSL. TWIG needs at least PHP 5.2.7 to run.

Installation of Composer
Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on, and it will manage (install/update) them for you. The following are the steps to install Composer on your machine.

Step 2:Go to https://getcomposer.org/doc/00-intro.md#globally and follow the instructions in order to install Composer globally (i.e., using the composer command on CLI instead of PHP composer.phar). Once you are done with installing Composer on your CLI, just check it by typing composer on your CLI (terminal or cmd).

Figure 1: Installation of TWIG

Installing TWIG

Now that you have successfully installed Composer on your machine, its time to bring in the giant. Follow the steps given below to install and start using TWIG in your projects.
First, it is necessary to traverse into your project directory on your CLI to install TWIG.Step 1: Execute the command:

composer require twig/twig:~1.0

TWIG is now installed on your project. When this has been executed, you will have two files and a folder in your projects folder, namely, composer.json, composer.lock and vendor (which contains TWIG). See Figure 1 above.
All you need now is to use TWIGs API to start implementing it in your project files.
So now, lets create a PHP API to render TWIG templates, create a PHP file named index.php and a new folder named views, with the following code in it:

Now open the browser and enter the URL localhost/~project_folder~/
The output should be something like whats shown in Figure 2.

So, what happened here? If you want to know how the initial {{name}} has changed to Sameer here, you are in the right place. Now lets rewind a bit; in the file index.php, you included a file autoload.php, which is nothing more than an anchor file that links your project to TWIGs pre-built classes like Twig_Loader_Filesystem that you used in it.
So in that index.php file, you implemented TWIGs functions in the views folder, and then you loaded up a file named page.html passing an array to it (name => Sameer). Now comes the magic trick; TWIG has three main signs of execution: {{ }}, {% %} and {# #}. When either of these has been detected, instantly, TWIG responds and gives out the proper output.
Each of these signs is assigned for a specific task.{{ }} is used to display a variable.{% %} is used to perform programmatic operations such as looping, including inheriting a parent document, etc.{# #} is used to add comments to the code.

Our main focus will be on using programmatic operations the {% %} operations.

Figure 2: Output of page.html

Features available out-of-the-box

With its many capabilities, this lightweight framework extends the horizons of markup languages with its efficient features, which you get to use right out-of-the-box. Publishing constraints do not permit the explanation of all of these in one article.Use of looping in TWIG: Every programmer wants this feature to reduce lines of code in repetitive conditions. TWIG happens to serve this purpose well. With its {% for %} statement, TWIG is capable of printing loop statements. As an example, lets change the array passed to page.html via index.php in the snippet previously given; so the changed file is as follows:

You might notice here that the functional units in TWIG have a starting and ending tag (just like a markup). Here, it is {% for %} and {% endfor%}.Conditional statements: It is not surprising that TWIG also supports conditional statements such as if and else in the same fashion as the FOR looping block we saw above.Including documents: This is a nice way to include other documents/plugins in your Web page (just like PHP does). {% include pages/xyz.html %} will do the job neatly and cleanly!Inheritance: This ones a beast; all the languages out there have made peace with this feature that is great in preventing code redundancy and spaghetti code. With inheritance applied in a templating engine, we can achieve the milestone of creating a master-template, which will act as a frame to fit in the pieces we want to. Heres a good example of this feature.
Create a file in the views folder named base.html.twig and write the following code into it:

So here, what you can see is for every page. You just have to define what you want in each block; also, no specific order is required (but recommended) to edit these blocks. I can edit the title block after editing the body block, and it wont make any difference.
In this article, we have covered just four of the features that we use in our daily work as developers, but the list keeps growing for TWIGs features.
You can play with many other features while using the MVC and CMS architectures like building forms out of the objects, creating URLs from the route names, and many others. For more detailed documentation and features, you can visit: http://twig.sensiolabs.org/documentation.