Simplify Your WordPress Theming With Twig And Timber

Simplify Your WordPress Theming With Twig And Timber

In a recent article on future features that WordPress could consider, I included adding a templating language to the core.

One such language is Twig and implementation already exists for WordPress via the Timber plugin.

So, what is a templating language, how does it work in a WordPress environment, and is it worth the effort?

Twig logo
Templating languages can bring massive advantages to WordPress theme development

Twig, from SensioLabs, is a “flexible, fast, and secure template engine for PHP”.

In a nutshell, Twig provides a meta-language (it is compiled into PHP) specifically designed for turning data into formatted output. That output is generally HTML but it doesn’t have to be – it can quite happily be XML, JSON or any plain-text format.

The output is generated by providing the Twig engine with the requisite data (as a PHP object) and telling it which template to render. The engine takes care of the rest.

But why change? There are thousands of existing WordPress themes that seem to do okay (some more than okay) using PHP. What’s the big deal with templating languages.

Advantages Of Using A Templating Language

The Twig website lists 6 major advantages of using the Twig templating language:

  1. Concise – compared to PHP, Twig is very concise making it easier to write and maintain
  2. Template orientated – it is a language that is purpose-built for creating output, rather than being a multi-purpose language such as PHP
  3. Full-featured – Twig is powerful, with inheritance and blocks making the modular design very easy.
  4. Easy to learn – you certainly don’t need to be a developer to get the hang of Twig
  5. Extensibility – developers can add plugins to ensure that Twig can cover any front-end requirement
  6. Fast – this advantage may depend on how you rate your PHP skills as Twig is compiled down to PHP. I think it’s highly likely that for me, at least, the resultant PHP will be better than what I can come up with.

Biggest Advantage Is Separation Of Data And Design

What I really like about Twig is that it completely separates data from design. Twig is a template engine: you provide it with data and tell it which template to render.

This means that the underlying application is now only concerned with collating that data, there’s no requirement for its own themes. For WordPress that also means that plugins become data focussed whilst front-end controls, such as sliders, become the domain of Twig.

What Does Twig Look Like?

Twig is designed to work with any PHP application and it’s very easy to bootstrap it for testing (another of its advantages). A simple PHP file to render a template might look like this:

And the actual Twig template:

All very straight-forward and a lot cleaner than the traditional PHP/HTML mix. In fact, there are several CMS, such as Pico, that use this kind of approach (or perhaps a little more sophisticated although it does describe itself as “stupidly simple”!) to generate sites.

Timber: Bringing Twig To WordPress

We are, of course, interested in Twig and WordPress and it’s the Timber plugin that brings the two together. For some reason, there are 2 plugins called Timber in the WordPress repository so make sure you get the right one!

The plugin is the impressive work of Boston editorial designers Upstatement and performs three main tasks:

  1. Integrates the Twig engine into WordPress
  2. Creates a foundation WordPress data set
  3. Handles the rendering of Twig templates

Whereas in a normal WordPress theme you are mixing the data collation and its subsequent formatting in the same PHP files (think The Loop), a Timber template splits the two functions. In its basic form, the template file is only concerned with collating the data and then using that data to render a template, or view if you like, that is held in a separate file.

An example will help greatly, so let’s walk through one.

Here’s the index.php file for the Bosco theme (I’ve picked this theme as it is fairly simple):

The theme contains the familiar WordPress Loop and uses the get_template_part function to generate the output for each post in the list. (For the example, we are going to assume that all posts are of the standard format.)

With Timber, though, the index.php is only concerned with collating the required data:

It uses pre-baked Timber methods to get the generic data and then renders the index.twig template:

Not much in this template as I’ve followed the same modular approach as the original (i.e. code that gets used in multiple locations is placed in its own file) but we can already see Twig’s concise nature and powerful features at work.

First, there’s the else on the for statement. It works like the else on an if statement and will execute if the posts variable is empty. No need to wrap the for in an additional if statement. It’s also possible to perform actions based on the index value of the loop, so outputting a header on the first iteration or a footer on the last iteration, for example.

Second, there’s the use of Twig inheritance. In this case, the index template is extending the base template and providing content for the content block.

Let’s have a look at the base template:

There’s an import statement at the top of the file which makes some custom macros available to all files. For the sake of brevity, I’ve kept the original get_header, get_sidebar and get_footer functions (but called using Timber) and so the only block is the content block.

So, let’s have a look at the content.twig template:

This is a bit more interesting.

This template is only concerned with outputting a single article element and it’s pretty easy to work out what’s going on, even without being familiar with the Twig language.

All the variables being checked in the if statements or being output in the {{ }} statements are assembled by the PHP file and are passed to the Twig template.

The Timber plugin not only collates most of the data itself it also provides a few WordPress-specific essentials. For example, a post’s content is accessible via post.post_content, however, this is the raw content and so Timber provides the post.content method which will return the content after applying all filters and running all shortcodes.

You’ll see at the bottom of this template that there’s a couple of calls to macros: to output the post meta and to output the posts categories and tags.

The macros are stored in a Twig file (I’ve called it macros.twig but it could be any name) which is imported in the base.twig template. They don’t automatically have access to the data, so this gets passed to the macros:

This is where the advantages of an extensible templating language start to shine. A macro could be anything from outputting post meta to elaborate menuing to a full-screen slider and rather than being added as a plugin, it simply gets added as a Twig macro. All that needs to happen on the PHP-side of things is to ensure that the macro has the data it needs.

OK, But PHP And Twig? Isn’t That Doubling-Up?

The general assumption is that a Timber theme will follow the general convention and create a PHP file for each template that a theme may require, using the WordPress Template Hierarchy as a guide.

As we know, the Template Hierarchy is a wonderful thing. It allows us to easily get very specific with our templates. If we want to output category post lists differently to the other archives, we create a category.php file and it automatically gets used. If we want to get even more specific and have our sport category post list displayed differently to other categories then we create a category-sport.php.

This allows for incredible flexibility without the need to do any reconfiguring – simply drop a template into the theme directory with the appropriate name and it will automatically take its place in the template pecking order.

With Timber and Twig because the PHP files are just collating data there tends to be quite a lot of repetition. It’s possible, therefore, to take advantage of the WordPress Template Hierarchy and create just a single index.php that can generate the data we need and then work out the correct Twig template to render:

Timber Deserves A Closer Look

This has been brief overview of what is a powerful and thought-provoking plugin and if it has whet your appetite then I strongly recommend installing the plugin, browsing the Timber and Twig documentation and either grabbing the Timber Starter Theme (part of the plugin package) or converting an existing theme to get a feel for how it all works.

I think what you make of Timber and Twig will probably depend on the type of theme you are trying to build. A sidebar heavy, widget laden theme is not the best choice and it’s interesting to note that Upstatement are very much focussed on news media organisations.

You might also find that you are short on data and you’ll need to either extend Timber or simply update the PHP components of your theme to ensure that all the required data (logged in user data, for example) is being provided to the Twig templates.

What I really like about the Timber and Twig combination is the separation of data and design which means that designing a theme for WordPress (or any other CMS that uses Twig, of course) doesn’t require any knowledge of PHP and perhaps not even that much knowledge of WordPress itself.

Agree on what data is going to be made available and developer and theme designer can truly work on a site simultaneously.

A Possible Addition To The WordPress Core?

The advantages of a templating language also make me think that it should be seriously considered as potential update to the WordPress core.

Much has been recently been written about the need for WordPress themes to return to being clean, design only, and for functionality to be split out into plugins. If nothing else, Twig forces the theme developer down this path.

You can imagine that it would be relatively straight-forward to build the dataset and make it available to a templating engine such as Twig although the huge library of existing themes and the massive install base might prove a massive hurdle.

However, that doesn’t mean that Twig and its ilk should be summarily dismissed. Templating languages bring big advantages to theme development, not the least of which is a level of simplicity that is often missing from the traditional WordPress theme.

For that reason alone, Twig via the Timber plugin is worth investigating.

Do you have experience with using a templating language either on WordPress or another CMS?

Chris Knowles

Chris Knowles A WordPress pro, Chris has a bent on hacking WordPress, content management, and online media.