Fetch content from rich text field

送分小仙女□ 提交于 2021-01-28 21:12:43

问题


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


回答1:


references stands for a reference 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. ​



来源:https://stackoverflow.com/questions/65751495/fetch-content-from-rich-text-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!