Home > Blockchain >  For Astro.js, how to access frontmatter variables in ld json schema.org SEO JSON?
For Astro.js, how to access frontmatter variables in ld json schema.org SEO JSON?

Time:12-21

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?

CodePudding user response:

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.

CodePudding user response:

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}
  }
`}/>
  • Related