如何遍历 Jekyll 中 _data 文件夹中的每个文件?
目前我在一个名为 sidebarlist.yml 的文件中有一个文件列表,如下所示:
- file1
- file2
- file3
为了遍历所有这些文件,我使用以下代码:
{% for sidebar in site.data.sidebarlist %}
{% for entry in site.data.sidebars[sidebar].entries %}
...
{% endfor %}
{% endfor %}
我想避免使用 sidebarlist.yml 而只是自动遍历 _data 中的所有文件。我可以这样做吗?
最佳答案
嵌套循环允许您遍历 _data 文件的内容。
当我这样做时,我使用了 subdirectory ,因为我不想遍历每个数据文件,而且我认为这适用于许多用例。它还使我的 _data 目录更整洁一些。
我的 _data 目录如下所示:
_data/
navigation.yml
news.yml
people/
advisors.yml
board.yml
staff.yml
people/中的每个文件都使用如下结构:
- name: Anne Smith
role: Role A
url: mysite.com
- name: Joe Shmoe
role: Role B
url: mysite.org
在我遍历每个数据文件的页面上:
{% for people_hash in site.data.people %}
{% assign people = people_hash[1] %}
{% for person in people %}
<li>{{ person.name }}, {{ person.role }}</li>
{% endfor %}
{% endfor %}
这导致:
<li>Anne Smith, Role A</li>
<li>Joe Shmoe, Role B</li>
它与您已经完成的非常相似,但不需要额外的 yaml 文件。
注意使用
people_hash[1]
- 这是针对数组中的适当值。如果你这样做:
{% for people_hash in site.data.people %}
{% assign people = people_hash[1] %}
<pre>{{ people }}</pre>
{% endfor %}
您将获得返回的值数组,这将有助于您调试模板。
关于jekyll - 如何遍历 Jekyll 的 _data 文件夹中的所有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39579632/