Simple PHP Templating System

As part of a new project I've just begun working on, I've started employing HTML templates. One of the main uses of HTML templates is to allow for easier debugging and management in the long run. It keeps dynamic code off the actual static part of the page and placeholders are replaced by dynamic values on-the-fly by the templating engine.

Now, I didn't want a full templating system… that was a little overkill for the little project I had in mind. I needed something that could be done in a couple of lines for use with the Raspberry Pi I've just ordered.

So, without any further ado… here is my simple templating function: processTemplate

The Code

<?php
function processTemplate($templateName,$replacementPair = array()){
    $template = file_get_contents("tpl/".$templateName.".tpl");
 
    //Perform replace/matching
    $replacements = array();
    $matches = array();
 
    foreach($replacementPair as $smatches=>$sreplacements){
        $replacements[] = $sreplacements;
        $matches[] = '{$'.$smatches.'}';
    }
    $template = str_replace($matches, $replacements, $template);
    return $template;
}
?>

Usage

Now for the all important usage:

Example template page (located at tpl/example.tpl):

<!DOCTYPE>
<html>
    <head>
        <title>{$title}</title>
        <style>
            body{
                font-family: sans-serif;
                font-size: {$fontsize};
            }
        </style>
    </head>
    <body>
        {$content}
    </body>
</html>

To dynamically fill the contents in a PHP script, you would use the following code:

<?php
$templatingData = 
    array(
        "title"=>"Awesome Page Title",
        "fontsize"=>"20px",
        "content"=>"Lorem ipsum..."
    );
echo processTemplate("example",$templatingData);
?>

and the script will produce:

<!DOCTYPE>
<html>
    <head>
        <title>Awesome Page Title</title>
        <style>
            body{
                font-family: sans-serif;
                font-size: 20px;
            }
        </style>
    </head>
    <body>
        Lorem ipsum...
    </body>
</html>

comments powered by Disqus

Old Comments

Add a New Comment
or Sign in as Wikidot user
(will not be published)
- +

Add a New Comment

Unless otherwise stated, all of the site's contents (including articles, blog post and code snippets) is:
Copyright © Kenneth Tsang 2014