foreach

Syntax

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

where:

Description

The foreach tag 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.

Examples

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

[#parameters]in model : uml21[/#parameters]
[#file]result.xml[/#file]
Package contents:
[#set]package = model.getInstances(“Package”).first()[/#set]
[#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) :

[#parameters]in model : uml21[/#parameters]
[#file]result.xml[/#file]
[#comment]'package.ownedElement.name' evaluates to a collection containing the name of each owned element of the package[/#comment]
Package contents:
[#set]package = model.getInstances(“Package”).first()[/#set]
[foreach name in package.ownedElement.name]
    name: ${name}
[/#foreach]