在 liquid 中循环遍历目录及其子目录文件
Loop through a directory and its sub-directories files in liquid
我是 liquid 模板语言的新手,关于我正在使用的由 jekyll 提供支持的网站,我们发布帖子,有时发布系列帖子,因此我们在 _posts
目录中为系列帖子创建了一个子目录。如果我不知道它们的名称或编号,我可以遍历目录 _posts
及其子目录中的所有文件吗?
我的文件树:
root
|
_posts/
|
post1.md
post2.md
series_name/
|
post3.md
您问题的简短回答是是。
解决方案
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}}
你可以决定这是否有用。
我真的不知道这是否有帮助,但无论如何我都会写下我的解决方案,只是因为我没有真正找到一个快速的解释。
要遍历文件,您只需在 _config.yml
文件中添加以下代码片段:
collections:
articles:
output: true
之后你可以像这样调用一个for循环:
注意:请注意,您的文件位于根目录中,在此示例中,例如_articles/article01.md
.
例子
{% for article in site.articles %}
{{ forloop.index }}yes
{% endfor %}
您可以在本教程中看到行为 video,但没有在 _config.yml
文件中包含集合标签的注释
我是 liquid 模板语言的新手,关于我正在使用的由 jekyll 提供支持的网站,我们发布帖子,有时发布系列帖子,因此我们在 _posts
目录中为系列帖子创建了一个子目录。如果我不知道它们的名称或编号,我可以遍历目录 _posts
及其子目录中的所有文件吗?
我的文件树:
root
|
_posts/
|
post1.md
post2.md
series_name/
|
post3.md
您问题的简短回答是是。
解决方案
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}}
你可以决定这是否有用。
我真的不知道这是否有帮助,但无论如何我都会写下我的解决方案,只是因为我没有真正找到一个快速的解释。
要遍历文件,您只需在 _config.yml
文件中添加以下代码片段:
collections:
articles:
output: true
之后你可以像这样调用一个for循环:
注意:请注意,您的文件位于根目录中,在此示例中,例如_articles/article01.md
.
例子
{% for article in site.articles %}
{{ forloop.index }}yes
{% endfor %}
您可以在本教程中看到行为 video,但没有在 _config.yml
文件中包含集合标签的注释