Hi guys and gals!
I want to know if I am on the right track.
I am working on a simple in-house cms. Here is a templating function I wrote to test an idea. It does work.
- The function loads the template file,
- finds all the template variables (eg. {_variable_}).
- if the variable was passed to the function ($value array) it will be replaced in the template
- Else it will replace it with output from a php file with the same name as the variable
Your feedback and ideas welcome!
function humpot_templater($vars=array(), $template="template.html", $php_blocks_folder=""){
ob_start();
if(!@include($template)) {
//include the template file
print("Template not found at: ./".$template);
}
$html=ob_get_clean();
preg_match_all('/\{_(.*?)_\}/', $html, $matches, PREG_PATTERN_ORDER);
if (isset($matches[1])){
foreach($matches[1] as $variable){
if(isset($vars[$variable]) && is_array($vars)){
//get the variable already set in $vars arry
$templ_replacements[$variable]=$vars[$variable];
} else {
//include the php code block coresponing to the template variable
//block must output a string (can be script, css or html)
ob_start();
if(!@include($php_blocks_folder.$variable.'.php')){
print ("Error: Template variable '".$variable."' was not set or './".$php_blocks_folder.$variable.".php' does not exist.");
}
$templ_replacements[$variable]=ob_get_clean();//if the block exists then this now countains its output
}
}
}
return preg_replace("/{_(.*?)_}/ime", "\$templ_replacements['$1']",$html);
}