Loops and Loop Control

Most repetition in PAD is a data tag iterating its rows - that story is on levels and occurrences. This page is about the counting loops, and about steering any loop from inside.

while and until

{while} renders its content as long as its condition holds, and {until} renders until its condition becomes true - checked before each pass, so an until that is already true renders nothing. {increment} and {decrement} step a variable by one:

PHP
HTML
fragments/loops_1.pad
Result
{set $i = 1/}
{while $i le 5}
{$i}
{increment $i/}
{/while}
1 2 3 4 5
PHP
HTML
fragments/loops_2.pad
Result
{set $count = 3/}
{until $count eq 0}
{$count},
{decrement $count/}
{/until}
lift off
3, 2, 1, lift off

Steering a loop: continue, cease and break

All three name the tag they act on, so they reach the right loop from however deep they are written. {continue 'tag'} skips the rest of the current occurrence; {cease 'tag'} is the graceful stop - the current occurrence finishes, then the loop ends; {break 'tag'} is the hard stop, ending the occurrence mid-way:

PHP
HTML
fragments/loops_3.pad
Result
{data 'ns'}[1, 2, 3, 4, 5]{/data}
<p>continue skips one: {ns}{if $ns eq 3}{continue 'ns'}{/if}{$ns} {/ns}</p>
<p>cease ends gently: {ns}{if $ns eq 4}{cease 'ns'}{/if}{$ns} {/ns}</p>
<p>break ends at once: {ns}{if $ns eq 4}{break 'ns'}{/if}{$ns} {/ns}</p>

continue skips one: 1 2 4 5

cease ends gently: 1 2 3 4

break ends at once: 1 2 3

The same value stopped both: cease still shows the 4 its occurrence had started, break does not.

A heading per group

In a sorted list, {ifchanged $field} renders its block only when the value differs from the row before - the first row always - so each group gets one heading:

PHP
HTML
fragments/loops_4.pad
Result
{data 'orders'}
[ {"customer":"Ann","number":101}, {"customer":"Ann","number":102},
{"customer":"Bob","number":103}, {"customer":"Cleo","number":104},
{"customer":"Cleo","number":105} ]
{/data}

{orders sort='customer'}
{ifchanged $customer}<h4>{$customer}</h4>{/ifchanged}
<p>Order {$number}</p>
{/orders}

Ann

Order 101

Order 102

Bob

Order 103

Cleo

Order 104

Order 105