Thursday, December 20, 2007

On Using Templates

I am starting a project for SEOWeboworks in downtown Plymouth as my first real work experience. I am working a test project they want me to work on before I start doing actual work. The project uses a templating structure that will auto-generate similar web pages for their Ticketing website replacing the artist's name on each page. I have tried using php classes with the str_replace() function but that failed. It recognizes the variable I want to replace and the variable I want to replace it with but somehow replaces it with blank space. The following was my attempt:

class template {
//this template will replace {artist} with the artist's name
var $template;

//This method will import the contents of the template file into the template property of the class
function load_tpl($filename) {
$this->template = file_get_contents($filename);
}

//This method will replace the tag_names found in the template with the given replacement data
function parse_tags($tag_name, $replacememt) {
$this->template = str_replace($tag_name, $replacement, $this->template);
echo "replace ".$tag_name." with ".$replacememt;
}

//This method will output the contents of the template file to the browser
function output() {
echo $this->template;
}
}
?>

and that failed

So now I have decided to try XTemplates and we'll see how that goes.

Update:
So the new XTemplate setup is working props to Peter for the tips on how to use it. Here it is:


include_once('xtemplate.class.php');

//load new xtemplate
$xtpl = new XTemplate('artist_page.xtpl');

//this template will replace {artist} with the artist's name
$artist=$_POST["artist"];
$xtpl->assign('artist', $artist);

//output new page
$xtpl->parse('main');
$xtpl->out('main');
?>

definitely much simpler than the previous code block.

Now on to add more functionality!

1 comment:

Efeion said...

I am glad you got that working, templates are weird at first, but once you get used to them you can't live with out them.