Control Structures
Like most programming languages, Smarty provides control structures for efficient coding.
Control structures in Smarty are actually built-in Template or Block functions. Here are some useful ones:
{if},{elseif},{else} - {if} statements in Smarty have much the same flexibility as PHP if statements, with a few added features for the template engine. Every {if} must be paired with a matching {/if}. {else} and {elseif} are also permitted. All PHP conditionals and functions are recognized, such as ||, or, &&, and, is_array(), etc.
{foreach},{foreachelse} - {foreach} is used for looping over arrays of data and can also loop over associative arrays. {foreach $arrayvar as $itemvar} or {foreach $arrayvar as $keyvar=>$itemvar}. Since it is a block each {foreach} must be paired with a matching {/foreach}
{for}{forelse} - The {for}{forelse} tag is used to create simple loops and must be matched with an ending {/for}. {forelse} is executed when the loop is not iterated. The following different formarts are supported:
- {for $var=$start to $end} simple loop with step size of 1.
- {for $var=$start to $end step $step} loop with individual step size.
{while} - {while} loops in Smarty have much the same flexibility as PHP while statements, with a few added features for the template engine. Every {while} must be paired with a matching {/while}. All PHP conditionals and functions are recognized, such as ||, or, &&, and, is_array(), etc.