Smarty Conditionals
Conditionals can be created in Smarty using the "if", "ifelse", and "else" functions. Unlike conditionals in PHP, a Smarty conditional uses closing and opening {if}{/if}. Smarty supports the same comparative operators as PHP: ==, !=, >, <, >=, <=, and ===. Smarty also uses text equivalents: "eq" for ==, "ne" or "neq" for !=, "gt" for >, and so on. You can also use: logical operators (&&, ||, "and", "or"); the negation operator (!, or the equivalent "not"); the modulus operator (% or "mod"); and a few strings like "is even", "is not even", and so on.
A basic conditional in a Smarty template looks like
{if $var eq 'some value}
This is printed.
{elseif $var eq 'this value}
This is printed instead.
{else}
This is the default.
{/if}
Note that unlike a conditional in PHP, you don't have to use echo statements to print values, as this is within a Smarty template.
Smarty Loops
The "section" and "foreach" functions can be used to create loops. "section" is like a standard FOR loop; "foreach" can be used on a single associative array, like a FOREACH loop in PHP. The PHP code
for ($i = 1; $i <= 10; $i++) {
echo $i . '';
}
would be written in a Smarty template as
{section name='i' start=1 loop=10}
{$smarty.section.i.index}
{/section}
The "start" value is the beginning index position; "loop" indicates how many times the loop should run.
The "sectionelse" function can be used if an array has no items in it (and therefore the loop is never executed):
{section name='this_loop' start=1 loop=10}
{$smarty.section.this_loop.index}
{sectionelse}
There are no items to print.
{/section}
The "foreach" function has two required arguments: "from", which is the array being used, and "item", which is the name of the current array element within the loop. The PHP code
foreach ($array as $v) {
echo $v . '';
}
would be written in a Smarty template as
{foreach from=$array item=v}
{$v}
{/foreach}
The "foreach" function can also reference array keys. The PHP code
foreach ($array as $k => $v) {
echo "$k: $v ";
}
would be written in a Smarty template as
{foreach from=$array item=v key=k}
{$k}: {$v}
{/foreach}
|