Hugo DoIt 主题随机文章功能实现

看到别人博客里有“随机文章”按钮,我也想有一个!查到前人已经写过 Hugo 博客的随机文章实现方法,本以为跟着做就可以了,结果还是踩了几个坑。一开始以为是 Hugo DoIt 主题的问题,后来发现主要是自己前端知识太少。本文总结了我在 Hugo 的 DoIt 主题上实现随机文章功能的过程,包括最终方案和踩过的坑。

目标:点击骰子或“随便看看”按钮,随机跳转到某篇博客文章。

本文适用人群:跟着教程做但是没跟明白的前端新手。

此处按照椒椒教程,对应 DoIt 的文件夹命名方式做了一点点修改。

在项目目录新建文件 layouts/_partials/random.html,内容如下:

<script>
function goToRandomPost() {
  const pages = [
    {{- $posts := where .Site.RegularPages "Type" "posts" -}}
    {{- range $i, $p := $posts -}}
      "{{ $p.RelPermalink }}?utm_source=random"{{ if ne (add $i 1) (len $posts) }},{{ end }}
    {{- end -}}
  ];

  if (pages.length === 0) {
    alert("没有找到文章!");
    return;
  }

  const rand = Math.floor(Math.random() * pages.length);
  window.location.href = pages[rand];
}
</script>

此处按照椒椒教程,做了一点点修改。注意: shortcodes 不会自动加载 partial,所以需要手动引入上一步创建的 random.html.

在项目目录新建文件 layouts/shortcodes/random.html,内容如下:

{{ partial "random.html" . }}
{{- if eq (index .Params 1) "button"}}
  <a onclick='goToRandomPost()' class="book-btn">{{ index .Params 0}}</a>
{{- else -}}
  <a onclick='goToRandomPost()' style="cursor: pointer;">{{ index .Params 0}}</a>
{{- end -}}

themes/DoIt/layouts/_partials/header.html 复制到项目目录 layouts/_partials/header.html

layouts/_partials/header.html 顶部引入 {{ partial "random.html" . }}

{{ partial "random.html" . }}

然后:

layouts/_partials/header.html<div class="menu-inner"> 内,添加:

<a class="menu-item random" onclick="goToRandomPost()" title="随机文章" style="cursor:pointer;">
  🎲 随便看看
</a>

layouts/_partials/header.html<div class="menu" id="menu-mobile"> 内,添加:

<a class="menu-item random" onclick="goToRandomPost()" title="随机文章" style="cursor:pointer;">
  🎲 随便看看
</a>

因为有了第二步设置的 shortcodes,现在可以在 Markdown 页面调用“随便看看”功能。使用方式是在你想要的地方插入:

{{< random "随便看看" >}}

或者

{{< random "随便看看" "button" >}}

就会显示成这样: 随便看看

完工。

  1. 尝试用 content/random/_index.md + layout = random 创建随机文章入口,但无效。

    • 结论:不需要额外创建 /random/ 页面。
  2. 想用 DoIt 自动生成的 index.json 来生成文章列表,但不行。

    • 原因:DoIt 生成的 index.json 是为了适配 Algolia 或 Fuse 搜索索引格式,每篇文章只包含 content, date, objectID 等字段,并没有 permalinkrelPermalink,无法跳转。
    • 结论:放弃 index.json,直接用 Hugo 模板生成列表。
  3. 找了半天才找到按钮应该加在哪里。

    • 指路:见上文的在菜单栏添加按钮、在博客文章里使用“随便看看”链接。

以上。

感谢椒椒写的教程,让更多的读者与博客文章不期而遇。