I'm having a hard time creating an algorithm to implement using loops in a simple template class.
I have my class below, it gets an HTML file, looks for specific strings that are in this file from values of an array and replaces it with > string from a variable, finally returns the changed HTML code as print
on the screen. It works fine, except when I need loops .
Note: I want to separate all my PHP code from PHP
Template Class
<?php
class Template {
private $file;
private $vars;
public function __construct($file = "") {
$this->vars = array();
$this->load($file);
}
public function load($file){
if(file_exists($file)){
if(file_get_contents($file)){
$this->file = file_get_contents($file);
return true;
}
else{
return die("Error: Could not load file \"{$file}.\"");
}
}
else{
return die("Error: file \"{$file}\" not found.");
}
}
public function show(){
if($this->file){
$output = $this->file;
foreach ($this->vars as $varName => $varValue) {
$tagToReplace = "{{$varName}}";
$output = str_replace($tagToReplace, $varValue, $output);
}
printf($output);
}
else {
return die("Error: template file is empty.");
}
}
public function setVar($varName, $varValue){
if(!empty($varName) && !empty($varValue)){
$this->vars[$varName] = $varValue;
}
}
}
?>
Example use index.php
<?php
$template = new Template("index.template.html");
$template->setVar("page_title", "Página Inicial");
$template->setVar("msg", "Bem vindo!");
$template->show();
?>
File index.template.html
<!DOCTYPE html>
<html>
<head>
<title>{page_title}</title>
</head>
<body>
<h1>{msg}</h1>
</body>
</html>