简体   繁体   中英

String interpolation is not allowed in graphql tag. (Gatsby)

Attempting to use an alias for a long complicated Ids within my graphql query:

FAILED TO COMPILE: String interpolation is not allowed in graphql tag:

const query = graphql`
  query MyQuery {
    wordpress {
      menu(id: "${wordpress("mainMenu")}") {
        ...rest of query
      }
    }
  }
`

You should use query variable instead.

Variables can be added to page queries (but not static queries) through the context object that is an argument of the createPage API. docs

// inside template file
export const query = graphql`
  query MyQuery($id: String!) {
    menu(id: { eq: $id }) {
        ...rest of query
    }
  }
`

Then you can provide such variable as part of the page's context in gatsby-node.js . For example:

// gatsby-node.js
const postTemplate = path.resolve(`./src/templates/post.js`)
allWordpressPost.edges.forEach(edge => {
  createPage({
    path: `/${edge.node.slug}/`,
    component: slash(postTemplate),
    context: {
      id: edge.node.id, // 👈
    },
  })
})

Have a look at this using-wordpress example from gatsby.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM