Skip to content
Suppenhuhn79 edited this page May 17, 2021 · 8 revisions

Data items that are arrays can be iterated. For each item in the array the child elements will be produced.

<ps:for-each list="myArray">
  <!-- elements-->
</ps:for-each>

Each array item will get additional properties:

  • _position <number> the items position within the array, starting at 1
  • _count <number> the total count of the arrays items

If the array items are simple types (string, number or boolean), the array items will be transformed to objects having the _position and _count-properties. The original value will become the _value-property.

Example

This example demonstrates the usage of Lists, "switch"-conditions and text.

Snippet:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<ps:pagesnippets xmlns:ps="https://github.com/suppenhuhn79/pagesnippets">
  <ps:snippet name="nameslist">
    <div>
      <ps:for-each list="names">
        <ps:text>{{_value}}</ps:text>
        <ps:choose>
          <ps:if test="{{_position}} &lt; {{_count}} -1">
            <ps:text>,&#32;</ps:text>
          </ps:if>
          <ps:if test="{{_position}} &lt; {{_count}}">
            <ps:text>&#32;and&#32;</ps:text>
          </ps:if>
          <ps:else>
            <ps:text>.</ps:text>
          </ps:else>
        </ps:choose>
      </ps:for-each>
    </div>
  </ps:snippet>
</ps:pagesnippets>

Script:

var data = {
  "names": ["Alice", "Bob", "Charly", "Debby"]
};
document.body.appendChild(pageSnippets.nameslist.produce(this, data));

Results in:

<div>Alice, Bob, Charly and Debby.</div>

Function calls / postproduction

If there is a <ps:call-function>-element among the child elements or any of them contains a ps:postproduction="…"-attribute, the data provided to the function is the current array item.

Empty arrays

You can produce extra output for empty arrays.

<ps:for-empty list="myArray">
  <!-- elements in case the list does not have any items -->
</ps:for-empty>

That is equivalent to <ps:if test="{{myArray.lenght}} === 0">.

Clone this wiki locally