Kostenloser Codeschnippsel: Simples Template System

S!equenz
Ich hatte den Codeschnippsel selbst hier von your-wbb.de, kann den Thread allerdings nicht mehr finden.

Jedenfalls ist der folgende Code ein simples "Template System" das bei mir als Basis für diverse Scripte dient und vllt. der ein oder andere ebenfalls nutzen möchte.

php:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:

<?php

// Template System Function(s)
function gettemplate($template,$fileformat="tpl")
{
return str_replace("\"","\\\"",implode("",file("path/to/templates/folder/".$template.".".$fileformat)));
}
# How to use: eval ("\$sub_template .= \"".gettemplate("sub_template")."\";");
## You can change $sub_template into your desired variable name, independent from the template (file) name
### You can call variables (defined before loading the tpl) in the tpl file
#### You need to replace "path/to/templates/folder/" with the actual path to YOUR templates folder
##### The $fileformat="tpl" means that your template files need to use the .tpl file extension. 
##### Example: template_name.tpl You can change it of course.

function display($template) {
echo $template;
}
# How to use: eval ("display(\"".gettemplate("main_template")."\");");
## You can call variables (defined before loading the tpl) in the tpl file

//How to use
eval ("\$sub_template .= \"".gettemplate("sub_template")."\";");
eval ("display(\"".gettemplate("main_template")."\");");
# You can load "sub templates" in a "main template" by simply placing the variable name of the 
# "sub template" into the main template file.

?>
Jaja "eval is evil" davon habe ich auch schon gehört. Ich seh es allerdings anders. smile
S!equenz
Ich hab den Code oben zwar recht gut kommentiert, denke mal aber anhand folgendem Beispiel ist es noch einfacher zu verstehen wie das ganze funktioniert:

index.php

php:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

<?php

function gettemplate($template,$fileformat="tpl")
{
return str_replace("\"","\\\"",implode("",file("path/to/templates/folder/".$template.".".$fileformat)));
}

function display($template) {
echo $template;
}

$timestamp time();
$time date("H:i"$timestamp);
$example_variable "Some other variable containing an ordinary string";

eval ("\$sub_template .= \"".gettemplate("sub_template")."\";");
eval ("display(\"".gettemplate("main_template")."\");");

?>


sub_template.tpl

code:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
Content before
<br>
<marquee>
Hey, man! It's currently $time, man!
</marquee>
<br>
$example_variable
<br>
Content after


main_template.tpl

code:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
<html>
<head>
<title>Index</title>
</head>
<body>

$sub_template

</body>
</html>