The Problem
I’m working on a project and have to generate the same template on 4 different pages. I was also using javascript to create the same template on the fly. Needless to say this wasn’t the most efficient way of doing things because if I needed to change 1 aspect of the template, I needed to edit 4 different files.
I tried to write a little function, inspired by CakePHP, that would take an array of information, open up a template, replace any text and then return the new content.
This means I can use 1 template over and over again throughout the app and not have to worry if I made changes to all the files.
The Function
//grab an element to use as a template
function show_element($name, $array, $path = null){
//add .php do the end of the name, by default it looks for a relative path
//unless $path is avaiable, then it'll check the path
$name = $path . $name.'.php';
//open up the file
$content = fread($fp = fopen($name, 'r'), filesize($name)); fclose($fp);
//loop through the file and replace any content that's needed
//inside the template $array['name'] is {NAME}
foreach($array as $a => $b){
//just in case, uppercase the array name
$el = '{' . strtoupper($a) . '}';
//replace the content
$content = preg_replace("/$el/", $b, $content);
}
//return the content, woop woop
return $content;
}
Simple Usage
element.php
We have our element file called element.php. Inside we have wrote out a simple line of text. We want the product name as well as the price to change depending on the information that we’ve passed through our function. Curly braces are our friends, so we wrap our variables in them. {NAME} will become the product name and {PRICE} the price.
NOTE: All the variable names in the template file must be uppercase and wrapped in curly braces or else they will not be replaced.
<p>By this product <strong>({NAME})</strong> for the awesome price of ${PRICE}</p>
index.php
Our second file we have our $products array with 4 simple products. We are looping though each product and using our show_element() function to replace the variables in our template file with our product information.
$products = array(
array('name' => 'awesome shoes', 'price' => '99.99'),
array('name' => 'awesome pants', 'price' => '9.99'),
array('name' => 'awesome hats', 'price' => '19.99'),
array('name' => 'awesome woop woops', 'price' => '3459.99')
);
foreach($products as $product){
echo show_element('element', $product);
}
Now we have a super simple, but very helpful template system that’s easy to use and install in any project!
