Archive for April, 2009

Simple Templating

I’ve seen a lot of code like this in the wild …

$a = <<<EOD
    <div>
    my name is $name
    blah blah blah....
    </div>
EOD;
call_api($a);

If this is the way you typically generate html for a page, I highly suggest you pull your head out of the sand and take a look around. Mahmud ahsan’s post outlines a basic example of output buffering and file inclusion …

ob_start();
include_once "html_markup.php";
$variable  = ob_get_contents();
ob_clean();
call_api($variable);

… and I’d like to take it a step further.

This sort of partial rendering is extremely common in any web application. A simple Template class with a static render method (a technique I learned from Sarfaraz Rydhan) is the quickest way to wrap this sort of functionality. Here’s what the class might look like :

class Template {
 
    static function render($tpl_name, $d = array())  {
        $tpl_dir = 'tpl/';
        $file_ext = '.tpl.php';
 
        $file = $tpl_dir . $tpl_name . $file_ext;
 
        if(file_exists($file)) {
            ob_start();
            include($file);
            $html = ob_get_contents();
            ob_clean();
        } else {
            $html = "Template ". $file ." Not Found."
        }
        return $html;
    }
 
}

Your template might look like this

<?php // [docroot]/tpl/user/greeting.tpl.php
    $name = $d['name'];
    $userid = $d['id'];
?>
<div class="user">Welcome back, <a href="/users/<?=$userid?>"><?=$name?></a></div>

To use this, you might say

echo Template::render('user/greeting', $user);

or

echo Template::render('user/greeting', array(
    'name' => $user_name,
    'id' => $user_id,
));

This would render the file tpl/user/greeting.tpl.php with an accessible mixed var $d which might represent a User model instance or an associative array (of key value pairs).

Using this sort of simple templating can encourage more thoughtful template file organization and a more granular template library.

Aptos post office sesh

File this under things I miss doing