Skip to content

first

The 'first' filter is designed to retrieve the first element of an array or string.

Functionality

  • Arrays: If the input value is an array, the first filter returns the first element of that array.
  • Strings: If the input value is a string, the first filter returns the first character of that string.

Syntax

    {{ array_variable | first }} 
Arguments

The first filter does not require any arguments.

Code Samples

Example 1: First Element of an Array

    {% assign colors = "red,green,blue" | split: "," %}

    {{ colors | first }} 

Output:

red
Example 2: First Character of a String
    {% assign message = "Hello, world!" %}

    {{ message | first }} 
Output:
H

Outliers and Special Cases

  • Empty Arrays: If the input array is empty, the first filter returns null.
  • Empty Strings: If the input string is empty, the first filter returns null.
  • Non-Array/String Input: If the input is neither an array nor a string, the first filter returns the original input value unchanged.

Key Points

  • The first filter is a simple and convenient way to access the initial element of a sequence.
  • It gracefully handles both arrays and strings.
  • It is particularly useful when you need to extract a specific piece of information from the beginning of your data.