-
Notifications
You must be signed in to change notification settings - Fork 10.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Discussion] Allow substitution in graphql string templates #3186
Comments
It sounds like you're looking for the GraphQL concept of fragments: http://graphql.org/learn/queries/#fragments. Gatsby doesn't support variable names in GraphQL queries as explained here: #2293 |
Thanks @calcsam. I had tried those before (and I'm using inline fragments elsewhere) but I guess I had the formatting wrong because I couldn't get them to work. Your comment inspired me to try them again and now I have it working. Fragments are more flexible than I thought. I guess that solves the issue! |
@sarahatwork how did you get them to work? Do you add them to an external |
Put them wherever it makes sense e.g. in the same page or in a component. Fragments are in a global namespace so you don't have to import them explicitly. |
They do need to be in a js file though. We don't support .graphql files atm. |
Yeah in my case it wound up being:
Still can't do everything I want, like a fragment containing inline fragments, but still reducing some repetition. |
Ah thank you both! I was confused by the syntax, I tried to declare them without template strings so no wonder it didn't work. Graphql was already nice but this is wonderful! |
I'm looking for a more general use case: interpolating the same query in different places. For example, the Sourcing from Ghost example could be fleshed out to output a list of posts with the title linking to the slug. That needs a page with another If interpolation in the |
I'm new to graphql, but I find a lot of my queries are very long and repetitive, and being able to interpolate repeated sections would make my code a lot easier to read and update.
Here's one section of graphql I have on one of my templates:
I wish I could write it like this:
But I get an error triggered by this code: https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby/src/utils/babel-plugin-extract-graphql.js#L10
This code does not run on queries in my
gatsby-node
file, so I've been taking advantage of interpolation there and it's made things a lot easier.I tried to look into a solution for this myself, but I'm a bit out of my element dealing with babel ASTs, so I thought I'd pause and see:
gatsby-node
and send the results to my templates usingtemplateContext
, but that feels wrong 😕The text was updated successfully, but these errors were encountered: