Iteration
You can easily iterate over Arrays and Object using built-in @each
tag.
Arrays
const users = [
{
username: 'virk'
},
{
username: 'joe'
},
{
username: 'nikk'
}
]
<ul>
@each(user in users)
<li> {{ user.username }} </li>
@endeach
</ul>
<ul>
<li> virk </li>
<li> joe </li>
<li> nikk </li>
</ul>
Objects
const veggies = {
tomato: '18',
potato: '77',
carrot: '41'
}
<ul>
@each((calories, name) in veggies)
<li> {{ name }} has {{ calories }} calories </li>
@endeach
</ul>
<ul>
<li> tomato has 18 calories </li>
<li> potato has 77 calories </li>
<li> carrot has 41 calories </li>
</ul>
Loop Variable
When iterating over data sets, you have access to a global $loop
variable holding the iteration information.
<ul>
@each(user in users)
<li> {{ ($loop.index + 1) }} - {{ user.username }} </li>
@endeach
</ul>
<ul>
<li> 1 - virk </li>
<li> 2 - joe </li>
<li> 3 - nikk </li>
</ul>
Loop Variable Properties
Property |
Description |
$loop.index |
Holds the iteration index, start from 0 |
$loop.first |
Whether or not the item is the first in the loop |
$loop.last |
Whether or not the item is the last in the loop |
$loop.total |
The total number of items |
$loop.isEven |
Whether or not an iteration count is an even number. |
$loop.isOdd |
Whether or not an iteration count is an odd number. The first item returns true for |
Conditional Loops
Quite often you want to show a fallback message when the iteration data set is empty. Edge makes it easier to make use of @else
tag within the @each
tag.
Template File
<ul>
@each(user in users)
<li> {{ user.username }} </li>
@else
<h2> No users found </h2>
@endeach
</ul>
Include Partial
Each tag also makes it easier to include a partial for each iteration round.
<li> {{ user.username }} </li>
@!each(user in users, include = 'partials.user')