自动将新帖子添加到侧边栏

Automatically add new posts to the Sidebar

我正在使用 VuePress and NetlifyCMS 作为内容管理。

我有 3 个集合(设计前端后端)其中包含无限数量的页面。这些页面是通过 NetlifyCMS 仪表板 创建的,并添加到定义的文件夹中。

这工作正常,但我遇到了问题。
由于我的新页面未在侧边栏配置中定义,因此无法从侧边栏界面访问它们。我怎样才能做到这一点,同时保持与下面相同的侧边栏格式?

config.js

[...],
sidebar: {
  '/design/': [{
    title: 'Design',
    children: [
      '',
      'foo 1',
      'foo 2'
    ]
  }],
  '/front-end/': [{
    title: 'Front-end',
    children: [
      '',
      'bar 1',
      'bar 2'
    ]
  }],
  '/back-end/': [{
    title: 'Back-end',
    children: [
      '',
      'baz 1',
      'baz 2'
    ]
  }]
},
[...]

config.yml

[...],
collections:
  - name: "design"
    label: "Design"
    folder: "docs/design"
    create: true
    slug: "{{slug}}"
    fields:
      - {label: "Title", name: "title", widget: "string"}
      - {label: "Body", name: "body", widget: "markdown"}
  - name: "front-end"
    label: "Front-end"
    folder: "docs/front-end"
    create: true
    slug: "{{slug}}"
    fields:
      - {label: "Title", name: "title", widget: "string"}
      - {label: "Body", name: "body", widget: "markdown"}
  - name: "back-end"
    label: "Back-end"
    folder: "docs/back-end"
    create: true
    slug: "{{slug}}"
    fields:
      - {label: "Title", name: "title", widget: "string"}
      - {label: "Body", name: "body", widget: "markdown"}

一种方法是在构建时将文件名导入配置。

将脚本添加到您的 docs/.vuepress 文件夹:

docs/.vuepress/childscript.js

var fs = require('fs');

module.exports = function(path) {
  var files = fs.readdirSync(path);
  var list = [""];
  for (var i in files) {
    var filename = files[i].split('.').slice(0, -1).join('.');
    if (filename.toLowerCase() !=="readme") list.push(filename);
  }
  console.log(`${path}: `, list);
  return list;
}

然后改变你的docs/.vuepress/config.js

var getChildren = require('./childscript');

[...],
sidebar: {
  '/design/': [{
    title: 'Design',
    children: getChildren('./docs/design/')
  }],
  '/front-end/': [{
    title: 'Front-end',
    children: getChildren('./docs/front-end/')
  }],
  '/back-end/': [{
    title: 'Back-end',
    children: getChildren('./docs/back-end/')
  }]
},
[...]

注意: 这里需要注意的是在读取目录时文件名的排序顺序。