wiziple / gatsby-plugin-intl

Gatsby plugin that turns your website into an internationalization-framework out of the box.
http://gatsby-starter-default-intl.netlify.com
325 stars 178 forks source link

accessing the intl object in graphql #70

Closed fabianrios closed 4 years ago

fabianrios commented 5 years ago

right now intl is an object passed to context on the creating page loop return { ...page, path: newPath, context: { ...page.context, intl: { language, languages, messages, routed, originalPath: page.path, redirect, }, }, }

so if I want to access it later on as part of the context is not possible unless we create some sort of intl Type for graphql that allow us to do so, something like this:

const Intl = new GraphQLObjectType({ name: 'Intl', fields: { language: { type: GraphQLString }, languages: { type: GraphQLList }, messages: { type: GraphQLString }, routed: { type: GraphQLString }, originalPath: { type: GraphQLString }, redirect: { type: GraphQLString }, } });

this will be usefull to create pages which can pull the language dynamically from graphql

erikjalevik commented 4 years ago

I am struggling with the same problem. I am trying to get a GraphQL query inside a template to read the intl.language value set in the context by gatsby-plugin-intl, so that the query can pass the current language code to the CMS.

I would like to be able to say something like:

export const query = graphql`
  query GenericPageQuery($slug: String!, $intl: Object!) {
    contentfulGenericPage(slug: { eq: $slug }, node_locale: { eq: $intl.language }) {
      slug
      ...
    }
  }
`

This is however not valid GraphQL. There is no type Object for the $intl variable, and furthermore the dot access in $intl.language also causes an error.

What is the correct way of doing this?

fabianrios commented 4 years ago

Honestly I clone this project and pass the language property of intl as a string to been able to use it. but there most be a better way to do this.

dsfrederic commented 4 years ago

+1

mmende commented 4 years ago

I managed to use the locale in page queries by adding it manually to the context in gatsby-node.js like so

exports.onCreatePage = ({ page, actions }) => {
  const { createPage, deletePage } = actions
  const { language } = page.context.intl
  deletePage(page)
  createPage({
    ...page,
    context: {
      ...page.context,
      language,
    },
  })
}

...this allows me to then use language in page queries like so e.g.

query MyQuery($language: String) {
  allQuotes(filter: { locale: { eq: $language } } ) {
    content
  }
}

Edit: ...just saw the last comment from @fabianrios suggesting exactly that.

fabianrios commented 4 years ago

solved in https://github.com/wiziple/gatsby-plugin-intl/pull/96