如何遍历Jekyll的_data文件夹中的所有文件? [英] How to loop through all files in Jekyll's _data folder?

查看:75
本文介绍了如何遍历Jekyll的_data文件夹中的所有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何遍历Jekyll的_data文件夹中的每个文件?

How can I loop through every file in my _data folder in Jekyll?

目前,我在名为sidebarlist.yml的文件中有一个文件列表,如下所示:

Currently I have a list of files in a file called sidebarlist.yml like this:

- file1
- file2
- file3

为了遍历所有这些文件,我使用以下代码:

In order to loop through all of these files, I use this code:

{% for sidebar in site.data.sidebarlist %}
{% for entry in site.data.sidebars[sidebar].entries %}
...
{% endfor %}
{% endfor %}

我想避免使用sidebarlist.yml,而只是自动遍历_data中的所有文件.我可以这样做吗?

I would like to avoid using sidebarlist.yml and just iterate through all files within _data automatically. Can I do this?

推荐答案

嵌套循环使您可以循环浏览_data文件的内容.

Nesting loops allows you to loop through the contents of _data files.

当我这样做时,我使用了子目录,因为我不想这样做循环遍历每个数据文件,我认为这适用于许多用例.它还使我的_data目录保持整洁.

When I did this I used a subdirectory, since I didn't want to loop through every data file, and I think that applies to many use cases. It also keeps my _data directory a little tidier.

我的_data目录如下:

My _data directory looks like this:

_data/
  navigation.yml
  news.yml
  people/
    advisors.yml
    board.yml
    staff.yml

people/中的每个文件都使用如下结构:

Each of the files within people/ uses a structure like this:

- name: Anne Smith
  role: Role A
  url: mysite.com
- name: Joe Shmoe
  role: Role B
  url: mysite.org

在我遍历每个数据文件的页面上:

And on the page where I'm looping through each of these data files:

{% 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文件.

It's very similar to what you've already done, but eliminates the need for that extra yaml file.

请注意使用people_hash[1]-这是针对数组中适当值的目的.

Note the use of people_hash[1] - this is what is targeting the appropriate values within the array.

如果相反,您这样做:

{% for people_hash in site.data.people %}
{% assign people = people_hash[1] %}

    <pre>{{ people }}</pre>

{% endfor %}

您将获得返回的值数组,这将有助于您调试模板.

You'll get the array of values that is returned, which should help you debug your template.

这篇关于如何遍历Jekyll的_data文件夹中的所有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆