我可以在Jekyll中创建嵌套集合吗?

时间:2016-05-17 13:35:04

标签: jekyll

我想使用Jekyll创建一个包含几个章节的手册,每个章节包含几个部分,并将每个部分存储在单独的Markdown文件中。我希望index.md看起来像这样:

<ol>
{% for chapter in site.chapters %}
  <li>
    <a href="{{chapter.url}}">{{chapter.title}}</a>
    <ol>
    {% for section in chapter.sections %}
      <li><a href="{{section.url}}">{{section.title}}</a></li>
    {% endfor %}
    </ol>
  </li>
{% endfor %}
<ol>

如果每个章节都是_chapters中的Markdown文件,并且我向_config.yml添加了正确的行,我可以遍历章节,从YAML标题中拉出标题字段,等等。有办法筑巢吗?我尝试在_chapters下创建具有各种名称的子目录,但是(a)Jekyll不会将它们作为子集合进行选择,并且(b)没有明显的地方存储章级信息(如章的总标题。)

(注意:我想我可以通过在_config.yml中明确枚举YAML块中的章节来执行此操作,或者在_data中创建单独的YAML文件,但我不想要不得不担心让枚举与实际的章节保持同步:我希望Jekyll能够自动获取更改。)

2 个答案:

答案 0 :(得分:16)

因此,我知道如何做到这一点的最好方法是颠倒你的想法。

您不是在撰写章节,而是在编写部分并将组织到章节中。

假设你有这样的设置:

  • _sections
    • section01.md
    • section02.md
    • section03.md
    • section04.md

但你希望它输出如下:

  • _site
    • 章节
      • chapter1.html(包含section01.md后跟section03.md
      • chapter2.html(包含section02.md后跟section04.md

如果是这种情况,您可以使用集合来实现。将chaptersection01.md的前缀中的section03.md属性设置为01,将chapter属性设置为section02.md和{{1}的前端转到section04.md

问题是生成章节的页面。你需要为每一章创建一个页面,但是如果你使用布局也不错。

这是我使用的布局(在02中):

_layouts/chapter.html

然后在--- layout: default --- <h1>Chapter {{ page.chapter }}</h1> {% for section in site.sections %} {% if section.chapter == page.chapter %} {{ section.output }} {% endif %} {% endfor %} 中,我有_chapters,看起来像这样:

chapter01.md

只需将其复制到--- chapter: 01 layout: chapter --- 并将chapter02.md属性设置为chapter,现在就有了第2章。

使这项工作所需的唯一其他事情是更新您的配置:

02

当您运行collections: sections: output: false chapters: output: true 时,您现在拥有jekyll build_site/chapters/chapter01.html。随着新部分的创建,它们将被添加到其前端的任何章节中。

这一切都让人感到困惑,所以我在http://paddycarver.github.io/jekyll-nested-collections-example/设置了一个示例,源代码为https://github.com/paddycarver/jekyll-nested-collections-example

答案 1 :(得分:0)

_collection要注意的一件事与_post相同:

  

嵌套文件的处理方式与根文件夹中的文件相同。

您可以使用weight安排降价文件,如下所示:

_chapter
   chapter1.md <- put weight: 10
   chapter2.md <- put weight: 20
   _chapter/section1
      section11.md <- put weight: 11
      section12.md <- put weight: 12
   _chapter/section2
      section21.md <- put weight: 21
      section22.md <- put weight: 22

然后按照path这样的

对索引文件进行排序
<ol>
{% assign items = site.chapter | sort: 'weight' %}
{% for item in items %}
  {% if not item.path contains '/section' %}
  <li>
    <a href="{{item.url}}">{{item.title}}</a>
    <ol>
  {% else %}
      <li><a href="{{item.url}}">{{item.title}}</a></li>
  {% endif %}
    </ol>
  </li>
{% endfor %}
<ol>

输出

<ol>
  <li>
    <a href="chapter1.html">chapter1</a>
    <ol>
      <li><a href="section11.html">section11</a></li>
      <li><a href="section12.html">section12</a></li>
    </ol>
  </li>
  <li>
    <a href="chapter2.html">chapter2</a>
    <ol>
      <li><a href="section21.html">section21</a></li>
      <li><a href="section22.html">section22</a></li>
    </ol>
  </li>
<ol>