Search code examples
rubymiddlemanmiddleman-4

Middleman loop through files in data folder


I am trying to figure out the right syntax for calling a range of files within the /data folder.

For example, I have a handful of files in /data, each formatted as article1.yml, article2.yml, etc. How might I loop through them in my template? I assume the most direct way would be calling an increment of numbers in the filename like this:

<% data.article-[1,2,3].each do |article| %> <p><<%= article.title %></p> <% end %>

I've seen others ask similar questions but haven't found a good example to look at that either loops through all available files, or like in my example loops through an increment of numbers.


Solution

  • @Anthonytkim are they in an a folder within data? i.e. /data/article/article1.yml? If so, to simply grab them all, try this:

    <% data.article.each do |id, article| %>
    ... do stuff ...
    <% end %>
    

    To only grab a few items, try using the first() syntax:

    <% data.article.first(7).each do |id, article| %>
    ... do stuff ...
    <% end %>
    

    If you want to grab a range from the middle, you can combine first(), and drop(). For instance, if I wanted items 5, 6, and 7:

    <% data.article.first(7).drop(4).each do |id, article| %>
    ... do stuff ...
    <% end %>
    

    If you want to output them in the reverse order, try this (which you can also combine with the first() and drop() syntax):

    <% data.article.reverse_each do |id, article| %>
    ... do stuff ...
    <% end %>