WordPress Twig Templates
WordPress 3 did a lot to turn it from a blogging platform into a proper CMS and version 3.1 builds on this further with the introduction of post formats. Version 3 also saw the introduction of a new default theme, TwentyTen. The default theme has become bloated, has a complex “parts” system for includes, calls headers and footers separately – overall, it involves too much PHP, too much of the model.
Most frameworks have a templating system that simplifies theme design and obscures as much of the PHP code as possible. WordPress has no such system in place, so we’ve started to develop one for it. We’ve used the Twig templating system, a powerful system with a straightforward syntax.
We’ve started to expose the various parts of the WordPress system through the use of objects and arrays, allowing familiar control structures to be used in themes rather that WordPress’ own system of functions and conditionals. Here’s a simple WordPress loop to run through some posts, echoing links and titles, using the existing WordPress templating:
<?php if(have_posts()): while(have_posts()): the_post() ;?>
<a href="<?php the_permalink(); ?>"><h2><?php the_title(); ?></h2></a>
<p><?php the_excerpt(); ?></p>
<?php endwhile; endif; ?>
Here’s the same loop using Twig templates from within WordPress themes:
{% for post in posts %}
<a href="{{ post.permalink }}"><h2>{{ post.title }}</h2></a>
<p>{{ post.excerpt }}</p>
{% endfor %}
Looks a lot simpler doesn’t it? It is. Twig has a huge feature set that can be used in templating, with well though out control structures. See Twig for Designers for a no-nonsense rundown of what it can do.
We’ve recreated most of the WordPress TwentyTen theme using Twig, which is available on GitHub. It’s in it’s early stages and there’s still quite some work to do, but it’s certainly interesting code to look at. We’ve also got an object reference for WordPress templates up on the GitHub wiki to guide you if you are having a play.
Feel free to get in touch via Twitter @acleon with any questions or suggestions.