Source for file IT.php
Documentation is available at IT.php
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2005 Ulf Wendel, Pierre-Alain Joye |
// +----------------------------------------------------------------------+
// | This source file is subject to the New BSD license, That is bundled |
// | with this package in the file LICENSE, and is available through |
// | the world-wide-web at |
// | http://www.opensource.org/licenses/bsd-license.php |
// | If you did not receive a copy of the new BSDlicense and are unable |
// | to obtain it through the world-wide-web, please send a note to |
// | pajoye@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Ulf Wendel <ulf.wendel@phpdoc.de> |
// | Pierre-Alain Joye <pajoye@php.net> |
// +----------------------------------------------------------------------+
// $Id: IT.php,v 1.20 2006/08/17 15:47:22 dsp Exp $
define('IT_TPL_NOT_FOUND', -2 );
define('IT_BLOCK_NOT_FOUND', -3 );
define('IT_BLOCK_DUPLICATE', -4 );
define('IT_UNKNOWN_OPTION', -6 );
* Integrated Template - IT
* Well there's not much to say about it. I needed a template class that
* supports a single template file with multiple (nested) blocks inside and
* The Isotemplate API is somewhat tricky for a beginner although it is the best
* one you can build. template::parse() [phplib template = Isotemplate] requests
* you to name a source and a target where the current block gets parsed into.
* Source and target can be block names or even handler names. This API gives you
* a maximum of fexibility but you always have to know what you do which is
* quite unusual for php skripter like me.
* I noticed that I do not any control on which block gets parsed into which one.
* If all blocks are within one file, the script knows how they are nested and in
* which way you have to parse them. IT knows that inner1 is a child of block2, there's
* no need to tell him about this.
* (hidden and automatically added)
* <td colspan=2>block2</td>
* To add content to block1 you simply type:
* <code>$tpl->setCurrentBlock("block1");</code>
* and repeat this as often as needed:
* $tpl->setVariable(...);
* $tpl->parseCurrentBlock();
* To add content to block2 you would type something like:
* $tpl->setCurrentBlock("inner1");
* $tpl->setVariable(...);
* $tpl->parseCurrentBlock();
* $tpl->setVariable(...);
* $tpl->parseCurrentBlock();
* This will result in one repition of block1 which contains two repitions
* of inner1. inner2 will be removed if $removeEmptyBlock is set to true which is the default.
* $tpl = new HTML_Template_IT( [string filerootdir] );
* // load a template or set it with setTemplate()
* $tpl->loadTemplatefile( string filename [, boolean removeUnknownVariables, boolean removeEmptyBlocks] )
* // set "global" Variables meaning variables not beeing within a (inner) block
* $tpl->setVariable( string variablename, mixed value );
* // like with the Isotemplates there's a second way to use setVariable()
* $tpl->setVariable( array ( string varname => mixed value ) );
* // Let's use any block, even a deeply nested one
* $tpl->setCurrentBlock( string blockname );
* // repeat this as often as you need it.
* $tpl->setVariable( array ( string varname => mixed value ) );
* $tpl->parseCurrentBlock();
* // get the parsed template or print it: $tpl->show()
* @author Ulf Wendel <uw@netuse.de>
* @version $Id: IT.php,v 1.20 2006/08/17 15:47:22 dsp Exp $
* @package HTML_Template_IT
* Contains the error objects
* @see halt(), $printError, $haltOnError
* First character of a variable placeholder ( _{_VARIABLE} ).
* @see $closingDelimiter, $blocknameRegExp, $variablenameRegExp
* Last character of a variable placeholder ( {VARIABLE_}_ ).
* @see $openingDelimiter, $blocknameRegExp, $variablenameRegExp
* RegExp matching a block in the template.
* Per default "sm" is used as the regexp modifier, "i" is missing.
* That means a case sensitive search is done.
* @see $variablenameRegExp, $openingDelimiter, $closingDelimiter
* RegExp matching a variable placeholder in the template.
* Per default "sm" is used as the regexp modifier, "i" is missing.
* That means a case sensitive search is done.
* @see $blocknameRegExp, $openingDelimiter, $closingDelimiter
* RegExp used to find variable placeholder, filled by the constructor.
* @var string Looks somewhat like @(delimiter varname delimiter)@
* @see IntegratedTemplate()
* RegExp used to strip unused variable placeholder.
* @brother $variablesRegExp
* Controls the handling of unknown variables, default is remove.
* Controls the handling of empty blocks, default is remove.
* RegExp used to find blocks an their content, filled by the constructor.
* @see IntegratedTemplate()
* Name of the current block.
* Content of the template.
* Array of all blocks and their content.
* Array with the parsed content of a block.
* Array of variables in a block.
* Array of inner blocks of a block.
* List of blocks to preverse even if they are "empty".
* This is something special. Sometimes you have blocks that
* should be preserved although they are empty (no placeholder replaced).
* Think of a shopping basket. If it's empty you have to drop a message to
* the user. If it's filled you have to show the contents of
* the shopping baseket. Now where do you place the message that the basket
* is empty? It's no good idea to place it in you applications as customers
* tend to like unecessary minor text changes. Having another template file
* for an empty basket means that it's very likely that one fine day
* the filled and empty basket templates have different layout. I decided
* to introduce blocks that to not contain any placeholder but only
* text such as the message "Your shopping basked is empty".
* Now if there is no replacement done in such a block the block will
* be recognized as "empty" and by default ($removeEmptyBlocks = true) be
* stripped off. To avoid thisyou can now call touchBlock() to avoid this.
* The array $touchedBlocks stores a list of touched block which must not
* be removed even if they are empty.
* @var array $touchedBlocks
* @see touchBlock(), $removeEmptyBlocks
* List of blocks which should not be shown even if not "empty"
* @var array $_hiddenBlocks
* @see hideBlock(), $removeEmptyBlocks
var $_hiddenBlocks = array ();
* Variables get cached before any replacement is done.
* Advantage: empty blocks can be removed automatically.
* Disadvantage: might take some more memory
* @see setVariable(), $clearCacheOnParse
* Clear the variable cache on parse?
* If you're not an expert just leave the default false.
* True reduces memory consumption somewhat if you tend to
* add lots of values for unknown placeholder.
* Root directory for all file operations.
* The string gets prefixed to all filenames given.
* @see HTML_Template_IT(), setRoot()
* Internal flag indicating that a blockname was used multiple times.
* Flag indicating that the global block was parsed.
* Flag indication that a template gets cached.
* Complex templates require some times to be preparsed
* before the replacement can take place. Often I use
* one template file over and over again but I don't know
* before that I will use the same template file again.
* Now IT could notice this and skip the preparse.
* $_options['preserve_data'] Whether to substitute variables and remove
* empty placeholders in data passed through setVariable
* (see also bugs #20199, #21951).
* $_options['use_preg'] Whether to use preg_replace instead of
* (this is a backwards compatibility feature, see also bugs #21951, #20392)
'preserve_data' => false ,
* Builds some complex regular expressions and optinally sets the
* Make sure that you call this constructor if you derive your template
* @param string File root directory, prefix for all filenames
')\s+-->(.*)<!--\s+END\s+\1\s+-->@sm';
* Sets the option for the template class
* @param string option name
* @param mixed option value
* @return mixed IT_OK on success, error object on failure
$this->_options[$option] = $value;
* Sets the options for the template class
* @param string options array of options
* 'preserve_data' => false,
* @param mixed option value
* @return mixed IT_OK on success, error object on failure
foreach ($options as $option => $value) {
if (PEAR ::isError ($error)) {
* Print a certain block with all replacements done.
function show($block = '__global__')
print $this->get($block);
* Returns a block with all replacements done.
* @param string name of the block
function get($block = '__global__')
$this->parse('__global__');
$this->err[] = PEAR ::raiseError (
if ($this->_options['preserve_data']) {
* Parses the given block.
* @param string name of the block to be parsed
* @see parseCurrentBlock()
function parse($block = '__global__', $flag_recursion = false )
if ($block == '__global__') {
foreach ($this->blockinner[$block] as $k => $innerblock) {
$this->parse($innerblock, true );
if (!$flag_recursion && 0 != count($values)) {
if ($this->_options['use_preg']) {
&$this, '_addPregDelimiters'),
$funcReplace = 'preg_replace';
$funcReplace = 'str_replace';
if ($this->_options['preserve_data']) {
array (&$this, '_preserveOpeningDelimiter'), $values
$outer = $funcReplace($regs, $values, $outer);
* Parses the current block
* @see parse(), setCurrentBlock(), $currentBlock
} // end func parseCurrentBlock
* The function can be used eighter like setVariable( "varname", "value")
* or with one array $variables["varname"] = "value"
* given setVariable($variables) quite like phplib templates set_var().
* @param mixed string with the variable name or an array
* %variables["varname"] = "value"
* @param string value of the variable or empty if $variable
* @param string prefix for variable names
} // end func setVariable
* Sets the name of the current block that is the block where variables
* @param string name of the block
* @return boolean false on failure, otherwise true
} // end func setCurrentBlock
* Preserves an empty block even if removeEmptyBlocks is true.
* @param string name of the block
* @return boolean false on false, otherwise true
* @see $removeEmptyBlocks
* Clears all datafields of the object and rebuild the internal blocklist
* LoadTemplatefile() and setTemplate() automatically call this function
* when a new template is given. Don't use this function
* unless you know what you're doing.
// we don't need it any more
* Clears all datafields of the object.
* Don't use this function unless you know what you're doing.
* You can eighter load a template file from disk with
* LoadTemplatefile() or set the template manually using this function.
* @param string template content
* @param boolean remove unknown/unused variables?
* @param boolean remove empty blocks?
* @see LoadTemplatefile(), $template
function setTemplate( $template, $removeUnknownVariables = true ,
$removeEmptyBlocks = true )
$this->template = '<!-- BEGIN __global__ -->' . $template .
'<!-- END __global__ -->';
} // end func setTemplate
* Reads a template file from the disk.
* @param string name of the template file
* @param bool how to handle unknown variables.
* @param bool how to handle empty blocks.
* @return boolean false on failure, otherwise true
* @see $template, setTemplate(), $removeUnknownVariables,
$removeUnknownVariables = true ,
$removeEmptyBlocks = true )
$template = $this->getFile($filename);
$template,$removeUnknownVariables, $removeEmptyBlocks
} // end func LoadTemplatefile
* Sets the file root. The file root gets prefixed to all filenames passed
* Make sure that you override this function when using the class
* @see HTML_Template_IT()
if ($root != '' && substr($root, -1 ) != '/') {
* Build a list of all variables within of a block
foreach ($this->blocklist as $name => $content) {
if (count($regs[1 ]) != 0 ) {
foreach ($regs[1 ] as $k => $var) {
} // end func buildBlockvariablelist
* Returns a list of all global variables
return array ($regs, $values);
} // end func getGlobalvariables
* Recusively builds a list of all blocks within the template.
* @param string string that gets scanned
foreach ($regs as $k => $match) {
$blockcontent = $match[2 ];
$this->err[] = PEAR ::raiseError (
$this->blocklist[$blockname] = $blockcontent;
$blocklist[] = $blockname;
foreach ($inner as $k => $name) {
'@<!--\s+BEGIN\s+%s\s+-->(.*)<!--\s+END\s+%s\s+-->@sm',
$this->blockparents[$name] = $blockname;
* Reads a file from disk and returns its content.
* @return string Filecontent
$filename = substr($filename, 1 );
$filename = $this->fileRoot . $filename;
if (!($fh = @fopen($filename, 'r'))) {
$this->err[] = PEAR ::raiseError (
$content = fread($fh, $fsize);
"#<!-- INCLUDE (.*) -->#ime", "\$this->getFile('\\1')", $content
* Adds delimiters to a string, so it can be used as a pattern
function _addPregDelimiters ($str)
* Replaces an opening delimiter by a special string
function _preserveOpeningDelimiter ($str)
* Return a textual error message for a IT error code
* @param integer $value error code
* @return string error message, or false if the error code was
if (!isset ($errorMessages)) {
' uniquewithin a template.'.
' Found "' . $blockname . '" twice.'.
'Unpredictable results '.
if (PEAR ::isError ($value)) {
$value = $value->getCode ();
return isset ($errorMessages[$value]) ?
$errorMessages[$value] : $errorMessages[IT_ERROR];
} // end class IntegratedTemplate
Documentation generated on Mon, 11 Mar 2019 14:43:07 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.
|