{case}

Renders the one branch whose {when} matches a value, with an {else} for none.

Conditions Tag pairs

Syntax

{case value} {when 'a'} ... {when 'b', 'c'} ... {/case}
{case value} {when 'a'} ... {else} ... {/case}

Parameters

value
An expression - a field such as $color, or any computed value - that each {when} is compared with.

Description

{case value} evaluates its value once and keeps only the branch of the first {when} that matches it. A {when} may list several values separated by commas - {when 'yellow', 'amber'} - and matches when any of them is equal. Each value is an expression of its own, so {when $limit} or {when 2 * 5} work too. The comparison is PHP's loose ==, so {when 3} matches the text '3'.

A branch runs from its {when} to the next one (or to {else} or {/case}). {else} opens the default branch, rendered when no {when} matched; without it nothing renders in that case. {when 'default'} is not a default - it is an ordinary branch matching the text default. A nested {case} or {if} inside a branch keeps its own {when} and {else}.

Under the strict syntax check the tag is held to its shape: a {case} without a value, without any {when} or without its {/case} is an error; so is text standing before the first {when} (it would never render), a {when} behind the {else}, a {when} without a value, and a value listed twice - only the first one could ever answer.

For a yes/no test use {if}; for a heading each time a value changes inside a loop, {ifchanged}.

Examples

Matching a value

The branch of the {when} that matches renders; a {when} can list several values.

Templateexamples/case/1-basic.pad
{set $light = 'amber'}
<p>The light is {$light}:
{case $light}
  {when 'red'} stop.
  {when 'yellow', 'amber'} slow down.
  {when 'green'} go.
{/case}</p>
Resultopen alone

The light is amber: slow down.

The else branch

{else} renders when no {when} matched - here inside a loop, once per row.

Templateexamples/case/2-else.pad
<ul>
{sequence '1..5', name='day'}
  <li>Day {$day}:
  {case $day}
    {when 1} Monday
    {when 2} Tuesday
    {when 3} Wednesday
  {else}
    later in the week
  {/case}
  </li>
{/sequence}
</ul>
Resultopen alone
  • Day 1: Monday
  • Day 2: Tuesday
  • Day 3: Wednesday
  • Day 4: later in the week
  • Day 5: later in the week

Computed values

The case value and the when values are expressions, compared loosely.

Templateexamples/case/3-expression.pad
{set $score = 7}
<p>{$score} is
{case $score % 2}
  {when 0} even
  {when 1} odd
{/case}
and
{case $score gt 5}
  {when TRUE} high.
{else}
  low.
{/case}</p>
Resultopen alone

7 is odd and high.

See also

  • {if} Renders its content only when a condition holds, with elseif and else branches.
  • {ifchanged} Renders its content when a value differs from the previous row of the loop around it - a heading per group.
  • {switch} Answers the next value of a rotating list on every call - striped rows without a counter.