Docly Developers
DocsUpdated 18 Oct 2026

For Loop Examples

Code examples (hashJS) for looping scenarios in hash templates.

Looping an array

Looping javascript syntax:

#for(let item of myArray) {#
    <div>#item.field1#</div>
#}#

Looping an array sorted by field

Looping javascript syntax:

#for(let item of myArray.sort((a, b) => a.Published - b.Published)) {#
    <div>#item.field1#</div>
#}#

Looping an array sorted by field and take a number of the first items

Looping javascript syntax, sorting numbers:

#for(let item of myArray.sort((a, b) => a.Published - b.Published).slice(0, 4)) {#
    <div>#item.field1#</div>
#}#

Sorting texts and dates:

#for(let item of myArray.sort((a, b) => a.name.localeCompare(b.name)).slice(0, 4)) {#
    <div>#item.field1#</div>
#}#

Loop in loop

It is possible to have loops running inside other overarching loops. See the example below:

#for(let user of users) {#
<div>User with name: #user.name#</div> <!-- Name of user  -->
<div>Has access to these folders:</div>
<ul>
    #for(let item of user.folders) {#
    <li>#item.Name#</li> <!-- Folder name -->
    #}#
</ul>
#}#

Recursive loop

Recursive / nested loops use the {{current}} keyword: the inner loop reuses the body of the loop around it. The inner loop must use the same variable name as the outer loop (here: item) — the body reads item.Elements, so with another name it would loop over the same list again and never stop.

#for(let item of Elements) {#
    <h2>#item.Title#</h2>
    <span>#item.Content#</span>
    <blockquote>#for(let item of item.Elements ?? []) {#{{current}}#}#</blockquote>
#}#

Specify multiple loops with the same template

Use the notation, where name is the array expression of the loop whose body you want to reuse:

// Loop array myItems:
#for(let item of myItems) {#
Title: #item.Title#<br />
#}#
 
// Loop another array and reuse the loop body above.
// The variable name must be the same (item), because the body reads item.Title:
#for(let item of myItems2) {#{myItems}#}#

The name inside the braces (myItems) is the array expression of the first loop. The first loop must run before the loop that reuses it.