#frontmatter api string to client side script
3 messages · Page 1 of 1 (latest)
Hi @silent needle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
You can pass a string from the frontmatter to a client-side script using data-* attributes. Here's a simple example:
- Create an Astro component with a frontmatter variable and store it in a
data-*attribute:
---
const message = 'Hello, world!';
---
<div data-message={message}>
<button>Click me!</button>
</div>
<script>
class MyComponent 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('my-component', MyComponent);
</script>
- Use the component in another Astro file:
---
import MyComponent from '../components/MyComponent.astro';
---
<my-component></my-component>
In this example, the message variable is stored in a data-message attribute. The custom element reads the data-message attribute using this.dataset.message and displays it in an alert when the button is clicked.