【问题标题】:Check for existence of file using Jekyll使用 Jekyll 检查文件是否存在
【发布时间】:2013-05-13 18:33:27
【问题描述】:

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

【问题讨论】:

    标签: jekyll liquid


    【解决方案1】:

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

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

    【讨论】:

    • 效率低得令人难以置信。
    • @KFunk 为什么?检查文件是否存在涉及 I/O,并且在您拥有大量静态文件之前可能会比这慢得多。另外,如果这是唯一的解决方案,我会接受。
    • @KFunk 可能,但性能并不是 Jekyll 的一个大问题,因为您只执行一次编译阶段。它最终会产生普通的旧静态 HTML。如果我的构建过程需要多几秒钟,我真的不在乎。
    • 至少在 Jekyll 3 中,这可以用于检查文件是否存在于 _includes、是否存在于集合中,或者是否存在由 Jekyll 处理的其他文件。但是,它确实适用于资产之类的东西。
    • @vossad01 的意思是,此方法不适用于包含前端的任何内容。引自 Jekyll 网站:“静态文件是不包含任何正面内容的文件。这些文件包括图像、PDF 和其他未渲染的内容。” OP要搜索图片所以用这个方法就好了。
    【解决方案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/
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        【讨论】:

        • 这是一个JS解决方案,作者要求液体
        猜你喜欢
        • 1970-01-01
        • 2011-06-26
        • 2012-07-19
        • 2022-06-10
        • 2017-10-02
        • 2021-12-25
        相关资源
        最近更新 更多