I am trying to make a Gallery. It should display images from different occasions like a blog.
For this I have a JSON file in which all posts (title, slug, date and images-folder-path) are stored. To display them I'm using GraphQL.
My problem now is to display all images for the respective post. In the JSON file only the path to the images is stored.
JSON structure:
[
{
"title": "Gallery 1",
"slug": "gallery-1",
"date": "02.01.2022",
"images": "./gallery-1/"
},
{
"title": "Gallery 2",
"slug": "gallery-2",
"date": "15.01.2022",
"images": "./gallery-2/"
}
]
Now for Gallery 1 I would like to get all the images stored in the ./gallery-1/ folder and so on.
query MyQuery {
allGalleriesJson {
edges {
node {
title
slug
date
images
}
}
}
}
When I run this GraphQL command, I get the string of the path. But now I would like to get all images in the folder with this string. How can I achieve that?
I think you want to use the filter
filter (quite redundant) to get all the images in the /gallery-1/
(or each gallery) folder.
To do that, you just need to provide a context variable to your template, using the context
available in your createPage
function.
createPage({
path: node.slug,
component: path.resolve(`./src/templates/your-template-file.js`),
context: {
slug: node.slug,
},
})
Note: this is an abstraction since no boilerplate has been provided. Tweak it as you wish but get the idea of passing a slug
for each gallery object.
After that, in your template (your-template-file.js
) you'll need to filter the query using the slug
provided (different for each page)
export const query = graphql`
query TemplateQuery($slug: String!) {
allGalleriesJson(filter: {fileAbsolutePath: {eq: $slug }}) {
edges {
node {
title
slug
date
images
}
}
}
Note: the allGalleriesJson
may be different or you may have galleriesJson
available. If so, use it, it's more performant to point a specific node than all of them
Here I'm using the eq
(equals) filter but you have a bunch available: https://www.gatsbyjs.com/docs/query-filters/
In the same way, you can use absolute paths (fileAbsolutePath
) or relative. Test your queries in the GraphiQL playground (localhost:8000/___graphql
).
Despite the query or the snippets may differ from this example, get the idea:
gatsby-node.js
+ createPage
)slug
variable into the template through the contextallGalleriesJson
to get your folder images