You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Astro+Contentful博客富文本图片等资源无法显示求助

解决Astro + Contentful富文本图片不显示问题

核心原因

Contentful API默认不会嵌套返回关联的资产(如图片),富文本中的embedded-asset-block节点仅包含资产引用ID,而非完整的图片URL、尺寸等数据,导致documentToHtmlString无法生成有效的图片标签。

解决步骤

1. 调用API时添加include参数拉取资产数据

在getEntries请求中加入include参数,指定关联层级(至少设为2,确保富文本内的资产被完整返回):

const data = await contentfulClient.getEntries<Post>({
  content_type: "post",
  "fields.slug": slug,
  include: 3 // 足够覆盖富文本中嵌套的资产关联
});

2. 自定义富文本渲染规则生成图片标签

默认的documentToHtmlString不会处理embedded-asset-block,需通过renderOptions自定义该节点的渲染逻辑,生成合法的<img>标签:

import { documentToHtmlString } from "@contentful/rich-text-html-renderer";
import { CONTENTFUL_IMAGE_LOADER } from "astro:assets";

// 自定义渲染配置
const renderOptions = {
  renderNode: {
    "embedded-asset-block": (node) => {
      const asset = node.data.target.fields;
      // 使用Astro的Contentful图片加载器生成优化后的URL
      const imageUrl = CONTENTFUL_IMAGE_LOADER({
        src: asset.file.url,
        width: asset.file.details.image.width,
        height: asset.file.details.image.height,
        format: asset.file.contentType.split("/")[1],
      });
      // 返回带alt属性的img标签
      return `<img src="${imageUrl}" alt="${asset.description || asset.title}" loading="lazy" />`;
    },
  },
};

// 生成HTML时传入自定义配置
post = {
  title,
  author,
  coverImage,
  tags,
  dateModified: new Date(dateModified).toLocaleDateString(),
  body: documentToHtmlString(body, renderOptions), // 传入renderOptions
  text 
};

3. 修正图片数据获取逻辑

之前的代码错误地从text.content获取图片,且取了空的content字段。正确的做法是从body.content中提取data.target的资产数据:

const getImages = body.content
  .filter(item => item.nodeType === 'embedded-asset-block')
  .map(item => item.data.target.fields); // 资产数据存在于data.target.fields中

验证

修改后重新运行项目,富文本中的图片会被正确解析为<img>标签,且图片URL有效,即可正常显示。

内容的提问来源于stack exchange,提问作者Kolade Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:06:11