[solved] Can I nest ranges looking at data?

I’m trying to loop through one set of data and inside that loop through a second set looking for appropriate matches.

My code has a file of speakers and a file of sessions they’re giving (data structure below). Sessions can have more than one speaker and speakers can have more than one session. That association is recorded as an array of session slugs on the speaker object (and vice versa).

I know I’ve got the loops set up right because they work when they are not nested:

Works :+1:

    {{ range $speaker := .Site.Data.berlin_speakers.speakers }}
        <div>slug: {{ $speaker.slug }}</div>
    {{ end }}

    {{ range $session := .Site.Data.berlin_sessions.sessions }}
        <div>slug: {{ $session.speakers }}</div>
    {{ end }}

But when I nest the loops the inner one stops working :-1:

    {{ range $speaker := .Site.Data.berlin_speakers.speakers }}
        <div>slug: {{ $speaker.slug }}</div>
            {{ range $session := .Site.Data.berlin_sessions.sessions }}
                <div>slug: {{ $session.speakers }}</div>
            {{ end }}
    {{ end }}

It does not output anything but it doesn’t throw any errors either.

(The ultimate goal is to loop through the speakers and output links to their sessions, so I’m also open to other ways I could achieve this).

The data looks something like this:

Speakers:

[[speakers]]
slug = "jo-doe"
first = "Jo"
last = "Doe"
bio = "Our title speaker!"
sessions = ["greatness", "the-title"]

[[speakers]]
slug = "harpreet-singh"
first = "Harpreet"
last = "Singh"
bio = "Harpreet is great!"
sessions = ["greatness"]

Sessions:

[[sessions]]
slug = "greatness"
speakers = ["harpreet-singh", "jo-doe"]
title = "Greatness"
summary = "It will be great!"

[[sessions]]
slug = "the-title"
speakers = ["jo-doe", "buddy-whats-his-name"]
title = "The Title"
summary = "Talking about titles."

Any help is appreciated :smile:

I try to avoid self promotion but I wrote this piece for this kind of threads which pop up quiet often: https://regisphilibert.com/blog/2018/02/hugo-the-scope-the-context-and-the-dot/

Bottom line: you need to use $ from inside a range to refer to the top level page context so:

{{ range $session := $.Site.Data.berlin_sessions.sessions }}
2 Likes

That solves it! And thank you for sharing the article! It was super appropriate and now I understand what’s going on :smile:

1 Like

Welcome to the discourse! :wink: