Access Content markdown file based on filename obtained from json Data file

Hello, I have a .json Data file, which contains a string array with slugs, let’s say ["red", "green", "blue"].

In my content directory I have markdown files like this: content/favorite/colors/red.md

When I loop over the ["red", "green", "blue"] array that I accessed from the .json file, how can I load the content markdown file in order to access its parameters and text? I’m only interested in loading the content from say 3 markdown files out of 1000, so would ideally fetch the file directly without any loop.

SHORT: getPage and printf :wink:

LONG:

{{ $yourJSONData := slice "red" "green" "blue" }}
{{ range $yourJSONData }}
  {{ $thePage := printf "favorite/colors/%s" . }}
  {{ $thePageYouWant := getPage $thePage }}
  {{ with $thePageYouWant }}
    Title: {{ .Title }}
    Content: {{ .Content }}
  {{ end }}
{{ end }}
  • you range through whatever part of your data configuration. I did a quick slice-collection here.
  • inside of the first range the dot (.) is one of your favourite colours
  • you print a path to the files with your favourite colours
  • the getPage “gets the page” and returns a page object
  • the with takes the page and puts it into the dot (.)
  • do your stuff with the page
  • move on to the next
1 Like

Thanks for the fast reply, the code is really great, and exactly what I need :slight_smile:
There’s one problem though, I for some reason get nopPage when I try to show the content of {{ $thePageYouWant }} even though I’m certain the page exists (if I open e.g. localhost:1313/favorite/colors/red/ then it will load the content of the red.md file).

When I do printf then I can also see the path is correct: I’ve tried where {{ $thePage }} returned:

  • /favorite/colors/red.md
  • favorite/colors/red.md
  • /favorite/colors/red
  • favorite/colors/red

Based on the documentation you linked, I think /favorite/colors/red.md would be correct, but not sure… I should probably also mention that in my project I support multiple languages, I’m not sure if that could have any impact, but I don’t think so since I use the full path which include the language (e.g. /en/favorite/colors/red.md).

The one thing I never know about is multilingual sites, but the docs say you should try the slash at the beginning and no file extension at the end:

Ahh great, the problem was that I included the language in the file path, so it became e.g. /en/favorite/colors/red but removing the language so it was simply /favorite/colors/red worked. Thanks a lot :slight_smile:

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