17
votes

How can I use Jekyll to test for the existence of a file?

To clarify, I want to run an {% if %} statement to check if an image file exists with the same name as the page I am on.

On my page in the YAML front matter:

----
  reference-design: true
----

In my layout:

{% if page.reference-design %}
    {% assign filename = page.path | remove_first: '.html' %}
    <!-- How can I check if file actually exists? -->
    <img src="images/reference_designs/{{ filename }}.png">
{% endif %}
4

4 Answers

22
votes

As of Jekyll 2, all site files are available via site.static_files. You can use this to check if a file exists. For example:

{% for static_file in site.static_files %}
    {% if static_file.path == '/favicon.ico' %}
        {% assign favicon = true %}
    {% endif %}
{% endfor %}
0
votes

This plugin worked for me: https://github.com/Wolfr/jekyll_file_exists

After you install it, you can use it like:

{% if page.reference-design %}
    {% assign filename = page.path | remove_first: '.html' %}
    {% capture img_exists %}{% file_exists {{ filename }}.png %}{% endcapture %}

    {% if img_exists == "true" %}
        <img src="images/reference_designs/{{ filename }}.png">
    {% endif %}
{% endif %}
0
votes

I had a similar problem to solve, but specifically looking for videos that matched the a specific directory / filename based on the markdown file.

Using file.size allowed me to test if the file (actually) exists.

 {% for video in site.video-demos %}
      {% assign path = page.id | replace: page.slug , ""  | prepend: '/assets/media/video' | append: video.directory | append: page.slug | append: ".mp4"  %}
      {% assign file_exists = site.static_files | where: "path", path  %}
      {% if file_exists.size != 0 %}
        {% include video-player.html filename = path title = video.title %}
      {% endif %}
 {% endfor %}

It loops through an array from my config to get part of the directory structure:

video-demos:
- title: iOS Voiceover Safari
  directory: ios/
- title: Android Talkback Chrome
  directory: android/
- title: Windows Jaws Chrome
  directory: jaws/
- title: Windows NVDA Chrome
  directory: nvda/
- title: MacOS Voiceover Safari
  directory: macos/