对于 Astro.js,如何访问 ld+json schema.org SEO JSON 中的 frontmatter 变量?

Cos*_*sta 1 javascript astrojs

我有一个名为“PageSEO”的 Astro.js 组件,用于我的网页的 SEO 信息。

页面将包含标题、描述、图像 URL、规范 URL 和一些附加信息。

这是我的 PageSeo.astro 文件的代码:

---
var { title, image, description, url } = Astro.props
---

<script type="application/ld+json">
  { 
    "@context": "http://schema.org",
    "@type": "WebPage",
    "name": {title},
    "image": {image},
    "url": {url}
  }
</script>
Run Code Online (Sandbox Code Playgroud)

变量 info 可以很好地进入前面的内容,但它不会进入 ld+json 脚本。

我已经尝试过data-title+this.dataset.titledefine:vars={{}}方法。两者都失败了。

有任何想法吗?

Bry*_*ell 6

define:vars不起作用,因为它假设是 Javascript 并创建一个带有变量<script>的立即调用函数const

相反,您可以使用set:html带有模板文字的指令

<script type="application/ld+json" set:html={`
  { 
    "@context": "http://schema.org",
    "@type": "WebPage",
    "name": ${title},
    "image": ${image},
    "url": ${url}
  }
`}/>
Run Code Online (Sandbox Code Playgroud)

编辑:这可以使用来改进JSON.stringify()

<script type="application/ld+json" set:html={JSON.stringify({ 
    "@context": "http://schema.org",
    "@type": "WebPage",
    name: title,
    image,
    url
})}/>
Run Code Online (Sandbox Code Playgroud)