compact

compact

Removes any nil values from an array.

For this example, assume site.pages is an array of content pages for a website, and some of these pages have an attribute called category that specifies their content category. If we map those categories to an array, some of the array items might be nil if any pages do not have a category attribute.

Input

{% assign site_categories = site.pages | map: 'category' %}

{% for category in site_categories %}
  {{ category }}
{% endfor %}

Output

business
  celebrities

  lifestyle
  sports

  technology

By using compact when we create our site_categories array, we can remove all the nil values in the array.

Input

{% assign site_categories = site.pages | map: 'category' | compact %}

{% for category in site_categories %}
  {{ category }}
{% endfor %}

Output

business
  celebrities
  lifestyle
  sports
  technology

© 2005, 2006 Tobias Luetke
Licensed under the MIT License.
https://shopify.github.io/liquid/filters/compact/

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部