Skip to content

truncatewords

The truncatewords filter is designed to shorten a string to a specified number of words. If the string exceeds the desired word count, it is cut off, and an ellipsis (...) or a custom string is appended to indicate the truncation.

Functionality

  • Strings: Takes a string as input.
  • Word Count: Requires an integer argument specifying the maximum number of words to keep in the output.
  • Ellipsis (Optional): Accepts an optional string argument to use as the truncation indicator. Defaults to "..." if not provided.
  • Truncation: Shortens the string to the given number of words, adding the ellipsis or custom string at the end.
  • Output: Returns the truncated string (or the original if it was shorter than the specified word count).

Syntax

    {{ input_string | truncatewords: word_count, ellipsis }}

Arguments

  • word_count: An integer representing the maximum number of words allowed in the output string.
  • ellipsis (optional): A string used to signify truncation. 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 | truncatewords: 4 }}
Output:
This is a very...
Example 2: Truncating with a Custom Indicator

    {% assign review = "This product is amazing! It exceeded my expectations in every way." %}
    {{ review | truncatewords: 5, "[Read More]" }}

Output:

This product is amazing! It exceeded [Read More]
Example 3: No Truncation Necessary

    {% assign short_text = "Hello world" %}
    {{ short_text | truncatewords: 10 }}

Output:

Hello world

Outliers and Special Cases

  • Empty Strings: If the input string is empty, the truncatewords filter returns an empty string.
  • Word Count Less Than 1: If the word_count is 0 or negative, it is typically treated as 1.
  • Non-String Input: If the input is not a string, the filter might attempt to convert it to a string or return an error.

Key Points

  • The truncatewords filter is ideal for displaying summaries or excerpts of longer text while maintaining readability.
  • It allows for customization with different truncation indicators to match the context of your content.
  • It is generally preferred over truncate when you want to preserve whole words rather than cutting off mid-word.