Posted on Mon Dec 28 2015
I wrote an article nearly a year ago about building a front-end WordPress theme using Backbone. Since then, I’ve done a lot more research and experimenting and have come up with a pretty solid way of developing “single-page-esque” WordPress themes with Backbone (or React/Flux, Angular, Ember or any other front-end framework).
You can use one single Twig template for both the server-side and the client-side rendering. This doesn’t eliminate the different server-side/client-side logic you still have to have to populate the templates with data, but it makes things a lot easier.
Without going terribly in-depth in this article (I have an example for that), the basic jist is that instead of writing WordPress loops in your PHP templates, you utilize Timber for that. A single.php template that was previously littered with logic and templating turns into a very simple file that looks something like this:
<?php get_header(); ?> <?php $data = Timber::get_context(); $data['post'] = new TimberPost(); Timber::render('templates/article.twig', $data); ?> <?php get_footer(); ?>
Timber does a lot of the heavy lifting of acquiring data for you, which is a huge plus.
I might do some more research on the REST API in the future and see if I can’t just use it in PHP, which would allow you to use the same data structure both on the server and the client side.
So far I’ve developed two sites that use the method described in this article: my blog (you’re on it!) and our culture blog at Flywheel. Both use Backbone (just plain Backbone, although the next site I build like this will probably utilize Marionette), Timber, twig.js, Gulp and Browserify.
My blog is open sourced on GitHub, so the entire theme is open for you to take a look at it. If you wish to install it locally to play around with, the only requisite (besides Node to run Gulp) is the Timber plugin.
With the completion of these two projects and the fact that they’re live and pulling in decent amounts of traffic, I’m pretty excited to develop this idea of WordPress client-side/server-side shared templating even further. Look forward for more detailed technical posts on the matter and maybe even an online course!
© 2021 Trevan Hetzel | Built with WordPress & React on Flywheel