For Loop Examples Last updated: 05. Oct 2023

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

Looping an array

Looping javascript syntax:

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

Looping an array sorted by field

Looping javascript syntax:

#for(var 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(var item of myArray.sort((a, b) => a.Published - b.Published).slice(0, 4)) {#
    <div>#item.field1#</div>
#}#

Sorting texts and dates:

#for(var 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(var user of users) {#
<div>User with name: #user.name#</div> <!-- Name of user  -->
<div>Has access to these folders:</div>
<ul>
    #for(var item in user.folders) {#
    <li>#item.Name#</li> <!-- Folder name -->
    #}#
</ul>
#}#

Recursi­ve loop

Recursive / nested loops use the {{current}} keyword in the template, see example:

#for(var item of Elements) {#
    <h2>#Title#</h2>
    <span>#Content#</span>
    <blockquote>#for(var item in Elements) {#{{current}}#}#</blockquote>
#}#

Specify multipl­e loops with same templat­e

Use the {templatename} notation, example:

// Loop array Items:
#for(var item of myItems) {#
Title: #Title#<br />
#}#
 
// Loop another array and reuse the loop body:
#for(var item in myItems2) {#{Items}#}#

The name "Items" is the same as the text in the loop array statement.