How to know which level you're at in a nested Experience Group hierarchy

This is an interesting problem I just had to solve, so I thought I’d share it here. The problem is how to know which level you’re in when rendering an Experience Group hierarchy in a custom Experience Page.

Looking at an example Experience Group hierarchy, here are the levels we’d like to know:

In most cases, the Group: Summary Node is used to retrieve the hierarchy. Its output looks like this:

It’s a recursive object where each group has a name, ID, and a collection of children. If we want to add a level property to each of these group objects to indicate its level in the hierarchy, we can do so with a Function Node:

let groups = payload.working.groups;

let setLevel = function(group, level) {
  group.level = level;
  group.children.forEach((child) => setLevel(child, level + 1));

setLevel(groups, 0);

The above function assumes you’ve placed the result of the Group: Summary Node on the payload at working.groups. It then recursively iterates over each group and adds the current level.

Now when you pass this into an Experience Page, you’ll be able to access the current level in your Handlebar templates.