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

在Astro JS的script标签中渲染动态内容遇问题求助

解决Astro中script标签无法渲染动态JSON数据的问题

问题出在Astro对普通<script>标签的处理逻辑上:默认情况下,Astro会将普通script标签内的内容视为静态文本,不会解析其中的模板表达式(即{stringifyData}这类语法)。

要解决这个问题,只需要给script标签添加is:inline指令,告诉Astro需要解析标签内的动态内容:

---
import getData from '../../helpers/getData.js'

const data = getData({
      // some data
    })

const stringifyData = JSON.stringify(data)
---

<html lang="en">
  
{stringifyData && (
  <script type="application/ld+json" is:inline>
    {stringifyData}
  </script>
)}
</html>

添加is:inline后,Astro会在构建时将{stringifyData}替换为实际的JSON字符串内容,最终渲染出正确的结构化数据脚本。

内容的提问来源于stack exchange,提问作者Billy Brown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:22:33