在 Jekyll 中生成菜单

Generate a menu in Jekyll

我正在使用 Jekyll(没有博客)构建一个静态站点,只有页面。
我想找到一种方法来生成(自动或使用 menu.yml 文件)菜单(如页脚上的 this website)。
我在页面的 YAML 中定义标题和章节属性:

---
layout: page
title: Title of the page
chapter: Title of the chapter
permalink: /title-of-the-chapter/title-of-the-chapter/
order: 3250
published: true
---

我想要这样的菜单:

<ul>
    <li>Title of the chapter</li>
        <ul>
            <li><a href="permalink">Title of the page</a></li>
        </ul>
</ul>

顺便说一句,我的文件是这样组织在文件夹中的:

01-chapter-one
    01-subchapter-one
        index.md
    02-subchapter-two
        index.md
02-chapter-one
    01-subchapter-one
        index.md

是否有自动执行此操作的解决方案(可能没有插件)(我有很多页面)?

只有使用插件才能实现完全自动化,即 vanilla Jekyll 无法自动循环您的文件夹并生成文件的分层列表。

因此,如果您想要一个没有插件的解决方案,您需要维护 data file 菜单层次结构:每次添加页面时,您还需要修改数据文件。

根据您想要的复杂程度,有不同的方法可以从数据文件中生成菜单:

  • 简单:Accessing _data in Jekyll (loop in loop)
  • 复杂(具有 "dynamic" 菜单):Excluding page from Jekyll navigation bar

这应该足以让您入门。如果您 运行 遇到问题,请提出更具体的问题。

分组数据是这里的诀窍,为此您需要辅助处理器。这个post处理最方便的地方是javascript,但这意味着你需要给自己留一些数据。

以下代码将您的所有页面的数组作为数组嵌入。然后可以 post 在页面 javascript.

中处理
<script>
let menu = [
  {% for p in site.pages %}
  {
    'chapter':'{{ p.chapter }}',
    'title':'{{ p.title }}',
    'url':'{{ p.url }}',
  }
  {% endfor %}
].filter(function(d){
    return d.title != '';
})
.reduce(function(a,d){
    a[d.chapter] = a[d.chapter] || [];
    a[d.chapter].push(d);
},{});
menu = Object
    .keys(menu)
    .map(function(key){
        let html = menu[key].map(function(d){
              return "<li>"+d.title+"</li>";
            })
            .join('');
        html = '<li>' + key + '<ol>'+html+'</ol></li>';
        return html.join('');
    })
    ;
menu.push('</ol>');
menu.unshift('<ol>');
document.write(menu.join(''));
</script>

我很确定排序没有正确执行,但这似乎大致正确。

此解决方案的一个好处是您实际上可以将 "chapters" 作为文件夹嵌入。您可以根据常见的文件夹结构生成嵌套,并使用 'index' 页作为 'chapter' 标题的标记。