Templating with Timber

Droo Hastings

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 %}
    <div class="content-wrapper">
        <article class="post-type-{{ post.post_type }}" id="post-{{ post.ID }}">
            <section class="article-content">
                <h1 class="article-h1">{{ post.title }}</h1>
                <h2 class="article-h2">{{ post.subtitle }}</h2>
                <p class="blog-author">
                	<span>By</span> {{ post.author.name }} <span>&bull;</span> {{ post.post_date|date }}
                </p>
                {{ post.content }}
            </section>
        </article>
    </div>
{% endblock %}

Which now allows us to do this

 <h1 class="article-h1"><a href="{{ post.link }}">{{ post.title }}</a></h1>

instead of the old way which is …

 <h1 class="article-h1"><a href=""></a></h1>

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

 {% extends "base.twig" %}
 
{% block content %}
    <div class="content-wrapper">
        <article class="post-type-{{ post.post_type }}" id="post-{{ post.ID }}">
            <section class="article-content">
                {% block headline %}
                    <h1 class="article-h1">{{ post.title }}</h1>
                    <h2 class="article-h2">{{ post.subtitle }}</h2>
                {% endblock %}
 
                <p class="blog-author"><span>By</span> {{ post.author.name }} <span>&bull;</span> {{ post.post_date|date }}</p>
                {{ post.content }}
            </section>
        </article>
    </div>
{% 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.

 

Last updated by on .

What Are Your Thoughts?

Your email address will not be published. Required fields are marked *