无法从Strapi向Astro框架获取富文本字段,求解决方案
解决Astro中Strapi富文本字段显示[object Object]的问题
问题原因
Strapi的富文本(Rich Text)字段默认返回符合Slate规范的结构化对象数组,而非直接可用的HTML字符串。在Astro模板中直接渲染这些对象时,会触发对象的toString()方法,最终显示为[object Object]。
解决方案
方案一:让Strapi直接返回HTML格式(推荐)
修改API请求URL,指定富文本字段以HTML格式返回,再通过Astro的set:html指令渲染HTML内容。
- 修改Fetch请求URL
将原请求中的populate参数扩展,为富文本字段指定format=html:
const response = await fetch('http://localhost:1337/api/courses?populate[image]=*&populate[body][format]=html&populate[bodybody][format]=html').then(res => res.json())
populate[image]=*:确保图片字段的完整数据被获取populate[body][format]=html:让body字段返回HTML字符串populate[bodybody][format]=html:同理处理bodybody字段
- 在Astro模板中渲染HTML
使用Astro的set:html指令代替直接输出变量,避免HTML被转义:
<p set:html={body}></p> <p class="bg-red-400 mt-28" set:html={bodybody}></p>
方案二:手动解析Slate对象为HTML(自定义场景)
如果需要自定义富文本渲染逻辑,可以使用Strapi官方工具函数解析Slate结构:
- 安装依赖:
npm install @strapi/utils
- 在Astro组件中导入并使用
renderRichText:
--- import Master from "../../layouts/MasterLayout.astro"; import { renderRichText } from '@strapi/utils'; const title = "Store Bright Coding"; const response = await fetch('http://localhost:1337/api/courses?populate=image').then(res => res.json()) const courses = response.data ---
- 渲染时调用函数转换:
<p set:html={renderRichText(body)}></p> <p class="bg-red-400 mt-28" set:html={renderRichText(bodybody)}></p>
完整修改后的Store.astro代码
--- import Master from "../../layouts/MasterLayout.astro"; const title = "Store Bright Coding"; // 修改请求URL,指定富文本字段返回HTML格式 const response = await fetch('http://localhost:1337/api/courses?populate[image]=*&populate[body][format]=html&populate[bodybody][format]=html').then(res => res.json()) const courses = response.data --- <Master {title}> <div class="row px-20"> <div> <h1 class="text-5xl font-bold mt-10">Store</h1> <div class="grid grid-cols-3 gap-5 h-screen"> {courses.map(({ attributes: {title, body, price, url, image, bodybody }}) => ( <div class="flex bg-red-400 mt-20"> <div class="bg-blue-300"> <img class="w-full" src={`http://localhost:1337${image.data?.attributes?.formats?.thumbnail?.url}`}> <div> <h4>{title}</h4> <!-- 使用set:html渲染HTML内容 --> <p set:html={body}></p> <p class="bg-red-400 mt-28" set:html={bodybody}></p> <h3>{`$${price}`}</h3> <a href={url}>More...</a> </div> </div> </div> ))} </div> </div> </div> </Master>
内容的提问来源于stack exchange,提问作者Nomi Dilshan
相关产品推荐
相关产品推荐

