我正在与 Astro 和 Contentful 合作开发一个博客。
内容是一个富文本字段,我正在使用
contentful/rich-text-html-renderer
包进行解析,如 Astro 文档中所示:
<article set:html={post?.body} />
不幸的是,图像和其他资产根本没有显示。
如何让图像显示?
编辑如下:
经过进一步调查,我发现图像根本不是来自 Contentful API:
---
import { documentToHtmlString } from "@contentful/rich-text-html-renderer";
import { Image } from 'astro:assets';
import { contentfulClient } from "../../lib/contentful";
import Layout from '../../layouts/Layout.astro'
import type { Post } from "../../lib/contentful";
export async function getStaticPaths() {
const { items } = await contentfulClient.getEntries<Post>({
content_type: 'post'
})
return items.map(item => {
return {
params: {
slug: item.fields.slug
},
// props: {
// allPosts: item
// }
}
})
}
let post;
const { slug } = Astro.params;
// const { allPosts } = Astro.props;
try {
const data = await contentfulClient.getEntries<Post>({
content_type: "post",
"fields.slug": slug,
});
const { title, author, coverImage, tags, dateModified, body, text } = data.items[0].fields;
post = {
title,
author,
coverImage,
tags,
dateModified: new Date(dateModified).toLocaleDateString(),
body: documentToHtmlString(body),
text
};
console.log("Body texts: ", body.content)
const getImages = text.content
.filter(item => item.nodeType === 'embedded-asset-block')
.map(item => item.content);
/*
Output:
Body texts: [
{ data: {}, content: [ [Object] ], nodeType: 'heading-1' },
{ data: {}, content: [ [Object] ], nodeType: 'paragraph' },
{ data: {}, content: [ [Object] ], nodeType: 'paragraph' },
{
data: {},
content: [ [Object], [Object], [Object] ],
nodeType: 'unordered-list'
},
{ data: {}, content: [ [Object] ], nodeType: 'paragraph' },
{
data: { target: [Object] },
content: [],
nodeType: 'embedded-asset-block'
},
{
data: { target: [Object] },
content: [],
nodeType: 'embedded-asset-block'
},
{
data: {},
content: [ [Object], [Object], [Object] ],
nodeType: 'paragraph'
}
]
*/
console.log("Images: ", getImages)
// output: Images: [ [] ]
} catch (error) {
return Astro.redirect("/404");
}
const authorPic = post?.author.fields.authorImage.fields.file.url
您可能忘记发布您的资产。如果您不发布资产,即使嵌入到
RichText
中,它们也不会显示。