Use different _data files in _include based off page user is on

I was trying to create a feature in my theme where if a user wanted to have some images in a gallery on one of their blog posts, they could create a file in _data, and then the images would be rendered in their post. This was based off of Adaptive Photo Layout with Flexbox | CSS-Tricks - CSS-Tricks.
The main issue for me is that I cannot figure out a way to make sure that each blog post doesn’t use the same images.
I wanted to make it so that the user doesn’t have to put any HTML code in their markdown, so I made a file in my _includes folder (which currently has hardcoded paths to some example images) which generates the images into the blog post.
The only way I thought of is if somehow the blog post file name could be parsed, and a folder with that name in _data would exist, where the user would put their images.
I don’t really know how to do this.
Can someone help?

1 Like

My theme is at https://github.com/Parmjot-Singh/jekyll-theme-dusk

Les’s imagine you have _data/galleries/cats.yaml and _data/galleries/dogs.yaml.

You access the variables contained in these files by using the following liquid variables : data.galleries['dogs'] and data.galleries['cats']

On the other hand, you can pass variables to your included partials in the following way :

{% include image-masonry.html gallery_id='dogs' %}

This will make the string 'dogs' available inside your partial as include.gallery_id. This means the variable data.galleries[include.gallery_id] will contain the variables defined in your _data/galleries/dogs.yaml file.

By accessing your data files this way, changing the value of gallery_id from the include tag will change the data file that your image-masonry.html partial accesses.

3 Likes

Sorry for the late reply.
This is not the solution I was looking for, but in a way, I guess this creates a better implementation of what I was trying to do. Thank you very much.

Here is the code I ended up with, disregarding CSS.

<div id="image-gallery">
    <ul>
        {%- for item in site.data.galleries[include.gallery_id] -%}
            <li>
                <img src="/assets/images/gallery/{{ include.gallery_id }}/{{ item.image }}">
            </li>
        {%- endfor -%}
    </ul>
</div>
1 Like