Ghost 博客系列IIII | 文章目录导航-TOC插件

TOC对于博客来说,是一个非常实用的功能,可以方便读者快速定位到感兴趣的内容。Ghost 博客没有自带的TOC功能,让我们使用tocbot来实现它。
我们先预览下效果:

这次我们会用到一个开源的toc插件,地址:https://tscanlin.github.io/tocbot/
这个插件可以定制化,我们只需要在css中注入一些样式,在js中注入一些配置即可。
css 注入
部分css代码我已经优化了一次,你也可以根据需要进行调整。

css建议放在 site header中
<!-- TOC start -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.12.3/tocbot.css">
<style>
.gh-content {
position: relative;
}
.gh-toc .toc-link{
text-decoration: none;
font-size: 1.4rem;
}
.gh-toc > .toc-list {
position: relative;
}
.toc-list {
overflow: hidden;
list-style: none;
}
.toc-list ul {
list-style-type: none;
}
.gh-content dl, .gh-content ol, .gh-content ul{
padding: 0 0.6rem 0 1.6rem;
}
.gh-content :is(li+li,li :is(ul,ol)){
margin-top: 0.4rem;
}
@media (min-width: 1300px) {
.gh-sidebar {
position: absolute;
top: 0;
bottom: 0;
margin-top: 4vmin;
grid-column: wide-start / main-start;
}
.gh-content > :is(.gh-sidebar) + * {
margin-top: 0;
}
.gh-toc {
position: sticky; /* On larger screens, TOC will stay in the same spot on the page */
top: 4vmin;
}
}
.gh-toc .is-active-link::before {
background-color: var(--ghost-accent-color); /* Defines TOC accent color based on Accent color set in Ghost Admin */
}
</style>
<!-- TOC end -->
js注入
js建议放在 site footer中
<!-- Tocbot Script -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.12.3/tocbot.min.js"></script>
<script>
tocbot.init({
// Where to render the table of contents.
tocSelector: '.gh-toc',
// Where to grab the headings to build the table of contents.
contentSelector: '.gh-content',
// Which headings to grab inside of the contentSelector element.
headingSelector: 'h1, h2, h3, h4',
// Ensure correct positioning
hasInnerContainers: true,
isCollapsedClass: '',
// 添加这一行来使用无序列表
orderedList: false
});
</script>
<!-- Tocbot Script end -->
html注入
到这里,你已经完成了TOC的依赖文件加载,现在我们需要将其注入到文章中。
注入到文章有两种方法,一种是每篇文章都需要注入,一种是全局注入。
每篇文章注入
这种方法不需要修改到模板文件,只需要在文章中嵌入一个html代码块

<aside class="gh-sidebar"><div class="gh-toc"></div></aside>
但是这种方式无法对所有文章生效,那么就需要全局注入。
全局注入
这种方法需要修改到模板文件,在文章的头部添加一个html代码块
在你的模板文件中,找到 post.hbs
文件,在 post.hbs
文件的头部添加以下代码:
<section class="gh-content gh-canvas">
<aside class="gh-sidebar"><div class="gh-toc"></div></aside> {{! 这里是TOC插入的地方 }}
{{content}}
</section>
重启Ghost博客,你会发现TOC已经生效了。
总结
通过以上步骤,我们已经成功为 Ghost 博客添加了文章目录导航(TOC)功能。主要实现了以下几点:
- 使用 tocbot 插件实现 TOC 功能,这是一个轻量级且易于配置的解决方案
- 通过 CSS 注入实现了美观的目录样式,包括响应式布局
- 通过 JS 配置实现了目录的自动生成和交互功能
- 提供了两种注入方式:
- 单篇文章注入:适合临时使用
- 全局注入:适合长期使用,需要修改模板文件
这个 TOC 功能不仅提升了博客的阅读体验,还能帮助读者快速定位到感兴趣的内容。如果你想要进一步优化,可以:
- 调整 CSS 样式以匹配你的博客主题
- 修改 tocbot 的配置参数来满足特定需求
- 添加目录折叠功能
- 优化移动端的显示效果