最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to pass variable from frontmatter to script in Astro JS? - Stack Overflow

programmeradmin0浏览0评论

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>

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>

Share Improve this question edited Mar 4, 2024 at 16:40 VLAZ 29k9 gold badges62 silver badges83 bronze badges asked Jul 18, 2023 at 15:31 Alexander KrupnitskyAlexander Krupnitsky 1411 silver badge10 bronze badges 2
  • You may need to get a little more specific in your post, because Astro is "by default" paired with the "Front Matter CMS", so your question needs to add more details: you're showing markdown, which "thing" is this markdown for? Is it pure Astro? If not, what else is involved? Also given that a title ends up being, unsurprisingly, the page title, is this just an example or is this the thing you needed? Because then the answer is "why would you need to access the variable itself, set the page title in that markdown frontmatter, and then get document.title in your JS." – Mike 'Pomax' Kamermans Commented Jul 18, 2023 at 15:35
  • Does this answer your question? How do I pass a server variable to client side JS in astro? – wassfila Commented Jul 18, 2023 at 20:35
Add a comment  | 

1 Answer 1

Reset to default 20

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>
发布评论

评论列表(0)

  1. 暂无评论