Loop Directive Complete Feature Documentation
I. Basic Syntax Forms (6 forms)
1. Forms with key and value (4 forms)
Form 1: <!--{loop $arr AS $key => $value}-->
<!--{loop $users AS $key => $user}-->
<p>Key: {$key}, Value: {$user['name']}</p>
<!--{/loop}-->Form 2: <!--{loop $arr AS $key $value}-->
<!--{loop $users AS $key $user}-->
<p>Key: {$key}, Value: {$user['name']}</p>
<!--{/loop}-->Form 3: <!--{loop $arr $key => $value}-->
<!--{loop $users $key => $user}-->
<p>Key: {$key}, Value: {$user['name']}</p>
<!--{/loop}-->Form 4: <!--{loop $arr $key $value}-->
<!--{loop $users $key $user}-->
<p>Key: {$key}, Value: {$user['name']}</p>
<!--{/loop}-->2. Forms without a key (2 forms)
Form 5: <!--{loop $arr AS $value}-->
<!--{loop $items AS $item}-->
<p>{$item}</p>
<!--{/loop}-->Form 6: <!--{loop $arr $value}-->
<!--{loop $items $item}-->
<p>{$item}</p>
<!--{/loop}-->II. Core Features
1. Automatic array checks
- Automatically checks whether the variable is an array
- Automatically checks whether the array is empty
- The loop body is not executed when the array is empty
2. Automatic loop information object ($_zte_loop)
- Provided automatically: no need to specify a name parameter manually
- Unified interface: all loops use the
$_zte_loopobject - Nesting support: access the parent loop through
$_zte_loop->parent
3. Loop index information
$_zte_loop->index- current index (starting from 0)$_zte_loop->iteration- current iteration number (starting from 1)$_zte_loop->length- total array length$_zte_loop->first- whether this is the first element (boolean)$_zte_loop->last- whether this is the last element (boolean)$_zte_loop->even- whether this is an even index (boolean, for alternating styles)$_zte_loop->odd- whether this is an odd index (boolean, for alternating styles)$_zte_loop->remaining- number of remaining iterations$_zte_loop->parent- parent loop object (for nested loops; null at the outermost level)
4. Nested loop support
- Multiple levels of nested loops are supported
- An object stack structure manages nested loops
- Each loop level has its own independent loop object
- Access outer loop information through
$_zte_loop->parent
5. loop-else branch
- The else branch is executed when the array is empty
- Syntax:
<!--{loop-else}--> - Must come before
<!--{/loop}-->
6. continue control
- Skips the current iteration and continues with the next
- Syntax:
<!--{continue}--> - Can only be used inside a loop
7. break control
- Breaks out of the current loop
- Syntax:
<!--{break}--> - Can only be used inside a loop
8. Expression support
- All valid PHP expressions are supported: as long as the expression returns a traversable array or an object implementing the Iterator interface, it can be used
- Function calls:
<!--{loop range(1, 10) AS $i}--> - Object method calls:
<!--{loop $obj->getItems() AS $item}--> - Chained object method calls:
<!--{loop $obj->$category->getItems() AS $item}--> - Array access:
<!--{loop $category['items'] AS $item}--> - Object property access:
<!--{loop $obj->items AS $item}--> - Nested function calls:
<!--{loop array_merge($arr1, $arr2, range(1, 10)) AS $item}--> - Complex expression combinations: any combination of PHP expressions is supported
Important note: the template engine uses the extractLoopExpression() method to extract the expression part and then passes it unchanged to PHP's foreach statement. Therefore, any valid PHP expression can be used, as long as it returns a traversable array or an object implementing the Iterator interface.
III. Usage Examples
Example 1: Basic loop
<!--{loop $items AS $item}-->
<p>{$item}</p>
<!--{/loop}-->Example 2: Loop with key and value
<!--{loop $users $key => $user}-->
<p>ID: {$key}, Name: {$user['name']}</p>
<!--{/loop}-->Example 3: Accessing loop index information
<!--{loop $items AS $item}-->
<p>
Index: {$_zte_loop->index},
Iteration: {$_zte_loop->iteration},
Total: {$_zte_loop->length},
<!--{if $_zte_loop->first}-->[first]<!--{/if}-->
<!--{if $_zte_loop->last}-->[last]<!--{/if}-->
{$item}
</p>
<!--{/loop}-->Example 4: Alternating styles (even/odd)
<!--{loop $items AS $item}-->
<div class="<!--{if $_zte_loop->even}-->even<!--{else}-->odd<!--{/if}-->">
{$_zte_loop->iteration}. {$item}
</div>
<!--{/loop}-->Example 5: Remaining count
<!--{loop $items AS $item}-->
<p>
{$item} ({$_zte_loop->remaining} left)
</p>
<!--{/loop}-->Example 6: loop-else branch
<!--{loop $emptyArray AS $item}-->
<p>{$item}</p>
<!--{loop-else}-->
<p>The array is empty</p>
<!--{/loop}-->Example 7: continue control
<!--{loop $items AS $item}-->
<!--{if $item == 'skip'}-->
<!--{continue}-->
<!--{/if}-->
<p>{$item}</p>
<!--{/loop}-->Example 8: Nested loops
<!--{loop $categories AS $category}-->
<h3>{$category['name']} (outer index: {$_zte_loop->index})</h3>
<ul>
<!--{loop $category['items'] AS $item}-->
<li>
Outer index: {$_zte_loop->parent->index},
Inner index: {$_zte_loop->index},
{$item['name']}
</li>
<!--{/loop}-->
</ul>
<!--{/loop}-->Example 9: Function calls
<!--{loop range(1, 10) AS $i}-->
<p>{$i}</p>
<!--{/loop}-->Example 10: break control
<!--{loop $items AS $item}-->
<!--{if $item == 'stop'}-->
<!--{break}-->
<!--{/if}-->
<p>{$item}</p>
<!--{/loop}-->Example 11: Multi-level nesting (3 levels)
<!--{loop $regions AS $region}-->
<h2>{$region['name']} (level 1 index: {$_zte_loop->index})</h2>
<!--{loop $region['cities'] AS $city}-->
<h3>{$city['name']} (level 2 index: {$_zte_loop->index}, parent index: {$_zte_loop->parent->index})</h3>
<ul>
<!--{loop $city['districts'] AS $district}-->
<li>
Level 1: {$_zte_loop->parent->parent->index},
Level 2: {$_zte_loop->parent->index},
Level 3: {$_zte_loop->index},
{$district['name']}
</li>
<!--{/loop}-->
</ul>
<!--{/loop}-->
<!--{/loop}-->Example 12: Using other directives inside a loop (if, switch)
<!--{loop $items AS $item}-->
<!--{if $_zte_loop->first}-->
<div class="first-item">First: {$item}</div>
<!--{elseif $_zte_loop->last}-->
<div class="last-item">Last: {$item}</div>
<!--{else}-->
<div class="normal-item">{$item}</div>
<!--{/if}-->
<!--{switch $_zte_loop->index}-->
<!--{case 0}-->
<span>Index is 0</span>
<!--{case 1}-->
<span>Index is 1</span>
<!--{default}-->
<span>Other index</span>
<!--{/switch}-->
<!--{/loop}-->Example 13: Array access expressions
<!--{loop $categories AS $category}-->
<h3>{$category['name']}</h3>
<!--{loop $category['items'] AS $item}-->
<p>{$item}</p>
<!--{/loop}-->
<!--{/loop}-->Example 14: Object property access and method calls
<!--{loop $obj->items AS $item}-->
<p>{$item}</p>
<!--{/loop}-->
<!--{loop $obj->getItems() AS $item}-->
<p>{$item}</p>
<!--{/loop}-->Example 15: Complex expressions
<!--{loop array_merge($arr1, $arr2) AS $item}-->
<p>{$item}</p>
<!--{/loop}-->
<!--{loop array_filter($items, function($item) { return $item['active']; }) AS $item}-->
<p>{$item['name']}</p>
<!--{/loop}-->Example 16: Chained object method calls
<!--{loop $obj->$category->getItems() AS $item}-->
<p>{$item}</p>
<!--{/loop}-->
<!--{loop $data->getCategories()->getItems() AS $item}-->
<p>{$item['name']}</p>
<!--{/loop}-->Example 17: Nested function calls
<!--{loop array_merge($arr1, $arr2, range(1, 10)) AS $item}-->
<p>{$item}</p>
<!--{/loop}-->
<!--{loop array_slice(array_filter($items, function($i) { return $i > 0; }), 0, 10) AS $item}-->
<p>{$item}</p>
<!--{/loop}-->Example 18: Mixed complex expressions
<!--{loop array_merge($obj->getItems(), $category['items'], range(1, 5)) AS $item}-->
<p>{$item}</p>
<!--{/loop}-->
<!--{loop $obj->getData()->filter(function($item) { return $item['active']; })->toArray() AS $item}-->
<p>{$item['name']}</p>
<!--{/loop}-->Examples 19-25: Complex expression boundary test cases
The following test cases verify the template engine's ability to handle complex expressions, including various boundary cases:
Example 19: Deeply nested function calls
<!--{loop array_slice(array_filter(array_map(function($x) { return $x * 2; }, range(1, 100)), function($x) { return $x > 10; }), 0, 10) AS $item}-->
<p>{$item}</p>
<!--{/loop}-->Explanation: tests multi-level nested function calls and anonymous functions.
Example 20: Chained object methods (multiple levels)
<!--{loop $obj->getData()->filter(function($item) { return $item['active']; })->map(function($item) { return $item['name']; })->toArray() AS $item}-->
<p>{$item}</p>
<!--{/loop}-->Explanation: tests multi-level chained object method calls, including anonymous functions.
Example 21: Mixing array access with object methods
<!--{loop $data['categories'][0]['items'] AS $item}-->
<p>{$item}</p>
<!--{/loop}-->
<!--{loop $obj->getCategories()['items'] AS $item}-->
<p>{$item}</p>
<!--{/loop}-->
<!--{loop $data[$key]['items'] AS $item}-->
<p>{$item}</p>
<!--{/loop}-->Explanation: tests mixing array access with object methods and dynamic key names.
Example 22: Parentheses inside string arguments
<!--{loop array_filter($items, function($item) { return strpos($item['name'], '(') !== false; }) AS $item}-->
<p>{$item['name']}</p>
<!--{/loop}-->Explanation: tests parentheses inside string arguments, ensuring the bracket-matching algorithm does not misjudge.
Example 23: Escape character handling
<!--{loop array_map(function($x) { return str_replace('\\', '/', $x); }, $paths) AS $path}-->
<p>{$path}</p>
<!--{/loop}-->Explanation: tests escape character handling, ensuring escape characters do not affect expression extraction.
Example 24: Complex conditional expressions
<!--{loop array_filter($items, function($item) { return $item['status'] == 'active' && $item['count'] > 0 && !empty($item['tags']); }) AS $item}-->
<p>{$item['name']}</p>
<!--{/loop}-->Explanation: tests expressions containing complex conditions.
Example 25: Mixing all complex features
<!--{loop array_merge(
$obj->getCategories()->filter(function($cat) { return $cat['active']; })->toArray(),
array_map(function($item) { return $item['name']; }, $data['items']),
range(1, 10)
) AS $item}-->
<p>{$item}</p>
<!--{/loop}-->Explanation: tests mixing all complex features (chained calls, anonymous functions, array access, function calls, multi-line format).
IV. Technical Implementation Details
1. Stack structure
$__zte_loop_stack- loop object stack (used to manage nested loops)
2. Code generation structure
if (is_array($arr) && sizeof($arr) > 0) {
// Initialize the stack
// Create the loop object and push it onto the stack
foreach($arr as $key => $value) {
// Update loop information
// Set the global $_zte_loop variable
// Loop body content
}
// Pop the stack and restore the parent loop
}3. Loop object structure
$_zte_loop = (object) array(
'index' => 0, // current index (starting from 0)
'iteration' => 1, // current iteration number (starting from 1)
'length' => count($arr), // total array length
'first' => true, // whether this is the first element
'last' => false, // whether this is the last element
'even' => true, // whether this is an even index
'odd' => false, // whether this is an odd index
'remaining' => 9, // number of remaining iterations
'parent' => $parentLoop, // parent loop object (for nested loops)
);V. Variable Scope
1. Loop variable scope
- Loop variables (such as
$item,$key,$value) are valid inside the loop body - After the loop ends, the loop variables still retain the values of the last iteration
- In nested loops, inner loops can access the variables of outer loops
2. $_zte_loop object scope
$_zte_loopis valid inside the loop body- After the loop ends,
$_zte_loopis cleared or restored to the parent loop object - In nested loops,
$_zte_loopalways points to the current loop object
3. Example
<!--{loop $items AS $item}-->
<p>{$item}</p>
<!--{/loop}-->
<!-- After the loop ends, $item is still accessible and holds the value of the last iteration -->
<p>Last item: {$item}</p>VI. Known Issues and Limitations
1. Limitations
- Loop variables must be arrays or objects implementing the Iterator interface
continueandbreakcan only be used inside a loop- Expressions must return a traversable array or an object implementing the Iterator interface
- Expressions must be valid PHP syntax; the template engine passes them unchanged to PHP's
foreachstatement
2. Caveats
- Loop variables persist after the loop ends, so beware of variable pollution
- In nested loops, the inner loop overwrites the outer loop's
$_zte_loop; useparentto access the outer loop breakonly breaks out of the current loop, not the outer loop- Complex expressions are re-evaluated on every iteration; if the computation is expensive, precompute it in PHP code
3. Expression Boundary Handling
The template engine's extractLoopExpression() method uses a bracket-matching algorithm and correctly handles the following boundary cases:
- ✅ Nested parentheses: supports arbitrarily deep nesting of parentheses (round brackets and square brackets)
- ✅ String literals: correctly handles parentheses, quotes and other special characters inside strings
- ✅ Escape characters: correctly handles escape characters without affecting expression extraction
- ✅ Multi-line expressions: supports expressions in multi-line format (such as Example 25)
- ✅ Dynamic properties: supports dynamic property access such as
$obj->$variable - ✅ Mixed syntax: supports any combination of array access, object methods and function calls
Known limitations:
- Expressions must be valid PHP syntax
- Expressions must return a traversable array or an object implementing the Iterator interface
- If the expression has a syntax error, an error is thrown at PHP runtime (this is normal PHP behavior)