1
I’m having trouble creating an algorithm to implement the use of loops in a class of template simple.
I have my class below, it gets an HTML file, looks for strings specifies that are in this file from values of a array and replaced by another string obtained from a variable, finally returns the changed HTML code in the form of print
on the screen. Works very well, except when I need to use loops.
Note: I want to separate all my HTML 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 of use index php.
<?php
$template = new Template("index.template.html");
$template->setVar("page_title", "Página Inicial");
$template->setVar("msg", "Bem vindo!");
$template->show();
?>
Filing cabinet index.template.html
<!DOCTYPE html>
<html>
<head>
<title>{page_title}</title>
</head>
<body>
<h1>{msg}</h1>
</body>
</html>
Where do you want to use these loops? I don’t understand very well...
– Andrei Coelho
Do you want to be able to use more than one variable? For example, two
<h1>
?– Andrei Coelho
Ah ta ta.. It’s in the
foreach
the problem. =)– Andrei Coelho