vLib Logo

5.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:


     Some text that only gets displayed if BOOL is true!


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.

   Invalid syntax:





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:


    This will output if the loop is not empty.





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.:

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.
   Shipment: additional 10 GPB.

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