In AnQiCMS website content operation, how to elegantly handle long text content so that it is both aesthetically pleasing and maintains integrity on the page is the key to improving user experience.Especially on the list page, card display, or introduction area, overly long text often leads to layout disorder, affecting the overall visual effect.AnQiCMS powerful template engine provides various flexible ways to solve this problem, the most commonly used one being the function of text truncation with an ellipsis.
AnQiCMS template system borrows the syntax of Django template engine, and has a series of practical filters (Filters) built-in. These filters can help us easily implement smart text truncation.By these features, you can flexibly decide whether to truncate based on the actual length of the content, and automatically add ellipses (…) after truncation to optimize the display of website content.
Understand core text truncation filter
In the AnQiCMS template, the implementation of text truncation mainly depends on the following core filters:truncatechars/truncatewordsas well as their versions for handling HTML contenttruncatechars_htmlandtruncatewords_html.
truncatechars(Truncated by character count)This filter will truncate text according to the specified character count.No matter the text is in Chinese, English or other symbols, it will count the characters one by one, truncate to the specified length, and automatically add an ellipsis at the end.It is worth noting that the specified length includes the number of characters for the ellipsis itself.- Usage Example:
{{ 变量名|truncatechars:长度 }} - Features: Simple and direct, suitable for scenarios with strict character count limits, but may truncate English content in the middle of words.
- Usage Example:
truncatewords(Truncated by word count)This filter is designed for English content, it will truncate the text to the specified number of words. It ensures the integrity of each word, and it will not truncate words liketruncatecharsThat is truncated in the middle of a word. An ellipsis is also automatically added after the truncation.- Usage Example:
{{ 变量名|truncatewords:长度 }} - FeaturesMaintain the integrity of English words to make truncated text more readable. For Chinese content, since there is no clear concept of 'word', its effect may not be as good.
truncatechars.
- Usage Example:
truncatechars_htmlandtruncatewords_html(Truncating HTML content)If your content contains HTML tags, such as formatted text in article details, use them directlytruncatecharsortruncatewordsThe HTML structure may be damaged, leading to unclosed tags, which may cause display abnormalities on the page. At this time,truncatechars_htmlandtruncatewords_htmlThey come into play. While truncating text, they intelligently handle HTML tags to ensure the truncated HTML structure remains valid, avoiding page chaos.- Usage Example:
{{ 变量名|truncatechars_html:长度|safe }}or{{ 变量名|truncatewords_html:长度|safe }} - Important NoticeEnsure to add at the end when using these filters
|safeFilter. This is because AnQiCMS (and most modern template engines) default to escaping output content to prevent XSS attacks. If not|safe, even_htmlThe filter retains the HTML structure, escaping will also convert<h1>tags to<h1>, causing the text to be displayed instead of parsed as HTML.|safeTell the template engine that this part of the content is safe and does not need to be escaped.
- Usage Example:
Application scenarios and code examples
Let's look at some common examples to see how to apply these truncation features in the AnQiCMS template.
Scenario one: Limiting the display length of article titlesOn the list page, to keep the titles 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 characters to guide users to click and view the details.
<p>
{{ item.Description|truncatechars:120 }} {# 截断简介,保留120个字符,并添加... #}
</p>
Scenario three: Previewing a part of the article with HTML format.Sometimes it is necessary to display a formatted excerpt of the article content on list pages or related article recommendations.
<div class="article-preview">
{# 截断文章内容,保留50个单词,并确保HTML结构正确 #}
{{ item.Content|truncatewords_html:50|safe }}
</div>
Scenario four: dynamically judge the length and truncate only when necessaryIf you want to display an ellipsis only when the text is truly too long, you can combinelengthThe filter makes the following 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, we truncate it; otherwise, we output it as is.
Tips and precautions for use
- The test is crucialIt is recommended to thoroughly test in the development environment before applying any truncation filters, to ensure that the truncation effect meets expectations, especially for Chinese and HTML content.
- Select 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 truncating too much and causing information loss, or truncating too little and making the effect not prominent.
- The specificity of Chinese content:
truncatewordsMainly for English, because it relies on spaces to distinguish 'words'. For Chinese content, since there is a lack of a natural word separator,truncatewordsMay treat the entire sentence as a 'word', or judge according to punctuation, the effect may not be as good.truncatecharsTherefore, when processing Chinese,truncatecharsis usually a safer choice. - HTML content and
|safe: It is emphasized again that any truncation filter with_htmlsuffix needs to be added immediately after it|safeFilter, otherwise the HTML tags will be escaped as text instead of being parsed by the browser.
Summary
AnQiCMS's template engine considers the details of content display carefully,truncatechars/truncatewordsCombined with its HTML version,|safeFilters such as these can help you easily implement intelligent text truncation.This not only effectively enhances the aesthetics and layout of the website page, but also optimizes the user reading experience, presenting your content in the most suitable form to visitors.In content operation, making good use of these template functions will greatly improve work efficiency and the professionalism of the website content.
Common Questions (FAQ)
truncatecharsandtruncatewordsWhat is the difference for Chinese content?truncatecharsIt truncates by character count and applies to both Chinese and English, accurately calculating the length of each character (including Chinese characters) and truncating when reaching the specified number.truncatewordsIt is truncated by word count, mainly designed for English as it depends on spaces or punctuation to distinguish words. For continuous Chinese text,truncatewordsMay consider it as a long "word" and unable to truncate as expected, or the truncation point is not very consistent with Chinese reading habits. Therefore, it is usually recommended to usetruncatecharsTo achieve more precise and controllable truncation effects.Why do you need to add
truncatechars_htmlortruncatewords_htmlwhen using|safeFilter?AnQiCMS template engine defaults to HTML-escape all output variable content to prevent potential cross-site scripting (XSS) attacks. This means that if your variable contains<h1>Such HTML tags, when output by default, will be converted to<h1>Therefore, they are displayed as plain text rather than being parsed by the browser as headings.truncatechars_htmlandtruncatewords_htmlAlthough the internal logic attempts to preserve the HTML structure, the final output is still affected by the template engine's escaping mechanism. Therefore, adding|safeThe filter tells the template engine that this part of the content is known and safe HTML, which does not require escaping and can be directly parsed by the browser, ensuring that formatted text is displayed correctly.Can the ellipsis (…) after text truncation be customized? For example, can it be replaced with “[View More]”?Built-in to AnQiCMS
truncatecharsandtruncatewordsThe filter defaults to using a fixed ellipsis (…) as the truncation marker, and there is no direct parameter provided in the document to modify this default marker. If you need to customize the truncation marker, you can combinelengthImplement filters and condition judgments manually.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.{% 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 note, replace manually
...may not be as good astruncatecharsThe smart handling of ellipsis characters is implemented internally. A more precise approach is to first truncate the required length of the string, and then manually judge whether a custom marker needs to be added.{% 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 offers greater flexibility, but requires you to manage length calculations more finely, especially when the content includes HTML, which can become complex.