因此,我一直在努力了解“内容丰富”的资产,例如可以将图像添加为单个内容字段的一部分,即描述(富文本) 我有一个中间件
NodeJS服务器,它聚合来自各个第三方的内容。这些第三方之一是 Contentful。但我注意到的是,使用下面的方法将图像完全排除在响应之外。 我尝试使用
@contentful/rich-text-html-renderer服务器端,我得到的只是段落。没有别的,当我确实设法使用 @contentful/rich-text-types 包含 BLOCKS 时,我注意到在查看返回的响应时,嵌入元素没有图像 url,只有来自 Contentful 的图像 ID。 我尝试过使用各种来源,他们都使用了两个 npm,显然都取得了成功,但我还没有看到这一点。这是一些代码片段。正如您所看到的,我期待某种 url,但与上传的图像字段不同,它不在有效负载中。嵌入资产似乎只引用图像 ID。那么如何在实际的富文本字段中添加图像呢?
这就是我在 Angular 中设置的
_returnHtmlFromRichText(richText) {
return documentToHtmlString(richText,
{
renderNode: {
[BLOCKS.EMBEDDED_ASSET]: (node, children) => {
// render the EMBEDDED_ASSET as you need
console.log(node.data)
//return `<img src="https://${<need url here>}"/>`
},
}
}
);
}
{
"target": {
"sys": {
"id": "ZIIO2DUlu5rFxMykjIwaX",
"type": "Link",
"linkType": "Asset"
}
}
}
Rich text
所有嵌入内容(图像或条目)都将像您所看到的那样链接。
为了获取图像的 URL,您需要像这样获取它:_returnHtmlFromRichText({raw, references}) {
return documentToHtmlString(richText,
{
renderNode: {
[BLOCKS.EMBEDDED_ASSET]: (node, children) => {
if (!references || !node) {
return null;
}
const referenceNode = references.find(
(reference) => node.data.target.sys.id ===
reference.contentful_id
);
const imageURL = referenceNode.media[0].file.url
return `<img src="${imageURL}"/>`
},
}
}
);
}
如果您还需要处理其他嵌入内容(例如
Entries
或
Inline-Entry
),您可以扩展此逻辑以满足其他情况。
raw
和references
基本上是richText.raw
和richText.references