@each

Iterate over collections and arrays to repeat content

The @each directive allows you to iterate over arrays and collections, repeating a block of content for each item. This is essential for rendering lists, galleries, navigation menus, and any repeated content patterns.

Syntax

@each(item in items)
    <!-- Content repeated for each item -->
@endeach

The loop variable (e.g., item) is scoped to the loop block and provides access to each element in the collection.

Parameters

Parameter
Description

item

The loop variable name you define to reference the current item

items

The collection or array to iterate over

Loop Variables

Within an @each loop, you have access to special loop variables that provide information about the current iteration:

Variable
Type
Description

::index

Number

The zero-based index of the current item

::isFirst

Boolean

Returns true if this is the first item in the collection

::isLast

Boolean

Returns true if this is the last item in the collection

These variables are accessed by appending them to your loop variable name (e.g., image::index, page::isFirst).

Examples

Basic List Iteration

Using Loop Index

Access the current index for numbering or JavaScript interactions:

Conditional Styling with isFirst and isLast

Apply different styles to the first or last items:

Grid Overlay with First/Last Detection

Iterate over pages and include different templates based on conditions:

Nested Loops

Loop through hierarchical data structures like nested navigation:

Passing Loop Items to Includes

Pass the current loop item to an include template:

Use the loop index for interactive elements:

Responsive Image Sources

Iterate over responsive image sources:

Best Practices

  1. Use meaningful variable names - Choose descriptive names like page, image, or track rather than generic names like item or i.

  2. Combine with @if for conditional rendering - Use loop variables with conditionals for first/last item styling.

  3. Extract complex item markup - For complex item templates, use @include to keep your main template clean.

  4. Access nested properties - Use dot notation to access nested properties: {{item.author.name}}.

Last updated

Was this helpful?