Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for existence of file using Jekyll

Tags:

jekyll

liquid

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 %}
like image 741
Wolfr Avatar asked May 13 '13 18:05

Wolfr


2 Answers

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 %}
like image 112
Jonathan Avatar answered Nov 01 '22 01:11

Jonathan


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/
like image 40
Charlie Triplett Avatar answered Oct 31 '22 23:10

Charlie Triplett