3
* Flight: An extensible micro-framework.
5
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
6
* @license MIT, http://flightphp.com/license
9
namespace flight\template;
12
* The View class represents output to be displayed. It provides
13
* methods for managing view data and inserts the data into
14
* view templates upon rendering.
18
* Location of view templates.
29
protected $vars = array();
41
* @param string $path Path to templates directory
43
public function __construct($path = '.') {
48
* Gets a template variable.
50
* @param string $key Key
53
public function get($key) {
54
return isset($this->vars[$key]) ? $this->vars[$key] : null;
58
* Sets a template variable.
60
* @param mixed $key Key
61
* @param string $value Value
63
public function set($key, &$value = null) {
64
if (is_array($key) || is_object($key)) {
65
foreach ($key as $k => $v) {
70
$this->vars[$key] = $value;
75
* Checks if a template variable is set.
77
* @param string $key Key
78
* @return boolean If key exists
80
public function has($key) {
81
return isset($this->vars[$key]);
85
* Unsets a template variable. If no key is passed in, clear all variables.
87
* @param string $key Key
89
public function clear($key = null) {
91
$this->vars = array();
94
unset($this->vars[$key]);
101
* @param string $file Template file
102
* @param array $data Template data
103
* @throws \Exception If template not found
105
public function render($file, $data = null) {
106
$this->template = $this->getTemplate($file);
108
if (!file_exists($this->template)) {
109
throw new \Exception("Template file not found: {$this->template}.");
112
if (is_array($data)) {
113
$this->vars = array_merge($this->vars, $data);
116
extract($this->vars);
118
include $this->template;
122
* Gets the output of a template.
124
* @param string $file Template file
125
* @param array $data Template data
126
* @return string Output of template
128
public function fetch($file, $data = null) {
131
$this->render($file, $data);
132
$output = ob_get_clean();
138
* Checks if a template file exists.
140
* @param string $file Template file
141
* @return bool Template file exists
143
public function exists($file) {
144
return file_exists($this->getTemplate($file));
148
* Gets the full path to a template file.
150
* @param string $file Template file
151
* @return string Template file location
153
public function getTemplate($file) {
154
if ((substr($file, -4) != '.php')) {
157
if ((substr($file, 0, 1) == '/')) {
162
return $this->path.'/'.$file;
167
* Displays escaped output.
169
* @param string $str String to escape
170
* @return string Escaped string
172
public function e($str) {
173
echo htmlentities($str);