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_falsewhich, when set totrue, will prevent the filter from replacing afalsevalue 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
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
Output: Example 2: Default Value for Empty StringOutput:
Example 3: Allowing False ValuesOutput:
Example 4: Default for Empty Array Output:Key Points¶
- The
defaultfilter 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.