Running `load_data` on co-located files

I have some co-located json files that I want to run load_data on from page.html, but I’m looking for a better way to find the json file’s paths. The structure is like this:

content
├── post1
│   ├── index.md
│   └── my_data.json
├── post2
│   ├── index.md
│   └── my_data.json
└── post3
    ├── index.md
    └── my_data.json

Currently I’m looping through page.assets looking for the asset with the right filename, like this:

{# find the path to my_data.json file path #}
{% for asset in page.assets %}
    {% if asset is ending_with("my_data.json") %}
        {% set_global my_data = load_data(path="content" ~ asset) %}
    {% endif %}
{% endfor %}

But it seems like this should be a one-liner. If there was a page.relative_dir, I could do this:

{% set_global my_data = load_data(path="content" ~ page.relative_dir ~ "my_data.json") %}

Or even better, if load_data paths could be relative to the page if it starts with ./:

{% set_global my_data = load_data(path="./my_data.json") %}

Or did I miss a simple way that’s already possible?

1 Like

I came up with a solution that works well enough for my use case: storing the path to my_data.json in each post’s [extra].

content/my_post/my_post.md

[extra]
my_data_path = "content/my_post/my_data.json"

templates/page.html

load_data(path=page.extra.my_data_path)

Since my posts are generated by a script, the [extra] my_data_path can be filled in automatically for each new post. That’s fine since in my case, all the names and paths are predictable.

Still, it would be very nice to be able to load data relative to the markdown file, load_data(path="./my_data.json"). I took a stab at implementing that in Zola but it seems like a pretty big change to give the load_data function access to anything about the current Page.

1 Like

Yeah, I think that would be too much of a change.