简体   繁体   中英

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.

Pages will have title, description, an image URL, a canonical URL, and some addition info.

Here is the code of my PageSeo.astro file:

---
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.

I've tried the data-title + this.dataset.title and the define:vars={{}} method. 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

Instead you can use the set:html directive with a template literal

<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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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