【问题标题】:Loop through a directory and its sub-directories files in liquid在液体中循环遍历目录及其子目录文件
【发布时间】:2015-10-23 22:47:08
【问题描述】:

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

【问题讨论】:

  • 这些文件是否在您的本地计算机上?您可以使用任何语言或脚本访问和循环它们。我不明白这和杰基尔有什么关系?它只是一个静态站点生成器
  • 感谢您的回复,您是对的,我将编辑问题,抱歉误会,我无法弄清楚如何在液体中循环文件,是的文件在我的本地机器上。
  • 这个SO thread 是你要找的吗?听起来很相似
  • 感谢您的帮助,我看到了问题,但这不是我要问的问题,我想遍历 _posts 目录及其子目录中的所有文件,就好像 _posts 目录没有子目录..有没有办法使用液体来做到这一点?

标签: loops liquid


【解决方案1】:

您的问题的简短回答是YES

解决方案

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

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

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

说明

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

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

您可以在这里清楚地看到该子目录并未出现在您最终站点的任何位置。

额外积分

您可以使用{{ post.path }} 和一些小心的字符串操作来检索原始目录结构。但是,此时在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}}

你可以决定这是否有用。

【讨论】:

    【解决方案2】:

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

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

    collections:
        articles:
                  output: true
    

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

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

    示例

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-26
      • 2011-03-10
      • 2016-03-24
      • 1970-01-01
      • 2011-12-24
      • 1970-01-01
      • 2016-06-28
      相关资源
      最近更新 更多