Automatically add new posts to the Sidebar

倾然丶 夕夏残阳落幕 提交于 2019-12-12 19:06:56

问题


I'm using VuePress and NetlifyCMS as Content Management.

I have 3 collections (design, front-end and back-end) which contains an indefinite number of pages. Those pages are created through the NetlifyCMS dashboard and are added to the defined folder.

  • New design pages are added to the design folder.
  • New front-end pages are added to the front-end folder.
  • [...]

This works fine but I'm facing an issue.
Since my new pages are not defined in the sidebar config, they are not available from the sidebar interface. How could I do that while keeping the same sidebar format as below?

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:


One way would be to import your filenames into the config at build.

Add a script to your docs/.vuepress folder:

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

Then change your 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/')
  }]
},
[...]

NOTE: The caveat here is the sort order of the filenames during the reading of the directory.



来源:https://stackoverflow.com/questions/53262091/automatically-add-new-posts-to-the-sidebar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!