自动添加侧边栏

2022/10/14 blog

# 自动添加侧边栏

最近将博客主题由vdoing (opens new window)换成了reco,但是reco本身不能够自动生成左边的侧边栏,根据作者的说明,还是可以自己生成侧边栏的。本着懒的原则,我写了一个Python脚本在每次编译的时候自动生成相应的侧边栏。同时还有一个脚本为每一篇文章自动生成永久链接。详情见:自动生成文章永久链接

废话少说,上代码:

import glob
import os


seiderbarPath = 'docs\.vuepress\config\sidebar.js'
docsPath = r'docs'
docsList = glob.glob(f'{docsPath}/**/*.md', recursive=True)

temp = {}
for doc in docsList:
    path, filename = os.path.split(doc)
    name, _ = os.path.splitext(filename)

    if filename in ['README.md']:
        continue

    if path.split(os.sep)[-1] in temp:
        temp[path.split(os.sep)[-1]].append(filename)
    else:
        temp[path.split(os.sep)[-1]] = [filename]

with open(seiderbarPath, 'w', encoding="utf-8", errors='ignore') as f:
    f.write('module.exports = {\n')

    for p in temp:
        title = p.split(os.sep)[-1]
        f.write(f"\t'/{title}/': [\n")
        for c in temp[p]:
            f.write(f"\t\t'{c}',\n")
        f.write('\t],\n')
    f.write('}')

参考文章:
侧边栏 | vuepress-theme-reco (opens new window)
侧边栏分组 | VuePress (opens new window)
自动生成多个侧边栏 (opens new window)