ViewFish Templating
Loop Indexes
Inside a {{@loop}} block, ViewFish automatically injects several meta-variables that give you information about the current iteration:
| Variable | Description |
|---|---|
{{@index}} |
Zero-based index of the current item (0, 1, 2, ...) |
{{@count}} |
One-based counter (1, 2, 3, ...) |
{{@first}} |
Truthy (1) on the first iteration, empty otherwise |
{{@last}} |
Truthy (1) on the last iteration, empty otherwise |
{{@total}} |
Total number of items in the loop |
Example
Template:
<ol>
{{@loop data=items}}
<li>
#{{@count}} of {{@total}}: {{name|ucwords}}
{{isset $@first}} ⭐ First!{{/isset}}
{{isset $@last}} 🏁 Last!{{/isset}}
</li>
{{/loop}}
</ol>
PHP:
$data = [
'items' => [
['name' => 'apple'],
['name' => 'banana'],
['name' => 'cherry'],
],
];
echo $t->render($template, $data);
Output:
<ol>
<li>#1 of 3: Apple ⭐ First!</li>
<li>#2 of 3: Banana</li>
<li>#3 of 3: Cherry 🏁 Last!</li>
</ol>
Using {{@first}} and {{@last}} with conditionals
Since {{@first}} and {{@last}} are truthy/empty values, you can use them with {{isset}} and {{unless}} to conditionally show content:
{{@loop data=people}}
{{name}}{{unless $@last}}, {{/unless}}
{{/loop}}
This produces a comma-separated list without a trailing comma.
You can see this in action in Example 8.