【问题标题】:How to loop through all files in Jekyll's _data folder?如何遍历 Jekyll 的 _data 文件夹中的所有文件?
【发布时间】:2016-09-19 18:16:01
【问题描述】:

如何在 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 中的所有文件。我可以这样做吗?

【问题讨论】:

    标签: jekyll liquid


    【解决方案1】:

    嵌套循环允许您遍历 _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 %}
    

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

    【讨论】:

    • 很好的答案;假设 OP 想要遍历一个 yaml 文件的平面列表,这个解决方案工作得很好。
    【解决方案2】:

    我已经阅读了你的问题标题,我会回答你最后一个问题:

    您不能循环浏览保存在 _data 文件夹中的文件。根据Jekyll Variable doc 和 Jekyll 目录结构,_data 中支持扩展名.yml .yaml .csv .json 的所有文件默认将加载到 site.data 中,如@wasthishelpfull 的回答,您可以通过{{site.data.*filename.data*}} 访问它并像this answer 一样循环

    如果你想遍历文件,创建一个文件夹(no underscore) 将其作为静态文件,并使用 jquery.get() 获取文件中的数据。

    或通过添加data_source: data_config.yml 中的_data 更改为data 并在url 端点/data see this post for more 处访问

    【讨论】:

      【解决方案3】:

      根据documentation,jekyll 会将 YAML 资源(.yml、.yaml、.json 和 .csv 文件)直接加载到site.data。如果您的文件使用其中一种格式,您可以:

      {% for data in site.data %}
          ...
      {% endfor %}
      

      【讨论】:

      • 谢谢,虽然这确实会加载数据文件,但它对我想要完成的工作并不完全有效。也许我的用例更复杂,因为我试图进入每个文件中的特定 yaml 级别。
      • 我不确定你想要完成什么,所以我没有详细说明我的答案。随意精确您的用例:)
      【解决方案4】:

      我假设你需要access jekyll site.data looping multi levels object

      {% assign my_data = site.data %}
      {% assign my_level = "sidebarlist.sidebars.sidebar" | split: "." %}
      
      {% for level in my_level %}
          {% assign my_data = my_data[level[i]] %}
          {% for data in my_data %}
              {{ data }} : {{ my_data[data] }}
          {% endfor %}
      {% endfor %}
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-26
        • 1970-01-01
        • 2019-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-24
        • 2020-08-09
        相关资源
        最近更新 更多