Kick-Start WordPress Development With Twig: Introduction

A lot has been written about the future of WordPress, and many believe that it lacks a templating language, especially when platforms like Django, Ruby on Rails, Node.js, Laravel, and even Drupal possess one. Facts like "WordPress powers nearly 25% of the web" make it difficult to question its current PHP-based templating system. But as the modularity in code is still missing, one can ask when the core will have a templating engine.

The good news is right here! The Twig templating engine along with a plugin called Timber can help us write super-clean and modular code in WordPress. In this series, we'll discuss its implementation and integration with WordPress. I will start with the very basics of what Twig is and why you need it, and in the next three articles, I will explain different types of Twig templates integrated with WordPress via Timber.

What Is Twig?

Twig is a flexible, fast and secure templating engine for PHP. Twig is brought to you by Fabien Potencier, the creator of the Symfony framework, and is considered to be feature-rich, extensive, quick and efficient. 

Generally, when you code in WordPress, you mix chunks of PHP with HTML (that's what we call spaghetti code). This is not attributed as super-clean markup. For the sake of a modular and Doing it Right™ approach, one needs to keep the View separate from Data. With Twig, you can separate the view layer from rest of the application. Twig works on the model-view-controller (MVC) pattern and it helps maintain clean code.

Why Use Twig?

Over the years, different PHP templating engines were developed, but Twig for sure surpasses all of them in the following capacities.

Feature-Rich

Twig is one of most feature-rich and powerful PHP templating engines. It supports multiple inheritance and automatic output escaping, and it helps divide the template into several blocks or components to maintain a modular design. Not only this, but developers can also add more plugins to meet any front-end requirements.

Fast and Efficient 

Templates which are compiled via Twig bear much less overhead when compared to ordinary PHP template. The coding routines get highly optimized, and you get to save a lot of your development time. It's also useful when you plan to change the base framework, since Twig helps create a separate templating layer which can be connected with any back-end framework, be it Laravel or WordPress.

Designer and Developer Friendly

Twig suits the requirements of both designers and developers. Even if you're not a code nerd, using Twig is simple, and it feels right to code a modular template based on components. Its syntax is easy to comprehend and refrains from implementing dynamic PHP operations in the template files. All in all, it's quite modern and is adaptable with all the latest coding standards. The output escaping concept is very comprehensive when handled with Twig. 

Let's start with a simple example.

In regular PHP you get an output like this:

In Twig, things get much more simplified, i.e. the above code gets compressed to:

Output escaping is just that simple in Twig. Just add double brace brackets, enter the name of the variable, and you get an output. Put a pipe with an e next to it and we've started escaping stuff. More on this in the next three articles of this series.

Secure

Twig sanitizes and secures the data on its own. Its exclusive sandbox mode intelligently monitors the entire code and filter the best possible results. This means that the user-generated templates can be easily and securely implemented. The sandbox environment can only be enabled globally or locally for specific templates like this:

In the case of any syntax error, Twig debugs your file by generating a message which contains the details like your filename and the line number with the problematic code.

Flexible

I've just mentioned that Twig is a modern templating engine, which also means that you can extend its functionality since it is quite flexible. It fully supports an efficient lexer and parser through which developers can define custom tags, filters, functions, etc.

Others

Apart from all the features mentioned above, Twig is very well documented and fully unit-tested. Its API and templating libraries are fully stable and can handle all sort of complex tasks. A dedicated online book and complete API documentation are also available.

Twig serves as the new template language for Drupal 8, which is my major motivation behind using this templating engine with confidence. The good folks at XWP, especially Weston Ruter, are working on a proposal to make Twig conform with WordPress.com VIP standards. 

Timber: Integrating Twig With WordPress

So far the entire discussion has revolved around two things. First, we should employ a modular approach of keeping templates separate from data while building custom WordPress themes and second, Twig can help us do that. But what brings these two together?

Different efforts have been made to achieve the very best of integrations between Twig and WordPress, and one such brave attempt is Timber, created by a web agency named Upstatement. It uses the Twig templating engine, which makes it possible to write modular and clean code in WordPress. 

Timber along with Twig can help you build fast and modular WordPress themes. This way you can keep your HTML code separate from the normal PHP files, ensuring a more sustainable code pattern. The concept of keeping HTML and PHP separate makes it possible for the PHP file to focus strictly on supplying data and logic while the HTML file (Twig file) concentrates on the view layer of the web application.

On the whole, Timber performs three main tasks:

  • It integrates Twig into WordPress.
  • It renders the Twig templates.
  • It adds a foundation WordPress data set.

I think their mission statement says it all:

Timber is a tool for developers who want to translate their HTML into high-quality WordPress themes through an intuitive, consistent and fully-accessible interface.

  • Intuitive: The API is written to be user-centric around a programmer's expectations.
  • Consistent: All WordPress objects can be accessed through polymorphic properties like slug, ID and name.
  • Accessible: No black boxes. Every effort is made so the developer has access to 100% of their HTML.

How Does Timber Work?

In the case of a regular WordPress theme, all the fragments of the PHP and HTML code are integrated and modified in the same PHP template files. However, with Timber, we split template files into two different data files: the PHP file, and the view/template file, i.e. the Twig file. 

So, the first one is saved with the file extension .php and the second one has .twig as its extension. Therefore, if you're creating template files for single.php, your files will be named single.php and single.twig

The former file collates the data, while the latter is the template which uses the data in HTML. This way you can add dynamic operations in your WordPress themes in a modular manner.

Let's summarize it all:

Timber handles your WordPress theme's template files in PHP and HTML (Twig) files. This way you separate the logic from display. It provides you with new ways to build, style and display your theme.

Conclusion

There's a lot to love about Twig. This article was just an introduction about the advantages of using a templating engine with WordPress. Modular code is better code and is easily maintainable. It's high time for developers to take this workflow shift, and I'm sure Twig can help them with that. 

In the upcoming articles, I'll show the practical implementation of the template files with Twig. We will look into how we can implement Twig for rendering WP Images, Comments and Menu, with code examples. Till then if you find any queries, feel free to ask. Don't forget to reach out on Twitter.

Tags:

Comments

Related Articles