PHP Classes

DirecTemplate: Template engine based on regular expressions

Recommend this page to a friend!
  Info   View files View files (10)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 750 All time: 4,481 This week: 560Up
Version License Categories
directemplate 1.0GNU General Publi...Templates


This class implements a template engine that uses regular expressions to parse and process template place holder parameters.

It supports:

- Loops within template blocks iterating over multiple values of a template parameter
- Conditional template blocks
- Transform template parameters using template functions with the same names of built-in PHP functions
- Assigning parameter variables within the templates
- Displaying sets of data split in multiple pages
- Plug-ins to apply custom transformation functions
- Caching processed templates

Picture of Helmut Daschnigrum
Name: Helmut Daschnigrum <contact>
Classes: 6 packages by
Country: Canada Canada
Age: ???
All time rank: 1037 in Canada Canada
Week rank: 305 Down9 in Canada Canada Down
Innovation award
Innovation award
Nominee: 1x


DirecTemplate - Simple, efficient template system Version 1.1.7 Copyright 2003-2005, Steve Blinch ============================================================================ OVERVIEW Variables: Variables assigned with $tpl->assign("myvar","value") can be accessed as {$myvar} in templates. Loops: Loops are structured as: {loop $iterator=$myvar} This element of myvar is: {$iterator}. The key is {$_loop.key}. {/loop} This is roughly equivalent in PHP to "foreach ($myvar as $iterator)". Inside loops, the value of the current element is assigned to {$iterator}, and the {$_loop} variable contains an array of various information about the current iteration of the loop. $_loop elements include: $_loop.key (the current key in the array) $_loop.iteration (current iteration) $_loop.odd (false if iteration is evenly divisible by 2) $_loop.first (true if this is the first iteration of the loop) $_loop.last (true if this is the last iteration of the loop) Conditionals: If statements are structured in the following manner: {if $var1==$var2} var1 equals var2 {/if} {if $var1} var1 is not false, zero, or null {/if} {if $var1==$var2} var1 equals var2 {else} var1 does not equal var2 {/if} {if $var1>$var2} greater {elseif $var1<$var2} lesser {else} equal {/if} Transformations: Transformations modify the text inside their tags. They are structured in the following manner: {tranform strtoupper}this string will appear in uppercase{/transform} -or- {$variable|strtoupper} Other transformations available currently include: ucfirst Identical to PHP functions of same names strtolower strtoupper ucwords urlencode urldecode htmlentities addslashes stripslashes abs round floor ceil striptags count Returns the number of elements if variable is an array, or 0 if not an array yesno Outputs "Yes" if contents are non-null/non-zero/true, otherwise displays "No" truefalse Same as "yesno", but outputs "True" or "False" random Outputs a random number (ignores any content) vardump Outputs var_dump(variable) - use "variable", not "{$variable}"! null Null transform, displays contents unmodified noquotes Replaces all "'s with &quot;'s nbsp Replaces all spaces with &nbsp;'s nl2br Replaces all newlines with <BR>'s base64_encode BASE64-encodes the variable chr Returns the character value of an ordinal value in a variable ord Returns the ordinal value of the variable vardump Dumps the contents of {$variable} mysqldatetime Converts a string from a MySQL DATETIME field to a more presentable format. Example usage: {$timestamp|mysqltimestamp:numeric:date} Note the use of colons; full=display date/time, date=date only, time=time only, verbose=use full words, numeric=numbers only. Verbose/numeric/unix must be specified before full/date/time. (Unix returns a UNIX timestamp, regardless off full/date/time). For a date()-style formatted date, it is also possible to use: {$date_var|mysqltimestamp:formatted:M_d,_H:ia} mysqltimestamp Same as mysqldatetime, but accepts a TIMESTAMP unixtimestamp Same as mysqldatetime, but accepts a UNIX timestamp gettime Same as mysqldatetime, but works with the current time sprintf Returns the content string formatted with the specified format string, eg: {$var|"$%.2f"} performs sprintf('$%.2f',$var) substr Returns a portion of the content string, eg: {$var|substr:2} performs substr($var,2), or {$var|substr:2:5} = substr($var,2,5) contains Determines whether a substring appears in a string, eg: {$var|contains:"string"} performs strpos($var,"string")!==false) str_replace Perform a search/replace on the content string. Be sure to use quotes around string literals Example usage: {$string_var|str_replace:"%%SOMETHING%%":"Something else"} {$string_var|str_replace:"%%SOMETHING%%":$somethingelse} preg_replace Perform a regular expression search/replace on the content string. Example usage: {transform preg_replace:/beer[\.]+/:donuts!}Mmm.... beer...{/transform} Note: the regex is urldecoded before being processed. As such, if you need to use a ':' character in your regex, use '%3A' instead. If you need a '%', use '%21' instead, etc. preg_match Identical in syntax to preg_replace, except it returns 1 if the content string matched, or 0 if not. mod Performs arithmetic operations on the content variable. eg: add {$var|add:2} adds 2 to $var and returns the sum. sub mul div and or xor in_array Determines whether a content variable appears in the specified array. {$var|in_array:myarray} returns true if $var is included in $myarray. in_keys Identical in syntax to in_array - determines whether $var is a key in the specified array. in_set Determines whether a content variable appears in the list of arguments provided. {$var|in_set:1:3:5} returns true if $var is 1, 3, or 5. ellipsis Returns a the content variable truncated to the specified length, with an ellipsis appended, eg: {$var|ellipsis:8} returns "Tests..." if $var is set to "Teststring" midellipsis Returns a the content variable truncated to the specified length, with an ellipsis in the middle, and the specified number of trailing characters intact, eg: {$var|midellipsis:8:2} returns "" if $var is set to "Teststring" dateselect Returns a <SELECT> suitable for choosing a date/time value, eg: {transform dateselect}basevarname|datetime:allownull:showtime|2003-04-04 00:00:00{/transform} Then use $this->parse_date_select() in your code to parse the submitted value and obtain a UNIX timestamp. Some transformations do not operate on variables, but instead just act as function calls. These transformations may be invoked using: {$_|transformation} Non-variable transformations currently available include: range Returns an array containing the specified numeric range, eg: {$_|range:5:10} returns an array containing (5,6,7,8,9,10). Includes: Use {include "filename.tpl"/} to parse the template filename.tpl and include its output inside the current template. Assigning variables within templates: Occasionally it may be necessary to set variables from within a template, rather than from the script itself. The procedure for doing this is somewhat convoluted due to the non-linear technique that DirecTemplate uses (for the sake of speed) to parse templates. Note that you cannot set variables conditionally within an {if} or {check} clause; {set}, {postset}, and {loopset} tokens are ALWAYS processed no matter where they are placed in the code. To assign a variable from within a template, use the following syntax: {set $varname}Value for variable, {$vars} permitted{/set} Note that variables set in this manner will be set BEFORE loops are executed. Thus, any variables created or modified during a loop will NOT be accessible through {set} tags. To perform a {set} operation AFTER all loops are executed, you may use: {postset $varname}Value for variable, {$vars} permitted{/postset} This latter notation should also be used if you intend to set variables from INSIDE a loop, such that any embedded variables will be parsed after the loop has been executed. And finally, if you need to set a variable from INSIDE a loop, which will also be USED inside the loop, use: {loopset $varname}Value for variable, {$vars} permitted{/loopset} Note that variables set using this final notation will ONLY be valid within during the loop in which they were defined; before and after the loop, their values should be treated as undefined. Multiple-page result sets: DirecTemplate has internal support for displaying sets of data (eg: result sets from a database server) spanning multiple pages, with a "search engine" style set of page navigation links. To prepare the template engine, use: $tpl->prepare_multipage($pagelimit,$totalitems,$baseurl) Where $pagelimit is the maximum number of items per page, $baseurl is the total number of items available, and $baseurl is the URL to which users should be sent when they click a link. In your template, use {$_multipage.nav} to display the navigation links. Custom plug-ins, transforms, and filters: To define a custom plug-in, add it to the $tpl->plugins array as in: $tpl->plugins = array("plugin_name"=>"function_to_call"); Then define a function as in: function function_to_call($arguments) { } $arguments is an array in the format array("argumentname"=>"value"); Use as: {plugin_name argumentname=value} To define a custom transform, add it to the $tpl->transforms array as in: $tpl->transforms = array("transform_name"=>"function_to_call"); Then define a function as in: function function_to_call($data,$arguments) { } $data is the data being transformed; $arguments is a list of arguments passed with the transform. Use as: {$data|transform_name:argument:...} Alternately, transforms and plugins may be defined using the TPL_CUSTOM_TRANSFORMS and TPL_CUSTOM_PLUGINS string constants, eg: define("TPL_CUSTOM_TRANSFORMS","transform_name:function_to_call|..."); To define a custom filter, add it to the $tpl->filters array as in: $tpl->filters = array("filter_name"=>"function_to_call"); Then define a function as in: function function_to_call($data) { } $data is the final version of the page after parsing, but before being returned or displayed. Your filter function should simply return the filtered version of the data. HISTORY 1.1.7 - Variables passed to transformations are now evaluated. - Added in_set transform. - Made caching system more flexible with regard to expirations. LICENSE This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA NOTES NOTE: If you don't need the advanced features of the templating engine (conditional processing, transforms, etc.) you can disable them by uncommenting the following constants (or defining them in your apps) to improve performance of your scripts.

  Files folder image Files  
File Role Description
Files folder imageexample (2 files, 1 directory)
Plain text file class_Template.php Class Main class file
Accessible without login Plain text file LICENSE Lic. License terms
Accessible without login Plain text file plugin_countries.php Aux. Plugin for country/province lists
Accessible without login Plain text file plugin_pngtransparency.php Aux. PNG transparency plugin for IE PNG support
Accessible without login Plain text file README Doc. Documentation

  Files folder image Files  /  example  
File Role Description
Files folder imagetemplates (3 files)
  Accessible without login Plain text file example.php Example Example script
  Accessible without login Plain text file style.css Data Example script stylesheet

  Files folder image Files  /  example  /  templates  
File Role Description
  Accessible without login Plain text file footer.tpl Data Example script footer template
  Accessible without login Plain text file header.tpl Data Example script header template
  Accessible without login Plain text file order.tpl Data Example script order template

 Version Control Unique User Downloads Download Rankings  
This week:0
All time:4,481
This week:560Up