Reputation: 123
I am a newbie to liquid templating language, regarding the website am working on it's powered by jekyll, we publish posts and sometimes series of posts so we make a sub directory for series posts in _posts
directory. Can I loop through all files in the directory _posts
and its sub directories given that I don't know their names or number ?
My file tree :
root
|
_posts/
|
post1.md
post2.md
series_name/
|
post3.md
Upvotes: 1
Views: 2203
Reputation: 151
I really dont know if this is helpfully but I will write down my solution anyway, only because I didnt really found a quick explanation.
To iterate through files you'll only need to add the following code snippet in your _config.yml
file:
collections:
articles:
output: true
After that you can call a for loop like this:
Note: Beware that you have your files in the root directory, in this example e.g. _articles/article01.md
.
Example
{% for article in site.articles %}
{{ forloop.index }}yes
{% endfor %}
You can see the behavior in this tutorial video but without the comment to include the collection tag in the _config.yml
file
Upvotes: 1
Reputation: 836
The short answer to your question is YES.
The Jekyll documentation guides you through displaying an index of all your _posts
. Specifically, you will want something like the following:
<ul>
{% for post in site.posts %}
<li>
<a href="{{ post.url }}">{{ post.title }}</a>
</li>
{% endfor %}
</ul>
I have tested this with subdirectories.
Jekyll appears to ignore any folder structure inside of _posts
while generating your _site
. My _site
has the following structure:
_posts/
|
post1.md
subdirectory/
|
post2.md
_site/
|
2015/
|
08/
|
05/
|
post1.html
post2.html
You can clearly see here that the subdirectory does not appear anywhere in your final site.
You can retrieve the original directory structure using {{ post.path }}
and some careful string manipulation. However, at this point it's probably easier to just set the Category
attribute in your YAML front matter. The category attribute can be retrieved with {{category}}
.
Purely as an academic exercise, I went ahead and retrieved the directory.
{% capture directory %}
{% assign path = post.path | remove_first:'_posts/' | split:'/' %}
{% for folder in path %}
{% unless forloop.last %}
{{ folder }}/
{% endunless %}
{% endfor %}
{% endcapture %}
Directory: {{directory}}
You can decide if this is useful.
Upvotes: 3