Jump to content

Could someone look over my code please?


jj20051

Recommended Posts

I've been trying to create a basic template system that will replace the data in {} correctly. The template system is supposed to auto load any pages called into the file by things like {load header} and replace the variables in there, but it doesn't... Here is my code and an example page:

<?php
$site_title = "This Title Works Just Fine";
$template_index = 'index.php';
$template_header = 'header.php';
$template = './templates/default';
class templateParser {
var $output;

function templateParser($templateFile='default_template.htm'){
(file_exists($templateFile))?$this->output=file_get_contents($templateFile):die('Error:Template file '.$templateFile.' not found');
}

function parseTemplate($tags=array()){
if(count($tags)>0){
foreach($tags as $tag=>$data){
$data=(file_exists($data))?$this->parseFile($data):$data;
$this->output=str_replace
('{'.$tag.'}',$data,$this->output);
} }
else {
die('[Error: 023 - Template Variables Invalid or Missing]');
} }

function parseFile($file){
ob_start();
include($file);
$content=ob_get_contents();
ob_end_clean();
return $content;
}

function display(){
return $this->output;
} }

// Tags
$tags = array(
'site_title'=>$site_title,
        'load_header'=>$template.$template_header
); 

// instantiate a new template Parser object
$tp=&new templateParser($template.$template_index);

// parse template file
$tp->parseTemplate($tags);

// display generated page
echo $tp->display();
?>

 

Example Page Code:

 

// index.php
{load_header}
<div id="container">
<div id="left">
<div id="lefttitle">{site_title}</div><br><p>
</p>
</div> 

// header.php
<title>{site_title}</title>
</head>
<body>
<div id="headertitle">{site_title}</div>

 

So the page loads fine... The problem is that the site title remains {site_title} and so does the "headertitle". The problem with this is that both are defined in the tags array and should be replaced by the variable $site_title. The "replacement" works just fine in index.php (replacing {site_title} like it should), but will not replace it in header.php which is why there is a problem. Can anyone help me fix this?

 

exampleimage.png

Link to comment
https://forums.phpfreaks.com/topic/218110-could-someone-look-over-my-code-please/
Share on other sites

Alright, I apologize... I assumed that because it drifted down past 20 that no one had really looked at it... I will wait until after its on the second page from now on.

 

Maybe I'll flip some code around to see if it helps.

 

Update: Apparently if I run it through the function parseTemplate twice (once before and after loading the pages that fixes the problem.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.