{if}

Renders its content only when a condition holds, with elseif and else branches.

Conditions Tag pairs

Syntax

{if condition} ... {/if}
{if condition} ... {else} ... {/if}
{if condition} ... {elseif condition} ... {else} ... {/if}

Parameters

condition
An expression. A comparison ($count gt 0) or a bare value, tested for its truth as PHP does: '', '0', 0 and FALSE fail.

Description

The content between {if} and {/if} renders when the condition is true. Inside it, {elseif condition} starts a branch that is tried when every branch before it failed, and {else} the branch that renders when none held. Only one branch ever renders.

The condition is a PAD expression: fields ($count), literals, the comparison operators eq ne gt lt ge le (or == != > < >= <=), and, or, not, range (a, b), in ('a', 'b'), like and matches. A bare value is tested for its truth - write a comparison when a value is meant: {if $count eq 0}.

A property of an enclosing loop reads as a value in the condition: {if first@items}, {if current@items eq 2}.

Under the strict syntax check (the default) a field that does not exist is an error rather than an empty value, so a typo in a condition is reported instead of silently taking the else branch.

Examples

A comparison

The branch whose condition holds renders; the others do not.

Templateexamples/if/1-basic.pad
{set $count = 3}
{if $count gt 0}
  <p>There are {$count} items.</p>
{else}
  <p>The list is empty.</p>
{/if}
Resultopen alone

There are 3 items.

elseif and else

The branches are tried in order - the first that holds wins.

Templateexamples/if/2-elseif.pad
{temperatures}
  {if $degrees lt 0}
    <p>{$city}: freezing</p>
  {elseif $degrees lt 20}
    <p>{$city}: mild</p>
  {else}
    <p>{$city}: warm</p>
  {/if}
{/temperatures}
PHPexamples/if/2-elseif.php
<?php

  $temperatures = [
    [ 'city' => 'Oslo',    'degrees' => -4 ],
    [ 'city' => 'Utrecht', 'degrees' => 12 ],
    [ 'city' => 'Seville', 'degrees' => 27 ] ];

?>
Resultopen alone

Oslo: freezing

Utrecht: mild

Seville: warm

A loop property as condition

first@ and last@ of the loop around read as a value.

Templateexamples/if/3-property.pad
{set $fruit = 'apple, pear, plum'}
<p>{sequence list=$fruit, name='fruit'}{if not first@fruit}, {/if}{$fruit}{if last@fruit}.{/if}{/sequence}</p>
Resultopen alone

apple, pear, plum.

See also

  • {case} Renders the one branch whose {when} matches a value, with an {else} for none.
  • {ifchanged} Renders its content when a value differs from the previous row of the loop around it - a heading per group.
  • {true} The constant TRUE: its content renders once, as a level of its own.
  • {false} The constant FALSE: its content is skipped and its @else@ part renders instead.