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 %}
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 %}
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 %}
Read http://ecommerce.shopify.com/c/ecommerce-design/t/testing-if-a-file-exists-29624. Also you might be able to play with capture
.