简体   繁体   中英

Fetch content from rich text field

I am following this documentation to render rich text from Contentful.

So far I have installed gatsby-source-contentful , now I am querying the rich text content with a graphQL query, before adding to my template.

Issue: I cannot query the references field.

From my understanding there was a recent breaking change that required the raw subfield to be queried...but unfortunately I can't query any subfield within raw .

I am not sure what the issue can possibly be.

Query

{
  allContentfulArticle {
    edges {
      node {
        content {
          raw
          references {
            ... on ContentfulArticle {
              contentful_id
              title
              slug
            }
          }
        }
      }
    }
  }
}

Error message在此处输入图像描述

references stands for areference content model , which is a way of retrieving data from another entry by adding them one by one in the main entry. The guide is assuming that you have followed exactly the same structure but it's not needed. If you don't have a reference content model, don't query it. The GraphQL playground ( localhost:8000/___graphql ) will show you all the available queryable fields.

In addition, the guide is using a GraphQL fragment on ContentfulAsset , not on ContentfulArticle , again, is assuming that you've added an asset entry for your article, don't query it if it's not available or you don't have it. You just need to customize the query for your use-case and your own fields.

{
  allContentfulArticle {
    edges {
      node {
        content {
          raw
        }
      }
    }
  }
}

With the query above, you should be able to gather all the raw data from the rich text model. However, you need to add a transformer in your Gatsby project, which will render and parse the correct component for each type of rich text (bold text, embedded entries, links, code, etc).

import { BLOCKS, MARKS } from "@contentful/rich-text-types"
import { renderRichText } from "gatsby-source-contentful/rich-text"
​
const Bold = ({ children }) => <span className="bold">{children}</span>
const Text = ({ children }) => <p className="align-center">{children}</p>
​
const options = {
  renderMark: {
    [MARKS.BOLD]: text => <Bold>{text}</Bold>,
  },
  renderNode: {
    [BLOCKS.PARAGRAPH]: (node, children) => <Text>{children}</Text>,
    [BLOCKS.EMBEDDED_ASSET]: node => {
      return (
        <>
          <h2>Embedded Asset</h2>
          <pre>
            <code>{JSON.stringify(node, null, 2)}</code>
          </pre>
        </>
      )
    },
  },
}

   renderRichText(node.bodyRichText, options)

More details here and in the gatsby-source-contentful docs .

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