跳转到内容

组合布局以集二者之长

现在你已经为每篇博客文章添加了布局,是时候让你的文章看起来像网站上的其他页面了!

准备好……

  • 将你的博客文章布局嵌套在主页面布局中

你已经有了一个 BaseLayout.astro 文件,用于定义页面的整体布局。

MarkdownPostLayout.astro 为常见的博客文章属性(如 titledate)提供了一些额外的模板,但你的博客文章看起来与网站上的其他页面不同。你可以通过嵌套布局来使你的博客文章与网站的其余部分外观相匹配。

  1. src/layouts/MarkdownPostLayout.astro 中,导入 BaseLayout.astro 并用它来包裹整个模板内容。别忘了传递 pageTitle 属性。

    src/layouts/MarkdownPostLayout.astro
    ---
    import BaseLayout from './BaseLayout.astro';
    const { frontmatter } = Astro.props;
    ---
    <BaseLayout pageTitle={frontmatter.title}>
    <meta charset="utf-8" />
    <h1>{frontmatter.title}</h1>
    <p>{frontmatter.pubDate.toString().slice(0,10)}</p>
    <p><em>{frontmatter.description}</em></p>
    <p>Written by: {frontmatter.author}</p>
    <img src={frontmatter.image.url} width="300" alt={frontmatter.image.alt} />
    <slot />
    </BaseLayout>
  2. src/layouts/MarkdownPostLayout.astro 中,你现在可以移除 meta 标签,因为它已经包含在你的 BaseLayout中了。

    src/layouts/MarkdownPostLayout.astro
    ---
    import BaseLayout from './BaseLayout.astro';
    const { frontmatter } = Astro.props;
    ---
    <BaseLayout pageTitle={frontmatter.title}>
    <meta charset="utf-8" />
    <h1>{frontmatter.title}</h1>
    <p>{frontmatter.pubDate.toString().slice(0,10)}</p>
    <p><em>{frontmatter.description}</em></p>
    <p>Written by: {frontmatter.author}</p>
    <img src={frontmatter.image.url} width="300" alt={frontmatter.image.alt} />
    <slot />
    </BaseLayout>
  3. https://:4321/posts/post-1 查看你的浏览器预览。现在你应该能看到由以下部分渲染的内容:

    • 你的**主页面布局**,包括你的样式、导航链接和社交页脚。
    • 你的**博客文章布局**,包括 frontmatter 属性,如描述、日期、标题和图片。
    • 你的**单篇博客文章的 Markdown 内容**,包括仅在这篇文章中编写的文本。
  4. 注意,你的页面标题现在显示了两次,每个布局各显示一次。

    MarkdownPostLayout.astro 中移除显示页面标题的那一行。

    src/layouts/MarkdownPostLayout.astro
    <BaseLayout pageTitle={frontmatter.title}>
    <h1>{frontmatter.title}</h1>
    <p>{frontmatter.pubDate.toString().slice(0,10)}</p>
    <p><em>{frontmatter.description}</em></p>
    <p>Written by: {frontmatter.author}</p>
    <img src={frontmatter.image.url} width="300" alt={frontmatter.image.alt} />
    <slot />
    </BaseLayout>
  5. 再次在 https://:4321/posts/post-1 查看你的浏览器预览,并验证该行不再显示,且你的标题只显示一次。进行任何其他必要的调整,以确保没有任何重复的内容。

请确保:

  • 每篇博客文章都显示相同的页面模板,并且没有内容缺失。(如果你的某篇博客文章缺少内容,请检查其 frontmatter 属性。)

  • 页面上没有重复的内容。(如果有内容被渲染了两次,请务必从 MarkdownPostLayout.astro 中移除它。)

如果你想自定义你的页面模板,你也可以这样做。

  1. 这允许你将一个布局嵌套在另一个布局中,并利用模块化组件的优势。

  2. 对于包含 Markdown 页面的项目,多个布局特别有用,例如……

  3. 以下哪项为你的所有页面提供模板?

贡献 社区 赞助