Jekyll在集合的子目录上发布嵌套循环问题

时间:2017-03-10 00:48:26

标签: for-loop jekyll liquid templating

提前感谢您提供任何帮助!

我正在尝试为集合d-foundation创建嵌套导航。我希望将嵌套导航的结构基于目录结构,而不是手动创建Yaml文件,因为我希望它尽可能地动态。我的目录结构的缩写版本如下所示:

|-Root/
|-d-foundation/
|--|-color.md
|--|-headings.md
|--|-formats.md
|--|--formats/
|--|--|-date.md
|--|--|-time.md

我将前面的内容放在.md文件中,以指定文件是父文件还是子文件,或者如果文件没有与任何内容相关联,则不包括其中任何一个属性。

此示例中的父级formats.md位于d-foundation

的根目录中
---
parent: true
parent-name: foo
---

子/孩子在formats目录中,其属性为:

---
child-of: foo
---

然后,我尝试首先遍历顶级文件,检测文件是否是父文件,然后遍历后续子文件:

<ul class="design-subnav">
   {% for foundation in site.d-foundation %}
   {% if foundation.child-of == nil and foundation.parent == nil %} 
   <li><a href="{{ foundation.url }}">{{ foundation.title }}</a></li>
   {% endif %}

   {% if foundation.parent != nil %}
   <li><span>{{ foundation.title }}</span>
         <ul>
            {% for child in site.d-foundation %}
            {% if child.child-of != nil %}
             <li><a href="{{ child.url }}">{{ child.title }}</a></li>
            {% endif %}
            {% endfor %} 
         </ul>
    </li>
    {% endif %} 
    {% endfor %}
</ul>

我知道[其中一个]我的问题在于我并没有将循环范围限制在每​​个父级(你可以这样做吗?)。结果是,如果我有几个子目录,第二个for循环将只打印出具有child-of属性的任何文件。看到这里,缩进最远的项目是孩子,你可以看到重复:

A screen shot showing the loop iterating over any children in the collection, not just limited to a parent

顶部不重复子节点的唯一原因是我只有一个父/子目录。

我已经把自己纠缠在这里,我想知道我能做些什么只能绕过每个父母各自的孩子。或者我是以完全倒退的方式解决这个问题?

1 个答案:

答案 0 :(得分:1)

使用if更改内部{% if child.child-of == foundation.parent %}以使用子类别过滤每个类别。

所以它看起来像:

<ul class="design-subnav">
   {% for foundation in site.d-foundation %}
   {% if foundation.child-of == nil and foundation.parent == nil %} 
   <li><a href="{{ foundation.url }}">{{ foundation.title }}</a></li>
   {% endif %}

   {% if foundation.parent != nil %}
   <li><span>{{ foundation.title }}</span>
         <ul>
            {% for child in site.d-foundation %}
            {% if child.child-of == foundation.parent %}
             <li><a href="{{ child.url }}">{{ child.title }}</a></li>
            {% endif %}
            {% endfor %} 
         </ul>
    </li>
    {% endif %} 
    {% endfor %}
</ul>

旁注:除了 nil false 之外,Liquid中的所有值都是真实的。因此,您可以使用if foundation.child-of代替if foundation.child-of != nil