0

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?

Costa Michailidis
  • 7,691
  • 15
  • 72
  • 124

1 Answers1

3

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

EDIT: this could be improved using JSON.stringify()

<script type="application/ld+json" set:html={JSON.stringify({ 
    "@context": "http://schema.org",
    "@type": "WebPage",
    name: title,
    image,
    url
})}/>
Bryce Russell
  • 647
  • 3
  • 8