Skip to content

For Loops

YAPL supports for loops to iterate over arrays and collections, allowing you to generate repeated content dynamically.

{% for item in items %}
{{ item }}
{% endfor %}

Iterate over a simple array of values:

{% for fruit in fruits %}
- {{ fruit }}
{% endfor %}

With variables:

{
fruits: ["apple", "banana", "cherry"];
}

Output:

- apple
- banana
- cherry

Iterate over arrays of objects to access their properties:

{% for technique in study_techniques %}
- **{{ technique.name }}**: {{ technique.description }}
{% endfor %}

With variables:

{
study_techniques: [
{ name: "Pomodoro", description: "25-minute focused work sessions" },
{
name: "Spaced Repetition",
description: "Review material at increasing intervals",
},
{
name: "Active Recall",
description: "Test yourself instead of re-reading",
},
];
}

Output:

- **Pomodoro**: 25-minute focused work sessions
- **Spaced Repetition**: Review material at increasing intervals
- **Active Recall**: Test yourself instead of re-reading

You can iterate over array literals directly in the template:

{% for num in [1, 2, 3, 4, 5] %}
{{ num }}{% if num < 5 %}, {% endif %}
{% endfor %}

Output:

1, 2, 3, 4, 5

For loops can be nested to iterate over multi-dimensional data:

{% for category in categories %}
## {{ category.name }}
{% for item in category.items %}
- {{ item }}
{% endfor %}
{% endfor %}

With variables:

{
categories: [
{ name: "Fruits", items: ["apple", "banana"] },
{ name: "Vegetables", items: ["carrot", "broccoli"] },
];
}

Output:

## Fruits
- apple
- banana
## Vegetables
- carrot
- broccoli

Like other YAPL constructs, for loops support whitespace control using the - modifier:

{%- for item in items -%}
{{ item }}
{%- endfor -%}

This removes whitespace around the for loop tags. See the Whitespace Control documentation for more details.

YAPL will throw an error if you try to iterate over a non-array value:

{% for item in notAnArray %}
{{ item }}
{% endfor %}

If notAnArray is a string or other non-array value, you’ll get an error:

For loop iterable must be an array, got: string

If the array is empty or undefined, the for loop content is simply skipped:

{% for item in emptyArray %}
This won't be rendered
{% endfor %}

Choose meaningful names for your iterator variables

{% for technique in study_techniques %} <!-- Good -->
{% for t in study_techniques %} <!-- Less clear -->

Consider adding conditional checks for empty arrays

{% if techniques %}
{% for technique in techniques %}
- {{ technique.name }}
{% endfor %}
{% else %}
No techniques available.
{% endif %}