Default Loop Variable Name
-
Rule: The default variable name for foreach loops SHOULD be
$item. -
Reason: Using a consistent default name makes code more predictable and easier to copy/reuse. However, more descriptive names are acceptable when clarity requires it.
Example (Correct):
<!-- Default naming -->
<ul n:foreach="$products as $item">
<li>{$item->name}</li>
</ul>
<!-- Descriptive naming when needed for clarity -->
<table>
<tr n:foreach="$orders as $order">
<td>{$order->number}</td>
<td>
<span n:foreach="$order->items as $item">{$item->name}</span>
</td>
</tr>
</table>
Using $iterator
-
Rule: The
$iteratorvariable SHOULD be used for loop metadata.
Example:
<ul>
<li n:foreach="$items as $item" n:class="$iterator->first ? first, $iterator->last ? last">
{$iterator->counter}. {$item->name}
</li>
</ul>
n:if and n:ifset
-
Rule: Use
n:iffor conditions andn:ifsetfor checking variable existence.
Example:
<p n:if="$showDescription">{$description}</p>
<div n:ifset="$optionalContent">
{$optionalContent}
</div>
n:class for Dynamic Classes
-
Rule:
n:classSHOULD be used for conditional CSS classes.
Example:
<div n:class="$isActive ? active, $isDisabled ? disabled, base-class">
Content
</div>
Summary:
- Default foreach variable name SHOULD be
$item. - Use
$iteratorfor loop metadata (counter, first, last). - Use
n:if,n:ifset, andn:classfor cleaner templates.