从富文本字段中获取内容 [英] Fetch content from rich text field

查看:101
本文介绍了从富文本字段中获取内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注

解决方案

引用代表

更多详细信息此处并在 gatsby-source-contentful 文档.

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 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. ​

这篇关于从富文本字段中获取内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆