-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.class.php
More file actions
95 lines (84 loc) · 2.99 KB
/
template.class.php
File metadata and controls
95 lines (84 loc) · 2.99 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
/**
* Simple template engine class (use [@tag] tags in your templates).
*
* @link http://www.broculos.net/ Broculos.net Programming Tutorials
* @author Nuno Freitas <nunofreitas@gmail.com>
* @version 1.0
*/
class Template {
/**
* The filename of the template to load.
*
* @access protected
* @var string
*/
protected $file;
/**
* An array of values for replacing each tag on the template (the key for each value is its corresponding tag).
*
* @access protected
* @var array
*/
protected $values = array();
/**
* Creates a new Template object and sets its associated file.
*
* @param string $file the filename of the template to load
*/
public function __construct($file) {
$this->file = $file;
}
/**
* Sets a value for replacing a specific tag.
*
* @param string $key the name of the tag to replace
* @param string $value the value to replace
*/
public function set($key, $value) {
$this->values[$key] = $value;
}
/**
* Outputs the content of the template, replacing the keys for its respective values.
*
* @return string
*/
public function output() {
/**
* Tries to verify if the file exists.
* If it doesn't return with an error message.
* Anything else loads the file contents and loops through the array replacing every key for its value.
*/
if (!file_exists($this->file)) {
return "Error loading template file ($this->file).<br />";
}
$output = file_get_contents($this->file);
foreach ($this->values as $key => $value) {
$tagToReplace = "[@$key]";
$output = str_replace($tagToReplace, $value, $output);
}
return $output;
}
/**
* Merges the content from an array of templates and separates it with $separator.
*
* @param array $templates an array of Template objects to merge
* @param string $separator the string that is used between each Template object
* @return string
*/
static public function merge($templates, $separator = "\n") {
/**
* Loops through the array concatenating the outputs from each template, separating with $separator.
* If a type different from Template is found we provide an error message.
*/
$output = "";
foreach ($templates as $template) {
$content = (get_class($template) !== "Template")
? "Error, incorrect type - expected Template."
: $template->output();
$output .= $content . $separator;
}
return $output;
}
}
?>