Page 1 of 1

pipe include statement

Posted: Wed Aug 25, 2004 8:24 pm
by phishncode
I would like to do something like this

This is for the templating system

the file file.php needs to be parsed with php and not output to the screen
any sugestions

$main = include("file.php");

$sidebar = $thecart2->displayside();
$template = loadtemplate("main_template.html");
$search = array("#Main#","#Side Bar#");
$replace = array($main,$sidebar);


$output = str_replace($search,$replace,$template);

echo $output;

Posted: Wed Aug 25, 2004 8:37 pm
by markl999

Code: Select all

ob_start();
include 'file.php';
$file = ob_get_contents();
ob_end_clean();
//$file now contains the output of the include

Posted: Wed Aug 25, 2004 8:44 pm
by John Cartwright
here is a templating class that I recently coded with a little help from feyd :P

functions.php

Code: Select all

<?php
	class templating
	{
		function parse($file)
		{				
			$file_contents = file_get_contents("template/".$file.".tpl");
		
				
				if (!empty($this->vars))
				{				
					$add = ""; 
					$pattern = '#\{(';
						
					foreach($this->vars as $k => $v)
					{
						$add .= (!empty($add) ? '|' : '') . preg_quote($k,'#');				
					}
	
					$pattern .= $add . ')\}#';
				
					while(preg_match($pattern, $file_contents, $match))
					{
						$file_contents = str_replace($match[0], $this->vars[$match[1]], $file_contents);
					}
				}
				
				echo $file_contents;
			}	
		
				
		function svar($var,$condition)
		{
			$this->vars[$var] = $condition;
		}
}		
?>
anypage.php

Code: Select all

<?php

include('functions.php');

$template = new templating();

$template->svar('var_name','condition');
$template->svar('var_name2','condition2');
$template->parse('whatever_your_template_file_is');


?>
Now let me break it down. Firstly lets look at parse(). It will loop through the array adding its values of the varaibles to the regular expression which will then be searched for on the specified file. Pretty simple huh?

now lets look at how we set the vars, very basic. At the very least, the function is the same as saying $varname = 'condition' but we need it to be a variable insiden the class so thats why I used a function.

Now let me explain the template file. This parse() function will look for your var name you sent to the function inside the file itself. So if you have set the svar("var_name","condition 333"); it will replace all the instances of {var_name} on the template file with "condition 333"
Note: Your template files, as of now need the extension .tpl


Hope this helps