Extract the article summary by word count instead of character count, which filter should be used in the template?

Calendar 👁️ 77

In website content operation, the way articles are summarized often directly affects readers' click intention and reading experience.A clear, concise, and meaningful abstract that helps readers quickly understand the main theme of the article.Especially in scenarios such as list pages and recommendation areas, we usually hope that the abstract can be intelligently extracted, controlling the length while maintaining readability.

When it comes to generating abstracts based on article content, truncation length is a core consideration.There are two common ways to truncate: by character count and by word count.Truncating by character count is precise, but it often results in words being abruptly cut off, affecting the readability.While truncating by word count can better maintain semantic integrity, making the abstract more natural for readers.

For AnQiCMS users, the system is based on Django template engine syntax, providing strong flexibility. We can easily achieve the need to truncate the article summary by word count using built-in filters. This feature mainly depends ontruncatewordsfilter.

truncatewordsFilter: Smart extract summary by word

truncatewordsA filter specifically designed to truncate strings based on word count, it intelligently truncates at word boundaries to ensure that each truncated word is complete, greatly enhancing the reading experience of the summary. This is different from truncating by characters (such astruncatecharsThe filter may cause words to be cut off halfwaytruncatewordsMore emphasis on semantic coherence

How to usetruncatewordsFilter?

In the template files of AnQiCMS, for example, while you are editing an article list page, througharchiveListAfter obtaining article data, the label will usually traversearchiveseach element in the setitemto display the article information. The summary or abstract of the article is generally stored initem.Descriptionin the field.

to beitem.DescriptionTruncate to a specified number of words, just use it like this:

{{ item.Description|truncatewords:30 }}

In this example,30Indicate that you want the abstract to be truncated to the first 30 words. The system will automatically handle the truncation logic and add an ellipsis ("...") at the end of the content to make the abstract look more complete and professional.

Handle content that includes HTML tags:truncatewords_html

Sometimes, the summary content you have may not be plain text, but is directly taken from the articleitem.Contentpart, anditem.ContentMay contain various HTML tags (such as<strong>/<em>/<p>etc.). If a string containing HTML tags is used directlytruncatewords, it may damage the HTML structure, causing the page to display abnormally.

To deal with this situation, AnQiCMS provides another very practical filter:truncatewords_html. This filter is withtruncatewordsIt functions similarly, but it will intelligently identify and process HTML tags, maintaining tag integrity while extracting content to avoid display errors on the page.

When you need to extract an abstract that may contain HTML tags, you can use it like this:

{{ item.Content|truncatewords_html:50|safe }}

here,50It indicates that the first 50 words are to be extracted. It is especially important to note that, due totruncatewords_htmlThe result is still HTML, to ensure that the browser correctly parses and displays these tags, you need to add it at the end of the filter chain|safe.|safeThe filter tells the template engine that this content is safe and does not need to be automatically escaped, thus allowing HTML tags to be rendered normally.

Tip and **Practice:

  • Select the appropriate word count:The length of the abstract does not have a fixed standard, usually 30 to 50 words is a common range.You can try different values based on the overall design of the website, the target audience, and the type of content to find the balance that best attracts readers.
  • Preview and adjust:In practical applicationtruncatewordsortruncatewords_htmlMake sure to preview the effect on different devices (PC, mobile) to ensure that the abstract is presented beautifully and clearly on various screen sizes.
  • withtruncatecharsThe difference is:AlthoughtruncatecharsIt can also extract text, but it calculates by character count, which may break a word in the middle. Compared to,truncatewordsandtruncatewords_htmlPay more attention to the integrity of words, it is a better choice in scenarios where it is necessary to maintain the readability of the text.

Bytruncatewordsandtruncatewords_htmlThese flexible and powerful filters make AnQiCMS summary generation both intelligent and beautiful, helping you present content better and attract readers.


Frequently Asked Questions (FAQ)

  1. Question:truncatewordsIs an ellipsis automatically added after truncation? Can the style or content of the ellipsis be modified? Answer:Yes,truncatewordsandtruncatewords_htmlThe filter automatically adds an ellipsis ("...") at the end after truncating the content.According to the AnQiCMS documentation, this ellipsis is a built-in 'translatable ellipsis sequence', and the document does not mention the option to directly customize the content or style of the ellipsis through filter parameters.If you need a very special ellipsis display, it may be necessary to use CSS or other JavaScript for style overlay or post-processing.

  2. Question: If the abstract of my article is too short, it does not reachtruncatewordsWhat is the number of words set, will it also add an ellipsis? Answer:No.truncatewordsThe filter will only truncate content that exceeds the set word count and add an ellipsis. For example, if the original content isitem.DescriptionThe number of words in the phrase itself is less than the number of words you have set to extract (for example30), then the content will be output as is without adding an ellipsis to maintain the integrity of the content.

  3. Question:truncatewords_htmlDoes the filter retain all tags when processing HTML content? For example, like<div>such block-level tags? Answer: truncatewords_htmlThe filter intelligently tries to preserve the integrity of the HTML structure during the extraction process, which means it will close tags as much as possible to avoid page errors.But it does not retain all tags and their styles.Its main purpose is to prevent HTML syntax errors caused by truncation, rather than retaining the rendering effect of all original HTML.For complex HTML structures, it is recommended to directly edit the summary field in the background management interface, providing a clean and concise HTML snippet or plain text as a summary, so that the front-end display will be more controllable.

Related articles

How to safely extract the content of an article containing HTML tags without destroying its structure?

In website content management and display, we often need to display the partial content of articles in article lists, homepage summaries, or related recommendation areas to attract readers to click.However, directly truncating the content of an article containing HTML tags can easily disrupt the original HTML structure, causing the page to display incorrectly and even affecting the overall layout and user experience.AnQiCMS (AnQiCMS) fully understands this pain point, its powerful template engine and built-in filters provide an elegant and secure solution, allowing you to worry-free about display issues caused by content truncation. Next

2025-11-09

How to extract the article title and display an ellipsis in Anqi CMS template?

In AnQi CMS template development, it is often encountered that article titles need to be displayed on the list page, but in order to ensure the beauty of the layout and unified layout, long titles need to be truncated and abbreviated with an ellipsis.This has improved the user experience and also made the page look cleaner and more professional.AnQi CMS with its flexible Django template engine syntax makes it very direct and efficient to implement this requirement.

2025-11-09

How to use AnQiCMS's 'Flexible Content Model' to customize the display structure and fields of articles, products, and other content?

## The secret of AnQiCMS content model: Creating a unique content display structure In the world of content management, website content is not uniform.The structure and fields of a blog article, as well as the description of an e-commerce product page, or the presentation of corporate event information, are often quite different.Traditional CMS systems may only provide fixed article or page templates, and once business needs change, the website seems to be struggling, and it is difficult to respond flexibly.However, AnQiCMS solves this pain point with its 'flexible content model' feature, allowing you to meet your actual business needs

2025-11-09

How to display a specific prompt to the visiting user when AnQiCMS is in shutdown mode?

During the use of the AnQiCMS website management, we occasionally encounter situations where we need to temporarily shut down the website, such as system upgrades, content maintenance, or data migration, etc.How can one clearly display specific prompts to the visiting user at this time, rather than a cold error page, which is particularly important.Our AnQi CMS is well-versed in this, providing us with a very user-friendly shutdown prompt function that allows the website to maintain a professional image even when temporarily 'resting'.Why do we need customized exit pop-ups?Imagine

2025-11-09

How to prevent XSS attacks and correctly escape HTML special characters when outputting article content in a template?

Managing and displaying content in AnQiCMS is the core task of website operation, but it is also crucial to ensure that these contents are presented safely and securely to users.Among them, cross-site scripting (XSS) attacks are a risk that should not be ignored, which may allow malicious code to be executed in the user's browser accessing your website, thereby triggering a series of security issues, such as stealing user data, tampering with page content, and even hijacking user sessions.

2025-11-09

How to automatically convert line breaks in user input plain text content to the HTML `<br/>` tag?

In daily website content operations, we often need to enter some multi-line text content in the Anqi CMS backend, such as the introduction of articles, the characteristics of products, or detailed descriptions in custom fields.This content is usually entered in plain text format, however, when we expect them to be displayed on the front-end web page with the original paragraph and line break effects, we find that they are often cramped into a line, losing their original formatting.This is not a problem with the AnQi CMS system itself, but a characteristic of the HTML web page rendering mechanism.in HTML

2025-11-09

How to count the number of times a specific keyword appears in the title or description of an article?

As users of Anqi CMS, we often need to manage and analyze website content in a refined manner, one common requirement being to count the frequency of specific keywords in article titles or descriptions.This not only helps us understand the effectiveness of content marketing, optimize SEO strategies, but also better grasp user concerns.AnQi CMS with its flexible template engine and rich built-in filters makes this operation feasible at the front-end template level.

2025-11-09

How to configure multiple sites in AnQiCMS to achieve independent display of content under different domain names?

AnQiCMS provides powerful multi-site management features, allowing you to easily operate multiple independent websites on the same system, each with its own domain and content.This is undoubtedly a very convenient and efficient solution for operators who have multiple brands, sub-sites, or need to provide differentiated content for different audience groups.Through a unified backend management entry, you do not have to deploy a separate system for each site, which greatly simplifies the operation and maintenance work, while also ensuring the complete independence of the front-end content display.Next, we will discuss in detail how to use AnQiCMS

2025-11-09