For Loop Examples Last updated: 21. Jun 2024
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(var item in user.folders) {#
<li>#item.Name#</li> <!-- Folder name -->
#}#
</ul>
#}#
Recursive loop
Recursive / nested loops use the {{current}} keyword in the template, see example:
#for(let item of Elements) {#
<h2>#Title#</h2>
<span>#Content#</span>
<blockquote>#for(var item in Elements) {#{{current}}#}#</blockquote>
#}#
Specify multiple loops with same template
Use the {templatename} notation, example:
// Loop array Items:
#for(let item of myItems) {#
Title: #Title#<br />
#}#
// Loop another array and reuse the loop body:
#for(let item in myItems2) {#{myItems}#}#
The name "Items" is the same as the text in the loop array statement.