Skip to content

参与和传播

¥Engagement and dissemination

您可以通过提供可供订阅的 RSS 源并集成讨论系统来提升读者参与度,并改善博客内容的传播。为了更详细地了解哪些人正在阅读或未阅读您的文章,您可能需要集成一个分析系统。您还可能希望在发布新博文时在社交媒体上发布。本教程将帮助您掌握所有这些主题。

¥You can foster reader engagement and improve the dissemination of content on your blog by providing an RSS feed that people can subscribe to and by integrating a discussion system. To learn more about who is or is not reading your posts, you may want to integrate an analytics system. You may also want to post on social media when you publish a new blog post. This tutorial gives you a leg up on all of these topics.

所需时间:通常 30 分钟

¥Time required: typically 30 minutes

RSS订阅

¥RSS feeds

RSS Feed允许用户订阅博客,以便在您发布新文章时收到通知。RSS Feed 阅读器通常用于访问用户关注的博客。它们通常支持下载博客内容以供离线阅读。

¥An RSS feed allows users to subscribe to a blog so that they get notified when you publish new posts. RSS Feed readers are often used to access blogs that a user follows. They usually support downloading the blog content for offline consumption.

为你的博客创建 RSS 源的一个简单方法是使用MkDocs RSS 插件,该插件与 Material for MkDocs 完美集成。由于它是第三方插件,因此你需要先安装它才能使用它。

¥An easy way to create an RSS feed for your blog is to use the MkDocs RSS Plugin, which is well integrated with Material for MkDocs. Since it is a third-party plugin, you need to install it before using it.

添加 RSS 源

¥Add an RSS feed

将 RSS 插件安装到您的项目中:

¥Install the RSS plugin into your project:

$ pip install mkdocs-rss-plugin

请务必按照基础博客教程中的说明配置site_namesite_descriptionsite_url 。RSS 插件会使用这些信息来构建 feed,因此请确保您已配置好它们。

¥It is important that have the site_name, site_description and site_url settings configured as instructed in the basic blog tutorial. The RSS plugin makes use of this information to construct the feed, so make sure you have configured them.

现在,在mkdocs.yml中配置插件。提供的选项将创建 RSS 条目的页面限制为博客文章,这可能正是您想要的。另请注意,日期字段的配置要与 Material for MkDocs 使用的格式相匹配,以便同时容纳创建日期和更新日期。

¥Now, configure the plugin in the mkdocs.yml. The options provided restrict the pages that RSS entries are created for to the blog posts, which is probably what you want. Also note the configuration of the date fields to match the format that Material for MkDocs uses to accommodate both a creation date and a date for updates.

plugins:
    - ...
    - rss:
        match_path: "blog/posts/.*"
        date_from_meta:
          as_creation: date.created
          as_update: date.updated

访问http://localhost:8000/feed_rss_created.xml即可查看 RSS feed 的完整 XML 格式。您可以使用 Firefox 或 Chrome 等浏览器来显示原始 RSS feed,或者使用curl获取 RSS feed 并使用xmllint进行格式化。(您可能需要安装这些工具。)

¥Have a look at http://localhost:8000/feed_rss_created.xml to see the RSS feed in all its XML glory. You can use a browser like Firefox or Chrome that can display the raw RSS feed or use curl to get the feed and xmllint to format it. (You may need to install these tools.)

curl -s http://localhost:8000/feed_rss_created.xml | xmllint --format -

您可能还想尝试使用 Feed 阅读器来查看您的 Feed。市面上有各种桌面和移动应用程序,以及在线服务。当然,要使用在线服务,您需要将项目部署到他们可以访问的地方。

¥You may also want to try your feed with a feed reader. There are various desktop and mobile apps as well as online services. Of course, to use the latter you will need to deploy your project somewhere that is accessible to them.

如果您未对博客插件的默认配置进行任何更改,此最低配置应该可以正常工作。有关如何根据您的需求调整订阅源的更多信息,请参阅RSS 插件的文档

¥This minimal configuration should work well if you have not made any changes to the default configuration of the blog plugin. For more information on adapting the feed to your needs, see the RSS plugin's documentation.

社交媒体按钮

¥Social media buttons

社交媒体按钮有两个用途:允许您的读者导航到您的社交媒体资料或通过他们自己的帐户分享您发布的内容。

¥Social media buttons can serve two purposes: to allow your readers to navigate to your social media profiles or to share content you have published via their own accounts.

¥Profile links

社交媒体资料的链接通常位于页面页脚,Material for MkDocs 让这变得简单。您只需提供必要的链接并定义要使用的图标即可。

¥Links to social media profiles a usually provided in the footer of pages and Material for MkDocs makes this easy. All you need to do is to provide the necessary links and define the icons to use.

添加社交媒体个人资料链接

¥Adding social media profile links

mkdocs.yml中添加一个extra部分,并在其中添加一个social部分,用于包含链接定义列表。这些链接定义包含要使用的徽标和指向个人资料的链接。

¥Add an extra section to your mkdocs.yml and, within it, a social section to contain a list of link definitions. These consist of the logo to use and the link to the profile.

extra:
  social:
    - icon: fontawesome/brands/mastodon
      name: squidfunk on Mastodon
      link: https://fosstodon.org/@squidfunk

对于icon ,您可以选择任何与主题捆绑在一起的有效图标路径。 name将用作图标的 title 属性,添加此属性可提高可访问性。对于流行的社交媒体系统,链接必须是绝对链接,并且需要包含方案,最有可能的是https://

¥For the icon, you can choose any valid path to an icon bundled with the theme. The name will be used as the title attribute for the icon and including this improves accessibility. For popular social media systems, the link needs to be absolute and needs to include the scheme, most likely https://.

你也可以使用其他方案。例如,要创建一个允许人们创建电子邮件的图标,请添加以下内容:

¥You can also use other schemes. For example, to cerate an icon that allows people to create an email, add this:

extra:
  social:
  - icon: /fontawesome/regular/envelope
    name: send me an email
    link: mailto:<email-address>

最后,您可以指定网站内的 URL,例如您的联系页面。也可以只指定页面的路径:

¥Finally, you can specify a URL within your site, such as to your contact page. It is possible to specify only the path to the page:

extra:
  social:
  - icon: /material/mailbox
    name: contact us
    link: /contact

分享和点赞按钮

¥Share and like buttons

添加允许人们在社交媒体上分享您的内容的按钮需要更多一些时间,这就是为什么有公司提供此类组件的原因。

¥Adding buttons that let people share your content on social media is a bit more involved, which is why there are companies offering components for this.

数据保护

¥Data Protection

使用社交媒体公司提供的集成功能“分享”和“点赞”按钮通常会留下大量数据痕迹,即使用户未与这些按钮交互。如果您选择在您的网站上集成此类功能,请注意数据保护的影响以及您作为提供商的义务,以确保仅在用户同意后才进行数据处理。

¥"Share" and "Like" buttons that use integrations provided by social media companies often leave copious data traces even when the user does not interact with these buttons. If you choose to integate such feature on your site please be aware of the data protection implications and your duties as a provider to ensure that processing occurs only once the user has granted consent.

此分享按钮的实现刻意不使用第三方代码。它支持分享到 Twitter/X 和 Facebook,而不会在用户浏览页面时向这些公司产生数据流。只有点击分享按钮时,才会与这些公司的服务器进行交互。

¥This implementation of share buttons deliberately does not use third party code. It supports sharing to Twitter/X and Facebook without causing a data flow to these companies whenever someone views the pages. Only when someone clicks a share button will there be interactions with those companies' servers.

添加分享按钮

¥Add share buttons

为了添加共享按钮,您可以添加一个附加用于共享当前页面的按钮的钩子。

¥In order to add the share buttons, you can add a hook that appends buttons for sharing the current page.

在项目根目录中创建一个目录hooks并在mkdocs.yml中对其进行配置:

¥Create a directory hooks in your project root and configure it in your mkdocs.yml:

hooks:
  - hooks/socialmedia.py

使用以下 Python 代码添加文件hooks/socialmedia.py

¥Add the file hooks/socialmedia.py with the following Python code:

from textwrap import dedent
import urllib.parse
import re

x_intent = "https://x.com/intent/tweet"
fb_sharer = "https://www.facebook.com/sharer/sharer.php"
include = re.compile(r"blog/[1-9].*")

def on_page_markdown(markdown, **kwargs):
    page = kwargs['page']
    config = kwargs['config']
    if not include.match(page.url):
        return markdown

    page_url = config.site_url+page.url
    page_title = urllib.parse.quote(page.title+'\n')

    return markdown + dedent(f"""
    [Share on :simple-x:]({x_intent}?text={page_title}&url={page_url}){{ .md-button }}
    [Share on :simple-facebook:]({fb_sharer}?u={page_url}){{ .md-button }}
    """)

该钩子首先检查当前页面是否为博客文章,然后附加分享按钮的 Markdown 代码。由于按钮使用图标,因此您还需要配置以下 Markdown 扩展:

¥The hook first checks if the current page is a blog post and then appends Markdown code for the share buttons. The buttons use icons, so you also need to configure the following markdown extensions:

markdown_extensions:
  - attr_list
  - pymdownx.emoji:
      emoji_index: !!python/name:material.extensions.emoji.twemoji
      emoji_generator: !!python/name:material.extensions.emoji.to_svg

添加讨论系统

¥Add a discussion system

允许读者对您的帖子发表评论是获得反馈、学习知识以及让读者有机会讨论其内容和主题的好方法。

¥Allowing your readers to comment on your posts is a great way of receiving feedback, learning something, as well as giving readers the opportunity to discuss the content and the topic it is about.

市面上有很多讨论系统,在选择适合你博客的讨论系统时,你需要考虑你的受众。同样,你也需要考虑现有的沟通渠道。例如,如果你是 Slack 的重度用户,你可能对这个系统有很强的偏好。记住,当你添加一个沟通渠道时,你需要做好定期使用它并主持讨论的准备。

¥There are plenty of discussion system out there and you will need to consider your audience when choosing one appropriate for your blog. Likewise, you will also need to consider existing commitments to communication channels. If you are a heavy user Slack, for example, you may have a string preference for this system. Consider that when you add a communication channel, you will need to be prepared to use it regularly and to moderate discussions.

Giscus 集成

¥Giscus integration

在本教程中,我们将使用Giscus ,因为它免费、开源,并且使用GitHub Discussions作为后端。由于许多 Material for MkDocs 用户都使用 GitHub,因此 Giscus 似乎是个不错的选择。

¥In this tutorial, we will be using Giscus because it is free, open source, and uses GitHub Discussions as a backend. Because a lot of users of Material for MkDocs use GitHub, this seems like an obvious choice.

要将 Giscuss 添加到您的博客,您需要执行以下步骤:

¥To add Giscuss to your blog you will need to go through a number of steps:

  1. 如果还没有 GitHub 存储库,请创建一个

    ¥Create a GitHub repository if there is not already one

  2. 开启讨论并安装Giscus 应用

    ¥Turn on discussions and install the Giscus app

  3. 配置将 Giscus 嵌入到您的博客所需的代码

    ¥Configure the code needed to embed Giscus into your blog

  4. 将代码添加到您的 MkDocs 项目

    ¥Add the code to your MkDocs project

您可能需要为本教程创建一个测试仓库,以便以后可以将其废弃。以下说明假设您是用户“example”,并创建了一个名为“giscus-test”的仓库。该仓库需要公开,以便人们能够使用讨论。

¥You may want to create a test repository for this tutorial that you can scrap later on. The instructions below assume that you are user "example" and that you create a repository "giscus-test." The repository will need to be public for people to be able to use the discussions.

在下面给出的说明中,如果您选择了其他名称(例如,当您想直接在现有存储库上工作时),则至少需要替换用户名,还需要替换存储库名称。

¥In the instructions given below, you will need to replace at least the username but also the repository name if you chose another name such as when you want to work directly on an existing repository.

开启讨论并安装 Giscus 应用

¥Turn on discussions and install the Giscus app

设置好仓库后,前往其设置页面,在General部分找到Features 。勾选Discussions复选框。您将看到Discussions出现在仓库的顶部导航栏中。如果您使用的是实时仓库,那么您可能需要在此时向“讨论”部分添加一些基本内容,然后再返回教程。

¥Once the repository is set up, go to its settings page and find Features in the General section. Tick the checkbox for Discussions. You will see that Discussions appears in the top navigation for the repository. If you are using a live repository then you may want to add some minimal content to the dicussions section at this point and come back to the tutorial.

接下来,您需要按照此句中的链接安装Giscus 应用程序,并选择Install ,然后按照说明选择 Giscus 应用程序的安装位置:

¥Next, you need to install the Giscus app by following the link in this sentence, and choosing Install, then following the instructions to choose where the Giscus app is to be installed:

  1. 选择您想要使用的存储库的帐户或组织。

    ¥Choose the account or organization for the repository you want to use.

  2. 选择仅在选定的存储库上安装,然后选择要使用的存储库。请注意,您可以在此处选择多个存储库。

    ¥Choose to install only on select repositories and select the one you want to use. Note that you can choose more than one repository here.

  3. 最后选择Install 。你可能需要进行身份验证才能执行此操作。

    ¥Select Install at the end. You may need to authenticate to give permission for this to happen.

  4. 您将进入设置中的Applications页面,您可以在其中控制 Gicsus 应用程序并根据需要将其卸载。

    ¥You will end up on the Applications page in your settings, where you can control the Gicsus app and uninstall it if so desired.

这就是创建 Giscuss 仓库所需的所有准备工作。接下来,是时候生成一段将 Giscuss 嵌入到您的网站的代码了。生成的代码片段如下所示:

¥That is all the preparation you will need for the repository. Next, it is time to generate a piece of code that embeds Giscuss in your site. The resulting code snippet will look something like this:

<script src="https://giscus.app/client.js"
        data-repo="<username>/<repository>"
        data-repo-id="..."
        data-category="Announcements"
        data-category-id="..."
        data-mapping="title"
        data-strict="1"
        data-reactions-enabled="1"
        data-emit-metadata="1"
        data-input-position="top"
        data-theme="preferred_color_scheme"
        data-lang="en"
        data-loading="lazy"
        crossorigin="anonymous"
        async>
</script>

配置将 Giscus 嵌入到您的博客所需的代码

¥Configure the code needed to embed Giscus into your blog

前往Giscus 主页并配置嵌入代码。有以下一些设置:

¥Go to the Giscus homepage and configure the embedding code. There are a number of settings:

  1. 选择语言

    ¥Choose the language

  2. 输入用户名/组织名称和存储库名称

    ¥Enter the username / organization name and repository name

  3. 选择如何将讨论映射到博客页面。由于博客文章的标题是 URL 的基础,因此使用Discussion title contains page <title>选项比较合理。

    ¥Choose how the discussions are to be mapped to the page on your blog. Because for a blog post the title is the basis of the URL, it makes sense to use the Discussion title contains page <title> option.

  4. Discussion Category下选择Announcements以将新讨论的创建限制为 Giscuss 和具有维护者或管理员权限的人员。

    ¥Under Discussion Category choose Announcements to limit the creation of new discussions to Giscuss and people with maintainer or admin permissions.

  5. Features下,选择以下内容:启用对主帖的反应发出讨论元数据将评论框放在评论上方

    ¥Under Features, select the following:

  6. Theme下,选择Preferred color scheme ,以便 Giscus 匹配用户为您的网站选择的配色方案。

    ¥Enable reactions for the main post

完成这些设置后,您现在需要将代码集成到您的网站。partials partials/comments.html就是为此目的而存在的,默认情况下为空。它包含在content.html部分文件中,因此会包含在您网站的每个页面上。您可能需要,也可能不需要。在本教程中,您将限制 Giscus 集成仅限于博客文章,但如果您希望 Giscus 讨论在每个页面上都处于活动状态,则可以轻松省略实现此目的的代码。

¥With these settings in place, you now need to integrate the code into your site. There is a partial partials/comments.html that exists for this purpose and is empty be default. It is included by the content.html partial, so will be included for every page on your site. You may or may not want this. In this tutorial, you will limit the Giscus integration to only blog posts but it is easy enough to leave out the code that achieves this if you want to have Giscus discussions active for every page.

添加 Giscus 集成代码

¥Add Giscus integration code

首先,您需要创建一个overrides目录,其中将包含您想要覆盖的模板和部分。

¥First, you need to create an overrides directory that will contain the templates and partials you want to override.

mkdir -p overrides/partials

您需要在mkdocs.yaml中声明它:

¥You need to declare it in your mkdocs.yaml:

theme:
  name: material
  custom_dir: overrides

现在添加一个文件overrides/partials/comments.html ,并粘贴你从 Giscus 主页获取的代码片段。在本地查看结果,你会发现集成功能已在网站的所有页面上启用。如果你想将其限制在你的博客文章中,则需要在 Giscus 脚本周围添加一个条件语句,用于测试是否应该包含评论。一个简单的方法是测试元数据标志:

¥Now add a file overrides/partials/comments.html and paste in the code snippet you obtained from the Giscus homepage. Look at the result locally and you will see that the integration is active on all pages of the site. If you want to restrict it to your blog posts, you need to add a conditional around the Giscus script that tests if comments should be included. A simple way of doing this is to test for a metadata flag:

{% if page.meta.comments %}
<script>...</script>
{% endif %}

缺点是,你现在需要手动为每篇博文开启评论功能——除非你想关闭部分博文的评论功能。要获取所有博文的评论部分,请使用如下代码:

¥The disadvantage is that you now need to manually turn on comments for each blog post - unless you want to turn them off on some. To get the comments section on all blog posts, use code like this:

{% if page.file.src_uri.startswith('blog/posts') %}
<script>...</script>
{% endif %}

您现在应该看到 Giscus 评论已添加在您的博客文章底部,但没有添加到其他页面上。

¥You should see now that the Giscus comments are added at the bottom of your blog posts but not on other pages.

下一步是什么?

¥What's next?

本博客教程到此结束。希望您喜欢本教程,并能按照自己喜欢的方式设置博客。还有许多其他功能和选项我们未能在此一一介绍。博客插件参考提供了该插件的详尽文档。您也可以参考社交插件教程,了解如何为您的博客文章生成社交卡片,当您将链接发布到社交媒体系统时,这些卡片会显示出来。

¥This is the end of the blog tutorial. We hope you have enjoyed it and manage to set up your blog the way you like it. There are numerous other features and options that we have not been able to cover here. The blog plugin reference provides comprehensive documentation for the plugin. You may also want to look at the social plugin tutorial to generate social cards for your blog posts that get displayed when you post links to social media systems.