[英]Fetch content from rich text field
我正在关注此文档以从 Contentful 呈现富文本。
到目前为止,我已经安装了gatsby-source-contentful
,现在我正在使用 graphQL 查询来查询富文本内容,然后再添加到我的模板中。
问题:我无法查询references
字段。
据我了解,最近发生了一项重大更改,需要查询raw
子字段……但不幸的是,我无法查询raw
中的任何子字段。
我不确定问题可能是什么。
询问
{
allContentfulArticle {
edges {
node {
content {
raw
references {
... on ContentfulArticle {
contentful_id
title
slug
}
}
}
}
}
}
}
references
代表参考内容 model ,这是一种通过在主条目中逐个添加来从另一个条目中检索数据的方法。 该指南假设您遵循了完全相同的结构,但它不是必需的。 如果您没有reference
内容model,请不要查询。 GraphQL 游乐场 ( localhost:8000/___graphql
) 将显示所有可用的可查询字段。
此外,该指南在ContentfulAsset
上使用 GraphQL 片段,而不是在ContentfulArticle
上,再次假设您已经为您的文章添加了一个资产条目,如果它不可用或您没有它,请不要查询它。 您只需要为您的用例和您自己的字段自定义查询。
{
allContentfulArticle {
edges {
node {
content {
raw
}
}
}
}
}
通过上面的查询,您应该能够从富文本 model 中收集所有原始数据。 但是,您需要在 Gatsby 项目中添加一个转换器,它将为每种类型的富文本(粗体文本、嵌入条目、链接、代码等)呈现和解析正确的组件。
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)
此处和gatsby-source-contentful
文档中的更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.