0

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.

  1. The function loads the template file,
  2. finds all the template variables (eg. {_variable_}).
  3. if the variable was passed to the function ($value array) it will be replaced in the template
  4. 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);
}

Edited by Setvir: n/a

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by Setvir
0

I want to know if I am on the right track.

Hi,
From the code snippet you have sent it appears you are on the right track but just keep in mind that regex otherwise known as the preg_ functions take up a lot of cpu. So in that code snippet the only suggestion I would make is to replace the last preg_replace with a loop ("for loop" probably) that finds the entries and replaces the entries by appending to a new string as it comes across each character. But other than that great job. :)

0

Thanks cwarn23,
Will implement the change you suggested.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.