【问题标题】:How can I loop on all items where a certain field is not empty?如何循环某个字段不为空的所有项目?
【发布时间】:2016-02-28 18:16:51
【问题描述】:

我想遍历集合中具有特定字段集(非空)的所有项目。我试过这个:

{% assign papers_with_demos=site.data.papers | where:"demo", not blank %}
{% if papers_with_demos.size > 0 %}
   <h2>demos</h2>
   {% for paper in papers_with_demos %}]
   ... 
   {% endfor %}
{% endif %}

但它不起作用;所有论文都被退回。

我的目标是,只有在一篇或多篇带有演示的论文时才会显示标题“演示”。

【问题讨论】:

    标签: jekyll liquid


    【解决方案1】:

    如果文件被退回,您必须使用数据文件。如果数据文件中特定键的值为空,它将返回 false。因此,您可以使用 forloop 来检查数据键,例如:

    {% for paper in site.data.papers %}
      {% if paper.demo %}
      something
      {% endif %}
    {% endfor %}
    

    您可以在 Jekyll 文档的数据文件部分找到更多信息。

    根据您的回复更新:

    {% for item in site.data.items %}
      {% if item.random %}
      {% assign random-val = item.random %}
        {% if random-val %}
        <p>true</p>
        {% endif %}
      {% endif %}
    {% endfor %}
    

    如果在 items.yml 中,这将返回 true,你有 - random: true,如果为空则什么都没有。

    【讨论】:

    • 好的,我知道我可以用“for”循环检查这个,但是,我想提前知道是否有任何带有演示的论文。查看更新后的问题。
    • 我的目标是标题“

      demos

      ”将被显示,只有当有一个或多个带有演示的论文时。如果我在循环期间检查条件,我无法提前知道是否会有任何带有演示的论文,所以即使不需要,我也可以打印标题......
    • 在我展示的更新示例中,当值为空时不打印任何内容。
    猜你喜欢
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 2016-05-10
    • 2013-10-08
    相关资源
    最近更新 更多