HTML_Template_Sigma
[ class tree: HTML_Template_Sigma ] [ index: HTML_Template_Sigma ] [ all elements ]

Class: HTML_Template_Sigma

Source Location: /HTML_Template_Sigma-1.3.0/HTML/Template/Sigma.php

Class Overview

PEAR
   |
   --HTML_Template_Sigma

Implementation of Integrated Templates API with template 'compilation' added.


Author(s):

Version:

  • Release: 1.3.0

Variables

Methods


Inherited Variables

Inherited Methods


Class Details

[line 131]
Implementation of Integrated Templates API with template 'compilation' added.

The main new feature in Sigma is the template 'compilation'. Consider the following: when loading a template file the engine has to parse it using regular expressions to find all the blocks and variable placeholders. This is a very "expensive" operation and is definitely an overkill to do on every page request: templates seldom change on production websites. This is where the cache kicks in: it saves an internal representation of the template structure into a file and this file gets loaded instead of the source one on subsequent requests (unless the source changes, of course).

While HTML_Template_Sigma inherits PHPLib Template's template syntax, it has an API which is easier to understand. When using HTML_Template_PHPLIB, you have to explicitly name a source and a target the block gets parsed into. This gives maximum flexibility but requires full knowledge of template structure from the programmer.

Integrated Template on the other hands manages block nesting and parsing itself. The engine knows that inner1 is a child of block2, there's no need to tell it about this:

 + __global__ (hidden and automatically added)
     + block1
     + block2
         + inner1
         + inner2

To add content to block1 you simply type:

  1. $tpl->setCurrentBlock("block1");
and repeat this as often as needed:
  1.    $tpl->setVariable(...);
  2.    $tpl->parseCurrentBlock();

To add content to block2 you would type something like:

  1.  $tpl->setCurrentBlock("inner1");
  2.  $tpl->setVariable(...);
  3.  
  4.  $tpl->setVariable(...);
  5.  
  6.  $tpl->parse("block2");

This will result in one repetition of block2 which contains two repetitions of inner1. inner2 will be removed if $removeEmptyBlock is set to true (which is the default).

Usage:

  1.  $tpl = new HTML_Template_Sigma[string filerootdir][string cacherootdir);
  2.  
  3.  // load a template or set it with setTemplate()
  4.  $tpl->loadTemplatefilestring filename [boolean removeUnknownVariablesboolean removeEmptyBlocks)
  5.  
  6.  // set "global" Variables meaning variables not beeing within a (inner) block
  7.  $tpl->setVariablestring variablenamemixed value );
  8.  
  9.  // like with the HTML_Template_PHPLIB there's a second way to use setVariable()
  10.  $tpl->setVariablearray string varname => mixed value ) );
  11.  
  12.  // Let's use any block, even a deeply nested one
  13.  $tpl->setCurrentBlockstring blockname );
  14.  
  15.  // repeat this as often as you need it.
  16.  $tpl->setVariablearray string varname => mixed value ) );
  17.  
  18.  // get the parsed template or print it: $tpl->show()
  19.  $html $tpl->get();



[ Top ]


Class Variables

$blocknameRegExp =  '[0-9A-Za-z_-]+'

[line 157]

RegExp for matching the block names in the template.

Per default "sm" is used as the regexp modifier, "i" is missing. That means a case sensitive search is done.


Type:   string


[ Top ]

$blockRegExp =  ''

[line 187]

RegExp used to find blocks and their content, filled by the constructor

Type:   string


[ Top ]

$closingDelimiter =  '}'

[line 147]

Last character of a variable placeholder ( {VARIABLE_}_ )

Type:   string


[ Top ]

$commentRegExp =  '#<!--\s+COMMENT\s+-->.*?<!--\s+/COMMENT\s+-->#sm'

[line 359]

RegExp used to find (and remove) comments in the template

Type:   string


[ Top ]

$currentBlock =  '__global__'

[line 207]

Name of the current block

Type:   string


[ Top ]

$fileRoot =  ''

[line 288]

Root directory for "source" templates

Type:   string


[ Top ]

$flagGlobalParsed =  false

[line 302]

Flag indicating that the global block was parsed

Type:   boolean


[ Top ]

$functionnameRegExp =  '[_a-zA-Z][A-Za-z_0-9]*'

[line 326]

Function name RegExp

Type:   string


[ Top ]

$functionPrefix =  'func_'

[line 320]

Function name prefix used when searching for function calls in the template

Type:   string


[ Top ]

$functionRegExp =  ''

[line 333]

RegExp used to grep function calls in the template (set by the constructor)

Type:   string


[ Top ]

$includeRegExp =  '#<!--\s+INCLUDE\s+(\S+)\s+-->#im'

[line 353]

RegExp used to find file inclusion calls in the template

Type:   string


[ Top ]

$openingDelimiter =  '{'

[line 139]

First character of a variable placeholder ( _{_VARIABLE} ).

Type:   string


[ Top ]

$removeEmptyBlocks =  true

[line 201]

Controls the handling of empty blocks, default is remove
  • Access: public

Type:   boolean


[ Top ]

$removeUnknownVariables =  true

[line 194]

Controls the handling of unknown variables, default is remove
  • Access: public

Type:   boolean


[ Top ]

$removeVariablesRegExp =  ''

[line 180]

RegExp used to strip unused variable placeholders

Type:   mixed


[ Top ]

$variablenameRegExp =  '[0-9A-Za-z._-]+'

[line 167]

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.


Type:   string


[ Top ]

$variablesRegExp =  ''

[line 174]

RegExp used to find variable placeholder, filled by the constructor

Type:   string


[ Top ]



Method Detail

HTML_Template_Sigma (Constructor)   [line 387]

HTML_Template_Sigma HTML_Template_Sigma( [string $root = ''], [string $cacheRoot = ''])

Constructor: builds some complex regular expressions and optionally sets the root directories.

Make sure that you call this constructor if you derive your template class from this one.


Parameters:

string   $root   —  root directory for templates
string   $cacheRoot   —  directory to cache "prepared" templates in

[ Top ]

addBlock   [line 959]

mixed addBlock( string $placeholder, string $block, string $template)

Adds a block to the template changing a variable placeholder to a block placeholder.

This means that a new block will be integrated into the template in place of a variable placeholder. The variable placeholder will be removed and the new block will behave in the same way as if it was inside the original template.

The block content must not start with <!-- BEGIN blockname --> and end with <!-- END blockname -->, if it does the error will be thrown.


Parameters:

string   $placeholder   —  name of the variable placeholder, the name must be unique within the template.
string   $block   —  name of the block to be added
string   $template   —  content of the block

[ Top ]

addBlockfile   [line 1002]

mixed addBlockfile( string $placeholder, string $block, string $filename)

Adds a block taken from a file to the template, changing a variable placeholder to a block placeholder.

Parameters:

string   $placeholder   —  name of the variable placeholder
string   $block   —  name of the block to be added
string   $filename   —  template file that contains the block

[ Top ]

blockExists   [line 1109]

bool blockExists( string $block)

Checks if the block exists in the template
  • Access: public

Parameters:

string   $block   —  block name

[ Top ]

clearVariables   [line 1273]

void clearVariables( )

Clears the variables

Global variables are not affected. The method is useful when you add a lot of variables via setVariable() and are not sure whether all of them appear in the block you parse(). If you clear the variables after parse(), you don't risk them suddenly showing up in other blocks.


[ Top ]

errorMessage   [line 495]

string errorMessage( integer|PEAR_Error $code, [string $data = null])

Returns a textual error message for an error code
  • Return: error message
  • Access: public

Parameters:

integer|PEAR_Error   $code   —  error code or another error object for code reuse
string   $data   —  additional data to insert into message

[ Top ]

get   [line 553]

string get( [string $block = '__global__'], [bool $clear = false])

Returns a block with all replacements done.

Parameters:

string   $block   —  block name
bool   $clear   —  whether to clear parsed block contents

[ Top ]

getBlockList   [line 1215]

array getBlockList( [string $parent = '__global__'], [bool $recursive = false])

Returns a list of blocks within a template.

If $recursive is false, it returns just a 'flat' array of $parent's direct subblocks. If $recursive is true, it builds a tree of template blocks using $parent as root. Tree structure is compatible with PEAR::Tree's Memory_Array driver.

  • Return: a list of child blocks
  • Throws: PEAR_Error
  • Access: public

Parameters:

string   $parent   —  parent block name
bool   $recursive   —  whether to return a tree of child blocks (true) or a 'flat' array (false)

[ Top ]

getCurrentBlock   [line 799]

string getCurrentBlock( )

Returns the current block name
  • Return: block name
  • Access: public

[ Top ]

getPlaceholderList   [line 1246]

array getPlaceholderList( [string $block = '__global__'])

Returns a list of placeholders within a block.

Only 'normal' placeholders are returned, not auto-created ones.

  • Return: a list of placeholders
  • Throws: PEAR_Error
  • Access: public

Parameters:

string   $block   —  block name

[ Top ]

hideBlock   [line 861]

mixed hideBlock( string $block)

Hides the block even if it is not "empty".

Is somewhat an opposite to touchBlock().

Consider a block (a 'edit' link for example) that should be visible to registered/"special" users only, but its visibility is triggered by some little 'id' field passed in a large array into setVariable(). You can either carefully juggle your variables to prevent the block from appearing (a fragile solution) or simply call hideBlock()

  • Return: SIGMA_OK on success, error object on failure
  • Throws: PEAR_Error
  • Access: public

Parameters:

string   $block   —  block name

[ Top ]

loadTemplateFile   [line 919]

mixed loadTemplateFile( string $filename, [boolean $removeUnknownVariables = true], [boolean $removeEmptyBlocks = true])

Loads a template file.

If caching is on, then it checks whether a "prepared" template exists. If it does, it gets loaded instead of the original, if it does not, then the original gets loaded and prepared and then the prepared version is saved. addBlockfile() and replaceBlockfile() implement quite the same logic.


Parameters:

string   $filename   —  filename
boolean   $removeUnknownVariables   —  remove unknown/unused variables?
boolean   $removeEmptyBlocks   —  remove empty blocks?

[ Top ]

parse   [line 595]

bool parse( [string $block = '__global__'], [bool $flagRecursion = false], [bool $fakeParse = false])

Parses the given block.

Parameters:

string   $block   —  block name
bool   $flagRecursion   —  true if the function is called recursively (do not set this to true yourself!)
bool   $fakeParse   —  true if parsing a "hidden" block (do not set this to true yourself!)

[ Top ]

parseCurrentBlock   [line 787]

bool parseCurrentBlock( )

Parses the current block

[ Top ]

placeholderExists   [line 1126]

string placeholderExists( string $placeholder, [string $block = ''])

Returns the name of the (first) block that contains the specified placeholder.
  • Return: Name of the (first) block that contains the specified placeholder. If the placeholder was not found an empty string is returned.
  • Throws: PEAR_Error
  • Access: public

Parameters:

string   $placeholder   —  Name of the placeholder you're searching
string   $block   —  Name of the block to scan. If left out (default) all blocks are scanned.

[ Top ]

replaceBlock   [line 1044]

mixed replaceBlock( string $block, string $template, [boolean $keepContent = false])

Replaces an existing block with new content.

This function will replace a block of the template and all blocks contained in it and add a new block instead. This means you can dynamically change your template.

Sigma analyses the way you've nested blocks and knows which block belongs into another block. This nesting information helps to make the API short and simple. Replacing blocks does not only mean that Sigma has to update the nesting information (relatively time consuming task) but you have to make sure that you do not get confused due to the template change yourself.


Parameters:

string   $block   —  name of a block to replace
string   $template   —  new content
boolean   $keepContent   —  true if the parsed contents of the block should be kept

[ Top ]

replaceBlockfile   [line 1077]

mixed replaceBlockfile( string $block, string $filename, [boolean $keepContent = false])

Replaces an existing block with new content from a file.

Parameters:

string   $block   —  name of a block to replace
string   $filename   —  template file that contains the block
boolean   $keepContent   —  true if the parsed contents of the block should be kept

[ Top ]

setCacheRoot   [line 447]

void setCacheRoot( string $root)

Sets the directory to cache "prepared" templates in, the directory should be writable for PHP.

The "prepared" template contains an internal representation of template structure: essentially a serialized array of $_blocks, $_blockVariables, $_children and $_functions, may also contain $_triggers. This allows to bypass expensive calls to _buildBlockVariables() and especially _buildBlocks() when reading the "prepared" template instead of the "source" one.

The files in this cache do not have any TTL and are regenerated when the source templates change.


Parameters:

string   $root   —  directory name

[ Top ]

setCallbackFunction   [line 1187]

mixed setCallbackFunction( string $tplFunction, callable $callback, [bool $preserveArgs = false])

Sets a callback function.

Sigma templates can contain simple function calls. This means that the author of the template can add a special placeholder to it:

 func_h1("embedded in h1")
Sigma will parse the template for these placeholders and will allow you to define a callback function for them. Callback will be called automatically when the block containing such function call is parse()'d.

Please note that arguments to these template functions can contain variable placeholders: func_translate('Hello, {username}'), but not blocks or other function calls.

This should NOT be used to add logic (except some presentation one) to the template. If you use a lot of such callbacks and implement business logic through them, then you're reinventing the wheel. Consider using XML/XSLT, native PHP or some other template engine.

  1.  function h_one($arg{
  2.     return '<h1>' $arg '</h1>';
  3.  }
  4.  ...
  5.  $tpl = new HTML_Template_Sigma... );
  6.  ...
  7.  $tpl->setCallbackFunction('h1''h_one');

template:

 func_h1('H1 Headline');

  • Return: SIGMA_OK on success, error object on failure
  • Throws: PEAR_Error
  • Access: public

Parameters:

string   $tplFunction   —  Function name in the template
callable   $callback   —  A callback: anything that can be passed to call_user_func_array()
bool   $preserveArgs   —  If true, then no variable substitution in arguments will take place before function call

[ Top ]

setCurrentBlock   [line 770]

mixed setCurrentBlock( [string $block = '__global__'])

Sets the name of the current block: the block where variables are added
  • Return: SIGMA_OK on success, error object on failure
  • Throws: PEAR_Error
  • Access: public

Parameters:

string   $block   —  block name

[ Top ]

setGlobalVariable   [line 747]

void setGlobalVariable( string|array $variable, [string|array $value = ''])

Sets a global variable value.

Parameters:

string|array   $variable   —  variable name or array ('varname' => 'value')
string|array   $value   —  variable value if $variable is not an array

[ Top ]

setOption   [line 476]

mixed setOption( string $option, mixed $value)

Sets the option for the template class

Currently available options:

  • preserve_data: If false (default), then substitute variables and remove empty placeholders in data passed through setVariable (see also PHP bugs #20199, #21951)
  • trim_on_save: Whether to trim extra whitespace from template on cache save (defaults to true). Generally safe to leave this on, unless you have <pre></pre> in templates or want to preserve HTML indentantion
  • charset: is used by builtin template callback 'h'/'e'. Defaults to 'iso-8859-1'

  • Return: SIGMA_OK on success, error object on failure
  • Access: public

Parameters:

string   $option   —  option name
mixed   $value   —  option value

[ Top ]

setRoot   [line 419]

void setRoot( string $root)

Sets the file root for templates. The file root gets prefixed to all filenames passed to the object.

Parameters:

string   $root   —  directory name

[ Top ]

setTemplate   [line 888]

mixed setTemplate( string $template, [boolean $removeUnknownVariables = true], [boolean $removeEmptyBlocks = true])

Sets the template.

You can either load a template file from disk with LoadTemplatefile() or set the template manually using this function.

  • Return: SIGMA_OK on success, error object on failure
  • See: loadTemplatefile()
  • Access: public

Parameters:

string   $template   —  template content
boolean   $removeUnknownVariables   —  remove unknown/unused variables?
boolean   $removeEmptyBlocks   —  remove empty blocks?

[ Top ]

setVariable   [line 723]

void setVariable( string|array $variable, [string|array $value = ''])

Sets a variable value.

The function can be used either like setVariable("varname", "value") or with one array $variables["varname"] = "value" given setVariable($variables)

If $value is an array ('key' => 'value', ...) then values from that array will be assigned to template placeholders of the form {variable.key}, ...

  • Access: public

Parameters:

string|array   $variable   —  variable name or array ('varname' => 'value')
string|array   $value   —  variable value if $variable is not an array

[ Top ]

show   [line 536]

void show( [string $block = '__global__'])

Prints a block with all replacements done.

Parameters:

string   $block   —  block name

[ Top ]

touchBlock   [line 831]

mixed touchBlock( string $block)

Preserves the block even if empty blocks should be removed.

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 show a message to the user. If it's filled you have to show the contents of the shopping basket. Now where to place the message that the basket is empty? It's not a good idea to place it in you application as customers tend to like unecessary minor text changes. Having another template file for an empty basket means that one fine day the filled and empty basket templates will have different layouts.

So blocks that do not contain any placeholders but only messages like "Your shopping basked is empty" are intoduced. 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 this you can call touchBlock()


Parameters:

string   $block   —  block name

[ Top ]


Documentation generated on Mon, 11 Mar 2019 15:56:01 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.