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

如何在Astro中转换WordPress REST API返回的&转义字符?

在Astro中处理WordPress API返回的HTML转义字符

当然可以处理,给你两种实用的解决办法:

方法一:在数据获取阶段用JS解析转义字符

写一个简单的工具函数,用浏览器原生的DOMParser来解码HTML实体:

function decodeHtmlEntities(str) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(str, 'text/html');
  return doc.documentElement.textContent;
}

之后在获取WordPress分类数据时,直接调用这个函数处理名称:

async function getCategories() {
  const res = await fetch('https://你的WordPress站点域名/wp-json/wp/v2/categories');
  const categories = await res.json();
  // 遍历分类,解码名称里的转义字符
  return categories.map(cat => ({
    ...cat,
    name: decodeHtmlEntities(cat.name)
  }));
}

这种方式会在数据层面完成转换,之后不管在哪个模板里用分类名称,都是已经解码好的内容。

方法二:在Astro模板中直接渲染转义内容

Astro自带setHTML指令,可以直接把带HTML实体的字符串作为HTML内容渲染,自动解析转义字符。比如在你的.astro页面里:

---
// 先获取分类数据
const categories = await getCategories();
---

<div class="category-list">
  {categories.map(cat => (
    <div class="category-item">
      <!-- 用setHTML渲染,自动解析&amp;为& -->
      <span setHTML={cat.name}></span>
    </div>
  ))}
</div>

这种方法更直接,不用额外处理数据,适合只在模板里用到分类名称的场景。

内容的提问来源于stack exchange,提问作者Mariano Schmands

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:09:57