Creating 2 layouts from same component with different context
See original GitHub issueHello,
I am developing a multilingual website and need to pass the current language to
the layout. For this I used createLayout
:
const path = require(`path`)
const slash = require(`slash`)
const MainLayout = path.resolve(`./src/templates/MainLayout.jsx`)
const homeTemplate = path.resolve(`./src/templates/Home.jsx`)
const languagePath = {
'ar-EG': '/',
'fr-FR': '/fr/',
}
Object.keys(languagePaths).forEach((locale) => {
createLayout({
component: slash(MainLayout),
id: `main-layout-${locale}`,
context: {
locale,
},
})
})
// home pages
Object.entries(languagePaths).forEach(([locale, languagePath]) => {
createPage({
path: languagePath,
component: slash(homeTemplate),
context: {
languagePath,
locale,
},
layout: `main-layout-${locale}`
})
})
The problem is that when I log props.layoutContext.locale
inside my
MainLayout
, I always get fr-FR
(on the arabic page and the french page)
While investigating, I could make it work when I duplicate my template/MainLayout file, and use one file for each language (this is very very ugly):
const MainLayout = path.resolve(`./src/templates/MainLayout.jsx`)
const MainLayout2 = path.resolve(`./src/templates/MainLayout2.jsx`)
// layout for each lang
Object.keys(languagePaths).forEach((locale, i) => {
createLayout({
component: slash(i === 1 ? MainLayout2 : MainLayout),
id: `main-layout-${locale}`,
context: {
locale,
},
})
})
After that I tried to debug it in gatsby, cloned the repo, and configured redux-devtools.
While examining the store, I noticed that the layouts are created correctly with the good context for each layout, and that pages are also created correctly, with their corresponding layout id.
I am a bit stuck because redux-tools resets its history while building, so I cannot look at the actions creating the pages to try and debug more.
Can you give me any indication to how to investigate further ?
Issue Analytics
- State:
- Created 6 years ago
- Comments:8 (3 by maintainers)
Top GitHub Comments
It is not nice to pass data from the page to the layout in my opinon, it is like passing data from a child to a parent when we can pass the data in the normal way.
I prefer creating a layout for each language. All pages of one language will use the same layout. Here is some code:
gatsby-node.js :
MainLayout.jsx
For the translated slugs I don’t know how you have to do it though.
Thanks @abumalick, I ended up using the English (base) slugs for the translated articles.
Seems it’s the way Gatsby is structured. In Jekyll you don’t specifically pass variables back up the layout, but the layout will execute one time for each page and so it can expect variables as if it were the page itself. In Gatsby it seems to render the template once, then repeat that for each page.