foreach, break

Syntax

[#foreach variableName in collection]
    body
[/#foreach]
or
[#foreach variableName : typeName in collection]
    body
[/#foreach]

where:

Description

The foreach directive processes a section of the template for each element contained within a collection. It processes the code between the start-tag and end-tag for the 1st element, then for the 2nd element, then for the 3rd element, etc until it passes the last one.

You may leave the foreach loop before it passes the last element of the collection using the break directive.

Examples

This code processes a UML package contents and outputs the name of its owned elements :

[#set package : uml21.Package = ...]
Package contents:
[#foreach element in package.ownedElement]
    name: ${element.name}
[/#foreach]

The above code would produce an output similar to the following:

Package Contents:
    name: Account
    name: Customer
    name: Bank

The code could be rewritten to iterate directly on owned elements names (thanks to automatic collection iteration) :

[#set package : uml21.Package = ...]
Package contents:
[#-- 'package.ownedElement.name' evaluates to a collection 
     containing the name of each owned element of the package --]
[#foreach name in package.ownedElement.name]
    name: ${name}
[/#foreach]

We could decide to break the loop when we encounter the name 'Customer' :

[#set package : uml21.Package = ...]
Package contents:
[#foreach name in package.ownedElement.name]
    name: ${name}
    [#-- break if we encounter a 'Customer' name --]
    [#if name == "Customer"]
        [#break]
    [/#if]
[/#foreach]

Which would result to an output similar to the following:

Package Contents:
    name: Account
    name: Customer