1

How to pass variable from frontmatter to script in Astro js. Like this:

---
const title = "this is title"
---

some content


<script>

const metatile = title

<script>
  • You may need to get a little more specific in your post, because Astro is "by default" paired with the "Front Matter CMS", so your question needs to [add more details](/help/how-to-ask): you're showing markdown, which "thing" is this markdown for? Is it pure Astro? If not, what else is involved? Also given that a title ends up being, unsurprisingly, the page title, is this just an example or is this _the thing_ you needed? Because then the answer is "why would you need to access the variable itself, set the page title in that markdown frontmatter, and then get `document.title` in your JS." – Mike 'Pomax' Kamermans Jul 18 '23 at 15:35
  • Does this answer your question? [How do I pass a server variable to client side JS in astro?](https://stackoverflow.com/questions/73511984/how-do-i-pass-a-server-variable-to-client-side-js-in-astro) – wassfila Jul 18 '23 at 20:35

1 Answers1

6

You can use the define:vars directive to pass the value to the client.

---
const title = "this is title"
---

<script define:vars={{title}}>
  alert(title);
<script>

The above method will disable any Vite bundling. If you need the script to be analyzed & bundled by Vite (if it uses TypeScript or imports) you can use this second method to set the value to a data-* attribute, then read it on the client.

---
const message = "Hello world";
---

<!-- Store the message prop as a data attribute. -->
<astro-greet data-message={message}>
  <button>Say message</button>
</astro-greet>

<script>
  class AstroGreet extends HTMLElement {
    constructor() {
      super();

      // Read the message from the data attribute.
      const message = this.dataset.message;

      const button = this.querySelector('button');
      button.addEventListener('click', () => {
        alert(message);
      });
    }
  }

  customElements.define('astro-greet', AstroGreet);
</script>
The Otterlord
  • 1,680
  • 10
  • 20