液体过滤器集合不为空

Kur*_*ren 3 liquid jekyll yaml-front-matter

对于某些页面(并非所有页面),我的前提是:

---
top-navigation:
    order: 2
---
Run Code Online (Sandbox Code Playgroud)

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

我正在尝试,sort:'top-navigation.order'但这是一个例外undefined method [] for nil:NilClass.我试过,where:"top-navigation", true但它不等于真正的价值观.

如何过滤包含top-navigation然后排序的页面?

mar*_*nuy 6

两个步骤:

  1. 创建一个包含top-navigation密钥的页面的数组.

    我们创建一个空数组,然后推送具有该键的项.

    {% assign navposts = ''|split:''%}
    {% for post in site.posts %}
    {% if post.top-navigation %}
    {% assign navposts = navposts|push:post%}
    {% endif %}
    {% endfor %}
    
    Run Code Online (Sandbox Code Playgroud)
  2. 按上排列上面的数组 top-navigation.order

    {% assign navposts = navposts|sort: "top-navigation.order"%}
    
    Run Code Online (Sandbox Code Playgroud)

打印结果:

{% for post in navposts %}
<br>{{ post.title }} - {{post.top-navigation}}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

用于页面使用site.pages.


小智 5

在 Jekyll 3.2.0+(和 Github Pages)中,您可以使用 where_exp 过滤器,如下所示:

{% assign posts_with_nav = site.posts | where_exp: "post", "post.top-navigation" %}
Run Code Online (Sandbox Code Playgroud)

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

然后,将其与排序放在一起,您将得到:

{%
  assign sorted_posts_with_nav = site.posts 
  | where_exp: "post", "post.top-navigation" 
  | sort: "top-navigation.order"
%}
Run Code Online (Sandbox Code Playgroud)

Liquid 还具有where过滤器,当您没有为其指定目标值时,它会选择该属性具有真值的所有元素:

{% assign posts_with_nav = site.posts | where: "top-navigation" %}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这个变体不适用于 Jekyll。