In AnQiCMS website content operation, how to elegantly handle long text content so that it is both beautiful and complete on the page, which is the key to improving user experience.Especially on the list page, card display, or introduction area, overly long text often leads to layout errors, affecting the overall visual effect.AnQiCMS's powerful template engine provides various flexible ways to solve this problem, the most commonly used being the feature of text truncation and adding an ellipsis.
AnQiCMS's template system draws on the syntax of the Django template engine, built-in a series of practical filters (Filters), which can help us easily implement intelligent text truncation.With these features, you can flexibly decide whether to truncate the content based on its actual length, and automatically add an ellipsis (…) after truncation to optimize the display of the website content.
Understand the core text truncation filter
In the AnQiCMS template, the implementation of text truncation mainly depends on the following core filters:truncatechars/truncatewordsAnd the versions they handle HTML contenttruncatechars_htmlandtruncatewords_html.
truncatecharsTruncated by character countThis filter will truncate text according to the specified character count.No matter the text is Chinese, English, or other symbols, it will count each character one by one, truncate after reaching a specified length, and automatically add an ellipsis at the end.It is noteworthy that the specified length includes the characters of the ellipsis itself.- Usage example:
{{ 变量名|truncatechars:长度 }} - Features: Simple and direct, suitable for scenarios with strict character count limitations, but may truncate English content in the middle of words.
- Usage example:
truncatewordsTruncated by word countThis filter is designed for English content, it will truncate text according to the specified word count. It ensures the integrity of each word, and it will not be liketruncatecharsThat is truncated in the middle of the word. An ellipsis is also automatically added after the truncation.- Usage example:
{{ 变量名|truncatewords:长度 }} - Features: Maintain the integrity of English words to make truncated text more readable. For Chinese content, since there is no clear concept of 'word', the effect may not be as good as
truncatechars.
- Usage example:
truncatechars_htmlandtruncatewords_htmlTruncate HTML contentIf your content contains HTML tags, such as formatted text in article details, use them directlytruncatecharsortruncatewordsIt may damage the HTML structure, causing tags not to close, which may lead to display errors on the page. At this time,truncatechars_htmlandtruncatewords_htmlThey come into play. While truncating text, they intelligently handle HTML tags to ensure that the truncated HTML structure remains valid and avoid page chaos.- Usage example:
{{ 变量名|truncatechars_html:长度|safe }}or{{ 变量名|truncatewords_html:长度|safe }} - Important reminderBe sure to add at the end when using these two filters
|safeThe filter. This is because AnQiCMS (and most modern template engines) defaults to escaping output content to prevent XSS attacks. If not added|safeEven though_htmlThe filter retains the HTML structure, escaping will also convert<h1>tags to<h1>, causing the text to be displayed instead of parsing the HTML.|safeTell the template engine that this part of the content is safe and does not need to be escaped.
- Usage example:
Actual application scenarios and code examples
Let us look at some common examples to see how to apply these truncation functions in the AnQiCMS template.
Scenario one: Limit the display length of the article title.On the list page, to make the title uniform, the length is usually limited.
<a href="{{ item.Link }}" title="{{ item.Title }}">
{{ item.Title|truncatechars:25 }} {# 如果标题超过25个字符,将截断并添加... #}
</a>
Scenario two: truncating the article summary or abstractThe article summary usually needs to be limited to a certain number of words to guide users to click and view the details.
<p>
{{ item.Description|truncatechars:120 }} {# 截断简介,保留120个字符,并添加... #}
</p>
Scenario three: Preview part of the article with HTML format.Sometimes it is necessary to display a formatted excerpt of the article's main content on the list page or in related article recommendations.
<div class="article-preview">
{# 截断文章内容,保留50个单词,并确保HTML结构正确 #}
{{ item.Content|truncatewords_html:50|safe }}
</div>
Scenario four: dynamically judge the length, truncate only when necessary.If you want to display an ellipsis only when the text is truly long, you can combinelengtha filter to make the judgment:
{% if item.Title|length > 30 %}
<span title="{{ item.Title }}">{{ item.Title|truncatechars:30 }}</span>
{% else %}
<span>{{ item.Title }}</span>
{% endif %}
In this example, we first judge whether the actual length of the title exceeds 30 characters. If it does, then truncate; otherwise, output as is.
Useful tips and precautions
- Testing is the key.Before applying any truncation filter in practice, it is recommended to thoroughly test in the development environment to ensure that the truncation effect meets expectations, especially for Chinese and content containing HTML.
- Choose the appropriate lengthThe setting of truncation length should be determined according to the page design, content type, and reading habits of the target audience, to avoid too much truncation causing information loss, or too little truncation causing the effect to be not obvious.
- The uniqueness of Chinese content:
truncatewordsPrimarily for English, as it relies on spaces to distinguish 'words'. For Chinese content, due to the lack of a natural word separator,truncatewordsIt may treat the entire sentence as a 'word' or judge according to punctuation, the effect may not be as good astruncatecharsdirectly. Therefore, when dealing with Chinese,truncatecharsit is usually a safer choice. - HTML content with
|safe: It is emphasized again, any truncation filter with a_htmlsuffix needs to be added immediately after it|safeThe filter, otherwise the HTML tags will be escaped as text, not parsed by the browser.
Summary
AnQiCMS's template engine considers the details of content display carefully, throughtruncatechars/truncatewordsCombined with its HTML version|safeFilters that can help you easily achieve intelligent text truncation.This not only effectively enhances the beauty and layout of the website page, but also optimizes the reading experience for users, presenting your content in the most suitable form to visitors.In content operation, using these template functions will greatly improve work efficiency and the professionalism of website content.
Frequently Asked Questions (FAQ)
truncatecharsandtruncatewordsWhat are the differences in Chinese content?truncatecharsIt is truncated by character count, applicable to both Chinese and English, it accurately calculates the length of each character (including Chinese characters), and truncates after reaching the specified number.truncatewordsIt is truncated by word count, mainly designed for English because it relies on spaces or punctuation marks to distinguish words. For continuous Chinese text,truncatewordsIt may be considered as a long 'word' that cannot be truncated as expected, or the truncation point may not be in line with Chinese reading habits. Therefore, it is usually recommended to usetruncatecharsTo achieve more precise and controllable truncation effects.Why are you using
truncatechars_htmlortruncatewords_htmlIt needs to be added when|safeFilter?AnQiCMS's template engine, to prevent potential cross-site scripting (XSS) attacks, defaults to escaping all output variable content. This means that if your variable contains<h1>Such HTML tags are converted by default to<h1>thereby displayed as plain text rather than being parsed by the browser as a title.truncatechars_htmlandtruncatewords_htmlAlthough internally it tries to preserve the HTML structure, it is still affected by the template engine's escaping mechanism when the output is finally generated. Therefore, add|safeThe filter tells the template engine that this part of the content is known and safe HTML, which does not need to be escaped and can be parsed directly by the browser, thus ensuring that formatted text is displayed correctly.Can the ellipsis displayed after text truncation be customized? For example, can it be replaced with "[View More]"??Built-in in AnQiCMS
truncatecharsandtruncatewordsThe filter uses a fixed ellipsis (…) as the truncation mark, and there is no direct parameter to modify this default mark in the current document. If you need to customize the truncation mark, you can combinelengthFilters and condition judgments can be manually implemented. You can determine if the actual length of the text exceeds your expected length.If it exceeds, manually truncate the text and append your custom marker at the end. For example:{% set max_length = 50 %} {% set original_text = item.Description %} {% if original_text|length > max_length %} {{ original_text|truncatechars:max_length|replace:"..."," [查看更多]" }} {# 先截断,再替换默认省略号 #} {% else %} {{ original_text }} {% endif %}Please, replace manually
...Maybe not as goodtruncatecharsThe internal implementation handles ellipsis characters intelligently. A more precise approach is to first cut the required length of the string, and then manually judge whether to add a custom marker.{% set max_chars = 50 %} {% set my_content = item.Description %} {% if my_content|length > max_chars %} {{ my_content|slice:("0:" + (max_chars - 6)) }}... [更多] {# 假设" [更多]"占6个字符 #} {% else %} {{ my_content }} {% endif %}This manual concatenation method can provide greater flexibility, but it requires you to manage length calculations more finely, especially when the content includes HTML, which can become complex.