Skip to the content
Documentation

Control structures

No ratings yet

The template language has conditions (if, switch) and loops (foreach, for, while, do). Each is a template function with a closing tag. Every example on this page was run on Exponential 6.0.15 and prints what its comment says.

if, elseif, else

{if eq( $fruit, 'apples' )}
    Apples
{elseif eq( $fruit, 'oranges' )}
    Oranges
{else}
    Bananas
{/if}

Comparisons and logic are operators: eq, ne, gt, ge, lt, le, and, or, not. They can be written as a call, eq( $a, $b ), or with a pipe, $a|eq( $b ). For a value inside an expression there is cond( $test, 'yes', 'no' ).

switch

{switch match=$fruit}
    {case match='apples'}Apples{/case}
    {case match='oranges'}Oranges{/case}
    {case}Unknown fruit{/case}
{/switch}

The {case} without match is used when no other case matches.

foreach

foreach walks through an array, with or without its keys:

{foreach $node.children as $child}
    <a href={$child.url_alias|ezurl}>{$child.name|wash}</a>
{/foreach}

{foreach array( 'a', 'b', 'c' ) as $key => $item}{$key}={$item}{delimiter},{/delimiter}{/foreach}
{* 0=a,1=b,2=c *}

It takes options after the variable: max and offset limit the passes, reverse walks backward, and sequence cycles through values, for example for alternating row classes. {delimiter} prints its content between two passes, {continue} goes on with the next pass ({skip} does the same and also leaves out the delimiter), and {break} ends the loop:

{foreach array( 1, 2, 3, 4, 5 ) as $n max 2 offset 1}{$n}{/foreach}
{* 23 *}

{foreach array( 'a', 'b', 'c' ) as $item sequence array( 'odd', 'even' ) as $row}{$row}:{$item} {/foreach}
{* odd:a even:b odd:c *}

{foreach array( 1, 2, 3 ) as $n}{if eq( $n, 2 )}{break}{/if}{$n}{/foreach}
{* 1 *}

for

for counts through a range of numbers, upward or downward:

{for 0 to 3 as $i}{$i}{/for}
{* 0123 *}

while and do

while repeats as long as its condition holds and checks it before each pass; do checks it after each pass, so it runs at least once:

{def $counter = 0}
{while ne( $counter, 3 )}{$counter}{set $counter = inc( $counter )}{/while}
{* 012 *}
{set $counter = 0}
{do}{$counter}{set $counter = inc( $counter )}{/do while ne( $counter, 3 )}
{* 012 *}
{undef $counter}

section and let

Templates written before version 3.6 of eZ Publish used {section} for both conditions and loops and {let} for variables. They still work, and some standard templates use them, but write new templates with if, foreach and def. A comparison: section and foreach.

Every option of each function: Control structures reference, and the generated pages for if, foreach, for, while, do and switch.

Contributors

Comments

Add a comment

Comments are read by a moderator before they appear.