3 * Integrated Template - IT
\r
5 * Well there's not much to say about it. I needed a template class that
\r
6 * supports a single template file with multiple (nested) blocks inside.
\r
9 * $tpl = new IntegratedTemplate( [string filerootdir] );
\r
11 * // load a template or set it with setTemplate()
\r
12 * $tpl->loadTemplatefile( string filename [, boolean removeUnknownVariables, boolean removeEmptyBlocks] )
\r
14 * // set "global" Variables meaning variables not beeing within a (inner) block
\r
15 * $tpl->setVariable( string variablename, mixed value );
\r
17 * // like with the Isotopp Templates there's a second way to use setVariable()
\r
18 * $tpl->setVariable( array ( string varname => mixed value ) );
\r
20 * // Let's use any block, even a deeply nested one
\r
21 * $tpl->setCurrentBlock( string blockname );
\r
23 * // repeat this as often as you neer.
\r
24 * $tpl->setVariable( array ( string varname => mixed value ) );
\r
25 * $tpl->parseCurrentBlock();
\r
27 * // get the parsed template or print it: $tpl->show()
\r
30 * @author Ulf Wendel <uw@netuse.de>
\r
31 * @version $Id: IT.php,v 1.4 2000/12/03 20:30:42 uw Exp $
\r
35 class IntegratedTemplate {
\r
38 * Contains the error objects
\r
41 * @see halt(), $printError, $haltOnError
\r
46 * Print error messages?
\r
49 * @see halt(), $haltOnError, $err
\r
51 var $printError = false;
\r
54 * Call die() on error?
\r
57 * @see halt(), $printError, $err
\r
59 var $haltOnError = false;
\r
62 * Clear cache on get()?
\r
65 var $clearCache = false;
\r
68 * First character of a variable placeholder ( _{_VARIABLE} ).
\r
71 * @see $closingDelimiter, $blocknameRegExp, $variablenameRegExp
\r
73 var $openingDelimiter = "{";
\r
76 * Last character of a variable placeholder ( {VARIABLE_}_ ).
\r
79 * @see $openingDelimiter, $blocknameRegExp, $variablenameRegExp
\r
81 var $closingDelimiter = "}";
\r
84 * RegExp matching a block in the template.
\r
85 * Per default "sm" is used as the regexp modifier, "i" is missing.
\r
86 * That means a case sensitive search is done.
\r
89 * @see $variablenameRegExp, $openingDelimiter, $closingDelimiter
\r
91 var $blocknameRegExp = "[0-9A-Za-z_-]+";
\r
94 * RegExp matching a variable placeholder in the template.
\r
95 * Per default "sm" is used as the regexp modifier, "i" is missing.
\r
96 * That means a case sensitive search is done.
\r
99 * @see $blocknameRegExp, $openingDelimiter, $closingDelimiter
\r
101 var $variablenameRegExp = "[0-9A-Za-z_-]+";
\r
104 * Full RegExp used to find variable placeholder, filled by the constructor.
\r
105 * @var string Looks somewhat like @(delimiter varname delimiter)@
\r
106 * @see IntegratedTemplate()
\r
108 var $variablesRegExp = "";
\r
111 * Full RegExp used to find blocks an their content, filled by the constructor.
\r
113 * @see IntegratedTemplate()
\r
115 var $blockRegExp = "";
\r
118 * Name of the current block.
\r
121 var $currentBlock = "__global__";
\r
124 * Content of the template.
\r
127 var $template = "";
\r
130 * Array of all blocks and their content.
\r
133 * @see findBlocks()
\r
135 var $blocklist = array();
\r
138 * Array with the parsed content of a block.
\r
142 var $blockdata = array();
\r
145 * Array of variables in a block.
\r
148 var $blockvariables = array();
\r
151 * Array of inner blocks of a block.
\r
154 var $blockinner = array();
\r
157 * Future versions will use this...
\r
160 var $blocktypes = array();
\r
165 * Variables get cached before any replacement is done.
\r
166 * Advantage: empty blocks can be removed automatically.
\r
167 * Disadvantage: might take some more memory
\r
170 * @see setVariable(), $clearCacheOnParse
\r
172 var $variableCache = array();
\r
177 var $clearCacheOnParse = true;
\r
180 * Controls the handling of unknown variables, default is remove.
\r
183 var $removeUnknownVariables = true;
\r
186 * Controls the handling of empty blocks, default is remove.
\r
189 var $removeEmptyBlocks = true;
\r
192 * Root directory for all file operations.
\r
193 * The string gets prefixed to all filenames given.
\r
195 * @see IntegratedTemplate(), setRoot()
\r
197 var $fileRoot = "";
\r
200 * Internal flag indicating that a blockname was used multiple times.
\r
203 var $flagBlocktrouble = false;
\r
206 * Flag indicating that the global block was parsed.
\r
209 var $flagGlobalParsed = false;
\r
212 * Builds some complex regular expressions and optinally sets the file root directory.
\r
214 * Make sure that you call this constructor if you derive your template
\r
215 * class from this one.
\r
217 * @param string File root directory, prefix for all filenames given to the object.
\r
220 function IntegratedTemplate($root = "") {
\r
222 $this->variablesRegExp = "@".$this->openingDelimiter."(".$this->variablenameRegExp.")".$this->closingDelimiter."@sm";
\r
223 $this->blockRegExp = '@!--\s+BEGIN\s+('.$this->blocknameRegExp.')\s+-->(.*)<!--\s+END\s+\1\s+-->@sm';
\r
225 $this->setRoot($root);
\r
227 } // end constructor
\r
230 * Print a certain block with all replacements done.
\r
233 function show($block = "__global__") {
\r
234 print $this->get($block);
\r
238 * Returns a block with all replacements done.
\r
240 * @param string name of the block
\r
245 function get($block = "__global__") {
\r
247 if ("__global__" == $block && !$this->flagGlobalParsed)
\r
248 $this->parse("__global__");
\r
250 if (!isset($this->blocklist[$block])) {
\r
251 $this->halt("The block '$block' was not found in the template.", __FILE__, __LINE__);
\r
255 if ($this->clearCache) {
\r
257 $data = (isset($this->blockdata[$block])) ? $this->blockdata[$block] : "";
\r
258 unset($this->blockdata[$block]);
\r
263 return (isset($this->blockdata[$block])) ? $this->blockdata[$block] : "";
\r
267 } // end func get()
\r
270 * Parses the given block.
\r
272 * @param string name of the block to be parsed
\r
274 * @see parseCurrentBlock()
\r
276 function parse($block = "__global__", $flag_recursion = false) {
\r
278 if (!isset($this->blocklist[$block])) {
\r
279 $this->halt("The block '$block' was not found in the template.", __FILE__, __LINE__);
\r
283 if ("__global__" == $block)
\r
284 $this->flagGlobalParsed = true;
\r
289 if ($this->clearCacheOnParse) {
\r
291 reset($this->variableCache);
\r
292 while (list($name, $value)=each($this->variableCache)) {
\r
293 $regs[] = "@".$this->openingDelimiter.$name.$this->closingDelimiter."@";
\r
294 $values[] = $value;
\r
296 $this->variableCache = array();
\r
300 reset($this->blockvariables[$block]);
\r
301 while (list($k, $allowedvar)=each($this->blockvariables[$block])) {
\r
303 if (isset($this->variableCache[$allowedvar])) {
\r
304 $regs[] = "@".$this->openingDelimiter.$allowedvar.$this->closingDelimiter."@";
\r
305 $values[] = $this->variableCache[$allowedvar];
\r
306 unset($this->variableCache[$allowedvar]);
\r
313 $outer = (0 == count($regs)) ? $this->blocklist[$block] : preg_replace($regs, $values, $this->blocklist[$block]);
\r
314 $empty = (0 == count($values)) ? true : false;
\r
316 if (isset($this->blockinner[$block])) {
\r
318 reset($this->blockinner[$block]);
\r
319 while (list($k, $innerblock)=each($this->blockinner[$block])) {
\r
321 $this->parse($innerblock, true);
\r
322 if (""!=$this->blockdata[$innerblock])
\r
325 $placeholder = $this->openingDelimiter."__".$innerblock."__".$this->closingDelimiter;
\r
326 $outer = str_replace($placeholder, $this->blockdata[$innerblock], $outer);
\r
327 $this->blockdata[$innerblock] = "";
\r
331 if ($this->removeUnknownVariables)
\r
332 $outer = preg_replace($this->variablesRegExp, "", $outer);
\r
336 if (!$this->removeEmptyBlocks)
\r
337 $this->blockdata[$block].= $outer;
\r
341 $this->blockdata[$block].= $outer;
\r
346 } // end func parse
\r
349 * Parses the current block
\r
350 * @see parse(), setCurrentBlock(), $currentBlock
\r
353 function parseCurrentBlock() {
\r
354 return $this->parse($this->currentBlock);
\r
355 } // end func parseCurrentBlock
\r
358 * Sets a variable value.
\r
360 * The function can be used eighter like setVariable( "varname", "value")
\r
361 * or with one array $variables["varname"] = "value" given setVariable($variables)
\r
362 * quite like phplib templates set_var().
\r
364 * @param mixed string with the variable name or an array %variables["varname"] = "value"
\r
365 * @param string value of the variable or empty if $variable is an array.
\r
366 * @param string prefix for variable names
\r
369 function setVariable($variable, $value="") {
\r
371 if (is_array($variable)) {
\r
374 while (list($var, $value)=each($variable))
\r
375 $this->variableCache[$var] = $value;
\r
379 $this->variableCache[$variable] = $value;
\r
383 } // end func setVariable
\r
386 * Sets the name of the current block that is the block where variables are added.
\r
388 * @param string name of the block
\r
389 * @return boolean false on failure otherwise true
\r
392 function setCurrentBlock($block = "__global__") {
\r
394 if (!isset($this->blocklist[$block])) {
\r
395 $this->halt("Can't find the block '$block' in the template.", __FILE__, __LINE__);
\r
399 $this->currentBlock = $block;
\r
402 } // end func setCurrentBlock
\r
405 * Clears all datafields of the object and rebuild the internal blocklist
\r
407 * LoadTemplatefile() and setTemplate() automatically call this function
\r
408 * when a new template is given. Don't use this function
\r
409 * unless you know what you're doing.
\r
417 $this->findBlocks($this->template);
\r
418 $this->buildBlockvariablelist();
\r
423 * Clears all datafields of the object.
\r
425 * Don't use this function unless you know what you're doing.
\r
434 $this->currentBlock = "__global__";
\r
436 $this->variableCache = array();
\r
437 $this->blocklist = array();
\r
438 $this->blockvariables = array();
\r
439 $this->blockinner = array();
\r
440 $this->blockdata = array();
\r
441 $this->blocklookup = array();
\r
442 $this->blocktypes = array();
\r
444 $this->flagBlocktrouble = false;
\r
445 $this->flagGlobalParsed = false;
\r
450 * Sets the template.
\r
452 * You can eighter load a template file from disk with LoadTemplatefile() or set the
\r
453 * template manually using this function.
\r
455 * @param string template content
\r
456 * @param boolean Unbekannte, nicht ersetzte Platzhalter entfernen?
\r
457 * @param boolean remove unknown/unused variables?
\r
458 * @param boolean remove empty blocks?
\r
459 * @see LoadTemplatefile(), $template
\r
462 function setTemplate($template, $removeUnknownVariables = true, $removeEmptyBlocks = false) {
\r
463 if (""==$template) {
\r
464 $this->halt("The given string is empty.", __FILE__, __LINE__);
\r
468 $this->removeUnknownVariables = $removeUnknownVariables;
\r
469 $this->removeEmptyBlocks = $removeEmptyBlocks;
\r
471 $this->template = '<!-- BEGIN __global__ -->'.$template.'<!-- END __global__ -->';
\r
474 if ($this->flagBlocktrouble)
\r
478 } // end func setTemplate
\r
481 * Reads a template file from the disk.
\r
483 * @param string name of the template file, full path!
\r
484 * @param boolean remove unknown/unused variables?
\r
485 * @param boolean remove empty blocks?
\r
487 * @return boolean false on failure, otherwise true
\r
488 * @see $template, setTemplate()
\r
490 function loadTemplatefile($filename, $removeUnknownVariables = true, $removeEmptyBlocks = true) {
\r
492 $template = $this->getfile($filename);
\r
494 return $this->setTemplate($this->getFile($filename), $removeUnknownVariables, $removeEmptyBlocks);
\r
495 } // end func LoadTemplatefile
\r
498 * Sets the file root. The file root gets prefixed to all filenames passed to the object.
\r
500 * Make sure that you override this function when using the class
\r
504 * @see IntegratedTemplate()
\r
507 function setRoot($root) {
\r
509 if (""!=$root && "/"!= substr($root, -1))
\r
512 $this->fileRoot = $root;
\r
514 } // end func setRoot
\r
517 * Build a list of all variables within a block
\r
519 function buildBlockvariablelist() {
\r
521 reset($this->blocklist);
\r
522 while (list($name, $content)=each($this->blocklist)) {
\r
523 preg_match_all( $this->variablesRegExp, $content, $regs );
\r
524 $this->blockvariables[$name] = $regs[1];
\r
527 } // end func buildBlockvariablelist
\r
530 * Returns a list of all
\r
532 function getGlobalvariables() {
\r
537 reset($this->blockvariables["__global__"]);
\r
538 while (list($k, $allowedvar)=each($this->blockvariables["__global__"])) {
\r
540 if (isset($this->variableCache[$allowedvar])) {
\r
541 $regs[] = "@".$this->openingDelimiter.$allowedvar.$this->closingDelimiter."@";
\r
542 $values[] = $this->variableCache[$allowedvar];
\r
543 unset($this->variableCache[$allowedvar]);
\r
548 return array($regs, $values);
\r
549 } // end func getGlobalvariables
\r
552 * Recusively builds a list of all blocks within the template.
\r
554 * @param string string that gets scanned
\r
558 function findBlocks($string) {
\r
560 $blocklist = array();
\r
562 if (preg_match_all($this->blockRegExp, $string, $regs, PREG_SET_ORDER)) {
\r
565 while (list($k, $match)=each($regs)) {
\r
567 $blockname = $match[1];
\r
568 $blockcontent = $match[2];
\r
570 if (isset($this->blocklist[$blockname])) {
\r
571 $this->halt("The name of a block must be unique within a template. Found '$blockname' twice. Unpredictable results may appear.", __FILE__, __LINE__);
\r
572 $this->flagBlocktrouble = true;
\r
575 $this->blocklist[$blockname] = $blockcontent;
\r
576 $this->blockdata[$blockname] = "";
\r
578 $blocklist[] = $blockname;
\r
580 $inner = $this->findBlocks($blockcontent);
\r
582 while (list($k, $name)=each($inner)) {
\r
584 $pattern = sprintf('@<!--\s+BEGIN\s+%s\s+-->(.*)<!--\s+END\s+%s\s+-->@sm',
\r
589 $this->blocklist[$blockname] = preg_replace( $pattern,
\r
590 $this->openingDelimiter."__".$name."__".$this->closingDelimiter,
\r
591 $this->blocklist[$blockname]
\r
593 $this->blockinner[$blockname][] = $name;
\r
594 $this->blockparents[$name] = $blockname;
\r
603 } // end func findBlocks
\r
606 * Reads a file from disk and returns its content.
\r
607 * @param string Filename
\r
608 * @return string Filecontent
\r
610 function getFile($filename) {
\r
612 if ("/" == substr($filename, 0, 1))
\r
613 $filename = substr($filename, 1);
\r
615 $filename = $this->fileRoot.$filename;
\r
617 if ( !($fh = @fopen($filename, "r")) ) {
\r
618 $this->halt("Can't read '$filename'.", __FILE__, __LINE__);
\r
622 $content = fread($fh, filesize($filename));
\r
626 } // end func getFile
\r
629 * Error Handling function.
\r
630 * @param string error message
\r
631 * @param mixed File where the error occured
\r
632 * @param int Line where the error occured
\r
635 function halt($message, $file="", $line=0) {
\r
637 $message = sprintf("IntegratedTemplate Error: %s [File: %s, Line: %d]",
\r
643 $this->err[] = $message;
\r
645 if ($this->printError)
\r
648 if ($this->haltOnError)
\r
653 } // end class IntegratedTemplate
\r