Templating with Timber

February 19, 2018
Templating is a big part of building a WordPress site. The more robust and extensive the site, obviously, the more code is involved in building out your templates. While we are able to compartmentalize our code by developing modularly, one thing that is seemingly unavoidable with php is the intermingling of php and html in our template files. Sure, we are used to doing it this way, but wouldn’t it be nice if we could separate our html into it’s own clean little ecosystem?Enter Timber! Timber is a WordPress plugin developed by Upstatement. Among other useful things, it allows us to keep our ‘php’ code and our markup in their own places for ease of human readability in our code.

Here’s an example from the documentation

Start by downloading the Timber starter theme available here. After installing the theme, you initialize Timber in your functions.php file

 <?php
$timber = new Timber\Timber();

You’re ready to start theming!

Continuing on with their example, find the file wp-content/themes/{timber-starter-theme}/templates/single.twig

Let’s start with a simple post:

 {% extends "base.twig" %}

{% block content %}

 

{{ post.title }}

 

{{ post.subtitle }}

 

By {{ post.author.name }} • {{ post.post_date|date }}

{{ post.content }}

 

 

{% endblock %}

Which now allows us to do this

{{ post.title }}


instead of the old way which is …

<a href=””>


Way cleaner with Timber. When we get to building out content blocks, Timber looks like this

 {% extends "base.twig" %}

{% block content %}

 

{% block headline %}

{{ post.title }}

 

{{ post.subtitle }}

{% endblock %}

By {{ post.author.name }} • {{ post.post_date|date }}

{{ post.content }}

 

 

{% endblock %}

When you read that, you immediately know what’s happening in that section!

This is just the tip of the iceberg with Timber. Check out the documentation if you want to give it a try here.

 

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive