#frontmatter inline scripts
1 messages · Page 1 of 1 (latest)
Hi @foggy wharf. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To access frontmatter variables in inline scripts in Astro, you can use the define:vars directive. This allows you to pass server-side variables from your component frontmatter into client-side <script> tags. Here's how you can do it:
- Define your variables in the frontmatter of your Astro component.
- Use the
define:varsdirective on your<script>tag, passing in the variables you want to use.
Here's an example:
---
const message = "Astro is awesome!";
---
<script define:vars={{ message }}>
alert(message);
</script>
In this example, the message variable defined in the frontmatter is passed to the inline script using define:vars={{ message }}. The script can then use this variable directly.
However, it's important to note a few things:
-
Using
define:varson a<script>tag implies theis:inlinedirective, which means your scripts won't be bundled and will be inlined directly into the HTML Source: Astro Docs - Script & Style Directives (https://docs.astro.build/en/reference/directives-reference/#definevars). -
This approach is not recommended for large amounts of data or for scripts that need to be reused across multiple components, as it can lead to duplication Source: Astro Docs - Script & Style Directives (https://docs.astro.build/en/reference/directives-reference/#definevars).
-
For more complex scenarios or when you need to pass variables to scripts that should be bundled, consider using alternative methods like passing variables to scripts manually or using data attributes Source: Astro Docs - Pass frontmatter variables to scripts (https://docs.astro.build/en/guides/client-side-scripts/#pass-frontmatter-variables-to-scripts).
Remember that this method is specific to Astro and allows you to bridge the gap between server-side and client-side code in a convenient way.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@foggy wharf Kapa.ai is still learning and improving, please let me know how I did by reacting below.