Adding Loops
With DocuBloom, you can easily create dynamic templates that include loops to iterate over arrays of data. This is particularly useful for generating lists, tables, or any repeated content based on your data structure.
Let’s explore how to use loops in your templates effectively.
Syntax Overview
To create a loop in your template, use the {FOR ... IN ...}
syntax to iterate over items in an array, and close the loop with {END-FOR}
.
Each item in the loop can be accessed using the $
prefix. Here’s a basic example assuming you have an array of items:
{
"items": [
{ "name": "Item 1", "price": 10 },
{ "name": "Item 2", "price": 20 },
{ "name": "Item 3", "price": 30 }
]
}
You can list these items in your template like this:
{FOR item IN items}
- {$item.name}: {$item.price}
{END-FOR items}
This will iterate over the items
array and output each item’s name and price.
A frequent mistake is to forget the $
prefix when accessing variables inside loops. Always use {$item.name}
instead of {item.name}
.
Creating Rows in Tables
To create rows in a table using loops, create your table structure in the template and use the loop syntax inside the table body to repeat rows for each item in your array.
------------------------------------------------
| Name | Price |
------------------------------------------------
| {FOR item IN items} | |
------------------------------------------------
| {$item.name} | {$item.price} |
------------------------------------------------
| {END-FOR item} | |
------------------------------------------------
This will generate a table where each row corresponds to an item in the items
array, displaying its name and price.
Nested Loops
You can also nest loops to handle more complex data structures. For example, if each item has a list of attributes, you can loop through those as well:
{
"items": [
{
"name": "Item 1",
"price": 10,
"attributes": ["Red", "Large"]
},
{
"name": "Item 2",
"price": 20,
"attributes": ["Blue", "Medium"]
}
]
}
You can access the attributes in your template like this:
{FOR item IN items}
- {$item.name}: {$item.price}
{FOR attr IN $item.attributes}
* {$attr}
{END-FOR attr}
{END-FOR item}
This will output each item’s name and price, followed by a list of its attributes.