+
+# Implementation
+# --------------
+
+
+# To track our position in the template and in the data, we use a linked
+# stack structure. Each node is a hash with a reference to the parent
+# node along with whatever other data you want to add. For each stack,
+# you simply keep a variable with a reference to the top element. Then
+# the push and pop operations are:
+
+# $top =& tem_push($top);
+# $top =& $top['parent'];
+
+function &tem_push(&$stack = NULL) {
+ static $refs = array();
+
+ # Since a PHP reference is *not* a pointer to data, but a pointer to
+ # a variable (or array slot), we *have* to first put the new node in
+ # $refs, and then reference it from $new.
+
+ $refs[] = array();
+ $new =& $refs[count($refs)-1];
+ if($stack) $new['parent'] =& $stack;
+ return $new;
+}
+
+# To fill out a template, we do a depth-first traversal of the template
+# tree, replacing all tags with the data values.
+
+# The data starts out as a nested set of key/value pairs, where the
+# values can be:
+
+ # a string to fill a value slot
+ # a hash to fill one instance of a sub-template
+ # an array of hashes to fill multiple instances of a sub-template
+
+# The middle form will be converted to the last form as we use it.
+
+function tem_data_as_rows($value) {
+ if(is_array($value)) {
+ # numeric keys, is already array of arrays -- expand sub-template for each.
+ if(array_key_exists(0, $value)) return $value;
+ # key/value pairs -- expand sub-template once.
+ else return array($value);
+ } elseif($value) {
+ # value -- expand sub-template once using only parent values
+ return array(array());
+ } else {
+ # empty value -- don't expand sub-template
+ return array();