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

问题描述 投票:0回答:2

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

loops liquid
2个回答
1
投票

对你的问题的简短回答是肯定的。

Solution

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

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

我用子目录测试了这个。

说明

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

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

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

额外的功劳

您可以使用{{ post.path }}和一些仔细的字符串操作来检索原始目录结构。但是,在这一点上,在Category中设置YAML front matter属性可能更容易。可以使用{{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
投票

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

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

collections:
    articles:
              output: true

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

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

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

您可以在本教程中查看video中的行为,但没有注释在_config.yml文件中包含collection标记

© www.soinside.com 2019 - 2024. All rights reserved.