布局
布局是特殊的 Astro 组件,可用于创建可重用的页面模板。
布局组件通常用于提供 .astro
或 .md
页面、页面骨架(<html>
、<head>
和 <body>
标签)和用于插入页面内容的 <slot />
。
布局通常为页面提供常用的 <head>
元素和常用 UI 元素,例如页眉、导航栏和页脚。
布局组件通常放置在项目中的 src/layouts
目录中。
---
---
<html lang="en">
<head>
<meta charset="utf-8">
<title>我很酷的 Astro 网站</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<nav>
<a href="#">主页</a>
<a href="#">文章</a>
<a href="#">联系</a>
</nav>
<article>
<slot /> <!-- 你的内容会被插入到这里 -->
</article>
</body>
</html>
---
import MySiteLayout from '../layouts/MySiteLayout.astro';
---
<MySiteLayout>
<p>我的页面内容,被包裹在一个布局中!</p>
</MySiteLayout>
📚 详细了解插槽。
Markdown 布局
Section titled Markdown 布局页面布局对于 Markdown 文件尤其有用。Markdown 文件可以在 frontmatter 顶部使用特殊的 layout
属性来指定要作为页面布局的 .astro
组件。
---
layout: ../../layouts/BlogPostLayout.astro
title: 博客文章
description: 我的第一篇博文!
---
这是一篇用 Markdown 写的文章。
页面布局对于 Markdown 文件特别有用。Markdown文件可以在 frontmatter 的顶部使用特殊的 layout
属性来指定使用哪个 .astro
组件作为页面布局。
---
const {frontmatter} = Astro.props;
---
<html>
<!-- ... -->
<h1>{frontmatter.title}</h1>
<h2>文章作者:{frontmatter.author}</h2>
<slot />
<!-- ... -->
</html>
📚 在我们的 Markdown 指南中了解有关 Astro Markdown 支持的更多信息。
布局组件无需包含整个页面的 HTML。你可以将布局分解为更小的组件,然后重用这些组件以创建更灵活、更强大的布局。
例如,博客文章的常见布局可能会显示标题、日期和作者。BlogPostLayout.astro
布局组件可以将此 UI 添加到页面,而其他部分则交由更广范围的样式来处理。
---
import BaseLayout from './BaseLayout.astro'
const {frontmatter} = Astro.props;
---
<BaseLayout>
<h1>{frontmatter.title}</h1>
<h2>文章作者:{frontmatter.author}</h2>
<slot />
</BaseLayout>