{switch}
Answers the next value of a rotating list on every call - striped rows without a counter.
Syntax
{switch 'odd', 'even'}
{switch 'red', 'green', 'blue'}
Parameters
-
values - Two or more values to cycle through; the first call answers the first, then each call the next, starting over after the last.
Description
{switch 'odd', 'even'} prints one of its values and moves one step on, so the next time it runs it prints the next one, and after the last it starts over. Written inside a loop it gives alternating values per row - a class or a background colour for zebra stripes - without counting anything yourself.
The position is remembered for the whole request and is keyed on the tag's text as written. Two {switch} tags written exactly alike therefore share one rotation, even in different loops: the second loop goes on where the first one stopped. Write them differently (another value, or other spacing) to give each its own rotation. A nested pass - a {code} or {sandbox} evaluation - takes its rotation steps back when it returns.
The rotation does not follow the row number, so a {switch} inside an {if} only steps on the rows where it runs. When the colour must follow the row itself, use the loop's property: {even@items ? 'even' : 'odd'}.
Under the strict syntax check a {switch} with no values is an error.
Examples
Striped rows
Each row takes the next background from the rotation.
<table>
{sequence '1..5', name='row'}
<tr style="background: {switch '#ffffff', '#e8eef7'}"><td>Row {$row}</td></tr>
{/sequence}
</table>
| Row 1 |
| Row 2 |
| Row 3 |
| Row 4 |
| Row 5 |
A longer rotation, shared
Three values cycle; a second switch written alike continues the same rotation.
<p>{sequence 4}{switch 'red', 'green', 'blue'} {/sequence}</p>
<p>{sequence 4}{switch 'red', 'green', 'blue'} {/sequence}</p>
<p>{sequence 4}{switch 'red','green','blue'} {/sequence}</p>
red green blue red
green blue red green
red green blue red
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.