【问题标题】:Liquid filter collection where not null不为空的液体过滤器集合
【发布时间】:2018-01-17 05:14:14
【问题描述】:

在我的 一些 页面(不是全部)的前面,我有:

---
top-navigation:
    order: 2
---

我想使用液体过滤所有具有top-navigation 对象的网站页面并按top-navigation.order 排序。

我正在尝试sort:'top-navigation.order',但这会引发undefined method [] for nil:NilClass 的异常。我试过where:"top-navigation", true,但它并不等同于真实值。

如何过滤具有top-navigation 的页面然后排序?

【问题讨论】:

    标签: jekyll liquid yaml-front-matter


    【解决方案1】:

    两步:

    1. 使用包含top-navigation 键的页面创建一个数组。

      我们创建一个空数组,然后推送有键的项目。

      {% assign navposts = ''|split:''%}
      {% for post in site.posts %}
      {% if post.top-navigation %}
      {% assign navposts = navposts|push:post%}
      {% endif %}
      {% endfor %}
      
    2. 将上述数组按top-navigation.order排序

      {% assign navposts = navposts|sort: "top-navigation.order"%}
      

    打印结果:

    {% for post in navposts %}
    <br>{{ post.title }} - {{post.top-navigation}}
    {% endfor %}
    

    对于页面使用site.pages

    【讨论】:

    • 这很好用。我什至为我的标签列表添加了一个 uniq 过滤器。
    • 在阅读了 jekyll 过滤器列表后来到了这里。有一个 "where: nil" 过滤器,从 v4.0.0 (docs) 开始可用。不知道如何获得匡威过滤器。无论如何,这个答案似乎更便携。
    【解决方案2】:

    在 Jekyll 3.2.0+(和 Github 页面)中,您可以像这样使用 where_exp 过滤器:

    {% assign posts_with_nav = site.posts | where_exp: "post", "post.top-navigation" %}
    

    在这里,对于 site.posts 中的每个项目,我们将其绑定到“post”变量,然后计算表达式“post.top-navigation”。如果它评估为真,那么它将被选中。

    然后,把它和排序放在一起,你会得到这个:

    {%
      assign sorted_posts_with_nav = site.posts 
      | where_exp: "post", "post.top-navigation" 
      | sort: "top-navigation.order"
    %}
    

    Liquid 还具有 where 过滤器,当您不给它一个目标值时,它会选择所有具有该属性真实值的元素:

    {% assign posts_with_nav = site.posts | where: "top-navigation" %}
    

    很遗憾,此变体不适用于 Jekyll。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-15
      • 1970-01-01
      • 1970-01-01
      • 2013-03-15
      • 2017-07-27
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多