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
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 }}
{% assign review = "This product is amazing! It exceeded my expectations in every way." %}
{{ review | truncatewords: 5, "[Read More]" }}
Output:
Example 3: No Truncation NecessaryOutput:
Outliers and Special Cases¶
- Empty Strings: If the input string is empty, the
truncatewordsfilter returns an empty string. - Word Count Less Than 1: If the
word_countis 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
truncatewordsfilter 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
truncatewhen you want to preserve whole words rather than cutting off mid-word.