Overview
@each is a method (not a loop structure) that is often used to iterate over arrays or collections.
It’s a more functional and concise way of doing loops, often preferred for array manipulation.
It’s like saying:
“For each item in the collection, do something with it!”
Syntax (Generic Form)
@each(cards:card) {
<i>Index @(_i): </i><b>@(card.name)</b>
}How It Works
-
The
@eachmethod iterates over each element in an array. -
It executes the provided function for each item in the collection, passing the item, index
@(_i), and the entire array as parameters. -
Using
@(_i)you can access the current item’s index,_iis built in.
Example (JavaScript)
index.js
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function (num) {
console.log(num * 2); // Double each number
});Output:
2
4
6
8
10Example (Zare)
res.render('index', {
items: [
{ name: 'Soap', price: 20 },
{ name: 'Rice', price: 50 },
{ name: 'Oil', price: 100 },
],
});index.zare
serve (
<ul>
@each (items:item) {
<li>@(item.name) - $@(item.price)</li>
}
</ul>
)Output:
<ul>
<li>soap - $20</li>
<li>Rice - $50</li>
<li>Oil - $100</li>
</ul>Key Points
-
@eachcannot break or continue the loop early. If you need that. -
It’s a keyword, and it only works with arrays (or array-like objects).
-
The block inside
{…}is executed for each element in the collection.
Last updated on