How to list files in a directory with Liquid?

Using the Jekyll collections API, which, as of 2015-08-07 came with the big warning

Collections support is unstable and may change

Define a collection in _config.yml and creates an _images folder in your root directory

collections:
- images

Without having to add YAML front-matter to your images, Jekyll will:

Files in collections that do not have front matter are treated as static files and simply copied to their output location without processing.

Static files have the following attributes:

  • file.path
  • file.extname

And then the code on your page would be something like (untested):

{% for image in site.images %}
     {% if image.extname == 'jpg' %}
         <img src="{{ file.url }}" />
     {% endif %}
{% endfor %}

It's not completely impossible without a plugin, but of course you'll need to use some kludges. For example, you can put the image paths in your YAML front matter and they'll be available when Jekyll processes your page.

---
carousel_images:
  - images/img01.png
  - images/img02.png
  - images/img03.png
---

# Lots of page-related code.

{% for img in page.carousel_images %}
  # Do something.
{% endfor %}

For site-wide images, you'll need a plugin. But if you want your images to be located in a specific page or post, this should do. :)

Hope that helps!


You can use this plugin. Copy and paste this code in a file inside the _plugins directory at the root of your Jekyll project.

https://gist.github.com/jgatjens/8925165

Then to use it just add the lines below

{% loop_directory directory:images iterator:image filter:*.jpg sort:descending %}
   <img src="{{ image }}" />
{% endloop_directory %}

Tags:

Liquid

Jekyll