3 # Copyright (C) 2008,2009 Joshua Grams <josh@qualdan.com>
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 # This is a simple template-handling system. You pass it a big data
20 # structure with key/value pairs, and a template string to fill out.
22 # Within a template, it recognizes tags delimited by tildes (~). When
23 # the template is filled out, the tags will be replaced with the
24 # corresponding data. Tags ending with '?' and '.' mark the start and
25 # end of a sub-template (for optional or repeated text), and can be
26 # wrapped in HTML comments (which will be removed along with the tags
27 # when the template is filled out).
29 require_once('code/wfpl/encode.php');
30 require_once('code/wfpl/file.php');
31 require_once('code/wfpl/misc.php');
37 function template($data, $template) {
38 return fill_template($data, parse_template($template));
41 function template_file($data, $filename) {
42 return fill_template($data, parse_template_file($filename));
45 function parse_template_file($filename) {
46 return parse_template(file_get_contents($filename));
49 # First we take the template string and break it up into an array
50 # of strings and sub-arrays. The first item in a sub-array is the name
51 # of the value or sub-template.
53 function parse_template($string) {
54 # Don't mess with the $stack/$tem assignments! Since
55 # PHP references point to the variable, not the data,
56 # it really does have to be written exactly like this.
57 $stack[] = array('name' => 'root', 'pieces' => array());
59 # note: for some reason this captures '<!--' but not '-->'.
60 $matches = preg_split("/(<!--)?(~[^~]*~)(?(1)-->)/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
61 foreach($matches as $match) {
62 if(substr($match,0,1) == '~') {
63 $args = explode(' ', substr($match,1,-1));
65 if(count($args) == 1 and $args[0] == '}') $name = '';
66 else $name = array_shift($args);
68 if(last($args) == '{') { # open block
70 $stack[] = array('name' => $name, 'pieces' => array(), 'args' => $args);
71 $tem['pieces'][] = &last($stack);
73 } elseif(last($args) == '}') { # close block
75 $cur = $stack[count($stack)-1]['name'];
76 if($name && $name != $cur) {
77 die("Invalid template: tried to close '$name', but '$cur' is current.");
79 array_pop($stack); $tem = &last($stack);
81 $tem['pieces'][] = array('name' => $name, 'args' => $args);
83 } elseif($match and $match != '<!--') { # static string
84 $tem['pieces'][] = $match;
90 # Then we do a depth-first traversal of the template tree,
91 # replacing all tags with the data values.
93 function fill_template($data, $template, $context = NULL, $keychain = NULL) {
95 foreach($template['pieces'] as $piece) {
96 if(is_string($piece)) $output .= $piece;
98 if($piece['pieces']) { # sub-template
99 $keychain[] = $piece['name'];
100 $data = tem_get($piece, $context, $keychain);
101 foreach(template_rows($data) as $key => $row) {
103 $output .= fill_template($row, $piece, $context, $keychain);
104 array_pop($keychain);
106 array_pop($keychain);
107 } else $output .= tem_get_enc($piece, $context);
114 # Replace top-level values in $main with top-level templates from $tem.
115 function merge_templates($main, $tem) {
116 $out = array('name' => $main['name'], 'pieces' => array());
118 $subs = top_sub_templates($tem);
120 foreach($main['pieces'] as $piece) {
121 if(is_array($piece) and !$piece['pieces'] and $subs[$piece['name']]) {
122 $piece = $subs[$piece['name']];
124 $out['pieces'][] = $piece;
134 # If a { tag has an argument, the corresponding tem_auto function is called.
135 # This allows it to mangle the data to automate some common cases.
137 # 'sep' (separator) sections will be shown for all but the last parent row.
142 # <!--~separator sep {~--><hr><!--~separator }"-->
146 function tem_auto_sep($piece, $context, $keychain) {
147 list($name, $index, $this_name) = array_slice($keychain, -3);
148 $array = _tem_get($name, $context);
149 if($index != count($array)-1) return true;
152 # 'once' sections will be shown once unless the corresponding data value
153 # is false. We check only for false; 0 or '' will not work.
155 function tem_auto_once($piece, $context, $keychain) {
156 $value = _tem_get(array_pop($keychain), $context);
157 if($value !== false) return true;
160 # 'evenodd' sections are given an 'evenodd' attribute whose value
161 # alternates between 'even' and 'odd'.
163 function tem_auto_evenodd($piece, $context, $keychain) {
164 $rows = _tem_get(array_pop($keychain), $context);
166 $text = array('even', 'odd');
167 foreach($rows as $key => $value) {
168 $rows[$key]['evenodd'] = $text[$even];
179 # Of course, nothing stops you from using these, but I don't know
180 # why you would want to...
183 # Convert value to array of hashes for use in sub-template expansion.
184 # This adds flexibility to how you represent your data.
185 function template_rows($value) {
186 if(is_array($value)) {
187 # numeric keys, is already array of arrays -- expand sub-template for each.
188 if(array_key_exists(0, $value)) return $value;
189 # key/value pairs -- expand sub-template once.
190 else return array($value);
192 # value -- expand sub-template once using only parent values
193 return array(array());
195 # empty value -- don't expand sub-template
200 function _tem_get($key, $context) {
202 $data = array_pop($context);
203 if(array_key_exists($key, $data)) return $data[$key];
207 function tem_get($piece, $context, $keychain)
209 if(count($piece['args'])) {
210 $func = "tem_auto_" . $piece['args'][0];
211 if(function_exists($func)) return $func($piece, $context, $keychain);
212 else die("ERROR: template auto function '$func' not found.<br>\n");
213 } else return _tem_get($piece['name'], $context);
216 # $tag is a hash with keys 'name' and 'args'.
217 function tem_get_enc($tag, $context)
220 $value = _tem_get($key, $context);
221 foreach($tag['args'] as $encoding) {
222 $func = "enc_$encoding";
223 if(function_exists($func)) $value = $func($value, $key);
224 else die("ERROR: encoder function '$func' not found.<br>\n");
229 function top_sub_templates($tem) {
231 foreach($tem['pieces'] as $piece) {
232 if(is_array($piece) and $piece['pieces']) {
233 $subs[$piece['name']] = $piece;