Posted on

这篇文章由 Apollo 主题作者 Matthias 的文章 Creating a Custom Homepage 翻译而来。

Apollo 主题提供了一个默认主页,用于列出您的最新博客文章。不过,您可能希望创建一个更能体现您个性和作品的自定义主页。本指南将带您逐步了解如何使用 Apollo 主题创建自定义主页。

1. 创建自定义主页模板

第一步是创建自定义主页模板。在 Zola 项目的根目录下,创建一个名为 templates/home.html 的新文件。该文件将包含自定义主页的 HTML 代码。

您可以使用以下代码作为起点:

{% extends "base.html" %} {% block main_content %}
<main>
  <article>
    <section class="body">
      <h1>欢迎访问我的自定义主页!</h1>
      <p>您可以在此介绍自己和作品。</p>
    </section>
  </article>
</main>
{% endblock main_content %}

此模板继承了主题的 base.html 模板,并用您自己的内容覆盖了 main_content 块。

2. 设置主页模板

接下来,您需要告诉 Zola 使用您的自定义主页模板。在 Zola 项目的 content 目录中,应该有一个 _index.md 文件。如果没有,请创建一个。

在此文件中,添加以下前置信息:

+++
template = "home.html"
+++

这会告诉 Zola 使用 templates/home.html 文件来渲染您的主页。

3. 向主页添加内容

现在你可以向主页添加内容了。content/_index.md 文件中的内容将在 templates/home.html 模板中作为 section 变量使用。

例如,你可以在 content/_index.md 文件中添加标题和一些介绍性文字:

+++
title = "你好!👋🏼"
template = "home.html"
+++

我是一名软件工程师,喜欢撰写关于技术和编程的文章。

然后,您可以在 templates/home.html 模板中显示此内容:

{% extends "base.html" %} {% macro home_page(section) %}
<main>
  <article>
    <section class="body">
      {{ post_macros::page_header(title=section.title) }} {{ section.content |
      safe }}
    </section>
  </article>
</main>
{% endmacro home_page %} {% block main_content %} {{
self::home_page(section=section) }} {% endblock main_content %}

4. 显示文章

您还可以在主页上显示近期文章列表。以下代码演示了如何显示最近的 5 篇文章:

{% extends "base.html" %} {% macro home_page(section) %}
<main>
  <article>
    <section class="body">
      {{ post_macros::page_header(title=section.title) }} {{ section.content |
      safe }}
    </section>
  </article>
</main>
{% endmacro home_page %} {% block main_content %} {{
self::home_page(section=section) }}

<h1>近期文章</h1>
<main class="post-list">
  {% set section = get_section(path="posts/_index.md") %} {{
  post_macros::list_posts(pages=section.pages | slice(end=5)) }}
</main>
{% endblock main_content %}

这段代码获取 posts 板块,然后使用 post_macros::list_posts 宏显示最近的 5 篇博文。

你还可以通过路径获取特定博文来突出显示它们:

{% set highlights = [ get_page(path="posts/my-first-post.md"),
get_page(path="posts/my-second-post.md"), ] %}
<main class="post-list">{{ post_macros::list_posts(pages=highlights) }}</main>

这只是一个起点。您可以随心所欲地自定义您的主页。

Table of Contents