📅  最后修改于: 2023-12-03 15:02:45.541000             🧑  作者: Mango
Liquid Truncate is a filter in the Liquid templating language that allows you to shorten a string to a specified length. This is especially useful for displaying a summary of a longer text.
To use the filter, simply add | truncate
to your Liquid variable and specify the desired length. For example:
{{ post.content | truncate: 150 }}
This will shorten the post.content
string to 150 characters.
If the string is shorter than the specified length, it will be returned as is. If the string is longer, it will be truncated and an ellipsis (...
) will be appended to the end of the shortened string.
The truncate
filter also accepts a number of options to customize its behavior.
The separator
option allows you to specify a character to use as the separator between words, so that the truncated string ends on a whole word instead of being cut off mid-word. For example:
{{ post.content | truncate: 150, separator: ' ' }}
This will truncate the post.content
string to 150 characters, but will ensure that the string ends on a whole word.
By default, the truncate
filter appends an ellipsis (...
) to the end of the truncated string. You can customize the ellipsis by passing the ellipsis
option:
{{ post.content | truncate: 150, ellipsis: ' (read more)' }}
This will truncate the post.content
string to 150 characters, and will append the string ' (read more)' to the end of the truncated string.
By default, the truncate
filter includes HTML tags and entities in the character count. You can strip HTML tags by passing the strip_html
option:
{{ post.content | truncate: 150, strip_html: true }}
This will truncate the post.content
string to 150 characters, without including any HTML tags or entities in the count.
Consider the following string:
{% raw %}
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dignissim ipsum ex, at commodo dolor rhoncus et. Sed ac risus sodales, euismod est sit amet, malesuada mauris. Vestibulum feugiat tellus a mauris feugiat et semper eros faucibus. Nullam vitae erat in leo euismod consectetur in sit amet sapien. Aliquam suscipit mauris eros, ac auctor justo rhoncus eu. Sed tincidunt, felis vitae venenatis finibus, purus dui luctus urna, nec pulvinar metus neque non elit."
{% endraw %}
Using the following Liquid code:
{{ string | truncate: 100, separator: ' ', ellipsis: '...' }}
This will output:
{% raw %}"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dignissim ipsum ex, at commodo dolor..."{% endraw %}
The truncate
filter is a handy tool for shortening text strings for display on a website or app. With a range of customization options, it can be adapted to suit a range of use cases.