在 Jekyll 上添加条件逻辑,查看数据文件中是否有条目

Add conditional logic on Jekyll looking if there's entries in a data file

我正在使用 Jekyll 制作一个工作列表页面,我决定创建一个单独的数据文件,其中包含可用的工作职位。

我想添加一个条件,如果没有可用的位置(数据文件为空),将显示一条特定消息。

所以我有一个 job.html 应该显示列表的地方,我尝试显示列表或消息的代码是:

<!-- Jobs -->
<section class="jobs">
    {% if site.data.jobs == '' %}
        <h1>No job openings right now!</h1>
    {% else %}
        {% for job in site.data.jobs %}
            <h1>{{ job.title }}</h1>
            <h2>{{ job.link }}</h2>
        {% endfor %}
    {% endif %}
</section>

它没有用,所以我试图通过仅验证是否有空标题标签来破解它,如下所示:

<!-- Jobs -->
<section class="jobs">
    {% if site.data.jobs.title == '' %}
        <h1>No job openings right now!</h1>
    {% else %}
        {% for job in site.data.jobs %}
            <h1>{{ job.title }}</h1>
            <h2>{{ job.link }}</h2>
        {% endfor %}
    {% endif %}
</section>

也没用。任何想法如何解决这个问题?

一个空的 "jobs" 数据文件将使 site.data.jobs 成为 false,因此您可以检查它以显示消息(如果 for 语句将不会执行是这样):

{% unless site.data.jobs  %}
    <h1>No job openings right now!</h1>
{% endunless%}

如果数据文件根本不存在,那么 site.data.jobs 将是 nil 所以上面的代码也可以工作。

其他解决方案

另一种方法是检查 site.data.jobs 数组的大小:

    {% assign jobs_size = site.data.jobs | size %}
    {% if jobs_size == 0 %}
        <h1>No job openings right now!</h1>
    {% else %}
    ...