#front matter in a script
1 messages · Page 1 of 1 (latest)
Hi @twilit trout. 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 inside a <script> tag in the same Astro file, you can use the define:vars directive. This allows you to pass server-side variables from your component frontmatter into the client-side script. Here's how you can do it:
- Define your variables in the frontmatter (between the
---fences):
---
const myFrontmatterVariable = "Hello from frontmatter!";
---
- Use the
define:varsdirective on your<script>tag and pass the variables you want to use:
<script define:vars={{ myFrontmatterVariable }}>
console.log(myFrontmatterVariable);
</script>
This approach allows you to use the frontmatter variable myFrontmatterVariable inside your script.
However, it's important to note that using define:vars on a <script> tag implies the is:inline directive, which means your scripts won't be bundled and will be inlined directly into the HTML according to the Astro documentation (https://docs.astro.build/en/reference/directives-reference/#definevars).
For more complex scenarios or to avoid inlining scripts, you might want to consider passing variables to scripts manually (https://docs.astro.build/en/guides/client-side-scripts/#pass-frontmatter-variables-to-scripts) using data attributes or other methods.
kapa.ai: Thank you for your question about Astro! I'm happy to help explain how to access frontmatter variables in a script tag within an Astro file.
To access frontmatter variables inside a <script> tag in the same Astro file, you can use the define:vars directive. This allows you to pass server-side variables from your component frontmatter into the client-side script. Here's how to do it:
- Define your variables in the frontmatter section:
---
const myVariable = "Hello from frontmatter!";
---
- Use the
define:varsdirective on your<script>tag to pass the variables:
<script define:vars={{ myVariable }}>
console.log(myVariable);
</script>
This will make myVariable available inside your script.
However, it's important to note that using define:vars on a <script> tag implies the is:inline directive. This means your scripts won't be bundled and will be inlined directly into the HTML as mentioned in the Astro documentation (https://docs.astro.build/en/reference/directives-reference/#definevars).