Use generic views with data arrays for a flexible, context-independent UI system

When you start digging into WordPress partials, things really open up on the theme side. Being able to reuse templates is a nice feature and can help keep your code nice and tidy but if your templates are using WordPress’ template tags, you can easily find yourself in situations where you need the markup from a partial but not the data.

To work around this, I use generic views that depend only on an array of data points. This allows me to reuse the same view in multiple places on a site without having to worry if I’m inside a post loop or rendering a specific template, etc. This really opens up flexibility in the UI and also makes it possible to move UI components between projects quite easily.

The basic use example

Once set up, rendering your views is as simple as the following:

Keeping the templates clean and ‘dumb’

The templates themselves all initialise their expected variables at the top of the file and the markup below. You’ll see there are no WordPress template tags in here which removes the context-dependency. ‘Dumb’ templates are nice and versatile.

Setting up the View class so it knows where your templates live

The View class (which I’ve provided further down) is simple to set up and it only needs to know where to look for templates.

An example of how to use the views in a WordPress template

Just so you understand the use-case, here is an example of the View class being used within a WordPress template to render a view.

Finally, the View class itself

The View class is a static class the is super simple to configure and just as easy to use as you’ve seen from the previous Gists. You are free to take, use, and modify this class however you need to.

One last thing…

If you liked this article, I'd be incredibly grateful if you tweeted about it.

Also, I don't send emails often but when I do, I try to fill them full of useful goodies. If you like code snippets & dev tips, join my mailing list. There's no catch but I'll probably want to tell you about any new plugins & tools I build.