Skip to main content
NiCE KnowledgeKnowledge

On October 21, we applied a security patch across all NiCE KM production environments to address a recently disclosed PHP vulnerability. The update was completed without service disruption, and our team continues to monitor the platform closely. No action is required on your part.

NiCE Knowledge Success Center

Use the foreach statement

Applies to:
All versions
Role required:
Draft Contributor
The foreach statement enables iteration over list or map. It also sets the the global variable __count to indicate how many iterations it has performed so far.

The foreach statement iterates over a list or map, and runs a block of DekiScript once per item and inserts each result into the page. It is the standard way to turn a list of data into repeated content, such as rows, list items, or cards, without writing it out by hand.

While it runs, foreach also sets the global variable __count, a 1-based counter of how many iterations have completed so far. Use __count any time the output needs to know its position. This can be for numbered lists; alternating styles such as table rows; or to know when an item is first, last, or somewhere in between.

Iteration

Over a list

Input:

{{ foreach(var x in [ 1, 2, 3 ]) { x } }}
                

Output on the page: 123

Each iteration's result is concatenated directly into the page. There is no automatic spacing or separator between items.

Over a map

Input:

{{ foreach(var x in { a: 1, b: 2, c: 3  }) { x } }}
                

Output on the page: 123

Note that foreach over a map iterates the map's values, not its keys. X here is 1, 2, 3, not a, b, c.

Use cases

Outcome Example
Number items __count + ". " + name
Alternate row / card styles __count % 2 == 0 ? "even" : "odd"
Detect the last item (to omit a trailing separator) compare __count to the list's length
Conditional logic tied to position Insert a divider every 3rd item

Numbered list

Iteration shows the mechanics, but the useful pattern is generating markup with __count to perform the numbering:

{{ foreach(var name in ["Alice", "Bob", "Carol"]) {
     __count + ". " + name + "<br/>"
} }}
                

Output on the page:

1. Alice
2. Bob
3. Carol

Striped table rows

__count can do conditional styling, such as alternating row classes in a table:

{{ foreach(var item in ["Widget", "Gadget", "Gizmo"]) {
     "<tr class=" + (__count % 2 == 0 ? "even" : "odd") + ">"
     + "<td>" + item + "</td></tr>"
} }}

Each <tr> gets class="odd" or class="even" based on its position, which so a CSS rule to shade every other row. This is a common pattern for readable tables.

  • Was this article helpful?