<% list_items = capture do %>
  <%
    docs_grouped_by_parent = imported_docs.each_with_object({}) do |page, hash|
      path_to_dir = page[:path].split("/").take(page[:path].split("/").count - 1).join("/")
      hash[path_to_dir] = [] unless hash[path_to_dir]
      hash[path_to_dir] << page
      hash[path_to_dir].sort_by! { |hash| hash[:title] }
    end
  %>
  <% docs_grouped_by_parent.keys.each do |subpath| %>
    <% list_of_links = capture do %>
      <% docs_grouped_by_parent[subpath].each do |page| %>
        <%= "<li><a href='#{page[:path]}' class='govuk-link'>#{page[:title]}</a></li>" %>
      <% end %>
    <% end %>

    <% if subpath == path_to_app_docs %>
      <%= list_of_links %>
    <% else %>
      <li><strong><%= subpath.sub(path_to_app_docs, "") %></strong></li>
      <ul>
        <%= list_of_links %>
      </ul>
    <% end %>
  <% end %>
<% end %>

<ul>
<%= list_items.strip %>
</ul>

<% list_items = capture do %>
  <%
    docs_grouped_by_parent = imported_docs.each_with_object({}) do |page, hash|
      path_to_dir = page[:path].split("/").take(page[:path].split("/").count - 1).join("/")
      hash[path_to_dir] = [] unless hash[path_to_dir]
      hash[path_to_dir] << page
    end
  %>
  <% docs_grouped_by_parent.keys.each do |subpath| %>
    <% list_of_links = capture do %>
      <% docs_grouped_by_parent[subpath].sort_by { |hash| hash[:title] }.each do |page| %>
        <%= "<li><a href='#{page[:path]}' class='govuk-link'>#{page[:title]}</a></li>" %>
      <% end %>
    <% end %>

    <% if subpath == path_to_app_docs %>
      <%= list_of_links %>
    <% else %>
      <li><strong><%= subpath.sub(path_to_app_docs, "") %></strong></li>
      <ul>
        <%= list_of_links %>
      </ul>
    <% end %>
  <% end %>
<% end %>

<ul>
<%= list_items.strip %>
</ul>

Sort at the point of use
Sort at the point of use

More efficient and conventional.
