0

Using Jekyll Liquid templates: how might I render items (in a collection) using a for loop, but only output those elements at the top of a collection hierarchy?

proj_folder
  - _items
    • item_1.md
    • item_2.md
    - subfolder_1
      • item_1-1.md
      • item_1-2.md
    - subfolder_2
      • item_2-1.md
      • item_2-2.md

OK, so if I do a standard for loop:

{% for item in site.items %}        
    <p>{{ item.name }}</p>
{% endfor %} 

I will get something like:

Item 1
Item 2
Item 1-1
Item 1-2
Item 2-1
Item 2-2

But I really want to stop at the top level. So I instead want only this (without the sub-folders):

Item 1
Item 2

I have seen posts where people monkey with frontmatter, explicitly tagging top-level items as "top" or some such. This won't work for me; I need to do this in template logic only. Possible?

Thanks.

allanberry
  • 7,325
  • 6
  • 42
  • 71

1 Answers1

1

You could look at the page.url to determine whether it is a subfolder or not. You could split it on a slash and check the length.

Something like this (not tested):

{% for item in site.items %}
    {% assign itemurl = item.url | split: '/' %}
    {% unless itemurl[1] %}
      <p>{{ item.name }}</p>
    {% endunless %}
{% endfor %} 
Mr. Hugo
  • 11,887
  • 3
  • 42
  • 60