Astro中如何在Markdown正文调用Frontmatter属性变量?
问题
我在Astro的.md文件中编写了如下Frontmatter:
--- title: A great movie director: John Doe ---
我本以为使用[actor]、{{actor}}或{frontmatter.actor}这类语法,就能在Markdown正文中将Frontmatter属性作为变量使用并渲染对应值,示例代码如下:
--- title: A great movie director: John Doe --- ## My thoughts about {{actor}} We all know the great director {{director}} and we have seen all his films.
请问这种用法是否可行?
回答
这种用法不可行。
Astro里的纯.md文件属于静态Markdown内容,默认不会解析正文里的模板语法(比如{{ }}),这些语法会被当作普通文本原样输出,没法渲染Frontmatter里的变量值。
如果要在内容里调用Frontmatter变量,有两种常用方案:
- 把文件后缀改成
.astro,在Astro组件里可以直接用{{ frontmatter.director }}这类语法,同时也能写Markdown内容(可以用<Markdown>组件包裹,或者开启MDX语法直接编写) - 使用Astro的Content Collections功能,把Markdown文件放到指定集合目录,然后通过页面组件读取内容,在模板里调用Frontmatter变量来渲染。
内容的提问来源于stack exchange,提问作者Nacho B
相关产品推荐
相关产品推荐

