20

如何使用 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

4 回答 4

22

从 Jekyll 2 开始,所有站点文件都可以通过site.static_files. 您可以使用它来检查文件是否存在。例如:

{% for static_file in site.static_files %}
    {% if static_file.path == '/favicon.ico' %}
        {% assign favicon = true %}
    {% endif %}
{% endfor %}
于 2014-10-16T17:20:38.153 回答
2

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

使用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/
于 2021-03-16T18:20:13.707 回答
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 %}
于 2020-06-21T16:27:24.750 回答
-3

阅读http://ecommerce.shopify.com/c/ecommerce-design/t/testing-if-a-file-exists-29624。你也可以玩capture.

于 2013-05-13T18:46:24.927 回答