使用Jekyll检查文件是否存在

时间:2013-05-13 18:33:27

标签: jekyll liquid

如何使用Jekyll测试文件是否存在?

为了澄清,我想运行一个{% if %}语句来检查一个图像文件是否与我所在页面的名称相同。

在YAML前面的我的页面上:

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

在我的布局中:

{% 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 个答案:

答案 0 :(得分:19)

自Jekyll 2起,所有网站文件均可通过site.static_files获取。您可以使用它来检查文件是否存在。例如:

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

答案 1 :(得分:0)

此插件为我工作:https://github.com/Wolfr/jekyll_file_exists

安装后,您可以像这样使用它:

{% 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 %}

答案 2 :(得分:0)

我有一个类似的问题需要解决,但专门寻找与基于 Markdown 文件的特定目录/文件名匹配的视频。

使用 file.size 允许我测试文件(实际上)是否存在。

 {% 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 %}

它从我的配置中遍历一个数组以获取目录结构的一部分:

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/

答案 3 :(得分:-3)