How do the `truncatechars` and `truncatewords` filters control the truncation display of long text and add an ellipsis?

Calendar 👁️ 80

In website content operation, we often encounter such situations: In order to maintain the neatness and consistency of the page layout, we need to truncate long texts, such as in article lists or product summaries.If cut simply and brutally, it may not only lead to incomplete meaning of text, but may also destroy the structure of text containing HTML tags, affecting the beauty and function of the page.

Anqi CMS provides us with an elegant solution to this problem with its flexible template engine.By using a built-in text filter, we can easily control the display length of long text, and add ellipses at appropriate positions, thus optimizing the user interface without sacrificing the readability of the content.Today, let's delve into two very practical text processing tools:truncatecharsandtruncatewordsFilter, as well as their respective HTML-friendly versions.

truncatechars: Precision truncation by character.

truncatecharsThe filter can truncate text according to the number of characters you specify. It counts from the beginning of the text and truncates here once it reaches the number of characters you set, and automatically adds three ellipses at the end....)

For example, if you have a text such as: 'Anqi CMS is a powerful content management system.' and you want to display only the first 10 characters, you can use it like this:

{{ "安企CMS是一个功能强大的内容管理系统。"|truncatechars:10 }}

This code's output will be: "AnQi CMS is a function..."

It should be noted that,truncatecharsWhen counting, the three ellipses added at the end are also counted in the total number of characters you set.This means that if you set the truncation to 10 characters, the actual number of content characters displayed will be 7 characters plus 3 ellipses.

Considerations when text contains HTML tags:truncatechars_html

If your text content contains something like<b>(bold),<em>(italic) or<p>(Paragraph) such HTML tags should be used directlytruncatecharsMay cause the HTML structure to be destroyed, for example, tags are not properly closed, which may cause page display anomalies.

In order to avoid this situation, Anqi CMS providestruncatechars_htmlFilter. It can intelligently parse HTML structure, ensuring that all open tags are correctly closed during truncation, thereby protecting the integrity of the page.

For example, a text with HTML tags:“<p><b>安企CMS</b>是一个功能强大的内容管理系统,致力于提供高效解决方案。</p>To truncate the first 25 characters while maintaining the HTML structure, you can use:“

{{ "<p><b>安企CMS</b>是一个功能强大的内容管理系统,致力于提供高效解决方案。</p>"|truncatechars_html:25 }}

The output will be:“<p><b>安企CMS</b>是一个功能强大...</p>"

You can see, even after truncation,<b>and<p>the tag still received the correct closing, avoiding page errors.

truncatewords: Intelligent truncation by word

withtruncatecharsTruncation by character is different,truncatewordsThe filter is based on the number of words to truncate the text. This is especially useful for English content, as it can maintain the integrity of each word, avoiding half words, and making the truncated text more readable.

For example, if you have an English text such as 'AnQiCMS is a powerful content management system.', and you want to display only the first 3 words, you can use it like this:

{{ "AnQiCMS is a powerful content management system."|truncatewords:3 }}

The output will be: “AnQiCMS is a…”

withtruncatecharsdifferent,truncatewordsWhen counting,Ellipses are not counted in word count.This means that if you set the truncation to 3 words, it will display 3 complete words followed by an ellipsis.

HTML text word truncation:truncatewords_html

Similarly, when HTML content needs to be truncated by word,truncatewords_htmlthe filter provides withtruncatechars_htmlA similar security mechanism. It recognizes and closes HTML tags within the text, and truncates it by word count.

For example, an English text containing HTML tags: <p><b>AnQiCMS</b> is a powerful content management system.</p>If you want to truncate the first 5 words and maintain the HTML structure:

{{ "<p><b>AnQiCMS</b> is a powerful content management system.</p>"|truncatewords_html:5 }}

The output will be: "<p><b>AnQiCMS</b> is a powerful content ...</p>"

Here, HTML tags are handled properly, and the text is also truncated by word count.

When and how to use these filters?

Choose which filter to use, depending on your specific needs and content characteristics.

  • When you need to strictly control the physical width of the display area.:truncatecharsortruncatechars_htmlIt is usually a better choice because it counts characters instead of words, ensuring a consistent visual length.This is particularly important on multilingual websites because there is a big difference in the length of words in different languages.
  • When you want to maintain the semantic integrity of the text.:truncatewordsortruncatewords_htmlIt is more suitable, especially when dealing with English content, as it can avoid broken words and make the text more natural.
  • Used in scenarios such as article summaries, product descriptions, comment previews, etc.These filters are all useful. They help you display key information within limited space and guide users to click for more details.
  • The most important point.:If your content may contain any HTML tags(such as bold, italic, links, etc.), pleaseAlways use the version_htmlwith suffixfor exampletruncatechars_htmlortruncatewords_htmlThis will ensure that the HTML tags are correctly closed during truncation, avoiding layout chaos or functional anomalies. Even if you are not sure if the content contains HTML, use_htmlVersion is also a safe practice.

In summary,truncatecharsandtruncatewordsAnd its HTML friendly version is a powerful tool for content operation of Anqi CMS.They can help you easily achieve fine-grained control over content display, enhancing the overall user experience and professionalism of the website.


Frequently Asked Questions (FAQ)

  1. Question: Is the ellipsis "..." included in the set length after truncation?Answer: It depends on the type of filter you are using. Fortruncatecharsandtruncatechars_htmlYes, ellipsis

Related articles

How does the `slice` filter accurately extract the specified part of a string or array for display?

In the daily content management of Anqi CMS, we often need to accurately trim the text or data list displayed on the website to better adapt to different layouts, provide content previews, or optimize the user reading experience.At this point, the `slice` filter has become a very practical tool, which can help us flexibly extract the specified part of a string or array.### Core Function: Basic Usage of `slice` Filter The `slice` filter is like a tailor, capable of cutting according to the "scissors" position you provide

2025-11-07

How `list` and `split` filters convert a string to an array and how to process it in a template?

In the powerful template system of Anqi CMS, flexible data processing is the key to building dynamic websites.At times, the data we retrieve from the backend, such as tags, keywords, or custom field values, may be stored as comma-separated strings, but we want to treat them as individual items in the frontend template.At this point, the `list` and `split` filters provided by Anq CMS are particularly important, as they help us convert strings into arrays, thereby enabling more refined control and display in templates.Why do we need to convert a string to an array

2025-11-07

How to effectively use `if` and `for` tags for conditional judgment and data looping in AnQiCMS templates?

In AnQiCMS template development, `if` and `for` tags are undoubtedly the core tools for building dynamic content and flexible layouts.They allow us to display content based on specific conditions or efficiently loop through data, thereby transforming static templates into rich, user-responsive pages.AnQiCMS uses syntax similar to the Django template engine, making these operations intuitive and powerful.

2025-11-07

How to dynamically generate a guestbook form with custom form field types using the `guestbook` tag?

It is crucial to provide a convenient user communication channel in modern website operations, and a message board is one of the efficient ways to do so.AnQiCMS (AnQiCMS) fully understands this need, through its powerful template tag system, especially the `guestbook` tag, allowing you to dynamically generate guestbook forms on your website flexibly, and easily customize form fields to meet various business scenarios.

2025-11-07

How do the `urlize` and `urlizetrunc` filters automatically convert URLs in text to clickable links?

It is crucial to present information efficiently and aesthetically in website content operations.Especially when the content contains a large number of URLs or email addresses, manually converting them into clickable links is not only inefficient but also prone to errors.AnQiCMS (AnQiCMS) is well-versed in this, its template system provides the practical filters `urlize` and `urlizetrunc`, which can automatically identify URLs in text and intelligently convert them into clickable hyperlinks, greatly enhancing user experience and content management efficiency.###

2025-11-07

In which scenarios must the `safe` filter be used to prevent HTML content from being automatically escaped?

When using AnQiCMS for website content management and template development, we often encounter a problem related to HTML content display: Why does the rich text content I edit in the background display as a pile of original code with angle brackets on the front end, rather than a beautifully formatted effect?This is actually the "auto-escape" mechanism of AnQiCMS template engine at work, and to solve this problem, the `safe` filter has become the key tool we must master.### Why does automatic escaping occur? AnQiCMS

2025-11-07

How do the `removetags` and `striptags` filters remove specific or all HTML tags from HTML content?

In Anqi CMS, when managing website content, we often encounter such situations: articles imported from outside, comments submitted by users, or code generated by rich text editors may contain various HTML tags.These tags are sometimes necessary, but more often, they may disrupt the page layout, introduce unnecessary styles, and even pose potential security risks. 幸运的是,AnQiCMS provides two very practical template filters —— `removetags` and `striptags`

2025-11-07

How does the `add` filter work for adding numbers or concatenating strings in templates?

In AnQi CMS template design, we often need to perform some simple data processing, such as adding several numbers to display the total sum, or combining different text fragments into a complete sentence.At this time, the `add` filter is particularly convenient, as it is like a universal connector, capable of handling everything from arithmetic operations on numbers to the combination of text, making your template more flexible and dynamic.

2025-11-07