Children of a specified directory

Somewhere I dug up this snippet:

<ul>
  <% for page in current_page.children.sort_by {|x| x.data.title} %>
    <li><%= link_to page.data.title, page.url %></li>
  <% end %>
</ul>

This lists files in the current directory, and index.html.md pages in child directories. Instead of current_page, how do I specify a directory? I’d like a list of links to all matching files in a child directory.

Example: foo/index.html.md.erb contains, among other content, a list of links to foo/bar/*

Hi Shalako,

You can filter your site’s resources by accessing sitemap.resources.

Here’s a helper method you can use:

# Returns all pages under a certain directory.
def sub_pages(dir)
  sitemap.resources.select do |resource|
    resource.path.start_with?(dir)
  end
end

You can use it like this:

<ul>
<% sub_pages('recipes').each do |resource| %>
	<li><%= link_to resource.data.title, resource.url %></li>
<% end %>
</ul>

I’ve put together an example at https://github.com/Aupajo/example-for-shalako

2 Likes

Hello Aupajo,

That’s exactly what I was looking for, thank you!

1 Like