Traverse

A traverse flow allows a block of code to be executed once for each item in an array, and then for subsequent arrays contained within a specified key, if any. The order of iteration is guaranteed because iteration happens over sourced arrays.

The traverse flow loops through nested data recursively, flattening the output. Basic usage of the traverse tag is as follows:

Syntax

Basic syntax of traverse flow is as follows:

{[ traverse [key] into [value] source [source] ]}
    {{ value }}
{[/]}

With the following required attributes:

  • key - key of the iterated value within the current context

  • value - the newly created property where iteration data is stored

  • source - The source array

A traverse flow can be used to flatten nested structures, such as components. Components in Supernova are represented as a tree - parent components such as views can contain many other components (their children). This can go into unlimited depth.

In order to list all components in a hierarchy, iteration needs not only to go through the source array but also dive into all its descendants (children of the root view) and do that for unlimited depth.

Let's assume we have a variable componentTree defined that contains the following data (a simplified version of Supernova component data model):

"componentTree": {
    "name": "Container",
    "frame": "100, 100, 100, 100",
    "components": [{
        "name": "Subview 1",
        "frame": "0, 0, 50, 50",
        "components": []
    }, {
        "name": "Subview 2",
        "frame": "50, 50, 50, 50",
        "components": [{
            "name": "Sub-sub view 1",
            "frame": "0, 0, 50, 50",
            "components": []
        }]
    }]
}

The componentTree contains 4 views spread over 3 levels of depth. We can use traverse flow to allow for this nested iteration:

{[ traverse components into component source componentTree ]}
    {{ shape.name }}
{[/]}

The blueprint takes componentTree - the source dictionary as the first item of iteration and then checks for components key, expecting an array. If an array is encountered, the iteration continues within that leaf of the tree. The generated result will then look like this:

  Container
  Subview 1
  Subview 2
  Sub-sub view 1

Last updated