This repository was archived by the owner on Oct 23, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.php
90 lines (75 loc) · 1.86 KB
/
template.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
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
<?php
/**
* Contains the Template class
*
*/
namespace SmallPHPMVC;
/**
* A simple template engine.
*
* The set function sets variable used by the template.
* The remove function removes previously set variables.
* The show function includes the template code into its own scope and and displays the template.
*
* @author David Lancea
*/
class Template {
protected $_name = 'index';
protected $_layout = null;
/**
*
* @param string $name Name of the template to load
*/
public function __construct( $name = null ){
if( $name ){
$this->_name = $name;
}
$this->_layout = new Layout();
}
/**
* Sets variable used by the template.
*
* @param string $varname
* @param mixed $value
* @param booliean $overwrite Allow overwrite of previously set variable
*/
function set($varname, $value, $overwrite=false) {
if (isset($this->$varname) == true AND $overwrite == false) {
throw new \Exception ('Unable to set var `' . $varname . '`. Already set, and overwrite not allowed.');
}
$this->$varname = $value;
}
/**
* Removes a previously set variable
*
* @param string $varname
*/
function remove($varname) {
unset($this->$varname);
}
function getLayout(){
return $this->_layout;
}
function setLayout( Layout $layout ){
$this->_layout = $layout;
}
/**
* Includes the template code into its own scope and and displays the template.
*/
function show() {
$path = VIEW_PATH . DIRSEP . $this->_name . '.html.php';
if (file_exists($path) == false) {
throw new \Exception ('Template `' . $this->_name . '` does not exist.' );
}
// If there's no layout, simply include the template file and return.
if(!$this->_layout){
include ($path);
return;
}
ob_start();
include ($path);
$template_output = ob_get_clean();
$this->_layout->set('content', $template_output);
$this->_layout->show();
}
}