【问题标题】:Jekyll issues with nested looping over a collection's subdirectoriesJekyll 在集合子目录上的嵌套循环问题
【发布时间】:2017-03-10 00:48:25
【问题描述】:

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

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

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

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

本例中的父级是d-foundation 的根中的formats.md

---
parent: true
parent-name: foo
---

Child/ 子级位于 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

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

我在这里纠缠不清,我想知道我能做些什么来只遍历每个父母各自的孩子。还是我会以完全倒退的方式来解决这个问题?

【问题讨论】:

  • 我认为如果你用{% if child.child-of == foundation.parent %}更改内部if语句会解决它
  • @marcanuy 就是这样!非常感谢。
  • 不客气,将其添加为答案。

标签: for-loop jekyll liquid templating


【解决方案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>

旁注:Liquid 中的所有值都是真值,除了 nilfalse。所以你可以用if foundation.child-of代替if foundation.child-of != nil

【讨论】:

  • 啊,注意到了。感谢您的澄清。
猜你喜欢
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-17
  • 2013-11-03
  • 2016-06-23
  • 1970-01-01
  • 2017-09-20
相关资源
最近更新 更多