You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Astro外部脚本中获取Frontmatter的Ventana字段内容

解决Astro Frontmatter变量传递到客户端脚本的问题

你需要把Frontmatter里的Ventana变量注入到客户端脚本中,Astro支持在组件内的脚本里用大括号插值来实现,具体修改如下:

基础写法(适用于无特殊字符的内容)

直接将SomeThingThatsWork替换为'{Ventana}',Astro编译时会自动把变量值填充进去:

<script>
const el = document.querySelector('.current p:nth-child(3)');
const p = document.createElement('p');
p.textContent = '{Ventana}';
p.classList.add('ventana', 'font-helve');

el.after(p);
</script>

安全写法(适用于含特殊字符的内容)

如果Ventana的内容包含引号、换行等特殊字符,用JSON.stringify转义,避免脚本语法错误:

<script>
const el = document.querySelector('.current p:nth-child(3)');
const p = document.createElement('p');
p.textContent = {JSON.stringify(Ventana)};
p.classList.add('ventana', 'font-helve');

el.after(p);
</script>

原理很简单:Astro在构建组件时,会把Frontmatter中定义的Ventana变量值,替换掉脚本里{}包裹的部分,这样客户端脚本运行时就能拿到正确的字段内容了。

内容的提问来源于stack exchange,提问作者matiasdiez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 21:22:10