为hugo添加gittalk组件

目录

前言

最近在学习研究hugo静态站点生成,hugo自带的Disqus加载速度较慢,不适合在国内使用。

目前基于github的评论插件有gitalk以及gitment,2个插件都能很好的实现评论的功能。

最终选择了gitalk,该插件样式较为简约,支持markdown语法,自带加载load。

申请GitHub Oauth App

需要 GitHub Application,如果没有 点击这里申请Authorization callback URL 填写当前使用插件页面的域名。

以本站为例,须填写以下内容:

字段内容备注
Application namegittalk for xbc.me填写应用名称
Homepage URLhttps://xbc.me主页地址
Application description神秘极客gtalk留言插件备注
Authorization callback URLhttps://xbc.me回调地址

创建模板

在主题目录下,新建模板,如themes/mainload/layouts/partials/gitalk.html

{{ if .Site.Params.enableGitalk }}
<div id="gitalk-container"></div>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
  const gitalk = new Gitalk({
    clientID: '{{ .Site.Params.Gitalk.clientID }}',
    clientSecret: '{{ .Site.Params.Gitalk.clientSecret }}',
    repo: '{{ .Site.Params.Gitalk.repo }}',
    owner: '{{ .Site.Params.Gitalk.owner }}',
    admin: ['{{ .Site.Params.Gitalk.owner }}'],
    id: location.pathname, // Ensure uniqueness and length less than 50
    distractionFreeMode: false // Facebook-like distraction free mode
  });
  (function() {
    if (["localhost", "127.0.0.1"].indexOf(window.location.hostname) != -1) {
      document.getElementById('gitalk-container').innerHTML = 'Gitalk comments not available by default when the website is previewed locally.';
      return;
    }
    gitalk.render('gitalk-container');
  })();
</script>
{{ end }}

修改主题模板模板layouts/_default/single.html,在{{ partial “comment.html” . }}的下一行,添加以下内容:

{{ partial "gitalk.html" . }}

添加配置

需要修改config.toml配置,注意repo添加自己的版本库地址,一般是username.github.io。

[Params]
  enableGitalk = true

[Params.Gitalk]
    clientID = "xxx" # Your client ID
    clientSecret = "xxx" # Your client secret
    repo = "xbc.me" # The repo to store comments
    owner = "geekwho11" # Your GitHub ID
    admin= "geekwho11" # Required. Github repository owner and collaborators. (Users who having write access to this repository)
    id= "location.pathname" # The unique id of the page.
    labels= "gitalk" # Github issue labels. If you used to use Gitment, you can change it
    perPage= 15 # Pagination size, with maximum 100.
    pagerDirection= "last" # Comment sorting direction, available values are 'last' and 'first'.
    createIssueManually= false # If it is 'false', it is auto to make a Github issue when the administrators login.
    distractionFreeMode= false # Enable hot key (cmd|ctrl + enter) submit comment.

大功告成

完成后例子,可以参考这里gitalk 示例

参考链接

  1. 为 Hugo 添加谈笑风生区
  2. gtalk vs gitment
  3. 十分鐘超詳細替 Hexo Next 開啟 Gitalk 留言版