Skip to content

Compact ​

Last updated View as Markdown

Use compact to delete the nil items from an array. Empty strings, 0 and false are kept. When the input is nil, you get an empty array.

Example ​

Data
json
{
  "names": [
    "YouCan",
    "Amine",
    nil
    "Product",
  ]
}
liquid
Original names:

{% for name in names -%}
  - {{ name }}
{%- endfor %}

Names with compact filter:

{%- assign names = names | compact -%}
{% for name in names -%}
  - {{ name }}
{%- endfor %}

Output

Original names:

  • YouCan
  • Amine
  • Product

Names with compact filter:

  • YouCan
  • Amine
  • Product

Property ​

You can give a property name. Then the items with a nil value for that property are deleted.

liquid
{% assign with_images = products | compact: 'image' %}