Template content shows: How does the `truncatewords` filter truncate text by word count?

Calendar 👁️ 69

In the presentation of website content, we often need to condense lengthy text information to meet different layout requirements, such as displaying article summaries on list pages, brief descriptions on product cards, and so on.This not only makes the page look neater, but also helps visitors quickly grasp the core information.AnQiCMS (AnQiCMS) provides flexible template filters for such needs, among which,truncatewordsThe filter is a powerful assistant that truncates text based on word count.

Skillfully concise, making the content clear at a glance:truncatewordsFilter parsing

truncatewordsThe filter, as its name suggests, is mainly designed to truncate based on the number of words in the text. When the number of words in the original text exceeds the threshold you set, it will intelligently cut off at the end of the last complete word and automatically add an ellipsis at the end of the text (...This approach is clever in that it respects the integrity of words, avoiding the possibility of half-words or unclear semantics that could arise from character truncation, thus significantly improving readability.

How to usetruncatewords?

Using in Anqi CMS template,truncatewordsThe filter is very intuitive. You just need to pass the text variable to be processed through the pipe symbol|to the filter and specify the number of words you want to keep.

The basic syntax structure is as follows:

{{ text_variable|truncatewords:number }}

Heretext_variableIs the text content you want to truncate (such as article descriptionitem.Description),whilenumberThen it is the number of words you want to retain

Let's understand how it works through some specific examples:

Example 1: Truncating English text words

Assuming your text content is"This is a long test which will be cutted after some words.", if you want to keep the first 9 words:

{{ "This is a long test which will be cutted after some words."|truncatewords:9 }}

The output will be:This is a long test which will be cutted after some ...

Example 2: Truncating Chinese text words

For Chinese, Japanese, Korean and other languages that are not separated by spaces,truncatewordsThe filter's behavior is somewhat special. If the text does not contain spaces, the filter tends to treat the entire text as a 'word'.This means that it may not be truncated in the middle of the text unless you specify the number of words as 0.

Assuming your text content is"你好世界":

{{ "你好世界"|truncatewords:1 }}

the output is still:你好世界

This is because你好世界considered as a whole 'word.' But if the text contains spaces, for example"你好 世界":

{{ "你好 世界"|truncatewords:1 }}

The output may be:你好 ...

Therefore, when dealing with Chinese and other languages, if finer granularity truncation control is needed, it may be necessary to combine the actual text structure or consider using other filters.

Application scenarios in practice

truncatewordsFilters are widely used in website content operations:

  • Blog or news list page:When displaying the article list on the homepage or category page, the detailed content of each article may be long, which may make the page redundant. UsetruncatewordsIt can easily truncate the article description into an abstract of 30, 50 words, which can attract clicks while keeping the page neat.
  • Product display page:On e-commerce websites, if the product characteristics or brief introductions on the product list or search results page are too long, it will affect the user's browsing efficiency.Pass this filter to truncate the product description uniformly, ensuring that all cards or list items have consistent height, enhancing the visual experience.
  • Content recommendation module:In the sidebar or bottom content recommendation area, space is usually limited.truncatewordsCan help you quickly generate refined recommendation titles or summaries, improving the click-through rate of recommended content.

withtruncatecharsDifferences and choices

AnQi CMS also providestruncatecharsA filter that truncates text by specifying the number of characters. When should you choosetruncatewordsWhen to choosetruncatecharsWhat?

  • truncatewords:Consider maintaining the semantic integrity and independence of words.It is more suitable for scenarios that require displaying complete words and avoiding word segmentation to cause reading obstacles.The disadvantage is that the final character length cannot be controlled accurately.
  • truncatechars:Favor precise control of the final character length. It is more suitable for scenarios with strict display space constraints, even if truncation may occur in the middle of a word.

In general, if you place more emphasis on the readability and elegance of the content,truncatewordsit is a good choice. If there are strict requirements on character length,truncatecharsit is more suitable.

Process content containing HTML tags

It is worth noting that if your text content contains HTML tags (such as bolded or linked text generated by a rich text editor), use them directlytruncatewordsThe filter may disrupt the structure of HTML tags, resulting in abnormal display of the page.

In this case, Anqi CMS provides a special solution:truncatewords_htmlfilter.truncatewords_htmlCan intelligently parse and truncate HTML content, ensuring that all tags are properly closed to maintain the normal rendering of the page. When the truncated content may contain formatting, be sure to usetruncatewords_htmlTo ensure compatibility.

Summary

truncatewordsThe filter is a powerful and practical tool in Anqi CMS template, which can help you present text content summaries in an elegant and readable way, greatly enhancing the user experience and page aesthetics of the website. By understanding its working principle, and combiningtruncatecharsandtruncatewords_htmlThe feature, you can flexibly apply in different scenarios to create a more attractive website.


Frequently Asked Questions (FAQ)

1.truncatewordsandtruncatecharsWhat are the differences between filters? truncatewordsThe filter truncates the text based on the number of "words", it tries to preserve the integrity of the words, and adds an ellipsis after the last complete word. AndtruncatecharsThe filter truncates based on the number of "characters", regardless of whether it is in the middle of a word, it will truncate directly, and is usually used in scenarios where there are strict pixel or layout length restrictions on text.

2. What filter should I use if the content I need to truncate contains HTML tags?It is recommended to use for content containing HTML tags.truncatewords_htmlFilter. It can intelligently parse HTML structure, ensuring the correct closure of tags while truncating text, to avoid page layout chaos or display errors caused by truncation.Directly usetruncatewordsIt may destroy the HTML structure.

3.truncatewordsHow does the filter handle Chinese and other non-space-separated languages?For languages such as Chinese, Japanese, and Korean that do not have clear word spacing,truncatewordsThe filter usually considers a continuous segment of text as a 'word'.This means that if you set the word count to zero, it may not truncate in the middle of the text, but instead display the entire text unless the text contains spaces.In this case, if you need to control the truncation length precisely, you may need to consider using more carefullytruncatecharsor combined with other custom logic.

Related articles

How to safely truncate the article content using the `truncatechars_html` filter without destroying the HTML structure for website SEO?

In website operation, we often need to display the concise content of articles in article lists, search results summaries, or social media shares.This concise content should not only attract users' attention, but also ensure that the complex HTML structure behind it is not damaged, in order to avoid affecting the layout and user experience.For search engine optimization (SEO), a clean and effective code structure is crucial. AnQiCMS (AnQiCMS) is an enterprise-level content management system developed based on the Go programming language, deeply understanding the pain points and needs of website operation.It not only provides multi-site management, a flexible content model

2025-11-08

Array concatenation into a string: Application scenarios of the `join` filter in AnQiCMS templates?

In website content management, we often encounter the need to display a set of data, such as multiple tags, multiple image URLs, or custom multiple-choice content, in a unified string format.AnQiCMS (AnQiCMS) boasts its efficient architecture based on the Go language and a flexible template engine similar to Django, providing great convenience for content display.Today, let's delve deeper into a very practical tool for handling such needs - the `join` filter.What is the `join` filter? In the AnQi CMS template world

2025-11-08

What is the difference between the `make_list` filter and the `split` filter? When should `make_list` be used to split strings?

In AnQi CMS template development, we often need to process string data, such as splitting a long string into multiple independent parts for traversal, display, or further logical judgment.Anqi CMS provides a variety of filters (Filters) to help us complete these tasks, among which `make_list` and `split` are two commonly used string splitting tools.Although they can all convert strings to lists (or arrays), there are obvious differences in their functional focus and usage scenarios.

2025-11-08

`split` filter: How to split a long string into an array by a specific delimiter?

In the powerful functions of AnQi CMS, the flexibility of content display has always been our focus.Sometimes, you may need to enter a long string of information in a field on the back end, such as multiple keywords for an article, multiple parameters for a product specification, or a list of skills for a team member.This information is usually connected by specific delimiters (such as commas, semicolons, or pipes).However, when you want to display this information individually on the front page, even to style each part differently, the problem arises: how can you conveniently split this long string into independent items?

2025-11-08

How to get a specific digit from a number: Advanced usage of the `get_digit` filter in AnQiCMS template?

In AnQiCMS template development, flexible handling and displaying data is the key to enhancing website functionality and user experience.When faced with a sequence of numbers, such as product numbers, order numbers, or some kind of identification code, sometimes we do not need the entire number, but rather a specific digit at a certain position.At this time, the `get_digit` filter has become a very practical tool.It can help us extract the required part from the numbers accurately, providing more possibilities for the dynamic display of templates and logical judgment.

2025-11-08

What is the role of the `index` filter in processing string searches?

In the AnQiCMS template world, efficiently processing and displaying content is the core.Whether it is to dynamically adjust the page display based on user input or quickly locate key information in complex text, mastering the template function can greatly improve the operation efficiency of your website content.Today, let's delve into a very practical tool for string searching—the `index` filter.### `index` filter: 'Locate Expert' string Imagine you have a long article content or a list with multiple tags

2025-11-08

How to replace a specific keyword with another in AnQiCMS template?

In the flexible template system of AnQiCMS, dynamic content processing is an indispensable part of daily operation.Sometimes, we may need to replace a specific keyword in a string when displaying content, such as displaying a brand name uniformly or adjusting the presentation of certain text without modifying the original data.AnQiCMS's template engine provides a concise and efficient method to complete this task, among which the `replace` filter is our powerful assistant.###

2025-11-08

Remove extra spaces or specific characters from a string, which filter should be used first (`cut` or `trim`)?

In the template world of Anqi CMS, we often need to clean and format strings, such as removing extra spaces from user input or dealing with specific symbols mixed in with imported content from external sources.At this point, the `cut` and `trim` filters have become our reliable assistants.Although they can all 'remove characters', their working methods and applicable scenarios are fundamentally different.Understanding the difference between these two can help us handle content more efficiently and accurately, making the website display more professional and tidy.

2025-11-08