使用Jekyll检查文件是否存在

22

我如何使用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 %}
5个回答

24

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

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

9
极其低效。 - KFunk
1
@KFunk 为什么?检查文件是否存在涉及 I/O 操作,直到有相当数量的静态文件,它可能比这种方法慢。而且,如果这是唯一的解决方案,那我会采纳它。 - autra
13
可能吧,但是对于 Jekyll 来说,性能并不是一个非常大的问题,因为你只需要进行一次编译阶段。最终结果是简单的静态 HTML 文件。如果我的构建过程需要多花几秒钟时间,我并不在意。 - Jonathan
至少在Jekyll 3中,这对于检查文件是否存在于_includes中,是否存在于集合中或者其他由Jekyll处理的文件确实有效。但是,它不适用于像资产这样的东西。 - vossad01
2
@vossad01 的意思是,这种方法对于包含前置内容的任何内容都不起作用。引用 Jekyll 网站的话:“静态文件是不包含任何前置内容的文件。这些包括图像、PDF 和其他未渲染的内容。”OP 想要搜索图像,所以使用这种方法是可以的。 - Abel Cheung
显示剩余2条评论

2
我遇到了一个类似的问题需要解决,但是我特别想找与 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/

1

这个插件对我很有用: 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 %}

还有这个: https://github.com/k-funk/jekyll-if-file-exists - V. Rubinetti
还有这个: https://github.com/k-funk/jekyll-if-file-exists - V. Rubinetti

1
不是我的解决方案,但这段代码对我有效,并且避免了使用for循环。
{% assign jpg_path = "/images/my_image.jpg" %}
{% assign file = site.static_files | where: "path", jpg_path | first %}
{% if file %}
  <img src="{{ jpg_path }}">
{% endif %}

来源:https://devopsx.com/jekyll-check-if-file-exists/

-3

这是一个JS解决方案,作者要求使用Liquid。 - GeekUser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接