循环遍历目录及其子目录文件

时间:2015-08-01 08:45:02

标签: loops liquid

我是液体模板语言的新手,关于由jekyll提供支持的网站,我们发布帖子,有时发布一系列帖子,因此我们为_posts目录中的系列帖子创建子目录。我可以遍历目录_posts及其子目录中的所有文件,因为我不知道他们的名字或号码吗?
我的文件树:
root | _posts/ | post1.md post2.md series_name/ | post3.md

2 个答案:

答案 0 :(得分:1)

您问题的简短回答是

解决方案

Jekyll documentation引导您显示所有_posts的索引。具体来说,您需要以下内容:

<ul>
  {% for post in site.posts %}
    <li>
      <a href="{{ post.url }}">{{ post.title }}</a>
    </li>
  {% endfor %}
</ul>

我已经用子目录对此进行了测试。

说明

Jekyll在生成_posts时似乎忽略了_site内的任何文件夹结构。我的_site具有以下结构:

_posts/
    |
    post1.md
    subdirectory/
        |
        post2.md
_site/
    |
     2015/
        |
        08/
            |
            05/
                |
                post1.html
                post2.html

您可以清楚地看到,子目录不会出现在最终网站的任何位置。

额外学分

您可以使用{{ post.path }}检索原始目录结构,并进行一些仔细的字符串操作。但是,此时在YAML front matter中设置Category属性可能更容易。可以使用{{category}}检索category属性。

纯粹作为一项学术活动,我继续检索目录。

  {% capture directory %}
      {% assign path = post.path | remove_first:'_posts/' | split:'/' %}
      {% for folder in path %}
          {% unless forloop.last %}
              {{ folder }}/
          {% endunless %}
      {% endfor %}
  {% endcapture %}
  Directory: {{directory}}

您可以决定这是否有用。

答案 1 :(得分:1)

我真的不知道这是否有用,但无论如何我会写下我的解决方案,只是因为我没有真正找到一个快速的解释。

要遍历文件,您只需在_config.yml文件中添加以下代码段:

collections:
    articles:
              output: true

之后你可以像这样调用for循环:

注意:请注意您的文件位于根目录中,例如, _articles/article01.md

示例

{% for article in site.articles %}
    {{ forloop.index  }}yes
{% endfor %}

您可以在本教程中看到video中的行为,但没有评论在_config.yml文件中包含集合标记