Skip to content

truncate

The truncate filter is designed to shorten a string to a specified length. If the string exceeds the desired length, it is cut off, and an ellipsis (...) is appended to indicate the truncation.

Functionality

  • Strings: Takes a string as input.
  • Length: Requires an integer argument specifying the maximum desired length of the string.
  • Ellipsis (Optional): Accepts an optional string argument to use as the ellipsis character(s). Defaults to "..." if not provided.
  • Truncation: Shortens the string to the given length if it exceeds it, appending the ellipsis to the end.
  • Output: Returns the truncated string (or the original if it was shorter than the specified length).

Syntax

    {{ input_string | truncate: length, ellipsis }}

Arguments

  • length: An integer representing the maximum number of characters the output string should have.
  • ellipsis (optional): A string used to indicate that the string has been truncated. Defaults to "..." if not specified.

Code Samples

Example 1: Truncating a Long Sentence

    {% assign description = "This is a very long description that needs to be shortened." %}
    {{ description | truncate: 20 }}

Output:

This is a very long...
Example 2: Truncating with a Custom Ellipsis
    {% assign title = "Supercalifragilisticexpialidocious" %}
    {{ title | truncate: 15, "--more--" }}

Output:

Supercalifragi--more--
Example 3: No Truncation Necessary

    {% assign short_text = "Hello" %}
    {{ short_text | truncate: 10 }}

Output:

Hello

Outliers and Special Cases

  • Empty Strings: If the input string is empty, the truncate filter returns an empty string.
  • Length Less Than or Equal to Ellipsis Length: If the specified length is less than or equal to the length of the ellipsis, the filter might return only the ellipsis or raise an error, depending on the implementation.
  • Non-String Input: If the input is not a string, the truncate filter might attempt to convert it to a string or return an error.

Key Points

  • The truncate filter is valuable for controlling the display length of strings, especially in situations with limited space like previews or summaries.
  • It can be customized with a different ellipsis string to fit your design needs.
  • Be aware of the potential for the ellipsis to be cut off if the specified length is too short