Skip to main content

Overview

Loops in PromptL allow you to dynamically generate content or messages by iterating over lists or arrays. This is particularly useful for creating adaptive prompts based on user input or contextual data. With loops, you can:
  • Repeat sections of your prompt for each item in a list.
  • Access each item’s index for numbered output or additional logic.
  • Handle empty lists gracefully using the else clause.

Syntax

Basic Loop

A loop is defined using the for and endfor keywords, wrapped in {{ }}. The content inside the loop is repeated for each item in the list.

Loop with Index

You can include an index parameter to track the iteration count, starting from 0.

Loop with else

The else clause runs when the list is empty. Place it before the endfor keyword.

Examples

Basic Example: Listing Items

Output:

Example with Index

Output:

Handling Empty Lists

Output:

Advanced Usage

Iterating Over Objects

Loops can handle more complex data structures, such as arrays of objects.
For the input:
Output:

Nested Loops

You can use nested loops for iterating over multi-dimensional data.
For the input:
Output:

Best Practices

  1. Keep Loops Simple:
    • Avoid deeply nested loops unless necessary. Complex loops can make your prompts harder to read and maintain.
  2. Use Default Values:
    • Provide defaults for variables to prevent errors when lists are empty or data is incomplete.
    • Example: {{ item || "Unknown" }}
  3. Combine with Conditionals:
    • Use if statements inside loops for conditional logic.
  4. Debugging:
    • Temporarily output the list and its elements to ensure the loop is iterating as expected.

Debugging Tips

If your loop isn’t working as expected:
  • Verify Data: Print the list you’re iterating over to ensure it contains the expected data.
  • Check Syntax: Ensure endfor is present and properly matched with for.
  • Use else for Debugging: Add an else clause to confirm whether the list is empty.

Summary

Loops in PromptL enable you to iterate over lists dynamically, generate repeated content, and handle complex data structures. By combining loops with variables and conditionals, you can create powerful, adaptive prompts tailored to any use case.
Ready for more dynamic control? Explore Conditional Statements to complement your loops.