Those who are new to WordPress theming are often confused by the mixture of PHP and HTML markup in templates. It’s easy to accidentally break theme functionality when everything is placed in the same file.
For that reason, there’s a strong contingency of developers who prefer to integrate the Twig PHP templating engine with WordPress, using a starter theme or via plugins like TwigPress, Timber, or the like. Fans of Twig appreciate its concise syntax and find that it makes templates more readable.
Sprig is a new Twig-based starter theme for WordPress created by developer Zach Adams. The theme incorporates the power and flexibility of Twig templating to speed up development and make WordPress templates easier to edit.
Here’s an example of what the WordPress loop looks like in Sprig:
[php light=”true”]{% for post in posts() %}
{% include ‘content/content-excerpt.twig’ %}
{% endfor %}[/php]
For those who have never worked with a templating engine, the syntax may look rather unfamiliar, but the advantage is that it allows you to separate the necessities of getting/manipulating your data and rendering it out. Below is an example of the WordPress loop with arguments:
[php light=”true”]
{% for post in posts({
‘post_type’:’post’,
‘posts_per_page’:4
}) %}
{% include ‘content/content-excerpt.twig’ %}
{% endfor %}[/php]
Sprig Features
Sprig utilizes Bower for frontend package management. It comes pre-loaded with either Bootstrap or Foundation to get started. Sprig uses Gulp to automate tasks such as compiling, concatenating, and minifying CSS and Javascript.
The theme was developed using the best parts of Underscores, Roots, and TwigPress, which bring in a number of additional functions and scripts useful for theme development.
Does Twig Introduce a New Layer of Abstraction?
The main argument some theme developers have against using a templating engine like Twig is that it introduces a new layer of abstraction, as well as another thing to learn on top of WordPress’ usual way of structuring template files. Some believe that the separation of concerns prohibits a theme developer from gaining a true understanding of how WordPress works.
Adams clearly states that the purpose of Sprig is to help theme developers spend less time wading through template markup code and instead focus their efforts on creating beautiful themes. The Twig templating engine may not be your cup of tea, but many developers find that it helps them produce cleaner template code that is easier to reuse.
If Sprig helps get you from here to there faster, then it might be worth incorporating into your theme development workflow. Check out the full documentation on GitHub. The project is still under active development and Adams recommends you test Sprig heavily before using it in production.
Think of “twig” as a case not of “in addition”, but a case of “instead of”. It’s easier to use instead of the old way, then replace the old way with “twig”.