Stand with Ukraine 🇺🇦
Products
Services
Blog
About Us

Foreach

The #foreach directive is a looping construct in the Velocity that iterates over elements in a collection.

#set($fruits = ["Apple", "Banana", "Cherry"])

#foreach ($fruit in $fruits )
  $fruit
#end

Loop Variables

Example with usage of accessible foreach context variables.

  • $foreach.index: Zero-based index of the current iteration.

  • $foreach.count: One-based index of the current iteration.

  • $foreach.first: true if the current iteration is the first, else false.

  • $foreach.last: true if the current iteration is the last, else false.

  • $foreach.parent: References the parent loop’s context in nested loops.

  • $foreach.hasNext: Returns whether next element it present

  • $foreach.top: Returns the top-level loop context.

  • $foreach.stop: Stepping out from the loop

#set($array = ["First", "Second", "Third"])

#foreach ($element in $array)
  <li>
  1-based index : $foreach.count <br>
  0-based index : $foreach.index <br>
  First : $foreach.first <br>
  Last : $foreach.last <br>
  Has next : $foreach.hasNext <br>
  Value : $element <br>
  </li>
#end

Else block

Else block is accessible in for loop, and will be executed if provided parameter is null, empty or does not have any valid iterator. In this case $array is not defined so it is null

#foreach ($element in $array)
  #else 
  Array is null, empty or does not have any valid iterator 
#end

Range definition

For loop can also be defined using range argument, in this example for loop will have 5 iterations

#foreach ($item in [1..5])
    $item
#end

Use cases

Foreach is very useful when working wiht Confluence REST Api via $ConfluenceManager object in context.

Iterating child pages of current page

#set ( $children = $ConfluenceManager.get("/wiki/api/v2/pages/${page.id}/children").results )

#foreach($child in $children)
  $child.title
#end

Pagination of pages inside space

Retrieving all pages from space is limited per request, due maximum value for limit parameter is 250. This code snippet will allow to retrieve all of the pages using pagination. This code is available in Page Pagination macro in User Macro Library.

#set($allPagesInSpace=[])

#set($link="/wiki/api/v2/spaces/$space.id/pages?limit=250")

#foreach($n in [1..1000]) ## Range can be set to bigger number if needed
  #set($pages=$ConfluenceManager.get($link))
  #set($noPrint=$allPagesInSpace.addAll($pages.results))
  
  #if($pages._links.next)
    #set($link=$pages._links.next)
  #else
    #break
  #end
#end

#foreach ( $page in $allPagesInSpace )
  <li>$page.title</li>
#end