WordPress is great but sometimes there are aspects of the design that really irritate me. One of these annoyances is the extremely common but widely accepted practice of putting HTML markup inside the PHP methods/functions of the plugin itself.
Of course programmers can hardly be blamed for this as it is an extremely common, and widely accepted, practice but a lesson or two learned from Zend Framework (for example) can come in handy. The aim of the exercise is to maintain a degree of separation between the model and the view in the MVC style. MVC isn’t perfect but it does work, generally, and contains a great deal that encourages for good programming practice.
There are several ways of implementing templating for WordPress plugins and I’ll present one here. It’s pretty simple to use but easy to build on. We’re not tinkering with deep WordPress here but aiming to point at good practice
Here’s a simple example of a function that outputs some text.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php function showPanel($title, $somedata) { // Here we break out into HTML ?> <div class="panel"> <h3><?php echo $title ?></h3> <div class="panel-body"> <?php echo $somedata ?> </div> </div> <?php // and back again } ?> |
Essentially what happens is that the entire function, when called, will print the HTML content immediately.
Here is another way of doing it.
In this example the template is maintained separately and the showPanel() function returns a string built whilst buffering the output from the included file.
1 2 3 4 5 6 |
<div class="panel"> <h3><?php echo $title ?></h3> <div class="panel-body"> <?php echo $somedata ?> </div> </div> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php function showPanel($title, $somedata) { $content = null; ob_start(); include 'panel-template.phtml'; $content = ob_get_contents(); ob_end_clean(); return $content; } ?> |
That’s all there is to it really. I like this approach because of the clarity it brings.