Home » HTML » HTML_Template_Sigma » Manual
HTML_Template_Sigma: implementation of Integrated Templates API with template 'compilation' added. Class Trees for HTML_Template_Sigma() PEAR HTML_Template_Sigma
Introduction - template syntax
Introduction - template syntax – Creating and editing templates
Placeholders
The default format of placeholder is
{[0-9A-Za-z_-]+}
This means, the name of the placeholder can consist of upper- and lowercase letters, numbers, underscores and hyphens. The name must be placed between curly brackets without any spaces.
Actual values for the placeholders are set using setVariable() and setGlobalVariable() methods. Placeholders for which no values were set are removed from output by default.
Blocks
The format of a block is
<!-- BEGIN [0-9A-Za-z_-]+ -->
... block content ...
<!-- END [0-9A-Za-z_-]+ -->
The rules for the block name are the same like for placeholders. In contrast to placeholders the spaces in the block markup are required.
The nesting of blocks is permitted, but be careful while parsing. You have to parse() the innermost block first and then go from inner to outer.
In Sigma the whole template itself is treated as a virtual block called
"__global__". Most block-related functions use this block
name as default.
<!-- INCLUDE --> statements
It is possible to include a template file from within another template file using an <!-- INCLUDE filename --> statement:
... some content ...
<!-- INCLUDE filename.html -->
... some more content ...
When such a template file gets loaded, the <!-- INCLUDE filename.html --> will be replaced by contents of filename.html.
Some things to note:
-
<!-- INCLUDE -->statements are only processed when loading the template files from disk. If you use setTemplate() method to set the template or addBlock() and replaceBlock() to work with its blocks, then<!-- INCLUDE -->statements in these templates will not be replaced! - Although this functionality is implemented using addBlockfile(), unlike addBlockfile() no new blocks are created in the template.
-
<!-- INCLUDE -->statements are processed before any variable substitution can take place. So<!-- INCLUDE {placeholder} -->will not work unless you actually have a file named{placeholder}and want to load it.
Template functions
Sigma templates can contain simple function calls. This means that the author of the template can add a special placeholder to it
... some content ...
func_h1("embedded in h1")
... some more content ...
Sigma will parse the template for these placeholders and will allow you to define a callback function for them via setCallbackFunction(). Callback will be called automatically when the block containing such function call is parse()'d.
Format of such function name is as follows
func_[_a-zA-Z]+[A-Za-z_0-9]*
that means that it should start with a 'func_' prefix, then has a letter or an undercore and then a sequence of letters, digits or underscores. Arguments to these template functions can contain variable placeholders
func_translate('Hello, {username}')
but not blocks or other function calls.
Quoting of template function arguments
The information in this section applies to HTML_Template_Sigma version 1.1.2 and later, please upgrade if you have problems with template function arguments in previous versions.
Quoting of function arguments is not mandatory, the following is a perfectly valid template function:
func_uppercase(Some unquoted text)
But consider the following: function arguments are contained within
parentheses and separated by commas. Therefore if closing parenthesis
')' or comma ','
appears in function argument, it should be quoted.
The next thing to consider is that HTML_Template_Sigma is mostly targeted for generating HTML. Therefore a quoted string within an argument is most probably a tag attribute. The contents of such strings are not parsed for commas and parentheses. Therefore the following is also a perfectly valid template function:
func_foo(<a href="javascript:foo(bar, baz)">Do foo</a>)
But if you have an unmatched single or double quote in your argument or if the argument starts with a quote, it should be quoted.
Finally, the argument should be quoted if it is an empty string or if its leading or trailing whitespace is significant (leading and trailing whitespace will be removed from unquoted arguments).
The arguments can be quoted using either single or double quotes. If an
argument contains a quote of the same type, then it should be escaped using
the backslash symbol '\'. The backslash symbol
itself should also be escaped,
func_foo('O\'really')
func_foo('AC\\DC')
will pass O'really and AC\DC to
the relevant callbacks.
Valid and invalid template function arguments
Valid arguments:
func_foo(Some unquoted text)
func_foo("Some quoted text")
func_foo(<a href="javascript:foo(bar, baz)">Do foo</a>)
func_foo('O\'really')
func_foo('AC\\DC')
Invalid arguments:
func_foo(Hello, {username}) contains a comma, will yield two arguments instead of one
func_foo(O'really) unmatched single quote
func_foo('O'really') unescaped single quote
func_foo(, 'whatever') empty arguments should be quoted
Shorthand for template functions
Since release 1.1.0, instead of using
func_callback({var})
you can write
{var:callback}
There are 3 automatically registered template functions
- 'h' for htmlspecialchars()
- 'e' for htmlentities() (available since release 1.2.0)
- 'u' for urlencode()
- 'r' for rawurlencode() (available since release 1.2.0)
- 'j' for a method of Sigma that escapes the string for usage in Javascript string constants.
Thus, if you add {var:h} placeholder to the template, var will be have unsafe characters replaced by corresponding HTML entitites.
Since release 1.2.0 it is possible to provide the charset parameter for 'h' and 'e' callbacks via setOption().
Template comments
Since release 1.2.0 it is possible to add comments to the template file:
<!-- COMMENT -->
Some text here
<!-- /COMMENT -->
These comments will be removed from the output, unlike standard HTML comments.
Customizing the template syntax
It is possible to somewhat customize the syntax of templates by changing regular expressions (or their parts) used by Sigma for parsing.
The actual regular expressions used to parse templates are generated in constructor using parts specified as class properties. It is generally not safe to change the generated regular expressions (as their format is hardcoded in several places throughout Sigma), but you can override the properties:
- $openingDelimiter
- Start of variable placeholder, defaults to
'{'
- $closingDelimiter
- Start of variable placeholder, defaults to
'}'
- $blocknameRegExp
- Regular expression part for block names, defaults to
'[0-9A-Za-z_-]+'
- $variablenameRegExp
- Regular expression part for placeholder names, defaults to
'[0-9A-Za-z._-]+'
- $functionnameRegExp
- Regular expression part for function names, defaults to
'[_a-zA-Z][A-Za-z_0-9]*'
- $includeRegExp
- Complete regular expression for processing file inclusion, defaults to
'#<!--\s+INCLUDE\s+(\S+)\s+-->#im'
- $commentRegExp
- Complete regular expression for removing template comments, defaults to
'#<!--\s+COMMENT\s+-->.*?<!--\s+/COMMENT\s+-->#sm'
To customize some of the above parts you need to subclass
HTML_Template_Sigma and override the relevant properties
so that generated regular expressions will use the new parts. For example,
if you want to prevent Sigma treating {1} (which may appear
as a part of Javascript regular expression) as a placeholder (see
bug #18147)
you can do the following
<?php
class SanerPlaceholders extends HTML_Template_Sigma
{
var $variablenameRegExp = '[A-Za-z_][0-9A-Za-z._-]*';
}
$tpl = new SanerPlaceholders();
$tpl->setTemplate('{foo} {1} {bar}');
$tpl->setVariable('foo', 'foo value');
$tpl->show();
?>
Usage Example
Other usage examples
There are several usage examples in the package archive that cover most of its functionality. You are encouraged to review them along with the docs.
The table.html template file
<html>
<body>
<table cellpadding="2" cellspacing="0" border="1">
<!-- INCLUDE table_header.html -->
<!-- BEGIN table_row -->
<tr>
<td bgcolor="func_bgcolor('#CCCCCC', '#F0F0F0')">{first_name}</td>
<td bgcolor="func_bgcolor('#CCCCCC', '#F0F0F0')">{last_name}</td>
</tr>
<!-- END table_row -->
</table>
</body>
</html>
The table_header.html template file
<!-- COMMENT -->
This text will not appear in output.
<!-- /COMMENT -->
<tr>
<th>First name</th>
<th>Last name</th>
</tr>
The script
<?php
require_once 'HTML/Template/Sigma.php';
function toggle($item1, $item2)
{
static $i = 1;
return $i++ % 2? $item1: $item2;
}
$data = array (
array("Stig", "Bakken"),
array("Martin", "Jansen"),
array("Alexander", "Merz")
);
$tpl =& new HTML_Template_Sigma('.');
$tpl->loadTemplateFile('table.html');
$tpl->setCallbackFunction('bgcolor', 'toggle');
foreach ($data as $name) {
// assign data
$tpl->setVariable(array(
'first_name' => $name[0],
'last_name' => $name[1]
));
// process the block
$tpl->parse('table_row');
}
// print out the output
$tpl->show();
?>
The output
<html>
<body>
<table cellpadding="2" cellspacing="0" border="1">
<tr>
<th>First name</th>
<th>Last name</th>
</tr>
<tr>
<td bgcolor="#CCCCCC">Stig</td>
<td bgcolor="#CCCCCC">Bakken</td>
</tr>
<tr>
<td bgcolor="#F0F0F0">Martin</td>
<td bgcolor="#F0F0F0">Jansen</td>
</tr>
<tr>
<td bgcolor="#CCCCCC">Alexander</td>
<td bgcolor="#CCCCCC">Merz</td>
</tr>
</table>
</body>
</html>
Introduction - cache
Introduction - cache – How Sigma caches the "prepared" templates
Cache FAQ
- What exactly is this cache feature?
- What about data?
- Is the cached version regenerated when the template changes?
- Is there any TTL setting?
- Any way to flush the cache?
- Does this give significant performance gains?
- What exactly is this cache feature?
-
This is the way to bypass RegExp parsing on template load. Instead of parsing the original template on every request, we keep its internal representation (a serialized array, essentially) and load it instead.
-
Think about template compilation in Smarty. Only Sigma does not compile templates to PHP code.
- What about data?
-
No data caching is taking place. If you want to do this, consider using some of the PEAR's cache packages.
- Is the cached version regenerated when the template changes?
-
Yes.
- Is there any TTL setting?
-
No. Cached version is considered valid until the source template changes.
- Any way to flush the cache?
-
Yes, just delete all the files in the cache dir.
- Does this give significant performance gains?
-
Yes. The answer is based on personal experience.
-
If you are going to perform some benchmarks, then use some real-world complex templates, not artificial ones. The performance gain will be greater with bigger and more complex (dozens of blocks) ones.
Cache usage
Caching is completely transparent. To take advantage of this feature you only have to either pass a second parameter to the constructor or call a setCacheRoot() method later.
<?php
require_once 'HTML/Template/Sigma.php';
$tpl =& new HTML_Template_Sigma('./templates', './templates/prepared');
$tpl->loadTemplateFile('default.html');
// go on
?>
For each distinct template file in ./templates loaded with either loadTemplatefile(), addBlockfile(), replaceBlockfile() or <!-- INCLUDE --> a prepared version will be generated in ./templates/prepared.
constructor HTML_Template_Sigma()
constructor HTML_Template_Sigma() – constructor
Synopsis
require_once 'HTML/Template/Sigma.php';
void HTML_Template_Sigma::HTML_Template_Sigma (
string $root = ''
, string $cacheRoot = ''
)
Description
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.
Parameter
-
string
$root -
root directory for templates
-
string
$cacheRoot -
directory to cache "prepared" templates in
Throws
throws no exceptions thrown
See
see HTML_Template_Sigma::setRoot(), HTML_Template_Sigma::setCacheRoot()
Note
This function can not be called statically.
addBlock()
addBlock() – Adds a block to the template
Synopsis
require_once 'HTML/Template/Sigma.php';
mixed HTML_Template_Sigma::addBlock (
string $placeholder
, string $block
, string $template
)
Description
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.
Parameter
-
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
Return value
return SIGMA_OK on success, error object on failure
See
see HTML_Template_Sigma::addBlockfile()
Throws
| Error code | Error message | Reason | Solution |
|---|---|---|---|
| SIGMA_BLOCK_EXISTS | Block '$block' already exists |
Tried to add a block with a name that is already present in the template | Choose a different name for a new block |
| SIGMA_PLACEHOLDER_NOT_FOUND | Variable placeholder '$placeholder' not found |
There is no placeholder to replace by a new block in the template | Check the spelling of the placeholder name |
| SIGMA_PLACEHOLDER_DUPLICATE | Placeholder '$placeholder' should be unique, found in multiple blocks |
A placeholder to be replaced by a new block should appear only in one place | Check the spelling of the placeholder name, choose a different placeholder |
| SIGMA_BLOCK_DUPLICATE | The name of a block must be unique within a template. Block 'blockname' found twice. | The added block contains a subblock that has the same name as the existing one | Check the $template and rename the block to something else |
| SIGMA_CALLBACK_SYNTAX_ERROR | Cannot parse template function: (error description) | Bogus syntax for template function parameters. | Fix the template function definition, pay special attention to quoting rules. |
Note
This function can not be called statically.
addBlockfile()
addBlockfile() – Adds a block contained in the file to the template
Synopsis
require_once 'HTML/Template/Sigma.php';
mixed HTML_Template_Sigma::addBlockfile (
string $placeholder
, string $block
, string $filename
)
Description
Adds a block taken from a file to the template, changing a variable placeholder to a block placeholder.
Parameter
-
string
$placeholder -
name of the variable placeholder
-
string
$block -
name of the block to be added
-
string
$filename -
template file that contains the block
Return value
return SIGMA_OK on success, error object on failure
See
see HTML_Template_Sigma::addBlock()
Throws
| Error code | Error message | Reason | Solution |
|---|---|---|---|
| SIGMA_BLOCK_EXISTS | Block '$block' already exists |
Tried to add a block with a name that is already present in the template | Choose a different name for a new block |
| SIGMA_PLACEHOLDER_NOT_FOUND | Variable placeholder '$placeholder' not found |
There is no placeholder to replace by a new block in the template | Check the spelling of the placeholder name |
| SIGMA_PLACEHOLDER_DUPLICATE | Placeholder '$placeholder' should be unique, found in multiple blocks |
A placeholder to be replaced by a new block should appear only in one place | Check the spelling of the placeholder name, choose a different placeholder |
| SIGMA_TPL_NOT_FOUND | Cannot read the template file '$filename' |
File is unreadable for some reason | Check if the file exists and has correct permissions set |
| SIGMA_CACHE_ERROR | Cannot save template file 'filename' | A prepared template file cannot be saved | Check if the directory for prepared templates cache exists and is writeable for your script |
| SIGMA_BLOCK_DUPLICATE | The name of a block must be unique within a template. Block 'blockname' found twice. | The added file contains a block that has the same name as the existing one | Check the file and rename the block to something else |
| SIGMA_CALLBACK_SYNTAX_ERROR | Cannot parse template function: (error description) | Bogus syntax for template function parameters. | Fix the template function definition, pay special attention to quoting rules. |
Note
This function can not be called statically.
blockExists()
blockExists() – Checks if the block exists in the template
Synopsis
require_once 'HTML/Template/Sigma.php';
bool HTML_Template_Sigma::blockExists (
string $block
)
Description
Checks if the block exists in the template
Parameter
-
string
$block -
block name
Throws
throws no exceptions thrown
Note
This function can not be called statically.
clearVariables()
clearVariables() – Clears the variables
Synopsis
require_once 'HTML/Template/Sigma.php';
void HTML_Template_Sigma::clearVariables (
void
)
Description
Global variables are not affected, only the ones set via setVariable(). 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.
Throws
throws no exceptions thrown
Note
This function can not be called statically.
errorMessage()
errorMessage() – Returns a textual error message for an error code
Synopsis
require_once 'HTML/Template/Sigma.php';
string HTML_Template_Sigma::errorMessage (
integer $code
, string $data
= null
)
Description
Returns a textual error message for an error code. This is usually called when throwing a error, there is seldom need to call this method directly.
Parameter
-
integer
$code -
error code
-
string
$data -
additional data to insert into message
Return value
return error message
Throws
throws no exceptions thrown
Note
This function can not be called statically.
get()
get() – Returns a block with all replacements done.
Synopsis
require_once 'HTML/Template/Sigma.php';
string HTML_Template_Sigma::get (
string $block = '__global__'
, bool $clear
= false
)
Description
Returns a parsed block: block with all replacements done.
This method will automatically call parse(), only if called with $block='__global__' when '__global__' was not parse()'d before. In all other cases you should call parse() before calling get()
Parameter
-
string
$block -
block name
-
boolean
$clear -
whether to clear parsed block contents
Return value
return block with all replacements done
See
see HTML_Template_Sigma::show()
Throws
| Error code | Error message | Reason | Solution |
|---|---|---|---|
| SIGMA_BLOCK_NOT_FOUND | Cannot find block '$block' |
There is no block $block in the template |
Check the block name spelling, check whether you added all the necessary blocks to the template |
Note
This function can not be called statically.
getBlockList()
getBlockList() – Returns a list of blocks within a template.
Synopsis
require_once 'HTML/Template/Sigma.php';
array HTML_Template_Sigma::getBlockList (
string $parent = '__global__'
, bool $recursive
= false
)
Description
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.
Parameter
-
string
$parent -
parent block name
-
boolean
$recursive -
whether to return a tree of child blocks (TRUE) or a 'flat' array (FALSE)
Return value
return a list of child blocks
See
see HTML_Template_Sigma::blockExists(), HTML_Template_Sigma::getPlaceholderList()
Throws
| Error code | Error message | Reason | Solution |
|---|---|---|---|
| SIGMA_BLOCK_NOT_FOUND | Cannot find block '$parent' |
There is no block $parent in the template |
Check the block name spelling, check whether you added all the necessary blocks to the template |
Note
This function can not be called statically.
getCurrentBlock()
getCurrentBlock() – Returns the current block name
Synopsis
require_once 'HTML/Template/Sigma.php';
string HTML_Template_Sigma::getCurrentBlock (
void
)
Description
Returns the current block name (set by HTML_Template_Sigma::setCurrentBlock())
Return value
return block name
Throws
throws no exceptions thrown
Note
This function can not be called statically.
getPlaceholderList()
getPlaceholderList() – Returns a list of placeholders within a block.
Synopsis
require_once 'HTML/Template/Sigma.php';
array HTML_Template_Sigma::getPlaceholderList (
string $block = '__global__'
)
Description
Returns a list of placeholders within a block.
Only 'normal' placeholders are in the list, not ones automatically created for blocks and template functions.
Parameter
-
string
$block -
block name
Return value
return a list of placeholders
See
see HTML_Template_Sigma::placeholderExists(), HTML_Template_Sigma::getBlockList()
Throws
| Error code | Error message | Reason | Solution |
|---|---|---|---|
| SIGMA_BLOCK_NOT_FOUND | Cannot find block '$block' |
There is no block $block in the template |
Check the block name spelling, check whether you added all the necessary blocks to the template |
Note
This function can not be called statically.
hideBlock()
hideBlock() – Hides the block even if it is not "empty".
Synopsis
require_once 'HTML/Template/Sigma.php';
mixed HTML_Template_Sigma::hideBlock (
string $block
)
Description
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()
Parameter
-
string
$block -
block name
Return value
return SIGMA_OK on success, error object on failure
Throws
| Error code | Error message | Reason | Solution |
|---|---|---|---|
| SIGMA_BLOCK_NOT_FOUND | Cannot find block '$block' |
There is no block $block in the template |
Check the block name spelling, check whether you added all the necessary blocks to the template |
Note
This function can not be called statically.
loadTemplateFile()
loadTemplateFile() – Loads a template file.
Synopsis
require_once 'HTML/Template/Sigma.php';
mixed HTML_Template_Sigma::loadTemplateFile (
string $filename
, boolean $removeUnknownVariables
= true
, boolean $removeEmptyBlocks
= true
)
Description
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.
Parameter
-
string
$filename -
filename
-
boolean
$removeUnknownVariables -
remove unknown/unused variables?
-
boolean
$removeEmptyBlocks -
remove empty blocks?
Return value
return SIGMA_OK on success, error object on failure
Throws
| Error code | Error message | Reason | Solution |
|---|---|---|---|
| SIGMA_TPL_NOT_FOUND | Cannot read the template file '$filename' |
File is unreadable for some reason | Check if the file exists and has correct permissions set |
| SIGMA_CACHE_ERROR | Cannot save template file 'filename' | A prepared template file cannot be saved | Check if the directory for prepared templates cache exists and is writeable for your script |
| SIGMA_BLOCK_DUPLICATE | The name of a block must be unique within a template. Block 'blockname' found twice. | The loaded file contains two blocks sharing the same name | Check the file and rename one of the blocks to something else |
| SIGMA_CALLBACK_SYNTAX_ERROR | Cannot parse template function: (error description) | Bogus syntax for template function parameters. | Fix the template function definition, pay special attention to quoting rules. |
See
see HTML_Template_Sigma::setTemplate(), HTML_Template_Sigma::$removeUnknownVariables, HTML_Template_Sigma::$removeEmptyBlocks
Note
This function can not be called statically.
parse()
parse() – Parses the given block.
Synopsis
require_once 'HTML/Template/Sigma.php';
void HTML_Template_Sigma::parse (
string $block = '__global__'
, boolean $flagRecursion
= false
, boolean $fakeParse
= false
)
Description
Parses the given block. It substitutes local and global variables appearing in the block and set via setVariable() and setGlobalVariable(), calls all the callback functions and recursively processes the subblocks of the block.
Parameter
-
string
$block -
block name
-
boolean
$flagRecursion -
TRUE if the function is called recursively (do not set this to TRUE yourself!)
-
boolean
$fakeParse -
TRUE if parsing a "hidden" block (do not set this to TRUE yourself!)
Throws
| Error code | Error message | Reason | Solution |
|---|---|---|---|
| SIGMA_BLOCK_NOT_FOUND | Cannot find block '$block' |
There is no block $block in the template |
Check the block name spelling, check whether you added all the necessary blocks to the template |
See
see HTML_Template_Sigma::parseCurrentBlock()
Note
This function can not be called statically.
parseCurrentBlock()
parseCurrentBlock() – Parses the current block
Synopsis
require_once 'HTML/Template/Sigma.php';
void HTML_Template_Sigma::parseCurrentBlock (
void
)
Description
Parses the current block (set by HTML_Template_Sigma::setCurrentBlock())
Throws
throws no exceptions thrown
See
see HTML_Template_Sigma::parse(), HTML_Template_Sigma::setCurrentBlock()
Note
This function can not be called statically.
placeholderExists()
placeholderExists() – Checks whether the placeholder exists
Synopsis
require_once 'HTML/Template/Sigma.php';
string HTML_Template_Sigma::placeholderExists (
string $placeholder
, string $block = ''
)
Description
Checks whether the placeholder exists in the template, returns the name of the (first) block that contains the specified placeholder.
Parameter
-
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.
Return value
return Name of the (first) block that contains the specified placeholder. If the placeholder was not found an empty string is returned.
Throws
| Error code | Error message | Reason | Solution |
|---|---|---|---|
| SIGMA_BLOCK_NOT_FOUND | Cannot find block '$block' |
There is no block $block in the template |
Check the block name spelling, check whether you added all the necessary blocks to the template |
Note
This function can not be called statically.
replaceBlock()
replaceBlock() – Replaces an existing block with new content.
Synopsis
require_once 'HTML/Template/Sigma.php';
mixed HTML_Template_Sigma::replaceBlock (
string $block
, string $template
, boolean $keepContent
= false
)
Description
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.
Parameter
-
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
Return value
return SIGMA_OK on success, error object on failure
Throws
| Error code | Error message | Reason | Solution |
|---|---|---|---|
| SIGMA_BLOCK_NOT_FOUND | Cannot find block '$block' |
There is no block $block in the template |
Check the block name spelling, check whether you added all the necessary blocks to the template |
| SIGMA_BLOCK_DUPLICATE | The name of a block must be unique within a template. Block 'blockname' found twice. | The new block contains a subblock that has the same name as the existing one | Check the $template and rename the block to something else |
| SIGMA_CALLBACK_SYNTAX_ERROR | Cannot parse template function: (error description) | Bogus syntax for template function parameters. | Fix the template function definition, pay special attention to quoting rules. |
See
see HTML_Template_Sigma::replaceBlockfile(), HTML_Template_Sigma::addBlock()
Note
This function can not be called statically.
replaceBlockfile()
replaceBlockfile() – Replaces an existing block with new content from a file.
Synopsis
require_once 'HTML/Template/Sigma.php';
mixed HTML_Template_Sigma::replaceBlockfile (
string $block
, string $filename
, boolean $keepContent
= false
)
Description
Replaces an existing block with new content from a file.
Parameter
-
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
Return value
return SIGMA_OK on success, error object on failure
See
see HTML_Template_Sigma::replaceBlock(), HTML_Template_Sigma::addBlockfile()
Throws
| Error code | Error message | Reason | Solution |
|---|---|---|---|
| SIGMA_BLOCK_NOT_FOUND | Cannot find block '$block' |
There is no block $block in the template |
Check the block name spelling, check whether you added all the necessary blocks to the template |
| SIGMA_BLOCK_DUPLICATE | The name of a block must be unique within a template. Block 'blockname' found twice. | The loaded block contains a subblock that has the same name as the existing one | Check the file contents and rename the block to something else |
| SIGMA_TPL_NOT_FOUND | Cannot read the template file '$filename' |
File is unreadable for some reason | Check if the file exists and has correct permissions set |
| SIGMA_CACHE_ERROR | Cannot save template file 'filename' | A prepared template file cannot be saved | Check if the directory for prepared templates cache exists and is writeable for your script |
| SIGMA_CALLBACK_SYNTAX_ERROR | Cannot parse template function: (error description) | Bogus syntax for template function parameters. | Fix the template function definition, pay special attention to quoting rules. |
Note
This function can not be called statically.
setCacheRoot()
setCacheRoot() – Sets the directory to cache "prepared" templates in.
Synopsis
require_once 'HTML/Template/Sigma.php';
void HTML_Template_Sigma::setCacheRoot (
string $root
)
Description
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 HTML_Template_Sigma::_buildBlockVariables() and especially HTML_Template_Sigma::_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.
Parameter
-
string
$root -
directory name
Throws
throws no exceptions thrown
See
see HTML_Template_Sigma::HTML_Template_Sigma()
Note
This function can not be called statically.
setCallbackFunction()
setCallbackFunction() – Sets a callback function.
Synopsis
require_once 'HTML/Template/Sigma.php';
mixed HTML_Template_Sigma::setCallbackFunction (
string $tplFunction
, mixed $callback
, bool $preserveArgs
= false
)
Description
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.
Script:
<?php
function h_one($arg)
{
return '<h1>' . $arg . '</h1>';
}
// ...
$tpl = new HTML_Template_Sigma(' ... ');
// ...
$tpl->setCallbackFunction('h1', 'h_one');
// ...
$tpl->show()
?>template:
...
func_h1('H1 Headline')
...
Parameter
-
string
$tplFunction -
Function name in the template
-
mixed
$callback -
A callback: anything that can be passed to call_user_func_array()
-
boolean
$preserveArgs -
If TRUE, then no variable substitution in arguments will take place before function call
Return value
return SIGMA_OK on success, error object on failure
Throws
| Error code | Error message | Reason | Solution |
|---|---|---|---|
| SIGMA_INVALID_CALLBACK | Callback does not exist | The $callback is not an existing function or method |
Check spelling, check whether the object was correctly instantiated if using the method callback |
Note
This function can not be called statically.
setCurrentBlock()
setCurrentBlock() – Sets the name of the current block.
Synopsis
require_once 'HTML/Template/Sigma.php';
mixed HTML_Template_Sigma::setCurrentBlock (
string $block = '__global__'
)
Description
Sets the name of the current block: the one in which variables will be substituted.
Parameter
-
string
$block -
block name
Return value
return SIGMA_OK on success, error object on failure
Throws
| Error code | Error message | Reason | Solution |
|---|---|---|---|
| SIGMA_BLOCK_NOT_FOUND | Cannot find block '$block' |
There is no block $block in the template |
Check the block name spelling, check whether you added all the necessary blocks to the template |
Note
This function can not be called statically.
setGlobalVariable()
setGlobalVariable() – Sets a global variable value.
Synopsis
require_once 'HTML/Template/Sigma.php';
void HTML_Template_Sigma::setGlobalVariable (
mixed $variable
, string $value = ''
)
Description
Sets a global variable value. Global variables are "special": they do not get cleared after substitution and do not make blocks not empty if substituted.
Parameter
-
mixed
$variable -
variable name or array ('varname'=>'value')
-
string
$value -
variable value if $variable is not an array
Throws
throws no exceptions thrown
See
see HTML_Template_Sigma::setVariable()
Note
This function can not be called statically.
setOption()
setOption() – Sets the option for the template class
Synopsis
require_once 'HTML/Template/Sigma.php';
mixed HTML_Template_Sigma::setOption (
string $option
, mixed $value
)
Description
Sets the option for the template class. Currently it understands the following options:
- preserve_data
-
If set to TRUE, then do not substitute variables and remove unused placeholders in data added through setVariable() and setGlobalVariable(). See also bugs #20199 and #21951. Default is FALSE, for performance reasons.
- trim_on_save
-
Whether to trim extra whitespace from template on cache save. Generally safe to have this on, unless you have <pre></pre> in templates or want to preserve HTML indentantion. Default is TRUE
- charset
-
Character set to use by builtin 'h' and 'e' callbacks. Default is
'iso-8859-1'. Available since release 1.2.0
Parameter
-
string
$option -
option name
-
mixed
$value -
option value
Return value
return SIGMA_OK on success, error object on failure
Throws
| Error code | Error message | Reason | Solution |
|---|---|---|---|
| SIGMA_UNKNOWN_OPTION | Unknown option '$option' |
$option is not known to Sigma |
Check the option name spelling |
Note
This function can not be called statically.
setRoot()
setRoot() – Sets the file root for templates.
Synopsis
require_once 'HTML/Template/Sigma.php';
void HTML_Template_Sigma::setRoot (
string $root
)
Description
Sets the file root for templates. The file root gets prefixed to all filenames passed to the object.
Parameter
-
string
$root -
directory name
Throws
throws no exceptions thrown
See
see HTML_Template_Sigma::HTML_Template_Sigma()
Note
This function can not be called statically.
setTemplate()
setTemplate() – Sets the template.
Synopsis
require_once 'HTML/Template/Sigma.php';
mixed HTML_Template_Sigma::setTemplate (
string $template
, boolean $removeUnknownVariables
= true
, boolean $removeEmptyBlocks
= true
)
Description
Sets the template. You can either load a template file from disk with loadTemplateFile() or set the template manually using this function.
Parameter
-
string
$template -
template content
-
boolean
$removeUnknownVariables -
remove unknown/unused variables?
-
boolean
$removeEmptyBlocks -
remove empty blocks?
Return value
return SIGMA_OK on success, error object on failure
Throws
| Error code | Error message | Reason | Solution |
|---|---|---|---|
| SIGMA_BLOCK_DUPLICATE | The name of a block must be unique within a template. Block 'blockname' found twice. | The $template contains two blocks sharing the same name |
Check the $template and rename one of the blocks to something else |
| SIGMA_CALLBACK_SYNTAX_ERROR | Cannot parse template function: (error description) | Bogus syntax for template function parameters. | Fix the template function definition, pay special attention to quoting rules. |
See
see HTML_Template_Sigma::loadTemplateFile()
Note
This function can not be called statically.
setVariable()
setVariable() – Sets a variable value.
Synopsis
require_once 'HTML/Template/Sigma.php';
void HTML_Template_Sigma::setVariable (
mixed $variable
, string $value = ''
)
Description
Sets a variable value. The function can be used either like setVariable("varname", "value") or with one array $variables["varname"] = "value" given setVariable($variables)
Parameter
-
mixed
$variable -
variable name or array ('varname'=>'value')
-
string
$value -
variable value if
$variableis not an array
Throws
throws no exceptions thrown
Note
This function can not be called statically.
show()
show() – Prints a block with all replacements done.
Synopsis
require_once 'HTML/Template/Sigma.php';
void HTML_Template_Sigma::show (
string $block = '__global__'
)
Description
Prints a block with all replacements done.
Parameter
-
string
$block -
block name
Throws
throws no exceptions thrown
See
see HTML_Template_Sigma::get()
Note
This function can not be called statically.
touchBlock()
touchBlock() – Preserves the block even if empty blocks should be removed.
Synopsis
require_once 'HTML/Template/Sigma.php';
mixed HTML_Template_Sigma::touchBlock (
string $block
)
Description
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 introduced. 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()
Parameter
-
string
$block -
block name
Return value
return SIGMA_OK on success, error object on failure
See
see HTML_Template_Sigma::$removeEmptyBlocks
Throws
| Error code | Error message | Reason | Solution |
|---|---|---|---|
| SIGMA_BLOCK_NOT_FOUND | Cannot find block '$block' |
There is no block $block in the template |
Check the block name spelling, check whether you added all the necessary blocks to the template |
Note
This function can not be called statically.