It's essential to manage the display of text efficiently, especially on pages with multiple articles or product descriptions. Two useful filters in the Liquid template language help with this: truncate and truncatewords. Let's discuss these filters, explain their usage, and explore how they can be used as alternatives to the excerpt feature for displaying articles and content on your blog page.
Truncate Filter
The truncate filter shortens a string to a specified number of characters and appends an ellipsis or custom string to indicate that the text has been truncated. This filter is particularly helpful when displaying article titles or brief product descriptions in a limited space.
The first argument in the truncate filter indicates the maximum number of characters to display, while the second (optional) argument specifies a custom string to append after truncation.
Usage:
{{ 'Once upon a time in a land far, far away...' | truncate: 17 }}
{# Output: 'Once upon a time...' #}
{{ 'Once upon a time in a land far, far away...' | truncate: 17, '... (Read more)' }}
{# Output: 'Once upon a time... (Read more)' #}
TruncateWords Filter
The truncatewords filter functions similarly to the truncate filter but shortens the text to a specified number of words instead of characters. This filter is useful for displaying article excerpts or product descriptions while maintaining readability and context.
Similar to the truncate filter, the first argument in the truncatewords filter indicates the maximum number of words to display, while the second (optional) argument specifies a custom string to append after truncation.
Usage:
{{ 'Once upon a time in a land far, far away...' | truncatewords: 5 }}
{# Output: 'Once upon a time in a...' #}
{{ 'Once upon a time in a land far, far away...' | truncatewords: 5, '... (Read more)' }}
{# Output: 'Once upon a time in a... (Read more)' #}
Truncate and TruncateWords for Blog Pages
On blog pages, you may want to display a list of articles with their titles and a brief excerpt. While you can use the built-in excerpt feature from the Shopify Admin article page, the truncate and truncatewords filters offer an alternative way to manage text display without manually creating excerpts.
Example:
{% for article in blog.articles %}
{{ article.title | truncate: 30 }}
{{ article.content | truncatewords: 20, '... (Read more)' }}
{% endfor %}
In the example above, we use the truncate filter to limit article titles to 30 characters and the truncatewords filter to limit article content to 20 words, followed by a "Read more" link. This approach maintains a clean and consistent layout for your blog page, regardless of the original content's length.
Having trouble? Ask for help.