Skip to content

default

The default filter is a valuable tool for providing fallback values within your templates. It allows you to specify a default value that will be displayed if the input variable is either undefined, null, empty, or false.

Functionality

  • All Data Types: Accepts any data type as input, including strings, numbers, booleans, arrays, and objects.
  • Default Value: Requires a single argument specifying the default value to use.
  • Nil/Empty Check: Determines if the input is nil (null), empty (e.g., an empty string or an empty array), or, by default, false.
  • Optional Argument: Accepts an optional named argument allow_false which, when set to true, will prevent the filter from replacing a false value with the default.
  • Output:
    • Returns the input value if it is not nil, empty, or (optionally) false.
    • Returns the specified default value if the input is nil, empty, or (optionally) false.

Syntax

    {{ input_value | default: default_value, allow_false: true }}

Arguments

  • default_value: The value to be returned if the input is nil, empty, or (optionally) false.
  • allow_false (optional): A boolean value (true/false) indicating whether the filter should replace a false value with the default. Defaults to false, meaning false will be replaced with the default value.

Code Samples

Example 1: Default Value for Undefined Variable

    {{ undefined_variable | default: "Not Found" }}
Output:
Not Found
Example 2: Default Value for Empty String

    {% assign empty_string = "" %}
    {{ empty_string | default: "Default Text" }}

Output:

Default Text
Example 3: Allowing False Values

    {% assign show_banner = false %}
    {{ show_banner | default: true, allow_false: true }}

Output:

false
Example 4: Default for Empty Array

    {% assign empty_array = [] %}
    {{ empty_array | default: "No items in the list" }}
Output:
No items in the list

Key Points

  • The default filter is a safety net for preventing errors and ensuring a smooth user experience when data might be missing or invalid.
  • It is frequently used in conjunction with conditional logic to provide alternative content when a variable does not have an expected value.
  • The filter supports an optional parameter (allow_false) to control how it handles boolean false values.