How to handle truncation and add an ellipsis when truncating text with `truncatechars` and `truncatewords` filters, including HTML content?

Calendar 👁️ 59

In the increasingly fragmented information consumption era, the presentation of website content directly affects user experience.Whether it is the abstract of an article list, the preview of a product introduction, or various information stream cards, we need to convey the core information within a limited space while maintaining the page's cleanliness and the unity of layout.This brings up the need for text truncation. AnQiCMS, as a fully functional content management system, is well-versed in this and provides us with a powerful text truncation filter, especially its intelligent handling of HTML content, making content operation more relaxed.

The basics of text truncation:truncatecharswithtruncatewords

AnQiCMS template engine provides two basic text truncation methods:truncatecharsandtruncatewordsThey are each suited to different scenarios, understanding their differences is the first step in efficient content operation.

  • truncatecharsFilter: Precisely truncate by characterAs the name implies,truncatecharsThe filter is specified based on theCharacter countTo truncate text. Regardless of the content being in English, Chinese, or other languages, it will precisely cut the text to the character length you set and automatically add an ellipsis in the exceeded part(...For example, if you have a long title that needs to be displayed within a fixed number of characters, thentruncatecharsis the ideal choice.

    Example:Suppose there is some text"欢迎使用安企CMS,这是一个强大的内容管理系统!"If you use{{ 文本 | truncatechars:10 }}The output will be"欢迎使用安企CM..."You can see that the ellipsis is also counted in the total length.

  • truncatewordsFilter: Truncation based on single-word semanticsAndtruncatewordsThe filter then changed the truncation unit from a single character to 'word'.It will truncate based on the number of words in the text and add an ellipsis when it exceeds the specified number of words.This approach emphasizes the readability and semantic integrity of text, especially for English content, as it avoids truncating in the middle of a word.For Chinese and other non-space-separated languages, it processes according to its internal logic or directly by character (in AnQiCMS, it tends to identify continuous non-space character blocks as 'words').

    Example:Suppose there is some text"AnQiCMS is a powerful content management system for enterprises."If you use{{ 文本 | truncatewords:5 }}The output will be"AnQiCMS is a powerful content...".

Challenge and solution: Intelligent truncation of HTML content

In the actual content of a website, we rarely deal with plain text. Article summaries, product descriptions often include<strong>/<em>/<p>/<a>HTML tags, even images<img>tags. If you simply usetruncatecharsortruncatewordsTruncating content containing HTML can lead to unclosed tags, layout chaos, and even JavaScript errors.

AnQiCMS has fully considered this pain point and providedtruncatechars_htmlandtruncatewords_htmlthese advanced filters.

  • truncatechars_htmlandtruncatewords_htmlthe intelligence of itthese with_htmlThe suffix filter, its core intelligence lies in, while performing truncation operations, it willintelligently parse and process HTML tags. This means:

    1. Maintain the integrity of the HTML structure:The filter recognizes HTML tags within the content. Even if the truncation point falls in the middle of a tag, it ensures that all open tags are properly closed at the truncation point, thus preventing damage to the page structure.
    2. Avoid destroying media content:For<img>or<video>Self-closing or paired tags, the filter will not truncate within the tags but will do so before or after them to ensure the complete display or correct referencing of media content.
    3. Add ellipsis automatically:Just like the basic filter, when the content exceeds the specified length, it will also automatically add ellipses.

    Example:Suppose there is HTML content:"<p><strong>这是</strong>一段<em>很长的</em>测试文本,其中包含了一些HTML标签和<a href='#'>链接</a>,我们希望它在截断后依然保持美观。</p>"

    If you use{{ HTML内容 | truncatechars_html:20 }}The output might be:"<p><strong>这是</strong>一段<em>很长的</em>测试文本...</p>"(Please note that the actual output length may vary slightly due to the number of characters in the tags, but the key point is<strong>/<em>/<p>All tags are properly closed, the link may be truncated or retained, depending on the truncation point and internal logic.

    If you use{{ HTML内容 | truncatewords_html:5 }}The output may be: "<p><strong>这是</strong>一段<em>很长的</em>测试...</p>"Similarly, the HTML structure is preserved.

How to choose the appropriate filter?

Choosing the correct filter depends on your specific needs:

  1. If the content is plain text (or you do not care about the HTML structure):

    • The character count needs to be strictly controlled(For example, a fixed-size text box): Selecttruncatechars.
    • Need to truncate by semantic units, with more emphasis on readability(For example, English article abstract): Selecttruncatewords.
  2. If the content may contain HTML tags:

    • In any case, priority should be given to choosingtruncatechars_htmlortruncatewords_html.This is the key to ensuring that your website remains beautiful and functional after truncating content.
    • If neededCount to characters: Use.truncatechars_html.
    • If neededCount to words: Use.truncatewords_html.

Through these flexible and intelligent text truncation filters provided by AnQiCMS, you do not need to manually clean up HTML tags or worry about page rendering issues after truncation.They work silently behind the scenes, ensuring that your website presents itself neatly, professionally, and without error to visitors in any situation, greatly enhancing the efficiency of content operations and the user experience of the website.


Frequently Asked Questions (FAQ)

Q1: If the truncation length I set is longer than the actual length of the original text, how will the filter handle it? Will it still add an ellipsis?

A1:Will not. If the number of characters (or words, depending on the filter you use) of the original text does not exceed the truncation length you set, then the filter will not perform any truncation operation and will not add an ellipsis at the end of the text.It will directly output the original complete text.

Q2:_htmlCan the filter handle deeply nested HTML structures or HTML content that itself has some formatting errors?

A2: _htmlThe filter is designed to handle complex HTML structures, including nested tags, and will strive to keep them properly closed.For some minor format errors, it can usually be repaired and truncated.However, if the HTML content itself has severe and non-repairable structural issues, or the tag nesting level is extremely deep, it may still produce unexpected results.When publishing content on the content management backend, it is recommended to use a rich text editor to ensure the standardization of HTML format.

Q3: Truncate length (numberDoes the parameter contain the length of the ellipsis added at the end?

A3:Yes, it is intruncatecharsandtruncatechars_htmlthe filter you specifiednumberThe length represented by the parameter isincludeThe ellipsis added finally (...). This means that if set to10The total length of the truncated text plus the ellipsis is roughly 10 characters (one Chinese character counts as one character, and the ellipsis takes up three characters).

Related articles

How do the `trim`, `trimLeft`, and `trimRight` filters remove spaces or specific characters from the beginning or end of a string?

In website operation and content management, we often encounter the need for string processing, especially in data entry, content display, or API interaction.For example, the user may have mistakenly entered multiple spaces before and after the text box, or some data may have been sourced with unnecessary specific characters.These seemingly minor issues may affect the layout and aesthetics of the content, even causing functional abnormalities.The AnQi CMS template engine provides a series of powerful filters to help us easily deal with these string cleaning tasks.Today, let's get to know the three very practical filters: `trim`

2025-11-08

How to get the thumbnail version of the image according to the image address using the `thumb` filter in the Anqi CMS template?

In website content management, the effective use of images is crucial for improving user experience and page loading speed.AnQiCMS deeply understands this, providing powerful image processing functions, among which the `thumb` filter is a tool that helps us easily obtain the thumbnail version of images.Why thumbnails are so important?Imagine if all the images on your website loaded in their original high-definition large size, how heavy the page would become!

2025-11-08

How does the `stringformat` filter customize the formatted output of any variable like Golang's `fmt.Sprintf()`?

In content operation, the way content is presented often determines the first impression and reading experience of users.Sometimes, simple variable output cannot meet our needs for fine-grained data formatting display, such as retaining fixed decimal places for numbers or adding specific text before output.AnQi CMS provides powerful content rendering capabilities for template developers and content operators, and the `stringformat` filter is a key tool for achieving refined output.It is like the `fmt.Sprintf()` function in Go language, which can format the output of any variable according to custom specifications

2025-11-08

How `split` and `make_list` filters split a string into an array by a specified delimiter or character?

In Anqi CMS template development, flexibly handling string data is an indispensable skill for building dynamic pages.Sometimes, we need to split a long string into a data list using a specified character or string as a delimiter (which is what we commonly call an array);At other times, we may need to process each character of the string independently.AnQi CMS provides two very practical filters: `split` and `make_list`, which can help us easily meet these needs.###

2025-11-08

How to safely truncate text with HTML tags using `truncatechars_html` and `truncatewords_html` filters to prevent structure damage?

In website content operation, we often need to display the summary or part of the content in different scenarios, such as on the list page, search results, or related recommendations.This is when you need to truncate the content.If the content is plain text, a simple character or word cutter can handle the task well.However, when the content is rich in HTML tags, the problem becomes complex: directly cutting may cause the HTML tags to be truncated, thereby destroying the page structure, causing display errors, and even affecting the user experience.

2025-11-08

What are the differences between the `urlencode` and `iriencode` filters in URL parameter encoding, and which scenarios are they applicable to?

In website operation, the construction and processing of URL (Uniform Resource Locator) is a fundamental and critical task.It is crucial to properly encode URLs when dynamically generating links, handling user input as parameters, as it ensures the validity of the links, prevents garbled text, and potential security issues.AnQiCMS provides the `urlencode` and `iriencode` filters to help us better manage special characters in URLs.Although they are all used for encoding, their application scenarios and processing methods are different.

2025-11-08

How `urlize` and `urlizetrunc` filters automatically convert URLs and email addresses in text to clickable hyperlinks?

How to efficiently and beautifully convert text containing URLs and email addresses into clickable hyperlinks when managing website content in AnQi CMS, is a concern for many content operators.Manually adding the `<a>` tag to each URL or email is not only time-consuming and labor-intensive but also prone to errors.Luckily, AnQi CMS provides two very practical template filters——`urlize` and `urlizetrunc`, which can automatically complete this task and greatly improve the efficiency and user experience of content publishing.### `urlize`

2025-11-08

How to calculate the number of words in a string with the `wordcount` filter in Anqi CMS template?

When processing text content in the AnQi CMS template, we often need to perform various operations on strings, such as counting words, cutting content, and so on.Among them, calculating the number of words in a string is a common requirement, which is very useful in content analysis, SEO optimization, and even estimating the reading time of an article.AnQi CMS provides a simple and powerful tool——`wordcount` filter.### `wordcount` filter: Core functionality and purpose The `wordcount` filter is specifically used to count the number of words in a given string

2025-11-08