
前言
先前了解了如何使用 Markdown 與 MDX 來撰寫網頁,接著這個章節將會學習到如何替這些檔案設置畫面布局 (Layout)。布局可以想像成是常見的頁面的模板用於管理頁面常見的模式,定義布局頁面可以解省重複並統一管理頁面。
什麼是布局
前面提到通常會創建 src/layouts
資料夾,裡面存放的就是布局相關的 .astro
元件,事實上可以開心叫什麼名字都可以。那麼需要專門用於布局的元件做什麼?創建一個資料夾規劃放置這類型的元件,是一種常見的模式去管理網頁。布局元件具備被<slot/>
可以被注入內容。
前面樣式的章節有練習過使用 <slot/>
來製作 <Base>
元件,就是一種典型的布局用元件。
Markdown 與 MDX 的布局
通常會將 Markdown 或 MDX 這類資料透過布局元件去呈現,Astro 就提供了特別的 layout
Frontmatter 屬性用於指定該文件要使用的布局元件。
---layout: ../layouts/BaseLayout.astrotitle: '你好世界!'author: 'Joe Doe'date: '27 Sep 2023'---
所有 Frontmatter 屬性都可以在 Astro 元件中被存取得到
`layout` 屬性是特別存在於 Astro 的一項屬性
可以用它來指定位於 `src/pages` 的 Markdown 與 MDX 的布局元件
---// `src/layout/BaseLayout.astro`// 解構出 Frontmatter 資料const { frontmatter } = Astro.props;---
<html> <head> <title>{frontmatter.title}</title> </head> <body> <h1>{frontmatter.title} by {frontmatter.author}</h1> <!-- 被渲染的 HTML 將會被注入到 slot 當中 --> <slot /> <p>撰寫於: {frontmatter.date}</p> </body></html>
也可以額外的使用提供的 helper 來定義 Props (MarkdownLayoutProps
或 MDXLayoutProps
):
import type { MarkdownLayoutProps } from 'astro';
type Props = MarkdownLayoutProps<{ // 在這裡定義 frontmatter props title: string, author: string, date: string,}>;
以下是一個 Markdown/MDX 布局會透過 Astro.props
存取到的資料範例:
Astro.props = { file: '/home/user/projects/.../file.md', url: '/en/guides/markdown-content/', frontmatter: { title: 'Astro 0.18 Release', date: 'Tuesday, July 27 2021', author: 'Matthew Phillips', description: 'Astro 0.18 is our biggest release since Astro launch.', file: '/home/user/projects/.../file.md', url: '/en/guides/markdown-content/', }, headings: [ { depth: 1, text: 'Astro 0.18 Release', slug: 'astro-018-release', }, { depth: 2, text: 'Responsive partial hydration', slug: 'responsive-partial-hydration', }, ], rawContent: () => '# Astro 0.18 Release\nA little over a month ago, the first public beta [...]', compiledContent: () => '<h1>Astro 0.18 Release</h1>\n<p>A little over a month ago, the first public beta [...]</p>',};
像是 Markdown 的 Frontmatter、檔案位置連結、內容中的標題、渲染好的 HTML 都可以存取得到,
總結
使用 layout
Frontmatter 在 Markdown 或 MDX 當中可以快速的指定內容要採用哪個元件布局,當然你也可以手動的在 MDX 中引入想要布局的元件並添加到想要的地方。當然它不是強制的,你還可以透過其他方式去指定 Markdown 檔案的布局方式,更多會在下一章節中說明。
最後會建議實際動手練習,如果過程中有問題可以參考看看我的範例:
- 撰寫一個 Markdown 並且指定與撰寫它的
layout
。 - 製作一個
ArticleLayout.astro
元件並且透過 Props 提供的標題資訊製作顯示一個 Markdown 文章的目錄(Table of Content)。
延伸閱讀
- Layouts - Astro DOCS
- Day15 - 基礎布局 - 相同文章同步發布於 iThome 鐵人賽中