Search code examples
javascriptastrojs

how to pass variable from frontmatter to script in Astro JS?


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>


Solution

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