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

在Astro中如何将Strapi CMS获取的Markdown转为HTML?

在Astro中将Strapi返回的Markdown转为HTML

要处理从Strapi拉取的Markdown内容,你可以借助第三方Markdown解析库实现转换,以下是两种常用方案:

方案一:使用marked库

  • 首先安装依赖:
npm install marked
  • 在Astro组件中获取数据并解析:
---
import { marked } from 'marked';

// 调用Strapi接口获取文章数据
const res = await fetch('你的Strapi文章接口地址');
const post = await res.json();
// 将Markdown转为HTML
const htmlContent = marked(post.content);
---

<article>
  <h1>{post.title}</h1>
  <!-- 通过set:html将解析后的HTML插入页面 -->
  <div set:html={htmlContent}></div>
</article>
  • 自定义解析规则(如支持GFM、自动换行):
const htmlContent = marked(post.content, {
  gfm: true,
  breaks: true
});

方案二:使用remark生态

  • 安装所需依赖:
npm install remark remark-html
  • 在组件中进行解析:
---
import { remark } from 'remark';
import html from 'remark-html';

const res = await fetch('你的Strapi文章接口地址');
const post = await res.json();
// 处理Markdown内容
const processedContent = await remark().use(html).process(post.content);
const htmlContent = processedContent.toString();
---

<article>
  <h1>{post.title}</h1>
  <div set:html={htmlContent}></div>
</article>

注意:使用set:html时要确保内容可信,避免XSS风险。如果内容来自用户提交,建议额外添加过滤逻辑。

内容的提问来源于stack exchange,提问作者Remco Kersten

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:17:08