Day15 - Astro Series: Layout

Astro 系列文第十五日:基础布局

一个漂亮的渐变背景上面有一句标题:「基础布局」

前言

先前了解了如何使用 Markdown 与 MDX 来撰写网页,接着这个章节将会学习到如何替这些档案设置画面布局 (Layout)。布局可以想像成是常见的页面的模板用于管理页面常见的模式,定义布局页面可以解省重复并统一管理页面。

什么是布局

前面提到通常会创建 src/layouts 资料夹,里面存放的就是布局相关的 .astro 元件,事实上可以开心叫什么名字都可以。那么需要专门用于布局的元件做什么?创建一个资料夹规划放置这类型的元件,是一种常见的模式去管理网页。布局元件具备被<slot/> 可以被注入内容。

前面样式的章节有练习过使用 <slot/> 来制作 <Base> 元件,就是一种典型的布局用元件。

Markdown 与 MDX 的布局

通常会将 Markdown 或 MDX 这类资料透过布局元件去呈现,Astro 就提供了特别的 layout Frontmatter 属性用于指定该文件要使用的布局元件。

---
layout: ../layouts/BaseLayout.astro
subHeadline: '你好世界!'
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 (MarkdownLayoutPropsMDXLayoutProps):

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)。

延伸阅读