#Access frontmatter variable in script tag
1 messages · Page 1 of 1 (latest)
Hi @broken pulsar. 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 a script tag, you can use the define:vars={...} directive. This directive allows you to pass server-side variables from your component frontmatter into the client <script> tags. Any JSON-serializable frontmatter variable is supported, including props passed to your component through Astro.props. Values are serialized with JSON.stringify().
Here's an example:
---
const foregroundColor = "rgb(221 243 228)";
const backgroundColor = "rgb(24 121 78)";
const message = "Astro is awesome!";
---
<style define:vars={{ textColor: foregroundColor, backgroundColor }}>
h1 {
background-color: var(--backgroundColor);
color: var(--textColor);
}
</style>
<script define:vars={{ message }}>
alert(message);
</script>
However, 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. This is because when Astro bundles a script, it includes and runs the script once even if you include the component containing the script multiple times on one page. define:vars requires a script to rerun with each set of values, so Astro creates an inline script instead.
For scripts, you can also try passing variables to scripts manually. One way to do this is to use data-* attributes to store the value of variables in your HTML output. Scripts, including custom elements, can then read these attributes using an element’s dataset property once your HTML loads in the browser.
Here's an example:
---
const { message = 'Welcome, world!' } = Astro.props;
---
<!-- Store the message prop as a data attribute. -->
<astro-greet data-message={message}>
<button>Say hi!</button>
</astro-greet>
<script>
class AstroGreet extends HTMLElement {
constructor() {
super();
//...
}
}
</script>
In this example, a message prop is stored in a data-message attribute, so the custom element can read this.dataset.message and get the value of the prop in the browser.
Sources:
- Astro Directives Reference (https://docs.astro.build/en/reference/directives-reference#definevars)
- Astro Client-side Scripts Guide (https://docs.astro.build/en/guides/client-side-scripts/#pass-frontmatter-variables-to-scripts)