vlibTemplate documentation

Author: Kelvin Jones and Claus van Beek

Wiki: vLIB Wiki

German: vLIB website

Forum: vLIB support

Name: vlibTemplate

Package: vLIB


vLIB logo vlibTemplate documentation

Table of Contents
1. Synopsis
2. Description
3. Motivation
4. The Tags
4.1. TMPL_VAR name='VARNAME'
4.2. TMPL_LOOP name='LOOP_NAME'
4.3. TMPL_INCLUDE name='filename.html'
4.4. TMPL_PHPINCLUDE name='filename.html'
4.5. TMPL_[ELSE]IF name='BOOL'
4.6. TMPL_ELSE
4.7. TMPL_UNLESS name='BOOL'
5. vlibTemplate
5.1. vlibTemplate()
5.2. newTemplate()
5.3. setVar()
5.4. unsetVar()
5.5. getVars()
5.6. getVar()
5.7. setContextVars()
5.8. setLoop()
5.9. setDbLoop()
5.10. newLoop()
5.11. addRow()
5.12. addLoop()
5.13. getLoop()
5.14. unsetLoop()
5.15. reset()
5.16. clearVars()
5.17. clearLoops()
5.18. clearAll()
5.19. unknownsExist()
5.20. unknowns()
5.21. getUnknowns()
5.22. setUnknowns()
5.23. setPath()
5.24. getParseTime()
5.25. fastPrint()
5.26. pparse()
5.27. pprint()
5.28. grab()
6. vlibTemplateDebug
7. vlibTemplateCache
7.1. clearCache()
7.2. recache()
7.3. setCacheLifeTime()
7.4. setCacheExtension()
8. Options
9. Security
10. Bugs
11. Credits
12. Download
13. License
14. Install
15. Forum
16. Documentation In Other Lanuages

1.  Synopsis 

First of all you make a Template file. This is a normal HTML file with extra vlibTemplate markup tags.

For example, food.htm:

Example

  <HTML>

  <HEAD><TITLE>My Favourite Food</TITLE>

  <BODY>

  My favourite dish is <TMPL_VAR NAME="FAV1">,

  but I also like <TMPL_VAR NAME="FAV2">.

  </BODY>

  </HTML>


And now create this php script:

Example

  // include the vlibTemplate class
  include('vLIB/vlibTemplate.php');

  // make $tmpl an object of vlibTemplate
  $tmpl = new vlibTemplate('food.htm');

  // set the variables
  $tmpl->setVar('FAV1', 'Fish and Chips');
  $tmpl->setVar('FAV2', 'fajitas');

  // print the template
  $tmpl->pparse();


If everything goes well you should see the following in your browser:

My favourite dish is Fish and Chips, but I also like fajitas.


2.  Description 

vlibTemplate is a php class that is intended to make splitting PHP from HTML a simple and natural task. It makes use of the following vlibTemplate markup tags (like html tags); <tmpl_var>, <tmpl_loop>, <tmpl_include>, <tmpl_phpinclude>, <tmpl_comment>, <tmpl_if>, <tmpl_elseif>, <tmpl_else>, <tmpl_unless>, <tmpl_endloop>, <tmpl_endcomment>, <tmpl_endif> and <tmpl_endunless>.
The file written with these style tags is called a template. A template can be an HTML file to use on the web, or perhaps a text file to use as an e-mail template... as you can guess there are many many possibilities. The template file is always seperate from the php script that uses it, that way, a designer for example can change the template file without having to go through all of the php coding, thus saving the developer having to worry about it.
Using this class you set the values for the variables, loops, if statements ..etc which are declared in the template. This enables you to seperate all of the design from the data, which you create using PHP.

vlibTemplate has three user accessible classes. vlibTemplate, vlibTemplateDebug and vlibTemplateCache. vlibTemplate is the main class which handles all of the passing and has the majority of the functions. vlibTemplateDebug and vlibTemplateCache both extend vlibTemplate and inherit it's functionality.
You can therefore change the functionality of vlibTemplate just by appending Debug or Cache.
The debug class requires no parametres to be set, it prints out the vlibTemplate debug module with debug data for the current page. The cache class has a few extra functions that are utilisable, the class saves the parsed file into the filesystem to allow much faster page accesses and a faster site.
All are described in the following sections.


3.  Motivation 

Whilst there are quite a few php template classes out there, few of them support the basic features that are needed to develop full scale applications, like if constructs, loops (known as blocks in other template classes) and the ability to include other template files using a simple html-esque tag.

Any template classes that I've come across have been either lacking in features, or if they did have the features worth using, the syntax was too complicated and not intuitive enough.

This is why vlibTemplate came into being, and why it's more usable than any template system already out there. It has all of the features that you'll need to efficiently seperate your php and html (or whatever else), and it does it in an intuitive manner. It's also extremely quick, as it compiles the template into native php code using using just one pcre call.


4.  Tags 

Note: even though these tags look like HTML they are a little different as they're allowed to "break the rules".
Something like:

Example

  <IMG SRC="<TMPL_VAR NAME=IMAGE_SRC>">


is not really valid HTML, but it is a perfectly valid use and will work as planned.

The "NAME=" in the tag is optional, although for extensibility's sake I recommend using it. Example - "<TMPL_LOOP LOOP_NAME>" is acceptable.

The "TMPL_" bit of the tag is also optional, and can be omitted if you prefer to use the shorter versions, i.e.: <LOOP name="LOOP_NAME">.

If you're a fanatic about valid HTML and would like your templates to conform to valid HTML syntax, you may optionally type template tags in the form of HTML comments. This may be of use to HTML authors who would like to validate their templates' HTML syntax prior to vlibTemplate parsing, or who use DTD-savvy editing tools.

Example

  <!-- TMPL_VAR NAME=PARAM1 -->


You can also use a curly bracket syntax '{tmpl_var}' for use within comments (as to not break them with the comment style tag), or within html tags (as to not break the tag in your editor).

Example

  {TMPL_VAR NAME=PARAM1}





4.1.TMPL_VAR name='VARNAME'
4.2.TMPL_LOOP name='LOOP_NAME'
4.3.TMPL_INCLUDE name='filename.html'
4.4.TMPL_PHPINCLUDE name='filename.html'
4.5.TMPL_[ELSE]IF name='BOOL'
4.6.TMPL_ELSE
4.7.TMPL_UNLESS name='BOOL'

4.1.  <TMPL_VAR name='VARNAME'> 

The <TMPL_VAR> tag is very simple. For each <TMPL_VAR> tag in the template you call $tmpl->setvar('VARNAME', "VALUE").

When the template is output the <TMPL_VAR> is replaced with the VALUE text you specified.

Optionally there are 2 more attributes that you can add to this tag:

1) Escape .. value may be:

i) html -> html escapes the variable, i.e. exchanging '<' with '&lt;' , '>' with '&gt;' and '&' with '&amp;'.

ii) url -> url escpaes the string, i.e. exchanging ' ' with '+' and '/' with '%2F.

iii) sq -> escapes single quotes within a string, i.e. "I can't" becomes "I can\'t".

iv) dq -> escapes doubles quotes within a string, i.e. 'she said: "Hello!".' becomes 'she said: \"Hello!\".'

v) none -> turns off any escaping for this particular variable.

2) Format .. value may be:

i) strtoupper -> transforms var to upper case.

ii) uc -> same as strtoupper (upper case).

iii) strtolower -> transforms var to lower case.

iv) lc -> same as strtolower (lower case).

v) ucfirst -> makes the first character of the var uppercase.

vi) lcucfirst -> first transforms the var to lower case, then does a ucfirst on it.

vii) ucwords -> makes the first character of every word in the var upper case.

viii) lcucwords -> first transforms var to lower case, then does a ucwords on it.

Both of these tags may have extra elements added at any time. If in the future you need something added, then send an email to [email protected] and if we think it's feasable, we'll add it.

Here's an example of a complete tag:

Example

   My e-mail is: <TMPL_VAR NAME='email' escape='html' format='lc'>.




4.2.  <TMPL_LOOP name='LOOP_NAME'> 

There are 3 ways of assigning a vlibTemplate loop in PHP. The first way is the most complicated using the function setLoop().
This will be described first, and then the more recent methods, the 3 stage method and the Db result method.
All methods use 'exactly' the same template tags. They're just programmed differently in PHP.


The <TMPL_LOOP> tag is a bit more complicated. The <TMPL_LOOP> tag allows you to delimit a section of text and give it a name. Inside the <TMPL_LOOP> you place <TMPL_VAR>s.
Now you pass an array to setLoop() with a list of variable assignments.
The loop iterates over this list and produces output from the text block for each pass. Here's an example:



Example

   In the template:



   <TMPL_LOOP NAME='EMPLOYEE_INFO'>

         Name: <TMPL_VAR NAME='NAME'>

         Job: <TMPL_VAR NAME='JOB'>

   </TMPL_LOOP>



   In the script:

   $employee_array = array();

   array_push ($employee_arr, array('NAME' => 'Sam', 'JOB' => 'programmer' ));

   array_push ($employee_arr, array('NAME' => 'Steve', 'JOB' => 'designer' ));



   $tmpl->setLoop('EMPLOYEE_INFO', $employee_array);

   $tmpl->pparse();



   The output:

   Name: Sam
   Job: programmer

   Name: Steve
   Job: designer


As you can see above the <TMPL_LOOP> takes a list of variable assignments and then iterates over the loop body producing output.

Often you'll want to generate a <TMPL_LOOP>'s contents programmatically. Here's an example of how this can be done (many other ways are possible!):



Example

   // a couple of arrays of data to put in a loop:

   $words = array('I', 'Am', 'Cool');

   $numbers = array(1, 2, 3);



   $loop_data = array();  // initialize an array to hold your loop



   for ($i=0; $i < count($words); $i++) {

     array_push($loop_data, array('

                                 'WORD' => $words[$i],

                                 'NUMBER' => $numbers[$i]

                                ));

   }



   // finally, assign the loop data to the loop variable

   $template->setLoop('THIS_LOOP', $loop_data);


The above example would work with a template like:



Example

   <TMPL_LOOP NAME="THIS_LOOP">

      Word: <TMPL_VAR NAME="WORD"><BR>

      Number: <TMPL_VAR NAME="NUMBER"><BR>

   </TMPL_LOOP>


It would produce output like:



Example

   Word: I

   Number: 1



   Word: Am

   Number: 2



   Word: Cool

   Number: 3


<TMPL_LOOP>s within <TMPL_LOOP>s are fine and work as you would expect. If the syntax for the setLoop() call has you stumped, here's an example of a setLoop() call with one nested loop:



Example

  $template->setLoop('OUTER',array(

            0 => array(

                'name' => 'Steve',

                'surname' => 'Owen'

                'owns' => array(

                            0 => array(

                                    'est' => 'E20'),

                            1 => array(

                                    'est' => 'Flat 42B')

                            ),

            1 => array(

                'name' => 'Phil',

                'surname' => 'Mitchel'

                'owns' => array(

                            0 => array(

                                    'est' => 'The Vic'),

                                            1 => array(

                                    'est' => 'The Arches'),

                            2 => array(

                                    'est' => 'Snooker Club')

                            )

                 );


Basically, the loop must consist of an array where each array row represents a row of a loop. Therefore the values of each array must be an associative array of.. $variable_name => $variable_value.
If you build an inner loop, the $variable_name becomes the name of the loop, and you start again with the same structure.

NB: There is no limit to the amount of nested loops. Be aware that many loops (as in any php code), may slow down performance.

Inside a <TMPL_LOOP>, the only variables available are those defined within the setLoop() call. There are however work arounds to getting variables outside of the scope of the current loop.
If you wish to access a variable in a parent loop, you can prepend the variable name with the name of the loop, i.e.:



Example

  <TMPL_LOOP name="outer">
      <TMPL_VAR name="__ROWNUM__">

      <TMPL_LOOP name="inner">
          Inner loop row number is: <TMPL_VAR name="__ROWNUM__">,
          the outer loop row number is: <TMPL_VAR name="outer.__ROWNUM__">
      </TMPL_LOOP>
  </TMPL_LOOP>


To access the variables within the global namespace, you can either set the OPTION 'GLOBAL_VARS' to 1, or you can use the above syntax but use the vlibTemplate reserved word 'global' (always lowercase) like <TMPL_VAR name="global.TITLE">.

NB: '__ROWNUM__' is one of many vlibTemplate variables which is set when the OPTION 'LOOP_CONTEXT_VARS' is set to 1. See the OPTIONS section to see other variable and their meanings.


The second method for adding loops is the 3 stage method, a later addition to the class, using newLoop(), addRow() and addLoop() functions.
It uses the same template as before but the PHP side is much more simple.



Example

<?php
    [assign template .......]

   // a couple of arrays of data to put in a loop:

   $words = array('I', 'Am', 'Cool');

   $numbers = array(1, 2, 3);



   $tmpl->newLoop('THIS_LOOP');  // initialize a new loop


   for ($i=0; $i < count($words); $i++) {

     $tmpl->addRow(array('WORD' => $words[$i],'NUMBER' => $numbers[$i])); //adds a row

   }

   $tmpl->addLoop(); // adds the loop to the template

    [parse template .....]
?>


To see a working example have a look at the 'vlibTemplate_basicloop.php' example in the EXAMPLES folder of your vLIB distribution.


The third method for adding loops is an experimental function which takes the result resource of a database call, and generates the output. The PHP-side is even simpler than the 3 stage method. Here's an example:



Example

<?php
    [assign template .......]
   $cnx = mysql_connect('localhost','user','pass');
   mysql_select_db('test');

   $r = mysql_query('SELECT * FROM test_table LIMIT 0, 50', $cnx);


   $tmpl->setDbLoop('THIS_LOOP', $r, 'MYSQL');  // initialize a new loop


    [parse template .....]
?>


How simple was that!


4.3.  <TMPL_INCLUDE NAME/FILE='filename.html'> 

This tag includes a template directly into the current template at the point where the tag is found. The included template contents are used exactly as if its contents were physically included in the master template.
(it acts more as a php-style require than an include)

The file specified can be a full path - beginning with a '/'. If it isn't a full path, the path to the enclosing file is tried first. After that each of the 'additional' paths set in OPTIONS are tried. After that the OPTION 'TEMPLATE_DIR' is tried next, if it exists. Next, the relative path from the php script is consulted. As a final attempt, vlibTemplate tries from the directory where vlibTemplate is installed.

As a protection against infinitly recursive includes, an arbitary limit of 10 levels deep is imposed. You can alter this limit with the "MAX_INCLUDES" OPTION. See the entry for this option below for more details.




4.4.  <TMPL_PHPINCLUDE NAME/FILE='filename.php'> 

It is encouraged that you use this tag only in circumstances that you need to. It will basically execute the php code inside of the template file as if it were executed within the actual vlibTemplate class.



Example

<?php
  echo $GLOBALS['PHP_SELF'];
?>


Note
The use of this tag is strongly discouraged as it goes against the reasons for using a template system.
The only reason it is here is because I thought it would be asked for.



4.5.  <TMPL_[ELSE]IF name='BOOL'> 

The <TMPL_IF> tag allows you to include or not include a block of the template based on the value of a given parameter name. If the parameter is given a value that is equal to TRUE for PHP - like '1' - then the block is included in the output. If it is not defined, or given a false value - like '0' - then it is skipped. The parameters are specified the same way as with TMPL_VAR.

Example Template:



Example

   <TMPL_IF NAME="BOOL">

     Some text that only gets displayed if BOOL is true!

   </TMPL_IF>


Now if you call $template->setVar('BOOL', 1) then the above block will be included in the output.

<TMPL_IF> [<TMPL_ELSEIF>] </TMPL_[END]IF> blocks can include any valid vlibTemplate construct - VARs and LOOPs and other IF/ELSE blocks. Note, however, that intersecting a <TMPL_IF> and a <TMPL_LOOP> is invalid.



Example

   Invalid syntax:

   <TMPL_IF BOOL>

      <TMPL_LOOP SOME_LOOP>

   </TMPL_IF>

      </TMPL_LOOP>


Loops are kept in a different namespace to global variables. So if you want to access loop names from your if statements you must have the OPTION 'SET_LOOP_VAR' set to 1. This will ensure that when you set a loop that is not empty using setLoop(), a variable with that loop name is set using setVar().
This is true except when using <TMPL_IF> from within a loop where this is not a problem.

If the name of a TMPL_LOOP is used in a TMPL_IF, the IF block will output if the loop has at least one row. Example:



Example

  <TMPL_IF LOOP_ONE>

    This will output if the loop is not empty.

      <TMPL_LOOP LOOP_ONE>

        ....

      </TMPL_LOOP>

  </TMPL_IF>


Warning
WARNING: Much of the benefit of vlibTemplate is in decoupling your PHP and HTML. If you introduce numerous cases where you have TMPL_IFs and matching PHP if()s, you will create a maintenance problem in keeping the two synchronized. I suggest you adopt the practice of only using TMPL_IF if you can do so without requiring a matching if() in your PHP code.
Of course, this isn't always possible, it's just something that you should aim for.


vlibTemplate now supports an extended TMPL_IF syntax. The new OPTIONAL syntax gives you the opportunity to compare the value of a var name to a number or string. There are 2 attributes that apply to the new functionality; OP and VALUE. OP is the comparison OPerator that you want to use.
The default is '==' and the supported operators are '==', '!=', '<>', '<', '>', '<=' and '>='. VALUE is the string or number that you want to compare to (containing any characters except quotes), i.e.:



Example

Thank you for purchasing: <TMPL_VAR NAME="product_qty"> <TMPL_VAR NAME="product_name">.<br><br>

<TMPL_IF NAME="product_price" OP=">" VALUE="20.00">
   Your order comes with free shipment.
<TMPL_ELSE>
   Shipment: additional 10 GPB.
</TMPL_IF>


Note
To avoid any errors, always encapsulate the values of OP and VALUE in quotes.



4.6.  <TMPL_ELSE> 

You can include an alternate block in your TMPL_IF block by using TMPL_ELSE. NOTE: You still end the block with </TMPL_IF>, not </TMPL_ELSE>! Example:



Example

   <TMPL_IF BOOL>

     Some text that is included only if BOOL is true

   <TMPL_ELSE>

     Some text that is included only if BOOL is false

   </TMPL_IF>




4.7.  <TMPL_UNLESS name='BOOL'> 

This tag is the opposite of <TMPL_IF>. The block is output if the CONTROL_PARAMETER is set to false or not defined. You can use <TMPL_ELSE> and <TMPL_ELSEIF> with <TMPL_UNLESS> just as you can with <TMPL_IF>, however there is no <TMPL_ELSEUNLESS> tag.



Example

  <TMPL_UNLESS BOOL>

    Some text that is output only if BOOL is FALSE.

  <TMPL_ELSE>

    Some text that is output only if BOOL is TRUE.

  </TMPL_UNLESS>


If the name of a TMPL_LOOP is used in a TMPL_UNLESS, the UNLESS block is output if the loop has zero rows. Please see the OPTION section regarding <TMPL_IF/UNLESS> statements within loops.



Example

  <TMPL_UNLESS LOOP_ONE>

    This will output if the loop is empty.

  </TMPL_UNLESS>




5.  vlibTemplate 

vlibTemplate is the main class which does 95% of the processing.



5.1.vlibTemplate()
5.2.newTemplate()
5.3.setVar()
5.4.unsetVar()
5.5.getVars()
5.6.getVar()
5.7.setContextVars()
5.8.setLoop()
5.9.setDbLoop()
5.10.newLoop()
5.11.addRow()
5.12.addLoop()
5.13.getLoop()
5.14.unsetLoop()
5.15.reset()
5.16.clearVars()
5.17.clearLoops()
5.18.clearAll()
5.19.unknownsExist()
5.20.unknowns()
5.21.getUnknowns()
5.22.setUnknowns()
5.23.setPath()
5.24.getParseTime()
5.25.fastPrint()
5.26.pparse()
5.27.pprint()
5.28.grab()

5.1.  vlibTemplate() 

Function Description
 vlibTemplate ([string Filename [, array Options]])

You must define a filename when instantiating the vlibTemplate object, and it must be here that you define any template specfic OPTION parameters:

Example

  $options = array('STRICT' => 1,
                   'CASELESS' => 1);
  $tmpl = new vlibTemplate('./templates/default.html', $options);


Alternatively, if you wish to define your template file(s) seperate from the instantiation. You can omit both arguments or use only the Options argument in place of the Filename when instantiating the class and then use vlibTemplate::newTemplate('/your/file.html'); for each new template file, i.e.:

Example

  $options = array('STRICT' => 1,
                   'CASELESS' => 1);
  $tmpl = new vlibTemplate($options);
  $tmpl->newTemplate('./templates/default.html');

  ..or simply:

  $tmpl = new vlibTemplate();
  $tmpl->newTemplate('./templates/default.html');


When including your template, vlibTemplate will use the same include mechanisms used with the <TMPL_INCLUDE> tag.

Note
Look at the OPTION section to see in what ways you can manipulate vlibTemplate to work exactly as you need it.




5.2.  newTemplate() 

Function Description
 newTemplate (string Filename)

This is actually the function called by vlibTemplate() upon instantiation of the class. This function becomes useful to you if you use the reset() function or when you want to specify a new template file for your vlibTemplate object.

Note
This function takes a filename as the only parameter. The OPTIONS are always set by (and only by) vlibTemplate().




5.3.  setVar() 

Function Description
  setVar(mixed name [, mixed value])

setVar() can be called in two different ways

1) The most commonly used method, passing in a name and a value:



Example

   $tmpl->setVar('title', 'vlibTemplate test page'); // title is the name used in <TMPL_VAR>


2) Passing in an array of key=>value pairs, each element taken as a seperate var:



Example

   $myvars = array('fav_color' => 'blue',
                   'fav_tvshow'=> 'Eastenders');

   $tmpl->setVar($myvars);  // no second parameter





5.4.  unsetVar() 

Function Description
 unsetVar(string name [, string name...])

unsetVar() unsets each variable passed to it as a seperate parameter.

Example

    $tmpl->unsetVar('title', 'fav_color', 'fav_tvshow');





5.5.  getVars() 

Function Description
 getVars()

getVars() returns an associative array of all variables in vlibTemplate.

Example

   $allvars = $tmpl->getVars();

   print_r($allvars);






5.6.  getVar() 

Function Description
 getVar(string name)

getVar() returns the value of the variable 'name'.

Example

   $fav_color = $tmpl->getVar('fav_color');





5.7.  setContextVars() 

Function Description
 setContextVars()

setContextVars() is invoked when the OPTION 'GLOBAL_CONTEXT_VARS' is set, this is another way to invoke it yourself.

Example

   $tmpl->setContextVars();





5.8.  setLoop() 

Function Description
 setLoop(string loopname, array loop_rows)

setLoop() builds an array for using with <TMPL_LOOP>.

Please see the <TMPL_LOOP> section for information on how to build a loop.


5.9.  setDbLoop() 

Function Description
 setDbLoop(string loopname, resource db_result [, db_type])

setDbLoop() builds an array for using with <TMPL_LOOP> from a Database result resource or a statement for those databases where it applies (see below).
db_type is the name of the database that the result resource is associated to, if it's not specified then MYSQL is the default.
Below is a list of databases currently supported and information about the db_result needed to be passed:

MYSQL - a normal result resource
POSTGRESQL - a normal result resource
INFORMIX - resultid returned by ifx_query() or ifx_prepare()
INTERBASE - result identifier
INGRES - result identifier
MSSQL - result resource
MSQL - result resource
OCI8 - statement handle
ORACLE - cursor handle
OVRIMOS - resultid
SYBASE - result resource



Warning
This function is curently experimental, so as much testing as possible needs to be carried out. If you use any of these databases either succesfully or unsuccefully, please provide feedback to help us improve the function. Only MYSQL and INFORMIX have been tested.

Please see the <TMPL_LOOP> section for information on how to build a loop.




5.10.  newLoop() 

Function Description
 newLoop(string loopname)

newLoop() is part of the 3 stage method to add a loop, used instead of the complicated setLoop() function. This function assigns a loop name, which you'll use in your templates.
The following 2 functions will complete the 3 stage method, addRow() and addLoop().

Please see the <TMPL_LOOP> section for information on how to build a loop.


5.11.  addRow() 

Function Description
 addRow(array row [, loopname])

addRow() is the 2nd part of the 3 stage method to add a loop, used instead of the complicated setLoop() function. This function assigns a row to the loop specified by loopname. If loopname is not specified then the last loop set using newLoop() is assumed .
The array must be a single dimensional array. If it has key associations the those associations will be used as the variable names within the loop, other wise the variables will be called; _0, _1, _2, _3 ...etc.

Please see the <TMPL_LOOP> section for information on how to build a loop.


5.12.  addLoop() 

Function Description
 addLoop([loopname])

addLoop() is the 3rd part of the 3 stage method to add a loop, used instead of the complicated setLoop() function.
If loopname is specified then this function simply adds the entire loop into the array in the correct format. If it is ommited, then all loops set using newLoop() are added.
See the newLoop() and addRow() functions.

Please see the <TMPL_LOOP> section for information on how to build a loop.


5.13.  getLoop() 

Function Description
 getLoop([loopname])

getLoop() returns a loop that has been added using the 3-step-process. It simplifies creating an innerloop especially.
If loopname is specified then this function simply returns the entire loop before removing the loop automatically.
See the newLoop() and addRow() functions.

Please see the <TMPL_LOOP> section for information on how to build a loop.


5.14.  unsetLoop() 

Function Description
 unsetLoop (string loopname [, string loopname...])

unsetLoop() unsets each 'TOP LEVEL' loop passed to it as a seperate parameter.

Example

  $tmpl->unsetLoop('loop1','loop2');


Note
This will NOT work on nested loops, only the top level ones.




5.15.  reset() 

Function Description
 reset()

reset() will reset vlibTemplate to it original state (except it keeps hold of the OPTIONS).
After reset()ing vlibTemplate, you must use the function newTemplate() to initialize a new template.

Example

  $tmpl->reset();




5.16.  clearVars() 

Function Description
 clearVars()

clearVars() will remove all 'GLOBAL' variables from vlibTemplate (variables set using setVar()).

Example

  $tmpl->clearVars();




5.17.  clearLoops() 

Function Description
 clearLoops()

clearLoops() will remove all loops from vlibTemplate (variables set using setLoop()).

Example

  $tmpl->clearLoops();




5.18.  clearAll() 

Function Description
 clearAll()

clearAll() will remove all loops and variables from vlibTemplate (variables set using setLoop() and setVar()). This is particularly useful if, for example, you're using vlibTemplate as an e-mail template and sending it to many people. You will probably need different information in each e-mail, and can therefore use clearAll() and then go about re-entering all of the variables.

Example

  $tmpl->clearAll();




5.19.  unknownsExist() 

Function Description
 unknownsExist()

This function returns true if, after parsing, variables have been found in the template file that were not set using setVar(). This function may or may not have any effect depending on the OPTION setting of 'UNKNOWNS'.

Example

  if($tmpl->unknownsExist()) { ...




5.20.  unknowns() 

Function Description
 unknowns()

This function is an alias for unknownsExist().


5.21.  getUnknowns() 

Function Description
 getUnknowns()

This function returns an array of all unknowns found after parsing.

Example

  print_r($tmpl->getUnknowns());




5.22.  setUnknowns() 

Function Description
 setUnknowns(string unknown)

This function allows you to set the OPTION for 'UNKNOWNS'. See the OPTION section for more details.

Example

  $tmpl->setUnknowns('comment');




5.23.  setPath() 

Function Description
 setPath(string filepath[, string filepath...])

This function will give vlibTemplate a list of path to be used when trying to access a template file or a file include using <tmpl_include>.
You give it one argument for each path you want to set and it is set on a per file basis.

Example

  $tmpl->setPath('../templates', '/usr/local/apache/cgi-bin/mytemplates');




5.24.  getParseTime() 

Function Description
 getParseTime()

This function will allow you to get the time it took, in seconds and microseconds, for the template to be parsed. Therefore this function should only be used once one of the parsing functions has been called (fastPrint(), pparse(), or grab()). This function only works if the OPTION 'TIME_PARSE' is set to 1.

Example

  $tmpl->grab();
  echo $tmpl->getParseTime(); // will echo out the time it took to parse the template




5.25.  fastPrint() 

Function Description
 fastPrint()

This function parses the template file and prints the output. If possible, the output is compressed using gz compression and the output buffering functions.

Example

  $tmpl->fastPrint();




5.26.  pparse() 

Function Description
 pparse()

This function parses the template file and prints the output.

Example

  $tmpl->pparse();




5.27.  pprint() 

Function Description
 pprint()

This function is an alias for pparse();


5.28.  grab() 

Function Description
 grab()

This function parses the template file and returns the output instead of printing it. Therefore you can do what you please with it.

Example

  $output = $tmpl->grab(); ...




6.  vlibTemplateDebug() 

This class needs no configuring or any other knowledge. It simply prepends the output of your template file with code to popup the vlibTemplate Debug Module. This module shows a lot of extremely helpful information about the template you parse.


Example

To use vlibTemplateDebug, you just need to alter your class instantiaton to:
$tmpl = vlibTemplateDebug('mytemplates/mytemplatefile.html', $options);


Possibly the most helpful feature of the module is the error checking. It will basically parse through the entire template file that you're parsing, and any included files, and check the <tmpl_*> style syntax for validity. So if you receive vlibTemplate compile errors upon running your code through your browser you can use this module to find out exactly where you went wrong.

Note
This module is HTML based and makes use of javascript functions. Therefore, if you use php from the command line or using a non-javascript browser, you will not be able to use this module.



7.  vlibTemplateCache() 

This class is best used once you have created your template and are happy with it. The class will basically save the compiled template code to a file for subsequent accesses. This saves a lot of time skipping the entire compile phase. If you then need to make a change to the template, you must clear the cache.



Example

To use vlibTemplateCache, you just need to alter your class instantiaton to:
$tmpl = vlibTemplateCache('mytemplates/mytemplatefile.html', $options);


vlibTemplateCache will recache itself if either the compiled file has been deleted, the compiled file has passed the expiry date set by the OPTION 'CACHE_LIFETIME' or if you use clearCache() or recache() to do it manually.

Please see the OPTIONS section for further details of how you can configure your own cache system.

Note
vlibTemplateCache caches a template once all of the <tmpl_include>'s have been parsed. Therefore if you change one of the included files, you must recache for the changes to be taken into account.




7.1.clearCache()
7.2.recache()
7.3.setCacheLifeTime()
7.4.setCacheExtension()

7.1.  clearCache() 

Function Description
 clearCache()

This will manually clear the cached file, forcing vlibTemplate to take a new version of the template file into cache.

Example

  $tmpl->clearCache();




7.2.  recache() 

Function Description
 recache()

This function is an alias for clearCache().


7.3.  setCacheLifeTime() 

Function Description
 setCacheLifeTime(int seconds)

This function sets the lifetime of the cache for this template file to the integer seconds.

Example

  $tmpl->setCacheLifeTime(60); // sets the cache time to 1 minute




7.4.  setCacheExtension() 

Function Description
 setCacheExtension(string ext)

This function sets the extension that vlibTemplateCache will use to locate the cached file.

Example

  $tmpl->setCacheExtension('txt'); // sets the cache time to 1 minute


Note
Do not include the full stop ('.') in the above string.




8.  Options 

Below I'll describe the options that you can use when configuring vlibTemplate to work to your needs. All of the following options detailed below can be edited in your vlibIni.php file (called vlibIni.php-dist in the archive).

Each option can be set in the vlibIni.php file which will mean that this value is taken as a default for each template file you use, or they can be set in an array as the second parameter to vlibTemplate() the main class constructor.


9.  Security 

As vlibTemplate compiles the templates into native PHP code, the template files should be considered in the same way as any other PHP file in terms of security.

In the future, there will be an option for removing php-style code from the template but that will probably NOT be fool-proof. It is therefore in your interests to deal with the template files as you would a PHP file.


10.  Bugs 

If you find a bug, or what you think is a bug, then send an e-mail to [email protected] with any helpful information.

When submitting bug reports, be sure to include full details, including the VERSION of the class, a test script and a test template demonstrating the problem!


11.  Credits 

I had the idea to write vlibTemplate when I started to use PHP on a project after creating websites in Perl using the HTML::Template module available in the CPAN package. This module was my inspiration, and although vlibTemplate has been completely written from the ground up for PHP, it's tag syntax is extremely similar to that of HTML::Template.

In fact if you have templates written for HTML::Template, you will be able to write PHP code to use that template. If you're porting from vlibTemplate to HTML::Template, there are certain things in the template which will not work as slightly more features have been added to the tags than the perl module handles.

Anyway, many thanks to them for the inspiration. See http://www.cpan.org.


12.  Download 

Download the latest version of vLIB from http://vlib.sourceforge.net/download/.


13.  License 

vLIB is licenced under the OpenSource Artistic Licence.


14.  Install 

Please see the INSTALL file in the root of your vLIB distribution.


15.  Forum 

There are forums where you can discuss vlib at vLIB forum and support.


16.  Documentation In Other Languages 

Here you can find links to contributed documentaion in languages other than English.
Many thanks goes out to the authors of these sites:

German: HowTo use vlibTemplate (with many examples) - contributed by Claus van Beek.