自动向边栏添加新帖子

时间:2018-11-12 12:20:50

标签: vue.js vuejs2 netlify vuepress netlify-cms

我正在使用VuePressNetlifyCMS作为内容管理。

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

  • 新设计页面被添加到 design 文件夹中。
  • 新的前端页面被添加到前端文件夹中。
  • [...]

这很好,但我遇到了问题。
由于我的新页面未在侧边栏配置中定义,因此无法从侧边栏界面使用。如何在保持以下相同的边栏格式的同时做到这一点?

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"}

1 个答案:

答案 0 :(得分:2)

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

将脚本添加到您的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/')
  }]
},
[...]

注意: 这里的警告是在读取目录期间文件名的排序顺序。