Use generic views with data arrays for a flexible, context-independent UI system
Last updated • October 23rd, 2019
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters