在 Hugo 博客中实现:ADHD 友好的菜谱打勾功能
最近在整理 Obsidian 笔记,用 Syncthing 同步文档时,突然想到:为什么不直接把笔记发布到博客上呢? 这样随时随地都能查看。 尤其是我的菜谱笔记——与其埋在本地,不如直接放到博客里。这样一来,做饭时可以边看边打勾,不容易漏步骤(ADHD 友好 🤷♀️);另一方面,如果有人也想试试我喜欢的菜谱,也能更轻松地跟着步骤操作。
于是,我就折腾了一下,在 Hugo 博客里加了一个可交互的菜谱 Checklist 功能。
目标
- 菜谱的食材和步骤都有复选框
- 点击复选框后,对应的文字会被划掉
实现思路
- 定义一个 Shortcode
通过 {{< checklist >}} ... {{< /checklist >}}
包裹内容,生成交互式清单。
-
在 Markdown 文档里写菜谱
{{< checklist >}} [ ] 200g 面粉 [x] 100g 黄油 [ ] 2 个鸡蛋 {{< /checklist >}}
Shortcode 代码
在博客根目录下 layouts/shortcodes/
新建文件 checklist.html
:
<!-- checklist.html -->
<ul class="checklist">
{{- $lines := split .Inner "\n" -}}
{{- range $lines }}
{{- $line := trim . " \t\r\n" -}}
{{- if $line }}
{{- if findRE "^\\[x\\]" $line -}}
<li>
<label>
<input type="checkbox" checked onchange="this.nextElementSibling.classList.toggle('checked', this.checked)">
<span class="check-item checked">{{ replaceRE "^\\[x\\]\\s*" "" $line }}</span>
</label>
</li>
{{- else if findRE "^\\[ \\]" $line -}}
<li>
<label>
<input type="checkbox" onchange="this.nextElementSibling.classList.toggle('checked', this.checked)">
<span class="check-item">{{ replaceRE "^\\[ \\]\\s*" "" $line }}</span>
</label>
</li>
{{- end -}}
{{- end -}}
{{- end }}
</ul>
<style>
.checklist {
list-style: none;
padding: 0;
}
.checklist li {
margin: 0.3em 0;
}
.checklist input[type="checkbox"] {
margin-right: 0.5em;
}
.checklist .checked {
text-decoration: line-through;
color: #888;
}
</style>
使用效果
以上,装修完毕。