Hugo静态博客中添加评论功能

近期升级了一下 macgeeker.com , 主要解决了不能评论的问题. Hugo 支持一些评论系统的接入, 我比较了一下最终选择了 giscus

  • disqus
  • giscus
  • twikoo
  • valine
  • utterances

都各有特点吧, 我最终选择了 giscus , 基于 github discussions 实现的评论系统. 我选择它的理由

Giscus 是由 GitHub Discussions 驱动的评论系统,与GitHub Pages有非常好的天然联结。根据官网,Giscus的特性有:

  • 开源。
  • 无跟踪,无广告,永久免费。
  • 无需数据库。全部数据均储存在 GitHub Discussions 中。
  • 支持自定义主题!
  • 支持多种语言。
  • 高度可配置。
  • 自动从 GitHub 拉取新评论与编辑。
  • 可自建服务!(我并没有使用他的自建服务, 不想麻烦了, 毕竟文章本身才是最重要的)

原理

Giscus 使用 GitHub Discussions 作为数据库存储博客下面的评论。

Giscus 插件加载时,会使用 GitHub Discussions 搜索 API 根据选定的映射方式(如 URL、pathname、 等)来查找与当前页面关联的 discussion。如果找不到匹配的 discussion,giscus bot 就会在第一次有人留下评论或回应时自动创建一个 discussion。

要评论,访客必须按 GitHub OAuth 流程授权 giscus app 代表他发帖。或者访客也可以直接在 GitHub Discussion 里评论,作者可以在 GitHub 上管理评论。

安装Giscus

我使用的主题 hugo-clarity 默认不支持 giscus 的. 后面我会给出不支持giscus 的主题如果引入, 前面的操作都是一样的.

选择一个仓库

一般都是用你的hugo site 本身, 我就用 https://github.com/zmhu/macgeeker

安装

打开这个 https://github.com/apps/giscus 选择安装

Install

选择一个仓库

选择仓库

开启 Disucssions. 在仓库的 settings 里面, 把 disucssions 勾上

开启 Disucssions

最后生成配置 打开 discus 官网

配置

配置

引入hugo

config/config.toml 有的模板可以写在 config/params.toml, 把上面的配置信息里的几个关键的值复白制到模板里. 我这里是自建的模板, 如果你是主题自带模板, 那请参考主题配置文件里的变量命名.

 1[giscus]
 2enable = true
 3theme = 'dark_dimmed'
 4# theme = 'http://localhost:1313/css/giscus.css'
 5# You can refer to the official documentation of giscus to use the following configuration.
 6# 你可以参考官方文档来使用下列配置
 7category = "Announcements"
 8categoryId = "xxx"
 9mapping = "pathname"
10reactionsEnabled = "0"
11repo = "xxx"
12repoId = "xxxx"

layouts/parials/comments.html

 1<div class="post_comments">
 2    {{ if .Site.DisqusShortname }}
 3    {{ template "_internal/disqus.html" . }}
 4    {{ end }}
 5    {{ if .Site.Params.utterances }}
 6    {{ template "partials/utterances.html" . }}
 7    {{ end }}
 8    ## 增加了下面三行
 9    {{ if .Site.Params.giscus.enable }}
10    {{ template "partials/giscus.html" . }}
11    {{ end }}
12    <!-- add custom comments markup here -->
13</div>

layouts/parials/giscus.html

1<script src="https://giscus.app/client.js" data-repo="{{site.Params.giscus.repo}}"
2    data-repo-id="{{site.Params.giscus.repoId}}" data-category="{{site.Params.giscus.category}}"
3    data-category-id="{{site.Params.giscus.categoryId}}"
4    data-mapping="{{site.Params.giscus.mapping}}"
5    data-reactions-enabled="{{site.Params.giscus.reactionsEnabled}}"
6    data-theme="{{site.Params.giscus.theme}}" crossorigin="anonymous" async>
7</script>
8<noscript>Please enable JavaScript to view the comments powered by giscus.</noscript>

打开博客的文章页面, 最下面就会有 github 风格的评论了

如果某个文章不想开评论功能, 请在文章 markdown 文件的头部添加

1comments: false