Skip to content

导航、作者和分页

¥Navigation, authors, and pagination

博客插件提供博客风格的导航,默认包含按时间倒序排列的索引页和按年份排列的存档。本教程将介绍如何配置默认导航的详细信息、配置作者,以及如何使用类别和标签插件添加更多导航选项。

¥The Blog plugin provides blog-style navigation with a reverse-chronological index page and an archive organized by year by default. This tutorial shows how you can configure details of the default navigation, configure authors, and add more navigation options using categories and the Tags plugin.

所需时间:通常 30 分钟

¥Time required: typically 30 minutes

集成导航

¥Integrating navigation

到目前为止,您已经将导航交给了 Blog 插件和 MkDocs 处理。对于某些用例,这可能已经足够,并且无需在mkdocs.yml中声明nav部分即可。

¥So far, you have let the Blog plugin and MkDocs worry about navigation. For some use cases, this might be enough and it is simply sufficient to not declare a nav section in the mkdocs.yml.

但是,您可能希望将博客与其他内容以及您在配置的nav部分中定义的导航结构集成在一起。在这种情况下,您需要提供一个位置,以便博客插件将博客导航附加到其余导航结构。

¥However, you may want to integrate a blog with other content and a navigation structure that you have defined in the nav section of the configuration. In such cases, you need to provide a place where the Blog plugin should attach the blog navigation to the rest of the navigation structure.

与网站导航集成

¥Integrate with site navigation

将以下内容添加到您的mkdocs.yml中,以查看 Blog 插件如何将博客导航与整体导航结构集成。请注意,此时您唯一需要指定的是博客的索引页,其路径必须与blog_dir设置匹配,默认情况下为blog

¥Add the following to your mkdocs.yml to see how the Blog plugin can integrate the blog navigation with the overall navigation structure. Note that the only thing you need to specify at this point is the index page for the blog and its path must match the blog_dir setting, which is blog by default:

nav:
  - Home: index.md
  - Install: install.md
  - Usage: usage.md
  - Blog:
     - blog/index.md

您会注意到“博客”在导航结构中重复出现。为了避免这种情况,您可以使用navigation.indexes功能将博客索引设置为博客的部分索引页:

¥You will notice that "Blog" is duplicated in the navigation structure. To avoid this, you can use the navigation.indexes feature to make the blog index the section index page for the blog:

theme:
  name: material
  features:
    - navigation.indexes

独立博客

¥Stand-alone blog

如果您需要的是独立的博客,而不是与大型网站集成的博客,可以使用blog_dir配置选项来实现。要了解如何操作,请参阅设置博客。本教程的其余部分假设您将博客与大型网站集成。

¥If what you need is a stand-alone blog instead of one that is integrated with a larger site, this can be done by using the blog_dir configuration option. To see how this is done, see setting up a blog. The rest of the tutorial assumes that you are integrating the blog with a wider site.

添加页面

¥Adding pages

您可以将其他页面添加到博客版块,只需将它们放入docs/blog (并添加到导航栏即可)。博客存档将添加到这些页面的导航栏之后。

¥You can add additional pages to the blog section by putting them into docs/blog (and adding them to the navigation). The blog archive will be added to the navigation after these pages.

配置档案

¥Configuring the archive

默认情况下,博客存档仅按年份列出文章。如果您想按月份添加列表,可以配置存档的日期格式。

¥By default, the blog archive lists posts by year only. If you want to add listings by month, you can configure the date format for the archive.

按月组织帖子

¥Organize posts by month

将以下内容添加到您的mkdocs.yml以获取包含月份名称的列表(使用主题选项中选择的语言):

¥Add the following to your mkdocs.yml to get a listing with the month name (in the language selected in the theme options):

- blog:
    archive_date_format: MMMM yyyy

例如,如果您不想要完整的月份名称,则可以将日期配置为MM/yyyy

¥If you do not want the full month name, you can make the date configuration MM/yyyy, for example.

如果您想添加日期,可以添加一个占位符。例如,要获得美式输出,请将其设置为MM/dd/yyyy 。为了让插件按完整日期对博客文章进行排序,您还需要将archive_url_date_format设置为包含月份和日期,因此也将其设置为MM/dd/yyyy

¥If you want to add the day, you can add a placeholder for them. For example, to get an American-style output, make it MM/dd/yyyy. For the plugin to sort the blog posts by the full date, you will also need to set the archive_url_date_format to include the month and day, so make it MM/dd/yyyy as well.

使用类别

¥Using categories

分类是一种按主题访问博客文章的方式,同时保留每个分类列表中基于时间顺序的导航结构。当只有有限的几个不重叠的类别可供您分类文章时,可以使用分类。

¥Categories are a way to make blog posts accessible by topic while retaining the navigation structure based on chronology within each category listing. Use them when there is a limited set of non-overlapping categories that you can sort your posts into.

类别显示在主导航中,因此可以直接从那里访问。这意味着类别数量相对较少,否则主导航中的categories部分会显得过于拥挤。

¥Categories appear in the main navigation, so are directly accessible from there. This implies that there are relatively few categories as otherwise the categories section in your main navigation will become too crowded.

添加类别

¥Add a category

通过将类别添加到页面标题来为您的第一篇博客文章添加一个类别:

¥Add a category to your first blog post by adding it to the page header:

---
date: 2023-12-31
updated: 2024-01-02
categories:
  - Holidays
---

现在博客文章已分类, Holidays出现在主导航中的Categories下,博客文章出现在此类别的索引页中。

¥Now that the blog post has been categorised, Holidays appears under Categories in the main navigation and the blog post appears in the index page for this category.

单个还是多个类别?

¥Single or multiple categories?

虽然传统上博客文章只能属于一个类别,但 Material for MkDocs 实际上允许您指定多个类别。虽然这给了您一定的自由度,但您可能不应该过度使用,尤其是因为您可以使用标签来处理多个分类。我们将在下一步中介绍它们。

¥While it is traditionally the case that a blog post would belong to only one category, Material for MkDocs actually allows you to assign more than one. While this gives you a degree of freedom, you should probably not use this too much, not least because you can use tags to deal with multiple classifications. We will cover them in the next step.

Material 允许您控制博客作者可以使用哪些类别。您可以在mkdocs.yml中声明这些类别。这样,您可以确保每个人都遵守约定的类别,并且插件可以检测到拼写错误。

¥Material allows you to control which categories blog authors can use. You declare them in the mkdocs.yml. This way you can make sure everyone sticks to agreed categories and that the plugin detects typos.

控制您的类别

¥Control your categories

在博客插件的配置中添加categories_allowed条目,其中包含“假期”和“新闻”条目:

¥Add a categories_allowed entry to the configuration of the Blog plugin with the entries "Holidays" and "News":

plugins:
  - search
  - blog:
      archive_date_format: MMMM yyyy
      categories_allowed:
        - Holidays
        - News

现在,当您向博客文章添加与这两者之一不匹配的类别时,您应该会收到构建错误。

¥Now, when you add a category to a blog post that does not match one of these two, you should get a build error.

使用标签

¥Using tags

标签插件提供了另一种对博客文章进行分类的方法,使其能够独立于主导航结构进行访问。标签有助于轻松找到相关内容,即使它们位于导航层次结构的不同部分。

¥The Tags plugin provides another way to classify blog posts and to make them accessible independently of the main navigation structure. Tags are useful for making related content easily discoverable even if it is in different parts of the navigation hierarchy.

您可能有类似本教程的教程,以及更全面的设置指南和参考文档。为这三个页面添加相同的标签,表明它们是相关的。正如您将看到的,您可以从带有标签的页面导航到标签索引,然后从那里导航到其他带有相同标签的页面。

¥You may have a tutorial like this one as well as a more comprehensive setup guide and reference documentation. Adding the same tag to all three shows that they are related. As you will see, it is possible to navigate from a tagged page to the tag index and, from there, to other pages that carry the same tag.

启用插件并添加标签

¥Enable the plugin and add tags

首先,您需要将插件添加到您的mkdocs.yml中:

¥First, you need to add the plugin to your mkdocs.yml:

plugins:
  - search
  - blog:
      archive_date_format: MMMM yyyy
      categories_allowed:
        - Holidays
        - News
  - tags

完成后,您可以在页面标题中向帖子添加标签:

¥Once this is done, you can add tags to posts in the page header:

---
date:
  created: 2023-12-31
  updated: 2024-01-02
authors:
  - material
categories:
  - Holidays
tags:
  - new year
  - hogmanay
  - festive season
---

您应该会在文章顶部看到您定义的标签。不过,目前仅此而已。虽然博客插件会自动为类别创建索引页,但标签插件不会为标签创建索引页。这是因为标签插件并非专门针对博客。您可以将其用于任何网站内容,因此标签索引应该放在哪里并不明显。

¥You should see the tags that you defined at the top of the post. However, at the moment that is it. While the blog plugin automatically creates an index page for categories, the tags plugin does not do the same for tags. This is because the tags plugin is not specific for blogs. You can use it for any site content, so it is not obvious were the tag index should go.

您可以使用 Material for MkDocs 的公共版本配置基本标签索引。当然,Insider 版本也支持此功能,但它还提供了一种替代索引机制,允许任意数量的标签索引、作用域列表、影子标签、嵌套标签等等。

¥You can configure a basic tag index using the public version of Material for MkDocs. The Insider Edition supports this as well, of course, but also provides an alternative index mechanism that allows for an arbitrary number of tag indexes, scoped listings, shadow tags, nested tags, and much more.

添加标签索引

¥Adding a tags index

要使用公共版本配置标签索引,请在标签插件的配置中添加tags_file条目,并在nav部分中进行配置。请记住在现有tags条目的末尾添加冒号。

¥To configure a tag index using the public version, add a tags_file entry to your configuration of the tags plugin and configure it in your nav section. Remember to add a colon at the end of the existing tags entry.

plugins:
    - search
    - blog:
        archive_date_format: MMMM yyyy
        categories_allowed:
            - Holidays
            - News
    - tags:
        tags_file: blog/tags.md

nav:
    - Home: index.md
    - Install: install.md
    - Usage: usage.md
    - Blog:
        - blog/index.md
        - Tags: blog/tags.md

标签索引将附加到已配置的页面,您现在应该在指定的位置创建该页面。

¥The tag index will be appended to the configured page, which you should now create at the location specified.

请注意,您可以将标签索引页放在主导航中的任何位置,因此如果您在其他地方而不是仅在博客中使用标签,那么您可能希望将标签索引放在导航的博客部分之外。

¥Note that you can put the tag index page anywhere in your primary navigation, so if you are using tags elsewhere instead of just in your blog then you may want to have the tag index outside the blog section of the navigation.

要添加标签索引,您需要在 Markdown 文件中添加一个占位符,以指示插件在该位置插入索引。这意味着您可以在索引前后添加内容。至关重要的是,您可以在多个页面中添加占位符,每个页面都配置了应在索引中显示的标签子集。

¥To add a tag index, you add a placeholder in a Markdown file to tell the plugin to insert an index at that point. This means that you can add content before and after the index. Crucially, you can add placeholders in multiple pages, each with a configuration of what subset of tags should be displayed in the index.

最简单的索引页如下所示。在docs/tags.md下创建它。

¥The simplest index page looks like this. Create it under docs/tags.md.

# Tag index
<!-- material/tags -->

现在,您可能希望将博客的标签与页面其他部分使用的标签区分开。您可以通过为标签索引分配作用域来实现这一点。将以下内容放在docs/blog/tags.md下:

¥Now, you may want to keep the tags for your blog separate from tags you use in the rest of your page. You can achieve this by assigning the tag index a scope. Put the following under docs/blog/tags.md:

# Tag index  for the blog
<!-- material/tags { scope: true } -->

现在你有两个索引页:一个覆盖整个网站,一个仅覆盖博客。将两者都添加到导航中:

¥You now have two index pages: one covers the whole site and one covers only the blog. Add both to the navigation:

nav:
    - Home: index.md
    - Tags: tags.md
    - Blog:
        - blog/index.md
        - blog/tags.md

Insider Edition 中的标签插件功能极其强大,我们目前对其功能还只是皮毛。如果您在完成本教程的这一部分后还想了解更多信息,请查看标签插件参考

¥The tags plugin in the Insider Edition is an incredibly powerful tool and we can only scratch the surface of what is possible with it. If you want to explore more after you have worked for this part of the tutorial, have a look at the tags plugin reference.

定义作者

¥Defining authors

如果您的博客有多个作者,那么您可能需要识别每篇博文的作者。博客插件允许您创建一个包含作者信息的文件,然后在页眉中引用特定博文的作者。

¥If your blog has more than one author then you may want to identify the author for each blog post. The blog plugin allows you to create a file that contains the author information and to then reference the authors of a particular post in the page header.

创建作者信息

¥Create author info

创建包含以下内容的文件docs/blog/.authors.yml

¥Create a file docs/blog/.authors.yml with this content:

authors:
  team:
    name: Team
    description: Creator
    avatar: https://simpleicons.org/icons/materialformkdocs.svg
  squidfunk:
    name: Martin Donath
    description: Creator
    avatar: https://github.com/squidfunk.png

然后在第一篇帖子的标题中添加一行:

¥and then add a line to the header of the first post:

---
date:
  created: 2023-12-31
  updated: 2024-01-02
authors:
  - team
---

请注意, authors是一个列表,因此您可以指定多个作者。

¥Note that authors is a list, so you can specify multiple authors.

使用 Insiders 版本,您可以创建自定义作者索引页面,突出显示作者的贡献并提供有关他们的其他信息。

¥With the Insiders edition, you can create custom author index pages that can highlight the contributions of an author as well as provide additional information about them.

添加作者页面

¥Add author page

首先,您需要在mkdocs.yml中启用作者配置文件:

¥First, you need to enable author profiles in the mkdocs.yml:

plugins:
  - search
  - blog:
      archive_date_format: MMMM yyyy
      categories_allowed:
          - Holidays
          - News
      authors_profiles: true

检查您的博客,可以看到主导航中的archivecategories旁边现在有一个额外的条目,其中列出了作者及其贡献。

¥Check your blog to see that there is now an extra entry in the main navigation next to archive and categories that lists the authors and their contributions.

要自定义作者页面,您可以创建一个页面来覆盖默认生成的页面。首先,创建个人资料页面所在的author目录:

¥To customize the author page, you can create a page that overrides the one generated by default. First, create the author directory that the profile pages will live in:

docs
├── blog
│   ├── author
│   ├── index.md
│   └── posts
│       ├── draft.md
│       └── myfirst.md
└── index.md

然后创建一个页面docs/blog/author/team.md

¥Then create a page docs/blog/author/team.md:

# The Material Team

A small group of people dedicated to making writing documentation easy, if
not outright fun! Here are some of the things we have blogged about:

如您所见,作者索引会附加到您在 Markdown 文件中编写的内容中。

¥As you can see, the author index gets appended to the content you have written in the Markdown file.

分页

¥Pagination

当你的博客开始发展壮大时,你可能不再需要关注每页显示的文章数量。默认情况下,该插件在索引页上最多显示 10 篇文章。你可以分别更改主索引页、存档索引页和分类索引页的此数量。

¥Once your blog starts growing, you may not want to pay attention to the number of posts displayed per page. By default, the plugin displays up to 10 posts on the index pages. You can change this number separately for the main index, the archive index pages, and the category index pages.

更改分页

¥Changing pagination

再添加五篇博客文章,然后将分页设置设置为每页仅显示五篇:

¥Add five more blog posts, then set the pagination setting to show five per page only:

- blog:
    archive_date_format: MMMM yyyy
    categories_allowed:
        - Holidays
        - News
    authors_profiles: true
    pagination_per_page: 5

您将看到存档和分类页面的分页设置继承自您添加的设置。如果您希望为不同的索引页使用不同的设置,可以分别指定每个设置:

¥You will see that the pagination setting for archive and category pages are inherited from the setting you added. If you want to have different settings for the different index pages, you can specify each setting separately:

- blog:
    archive_date_format: MMMM yyyy
    categories_allowed:
        - Holidays
        - News
    authors_profiles: true
    pagination_per_page: 5
    archive_pagination_per_page: 10
    categories_pagination_per_page: 10

博客目录

¥Blog table of contents

当您拥有足够多的帖子时,您可能想要做的另一件事是打开为博客索引页生成目录的功能,让您的读者有机会快速浏览每个页面的内容以查找他们感兴趣的内容,而无需滚动(假设每页的帖子数量不是太多)。

¥Another thing you may want to do once you have a large enough number of posts is to turn on the function that produces a table of contents for the blog index pages, giving your readers the opportunity to quickly scan the content of each page for something that interests them without having to scroll (assuming that the number of post per page is not too big).

打开目录功能

¥Turn on the table of contents feature

要为博客索引页生成目录,请将以下内容添加到博客插件的配置中:

¥To produce a table of contents for the blog index pages, add the following to the configuration of the blog plugin:

- blog:
    blog_toc: true
    archive_date_format: MMMM yyyy
    # ...

自定义 slug

¥Custom slugs

如果由于某种原因,您对 Material for MkDocs 将标题转换为 slug 的方式不满意,您可以创建自己的 slugify 函数,或者您可以手动为特定帖子定义一个 slug。

¥If, for some reason, you are not happy with the way that Material for MkDocs turns headings into slugs, you can create your own slugify function or you can manually define a slug for a specific post.

Slugify 函数

¥Slugify function

要定义自己的 slugify 函数,你需要编写一个 Python 函数,根据配置中的附加参数将文本转换为 slug。你还需要编写一个返回该函数的函数。

¥To define your own slugify function, you need to write a Python function that converts text into a slug given additional arguments from the configuration. You also need to write a function that returns that function.

假设你想定义两个可以切换的 slugify 函数。第一个函数返回一个类似于默认 slugify 函数生成的 slug。第二个函数将 slugify 的结果拆分成单词,并根据最多五个单词返回一个 slug:

¥Say you want to define two slugify functions that you can switch between. The first one returns a slug similar to what the default slugify function produces. The second one cuts the result of that up into words and returns a slug based on a maximum of five of them:

import re, functools, unicodedata

RE_HTML_TAGS = re.compile(r'</?[^>]*>', re.UNICODE)
RE_INVALID_SLUG_CHAR = re.compile(r'[^\w\- ]', re.UNICODE)
RE_WHITESPACE = re.compile(r'\s', re.UNICODE)

def _make_slug(text, sep, **kwargs):
    slug = unicodedata.normalize('NFC', text)
    slug = RE_HTML_TAGS.sub('', slug)
    slug = RE_INVALID_SLUG_CHAR.sub('', slug)
    slug = slug.strip().lower()
    slug = RE_WHITESPACE.sub(sep, slug)
    return slug

def _make_slug_short(text, sep, **kwargs):
    words = _make_slug(text, sep, **kwargs).split(sep)
    return sep.join(words[:5])

def slugify(**kwargs):
    if 'short' in kwargs and kwargs['short']:
        return functools.partial(_make_slug_short, **kwargs)
    return functools.partial(_make_slug, **kwargs)
Save this code in ext/slugs.py and also add an (empty) __init__.py file to indicate that the directory is a module. Now you can configure your custom slugify code like this:

plugins:
- blog:
    # other entries omitted
    post_slugify: !!python/object/apply:ext.slugs.slugify
      kwds:
        short: true

将博客文章的标题改为超过五个字,并观察 slugify 函数如何缩短 URL。将short属性更改为false即可再次关闭此功能。

¥Change the heading of a blog post to be longer than five words and observe how the slugify function shortens the URL. Change the short attribute to false and you can turn this off again.

如果您只想影响单篇博文的 slug,可以通过在文章标题中手动指定来定义。请注意,这只是万不得已的选择。为每篇文章手动指定自定义 slug 会非常繁琐。

¥If you want to influence the slug only for a single blog post, you can define it manually by specifying it in the header of the post. Note that this is meant as a last resort option. Specifying a custom slug manually for every post would be tedious.

手动定义 slug

¥Manually define slug

例如,如果您希望 slug 为“ny-eve”而不是冗长的“happy-new-years-eve”,您可以添加以下内容:

¥If, for example, you wanted the slug to be 'ny-eve' instead of the somewhat lengthy 'happy-new-years-eve', you could add the following:

---
date:
  created: 2023-12-31
  updated: 2024-01-02
readtime: 15
pin: true
slug: ny-eve
---

该帖子的 URL 现在应为http://localhost:8000/blog/2023/01/31/ny-eve/

¥The URL for this post should now be http://localhost:8000/blog/2023/01/31/ny-eve/.

下一步是什么?

¥What's next?

您可能希望通过允许人们订阅 RSS 源、提供社交媒体个人资料链接、提供分享和点赞按钮,或设置评论系统来提升博客的互动性。参与度和传播度教程将指导您完成这些设置。

¥You may want to increase engagement with your blog by allowing people to subscribe to an RSS feed, by providing links to your social media profiles, by providing share and like buttons, or by setting up a comment system. The engagement and dissemination tutorial walks you through setting these up.