Foreach loops
This page is for designers who print lists. {foreach} is the loop you use most.
Contents
Syntax
From the syntax comment of lib/eztemplate/classes/eztemplateforeachfunction.php:
{foreach <array> as [$keyVar =>] $itemVar
[sequence <array> as $sequenceVar]
[offset <offset>]
[max <max>]
[reverse]}
[{delimiter}...{/delimiter}]
[{break}]
[{continue}]
[{skip}]
{/foreach}Keys and items
foreach $children as $child
<li>$child.name|wash</li>
/foreach
foreach $settings as $name => $value
<dt>$name|wash</dt><dd>$value|wash</dd>
/foreachOffset, max and reverse
foreach $articles as $article offset 1 max 3 {* items 2 to 4 *}
foreach $steps as $step reverse {* last to first *}When the list comes from a fetch, prefer offset and limit in the fetch: then the database does the work.
Delimiter
Printed between items, not after the last:
foreach $tags as $tag$tag|washdelimiter, /delimiter/foreachSequence
Alternating values, for example row classes:
foreach $rows as $row sequence array( 'odd', 'even' ) as $row_class
<tr class="$row_class">...</tr>
/foreach(For zebra tables, a CSS :nth-child rule is usually simpler.)
break, continue, skip
{break}leaves the loop.{continue}goes to the next item.{skip}goes to the next item without printing the delimiter.
foreach $children as $child
if $child.is_hiddenskip/if
node_view_gui content_node=$child view='line'
/foreachHabits
- No fetch inside a loop: fetch once before (Fetch performance).
{undef}loop helper variables after the loop if the template is included elsewhere.- Print an empty state when the list is empty:
{if $list|count}...{else}...{/if}.
Related pages
- For loops
- While and do loops
- Fetching nodes and lists
- Free documentation: this page is free to copy, translate and improve under the GNU FDL 1.3.
Become an Exponential Partner
Partners share their information, provide funding, contribute back and develop the products with us, and that is how Exponential grows. A partner website and dashboard are planned for mid-2027: please become a partner today to speed up our growth rate and land new features faster.