Shortcode accepting parameter of file located in data subfolders

Hello, I would like to create a shortcode that can load a data file with any path/filename.

Let’s say I have a shortcode called: shortcodes/feature.html containing something like this:

{{ $filename := (.Get "filename) }}
{{ $data := index .Site.Data $filename  }}
<p>{{ $data }}</p>

In my content markdown file I’d like to call the shortcode like this: {{< feature filename="somefolder/somefilename" >}}

The code works fine if I don’t include folder path and just call the file stored in the root of data, e.g. data/myfile.json can be obtained with {{< feature filename="myfile >}}, however data/myfolder/myotherfile.json cannot be called with {{< feature filename="myfolder/myotherfile >}}.

I’ve tried various things, such as {{< feature filename="myfolder.myotherfile >}}. I’ve also tried to update the shortcode to accept other parameters like {{< feature directory="myfolder" filename="myotherfile" >}} and then in shortcode write {{ $data := (index (index .Site.Data $directory) $filename }} after defining the variables like above. However, so far I’ve had no luck with any of my attempt, and I can’t find any documentation describing how to achieve this, or any code on GitHub that seems to solve this use case.

In the ideal scenario then there would be a solution that just had to accept a single parameter containing the full path containing an unlimited amount of subfolders, but would be very happy with any solution.

Any help would be much appreciated (:

index function accepts slice/array arguments, so we can split the filename value by / then pass it .to index function.

{{ $filename := (.Get "filename) }}
{{ $data := index .Site.Data (split $filename "/")  }}
<p>{{ $data }}</p>
2 Likes

Amazing, thank you so much <3

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.