简体   繁体   English

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

[英]For Astro.js, how to access frontmatter variables in ld+json schema.org SEO JSON?

I have an Astro.js component called 'PageSEO' to use for SEO info for my webpages.我有一个名为“PageSEO”的 Astro.js 组件,用于我的网页的 SEO 信息。

Pages will have title, description, an image URL, a canonical URL, and some addition info.页面将具有标题、描述、图像 URL、规范 URL 和一些附加信息。

Here is the code of my PageSeo.astro file:这是我的 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>

The variable info comes into the front matter fine, but it doesn't make it into the ld+json script.变量信息很好地进入了前端,但它没有进入 ld+json 脚本。

I've tried the data-title + this.dataset.title and the define:vars={{}} method.我试过data-title + this.dataset.titledefine:vars={{}}方法。 Both failed.都失败了。

Any ideas?有任何想法吗?

define:vars doesn't work because it assumes the <script> is Javascript and creates an immediately invoked function with const variables define:vars不起作用,因为它假定<script>是 Javascript 并使用const变量创建一个立即调用的函数

Instead you can use the set:html directive with a template literal相反,您可以将set:html指令与模板文字一起使用

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

It looks like you are trying to use JavaScript template literals to include the values of the title, image, and url variables in your PageSEO component.看起来您正在尝试使用 JavaScript 模板文字在您的 PageSEO 组件中包含标题、图像和 url 变量的值。

To do this, you need to wrap the variable names in ${} like this:为此,您需要将变量名称包装在 ${} 中,如下所示:

    <script type="application/ld+json">
      { 
        "@context": "http://schema.org",
        "@type": "WebPage",
        "name": "${title}",
        "image": "${image}",
        "url": "${url}"
      }
    </script>

This will allow the values of the variables to be included in the JSON-LD script.这将允许变量的值包含在 JSON-LD 脚本中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM