Timber is a plugin to separate PHP and HTML code. It makes your code cleaner and more maintainable. A great tool if you want to create a theme from scratch.
Let’s take a look at Timber in action. Here we have a standard posts loop:
<?php if ( have_posts() ): while ( have_posts() ): the_post(); ?>
<article>
<h2>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
<h2>
<p>
<?php the_excerpt(); ?>
</p>
<time>
Written by <?php the_author_posts_link(); ?> on <?php the_time('F jS, Y'); ?>
</time>
</article>
<?php endwhile; else: ?>
<h2> Sorry, no post found </h2>
<?php endif; ?>
With Timber, we split that into two: (1) PHP file for data processing and (2) Twig file for HTML templating:
<?php
$context = Timber::context();
$context['posts'] = Timber::get_posts();
Timber::render( 'index.twig', $context );
...
{% for p in posts %}
<article>
<h2>
<a href="{{ p.link }}">
{{ p.title }}
</a>
<h2>
<p>
{{ p.post_excerpt }}
</p>
<time>
Written by {{ p.author.display_name }} on {{ p.post_date | date }}
</time>
</article>
{% else %}
<h2> Sorry, no post found </h2>
{% endfor %}
...
All values that is passed in when calling Timber::render()
will be available to use in the Twig file, in the case above: posts
data.
Twig Syntax
Below is a brief introduction to Twig language. Visit the official docs for more info.
ECHO VARIABLE
{{ var_name }}
COMMENT
{# Use curly brace with hashtag #}
FOR LOOP
{% for p in posts %}
...
{% endfor %}
CONDITIONAL
{% if var == "..." %}
...
{% elseif var >= 10 %}
...
{% else %}
...
{% endif %}
FILTER – Run a function by passing in the variable
{{ p.post_date | date }} {# Format the date #}
{{ p.my_custom_field | shortcodes }} {# Run the shortcode #}
{{ my_array | length }} {# count the array #}
...
EXTENDS & BLOCK – Extend is to inherit another template while Block is to override certain part.
<nav class="top-nav"> ... </nav>
{% block content %}
{% endblock %}
<footer class="main-footer"> ... </footer>
{% extends "layout.twig" %}
{# Override the block content in layout.twig #}
{% block content %}
<article>
<h1> {{ post.title }} </h1>
{{ post.content }}
</article>
{% endblock %}
You will learn a lot more about Timber by taking a look at our basic theme. That theme has no styling and lack features. It is only intended for learning purposes.
If you are looking for fully-featured theme, try the official starter theme.
Conclusion
Timber makes developing a custom theme much easier and manageable. It applies the core idea of MVC framework which is to separate logic and interface.
If you are interested to learn more about Timber, check out the following:
- Basic Theme – Plain Timber theme intended for teaching you the rope about Timber.
- Starter Theme – Fully-featured theme built with Timber.
- Timber Official Docs
- Twig Language Docs
Feel free to ask question regarding Timber in the comment below 🙂