3 // Copyright (c) 2011 Blue Static
5 // This program is free software: you can redistribute it and/or modify it
6 // under the terms of the GNU General Public License as published by the Free
7 // Software Foundation, either version 3 of the License, or any later version.
9 // This program is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 // You should have received a copy of the GNU General Public License along with
15 // this program. If not, see <http://www.gnu.org/licenses/>.
17 namespace hoplite
\views
;
19 use \hoplite
\base\Profiling
;
21 require_once HOPLITE_ROOT
. '/base/filter.php';
22 require_once HOPLITE_ROOT
. '/base/profiling.php';
25 Renders a template with additional vars.
26 @param string The template name to render
27 @param array Variables with which to render.
29 function Inject($name, $vars = array())
31 echo TemplateLoader
::Fetch($name)->Render($vars);
34 /*! @brief Creates a URL via RootController::MakeURL().
35 This requires the root controller be set in the $GLOBALS as
36 hoplite\http\RootController.
39 function MakeURL($path)
41 return $GLOBALS['hoplite\http\RootController']->MakeURL($path, FALSE
);
45 Template parses a a text file (typically HTML) by expanding a small macro
46 language into "compiled" PHP.
48 The opening and close tags are user-customizable but the default is {% %}.
50 The open and close tags are translated to '<?php' and '?>', respectively.
52 Modifiers may be placed after the open and close tags as shorthand for
56 Evaluates a non-printing expression, treating it as pure PHP. This can
57 be used to evaluate conditions:
58 {% if (!$user->user_id): %}<p>Hello, Guest!</p>{% endif %}
61 Prints the value and automatically HTML-escapes it.
64 Prints $value by coerceing it to an integer. Other coercion types
65 are str (the default if no pipe symbol, above), int, float, and
70 /*! @var string The macro opening delimiter. */
71 static protected $open_tag = '{%';
73 /*! @var string The macro closing delimiter. */
74 static protected $close_tag = '%}';
76 /*! @var string The name of the template. */
77 protected $template_name = '';
79 /*! @var string The compiled template. */
80 protected $data = NULL
;
82 /*! @var array Variables to provide to the template. */
83 protected $vars = array();
86 Creates a new Template with a given name.
89 private function __construct($name)
91 $this->template_name
= $name;
94 static public function NewWithData($name, $data)
96 $template = new Template($name);
97 $template->data
= $template->_ProcessTemplate($data);
101 static public function NewWithCompiledData($name, $data)
103 $template = new Template($name);
104 $template->data
= $data;
109 Sets the open and closing delimiters. The caller is responsible for choosing
110 values that will not cause the parser to barf.
112 static public function set_open_close_tags($open_tag, $close_tag)
114 self
::$open_tag = $open_tag;
115 self
::$close_tag = $close_tag;
118 /*! Gets the name of the template. */
119 public function template_name() { return $this->template_name
; }
121 /*! Gets the parsed data of the template. */
122 public function template() { return $this->data
; }
124 /*! Overload property accessors to set view variables. */
125 public function __get($key)
127 return $this->vars
[$key];
129 public function __set($key, $value)
131 $this->vars
[$key] = $value;
134 /*! This includes the template and renders it out. */
135 public function Render($vars = array())
137 $_template = $this->data
;
138 $_vars = array_merge($this->vars
, $vars);
139 $render = function () use ($_template, $_vars) {
141 eval('?>' . $_template . '<' . '?');
146 $error = error_reporting();
147 error_reporting($error & ~E_NOTICE
);
151 error_reporting($error);
153 if (Profiling
::IsProfilingEnabled())
154 TemplateLoader
::GetInstance()->MarkTemplateRendered($this->name
);
156 $data = ob_get_contents();
161 /*! @brief Does any pre-processing on the template.
162 This performs the macro expansion. The language is very simple and is merely
163 shorthand for the PHP tags.
165 @param string Raw template data
166 @return string Executable PHP
168 protected function _ProcessTemplate($data)
170 // The parsed output as compiled PHP.
173 // If processing a macro, this contains the contents of the macro while
174 // it is being extracted from the template.
176 $length = strlen($data);
177 $i = 0; // The current position of the iterator.
178 $looking_for_end = FALSE
; // Whehter or not an end tag is expected.
179 $line_number = 1; // The current line number.
180 $i_last_line = 0; // The value of |i| at the previous new line, used for column numbering.
182 $open_tag_len = strlen(self
::$open_tag);
183 $close_tag_len = strlen(self
::$close_tag);
185 while ($i < $length) {
186 // See how far the current position is from the end of the string.
187 $delta = $length - $i;
189 // When a new line is reached, update the counters.
190 if ($data[$i] == "\n") {
195 // Check for the open tag.
196 if ($delta >= $open_tag_len &&
197 substr($data, $i, $open_tag_len) == self
::$open_tag) {
198 // If an expansion has already been opened, then it's an error to nest.
199 if ($looking_for_end) {
200 $column = $i - $i_last_line;
201 throw new TemplateException("Unexpected start of expansion at line $line_number:$column");
204 $looking_for_end = TRUE
;
209 // Check for the close tag.
210 else if ($delta >= $close_tag_len &&
211 substr($data, $i, $close_tag_len) == self
::$close_tag) {
212 // If an end tag was encountered without an open tag, that's an error.
213 if (!$looking_for_end) {
214 $column = $i - $i_last_line;
215 throw new TemplateException("Unexpected end of expansion at line $line_number:$column");
218 $expanded_macro = $this->_ProcessMacro($macro);
219 $processed .= "<?php $expanded_macro ?>";
220 $looking_for_end = FALSE
;
221 $i +
= $close_tag_len;
225 // All other characters go into a storage bin. If currently in a macro,
226 // save off the data separately for parsing.
227 if ($looking_for_end)
230 $processed .= $data[$i];
238 Takes the contents of a macro, i.e. the string between the open and close
239 tags, and transforms it into a PHP statement.
241 protected function _ProcessMacro($macro)
243 if (strlen($macro) < 1)
246 // If the macro has a modifier character, as described in the class comment,
247 // futher thransform the statement.
249 case '=': return $this->_ProcessInterpolation(substr($macro, 1));
250 default: return $macro;
255 Creates a printing expression for a value, optionally coercing and escaping
256 it to a specific type.
258 protected function _ProcessInterpolation($macro)
260 // The pipe operator specifies how to sanitize the output.
261 $formatter_pos = strrpos($macro, '|');
263 // No specifier defaults to escaped string.
264 if ($formatter_pos === FALSE
)
265 return 'echo hoplite\\base\\filter\\String(' . $macro . ')';
267 // Otherwise, apply the right filter.
268 $formatter = trim(substr($macro, $formatter_pos +
1));
270 switch (strtolower($formatter)) {
271 case 'int': $function = 'Int'; break;
272 case 'float': $function = 'Float'; break;
273 case 'str': $function = 'String'; break;
274 case 'raw': $function = 'RawString'; break;
276 throw new TemplateException('Invalid macro formatter "' . $formatter . '"');
279 // Now get the expression and return a PHP statement.
280 $expression = trim(substr($macro, 0, $formatter_pos));
281 return 'echo hoplite\\base\\filter\\' . $function . '(' . $expression . ')';
285 class TemplateException
extends \Exception
{}