What are the differences in the truncation logic of the `truncatewords` and `truncatechars` filters when truncating the abstract of an AnQi CMS article?

Calendar 👁️ 65

In AnQi CMS, in order to display the article summary on the list page or preview area, we often need to截取 article content. At this time,truncatewordsandtruncatecharsThese filters come into play.They can all help us condense long content, but there are significant differences in the truncation logic between them, especially when dealing with Chinese and English characters and words, their performance is even more different.Understanding these differences can help us better control the presentation effect of the summary.

truncatechars: precise character-based extraction of the summary

truncatecharsThe principle of the filter's operation is relatively straightforward: it starts counting characters from the beginning of the content one by one until it reaches the specified length. Once the set length is reached, the remaining content is truncated and an ellipsis is automatically added at the end (...)

Whether it is English characters, numbers, or Chinese characters,truncatecharsthey are all counted as independent characters. This means that if you set to extract 10 characters:

  • For English content, it may be truncated in the middle of a word, for example, after extracting 10 characters from “AnQiCMS is powerful”, it may become “AnQiCMS i…”.
  • For Chinese content, it accurately extracts the first 10 Chinese characters, for example, “AnQi CMS is a high-efficient and powerful content management system” is extracted to “AnQi CMS is a high-efficient and powerful content management…”.

Therefore, if you have a strict character count limit for the summary and do not mind content being cut off in the middle of a word, thentruncatecharsis an accurate and reliable choice.

truncatewords: Extract the summary by word logic

withtruncatecharsdifferent,truncatewordsThe filter focuses on "words" rather than individual characters.It will identify words based on spaces in the content and count the number of words.When the specified number of words is reached, the content will be truncated, and an ellipsis will be added at the end.

This logic of cutting words by words is very practical when processing English content.Because it ensures that the extracted summary is always composed of complete words, avoiding the appearance of half-words due to truncation.For example, after extracting 5 words from “AnQiCMS is a powerful and flexible system”, we get “AnQiCMS is a powerful and…”.}]

However, when processing Chinese content,truncatewordsThe performance does not seem ideal. Since the Chinese sentence structure usually does not have the "words" separated by spaces like English,truncatewordsThe filter tends to treat a continuous segment of Chinese text as a 'large word'. This means that if you try to usetruncatewordsExtracting Chinese content may not be able to split Chinese sentences into meaningful segments as expected, and may even retain the entire sentence, failing to achieve the desired extraction effect.For example, 'AnQi CMS is an efficient and powerful content management system' Even if set to extract 5 words, the result may still be a complete sentence because the entire sentence is recognized as a single 'word' or cannot be effectively split.

to take into account the HTML structure extraction:_htmlVariant

It is noteworthy that AnQi CMS also providestruncatechars_htmlandtruncatewords_htmlThese special filters. It is strongly recommended to use the one with HTML tags when your article abstract may contain elements such as images, links, bold text, etc._htmlThe variant suffix.

These_htmlThe filter intelligently handles HTML tags while extracting characters or words, ensuring that the extracted content still maintains a valid HTML structure and avoids displaying errors due to unclosed tags. Imagine if your summary was cut off in the middle of a sentence.<p>tags or<a>Tags in the middle, and_htmlVariants will help you close tags correctly, ensuring the correct rendering of the page.

Actual application scenarios and selection suggestions

When choosing to usetruncatecharsOrtruncatewordsAt that time, we need to consider the following aspects:

  • Content language:
    • If your website mainly publishesEnglish contentand hope that the abstract can maintain the integrity of the words,truncatewordsIs a better choice. If you pay more attention to the control of the total length of characters,truncatecharsit is more accurate.
    • If your website mainly publishesChinese contentthentruncatecharsusually provides a more expected truncation effect. Due to the characteristics of the Chinese language,truncatewordsThe logic for truncating Chinese content may not work according to our 'Chinese word' concept.
  • Truncation accuracy requirement:
    • When it is necessary to strictly control the number of characters, selecttruncatechars.
    • Select when the word integrity needs to be maintained (limited to English)truncatewords.
  • Does the content contain HTML?:
    • If the abstract is extracted directly from a rich text editor, it is likely to contain HTML tags. To avoid destroying the page layout of the abstract, it is essential to choosetruncatechars_htmlortruncatewords_html.

By understanding these differences, we can be more flexible and accurate in extracting article summaries in Anqi CMS, improving the user reading experience, and ensuring the good presentation of page content.


Frequently Asked Questions (FAQ)

Q1:truncatewordsIs there an alternative solution when the filter does not perform well in truncating Chinese content?A1: Yes, whentruncatewordsWhen the ideal word segmentation effect cannot be achieved for Chinese content, the most direct and effective alternative is to usetruncatecharsfilter.truncatecharsIt will cut according to the number of Chinese characters you specify, although it may not be able to split according to the "word" boundary of Chinese intelligently, but it can ensure that the length of the summary meets the expectation.If you want a more intelligent Chinese word segmentation summary, you may need to integrate a more complex Chinese word segmentation library on the backend, but this usually goes beyond the scope of the template filter.

Q2: How to determine if there is more content in the extracted article summary so that the 'Read More' link can be displayed?A2: In the template, you usually need to get the full content (or original length) of the article and the extracted abstract content, and then compare their lengths.If the length of the extracted summary is less than the length of the full content, it means there is more content available, and a "Read More" link can be displayed.{{ article.Description|length }}(The length of the original introduction) and{{ article.Content|truncatechars:100|length }}(The length of the extracted summary), or directly compare the original content with the extracted content for equality.

Q3: Will using these summary extraction filters affect SEO?A3: Using the summary truncation filter reasonably has a positive impact on SEO.The abstract can provide a brief overview of the page content for search engines, which helps search engines understand the theme of the page.Must be used.truncatechars_htmlortruncatewords_htmlHandle it to avoid breaking the HTML structureA tidy, semantically correct page is always more beneficial for SEO. At the same time, ensure that the full article content can be indexed by search engines on the detail page.

Related articles

How to safely use the `truncatechars_html` filter in Anqi CMS template to truncate HTML rich text content and automatically close tags?

In website content operation, we often need to display the partial content of articles, products, or single pages on list pages, abstract areas, or specific blocks.This content is often rich text that includes HTML tags. Simply truncating by character count may cause the HTML tags to be cut off, thereby破坏页面布局和显示效果.For example, a `<p>This is a paragraph<strong id=“test”>bold</span>` content that is abruptly truncated may cause the page to display unclosed tags.

2025-11-08

How to format Unix timestamp to 'YYYY-MM-DD HH:MM' and other localized date strings using the `stampToDate` filter in AnQi CMS?

In website content management, the display of date and time information is ubiquitous.Whether it is the publication time of the article, the listing date of the product, or the submission time of the comments, a clear and readable date format is crucial for improving user experience.AnQiCMS (AnQiCMS) fully understands this need and provides powerful template tags and filters, among which the `stampToDate` filter is a powerful tool to convert the original Unix timestamp into a localized date string that we are familiar with.This article will delve into the usage of the `stampToDate` filter

2025-11-08

In addition to `stampToDate`, how can the `date` filter of Anqi CMS implement custom date and time formatting when handling `time.Time` type?

In Anqi CMS, the display of dates and times often needs to be adjusted flexibly according to the actual needs of the website.We all know that the `stampToDate` filter is very convenient for handling Unix timestamps, as it can easily convert a string of numeric timestamps into the date format we need.But sometimes, the date value we handle in the template may already be a `time.Time` type object in Go language, rather than the original timestamp.In this case, Anqi CMS provides another powerful tool, that is `date`

2025-11-08

How to use the `divisibleby` filter in AnQi CMS template to achieve alternate row coloring or group output every N elements?

In website operation, a well-designed page layout and content display can significantly improve user experience and readability.Especially in scenarios with a long list of items, if all entries are presented in the same style, it is easy to cause visual fatigue.At this time, alternating line colors or grouping by a specific quantity can well solve these problems.

2025-11-08

How to use `upper`, `lower`, `capfirst`, and `title` filters to unify the English title case format of the CMS frontend page?

In website operation, the professionalism and consistency of content display are crucial for improving user experience and brand image.Especially when dealing with English titles, consistent capitalization not only makes the page look neater, but also indirectly affects the readability of the content.AnQiCMS (AnQiCMS) relies on the powerful features of the Django template engine and provides several very practical filters to help us easily format the case of English titles on the front-end page.

2025-11-08

How to efficiently remove specific punctuation marks or spaces from a string using the `cut` filter in the Anqi CMS template to clean up the output content?

In the daily operation of AnQi CMS, we often encounter situations where we need to refine the content output by templates.To make the page display cleaner, improve the user reading experience, or generate URLs that are more beneficial for SEO, removing unnecessary punctuation or extra spaces from strings is a very practical skill.The powerful template engine of Anqi CMS provides a rich set of filters to help us achieve these goals, among which, the `cut` filter is a simple yet extremely efficient tool.### `cut` filter

2025-11-08

How does the `add` filter in the Anqi CMS template implement the mixing of numbers and strings and how to handle type mismatches?

AnQiCMS (AnQiCMS) provides flexible and powerful tools for content creators and website developers with its Django-like template engine syntax.When building dynamic web content, we often need to combine different types of data (such as numbers and strings) together to form the final display effect.At this time, the `add` filter in the Anqi CMS template can come in handy.

2025-11-08

The `addslashes` filter in AnQi CMS, how to escape a string that may contain special characters to safely insert into JS or HTML attribute values?

In the daily operation of Anqi CMS, we often need to display the dynamic content stored in the database on the front end of the website.This content may come from user input, data scraping, or other channels, and it is inevitable that it will contain some special characters.If these special characters are not handled properly and directly inserted into JavaScript code or HTML attribute values, it may cause page layout chaos, functionality failure, and even serious security risks, such as cross-site scripting attacks (XSS).

2025-11-08