Skip to the content
Documentation
Help Start
Reading in:
  • German: 9,075 of 9,075 pages
About the help in other languages
All help pages

Foreach loops

Looping over arrays and fetch results with foreach: keys and items, offset, max and reverse, sequence for alternating classes, delimiter between items, break, continue and skip, and loop habits that keep templates fast.

Download as PDF

Address: https://doc.exponential.earth/exphelp/viewer/help/designers/templates/foreach-loops.md

On this page

Foreach loops

This page is for designers who print lists. {foreach} is the loop you use most.

Contents

  1. Syntax
  2. Keys and items
  3. Offset, max and reverse
  4. Delimiter
  5. Sequence
  6. break, continue, skip
  7. Habits

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>
{/foreach}

Offset, 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|wash}{delimiter}, {/delimiter}{/foreach}

Sequence

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_hidden}{skip}{/if}
    {node_view_gui content_node=$child view='line'}
{/foreach}

Habits

  • 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}.

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.

Something wrong on this page? Report an error

Documentation license

This documentation is free documentation, licensed under the GNU Free Documentation License 1.3 or later.

Exponential Copyright © 1998-2026 Exponential Foundation and 7x