...

View Full Version : Templates and PHP



Pompiuses
11-08-2003, 02:42 PM
I'm about start developing a new site using templates. I have no experience using templates so after searching the forum and reading about it I think i got the general idea. I made this simple example to illustrate how I think using templates might look like:

index.php

<?php

class Collect_Data
{

var $title;
var $content;

function Collect_Data()
{
$this->title = 'Template Test';
$this->content = 'Here is content';
$this->Print_Template();
}

function Print_Template()
{include('index.tpl');}

function Print_Title()
{echo $this->title;}

function Print_Content()
{echo $this->content;}

}

new Collect_Data();

?>

index.tpl

<html>
<head>
<title><?php $this->Print_Title(); ?></title>
</head>
<body>
<h1><?php $this->Print_Content(); ?></h1>
</body>
</html>

This would allow me to change the appearance of the site without changing my php code. Now I wonder if I've gotten this right!? Is this how templates should be used?

Any thoughts are appreciated :)

Spookster
11-08-2003, 02:52 PM
Not quite.

In your template file what you want to do is not have to use PHP or any other programming language except for either just HTML/CSS etc.

What you do is put markers into the page. Something like this:




<html>
<head>
<title>{pagetitle}</title>
</head>
<body>
{content}
</body>
</html>



Then when you need to use that template you use PHP to open and parse that file and replace the markers with whatever they are supposed to be replaced with and then send it to the browser.

Pompiuses
11-09-2003, 08:29 PM
Ok I've come up with this. What you think about it? Any drawbacks with it??

index.php

<?php
//This function fills the template with data
function getTemplate($tpl_name, $replaces)
{
$tpl = @implode('', @file('templates/'.$tpl_name));

foreach($replaces as $search => $replace)
{
$tpl = str_replace('((('.$search.')))', $replace, $tpl);
}

return $tpl;
}

//Initializing body template
$body_content = array();
$body_content['headline_body'] = 'My template engine';
$body_content['content_body'] = 'Works like a charm';
$body = getTemplate('body.tpl', $body_content);


//Initializing main template
$index_content = array();
$index_content['title_index'] = 'My template engine';
$index_content['body_index'] = $body;
$index = getTemplate('index.tpl', $index_content);

echo $index;

?>

index.tpl

<html>
<head>
<title>(((title_index)))</title>
</head>
<body>
(((body_index)))
</body>
</html>


body.tpl

<h1>(((headline_body)))</h1>
<br><br>(((content_body)))<br><br>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum