Include a file's contents only if the file exists


#1

I want to conditionally include a [text] file such that it will be included if it exists and I can provide fallback text if it does not.

When using the include directive Jekyll fails to build when the file does not exist. Among StackOverflow answers I have found 3 suggested potential solutions:

  • Put the files in a collection and find the desired file via iteration
    • I got as far as finding the StaticFileDrop for the file I want but cannot figure out how to read its contents
  • Capture the including the file file and then inspect the capture for the Liquid error.
    • Near as I could tell the Liquid error fails Jekyll build so there is no opportunity to react to it.
  • Inspect site.static_files for the desired file
    • files in the _includes directory do not appear here

As an undesirable workaround I realized I can flag the existence of the file in front matter. However, is there a way to react to the presence of the file so I do not need to explicitly/manually flag?


#2

I’m not clear on what you are trying to do - can you give a use case?

I don’t think you should be using the _includes folder, it is more of a templating thing - there is no actual _includes folder rendered in the _site folder.

If you put the text file in a folder - maybe called downloads or something, and then do whatever you were going to do with option 3 maybe it would work.


#3

Regarding what I am trying to do, see: https://json-schema-everywhere.github.io/yaml and check the “See examples…” box. Both of the code samples that display are sourced from their own file and sourced via {% include ... %}

The files are selected via convention. Ex:

{% include example.{{page.short_name | downcase}} %}

However, I recently encountered an exceptional case (TOML) causing me to want to add a new convention along the lines of:

{% if exists example.{{page.short_name | downcase}}.json %}
  {% include example.{{page.short_name | downcase}}.json %}
{% else %}
  {% include example.json %}
{% endif %}

The workaround was to use configuration (front matter) over convention.