How to use `truncatechars` and `truncatewords` in Anqi CMS template?

Calendar 👁️ 61

As an experienced website operator familiar with the operation of AnQiCMS, I know the exquisite presentation of content.How to elegantly handle the display of text content when building an engaging, user-friendly website experience.AnQi CMS, with its flexible Django-like template engine, provides us with powerful content control capabilities, among which the text truncation feature is a common tool we use to optimize page layout and improve reading experience.

This article will discuss in detail the two core filters used for text truncation in the Anqi CMS template:truncatecharsandtruncatewordsand introduce the important HTML security clipping method for handling rich text content, as well as the application strategies in actual operation.

Understandingtruncatechars:clip text accurately by character

In many scenarios, we need to precisely control the length of text, such as when generating web page meta descriptions, article card summaries, or brief prompts. At this point,truncatecharsThe filter can be put to use.

truncatecharsThe function is to truncate text based on a specified character count. It starts counting from the beginning of the text, and once the total character count reaches or exceeds the threshold set, the text is truncated and an ellipsis is automatically added at the end (...)

Use syntax and examples:

Use in AnQi CMS template,truncatecharsThe syntax is very concise. You just need to pass the variables you need to extract through the pipe symbol|Connected totruncatecharsFilter and then append the number of characters you want to retain.

For example, suppose we have a file namedarchive.DescriptionThe variable stores the descriptive content of an article. If we need to truncate it to no more than 50 characters:

{{ archive.Description|truncatechars:50 }}

This code will output intelligentlyarchive.DescriptionThe first 50 characters. If the original description exceeds 50 characters, the filter will append an ellipsis after the 50th character....)

Let's look at a specific example: ifarchive.DescriptionThe original text is: "Anqi CMS is an enterprise-level content management system developed based on the Go language, dedicated to providing an efficient, customizable, and scalable content management solution, aiming to become the preferred tool for small and medium-sized enterprises and content operation teams."

Use{{ archive.Description|truncatechars:30 }}It will output: 'Anqi CMS is an enterprise-level content management system developed based on Go language, committed to providing efficient and customizable...'Here, even a single Chinese character is counted as one character.

Understandingtruncatewords: Smartly cut text by word

withtruncatecharsPay attention to different character counts,truncatewordsThe filter focuses on truncating text based on word count. This is particularly useful for languages like English that are separated by spaces, as it ensures the integrity of the words in the truncated text, thus improving readability. And it is withtruncatecharsSimilar, if the number of words in the original text exceeds the specified value, it will also add an ellipsis at the end (...)

Use syntax and examples:

truncatewordsSyntax for usingtruncatecharsMaintain consistency, the only difference is that the parameter passed to the filter represents the number of words:

{{ archive.Description|truncatewords:10 }}

This line of code will outputarchive.DescriptionThe first 10 words. If the total number of words in the original text exceeds 10, the filter will also add "... "at the end.

For example, describe in English: Ifarchive.DescriptionThe original text is: ”AnQiCMS is an enterprise-level content management system developed based on Go language, committed to providing efficient, customizable, and extensible content management solutions, aiming to be the first choice for small and medium-sized enterprises and content operation teams.”

Use{{ archive.Description|truncatewords:15 }}Will output: ”AnQiCMS is an enterprise-level content management system developed based on Go language, committed to providing efficient, customizable...”It retains the full word.

Optimize website content display: When to use text truncation

These text truncation filters play a crucial role in website content operation, their main goal is to enhance user experience and ensure the neatness and consistency of page layout:

On the article or product list page, displaying complete and lengthy content makes the page look cumbersome and slow to load.By cleverly extracting the summary of the content, we can quickly attract the attention of users, stimulating their interest to click for more detailed information.

For search engine optimization (SEO), the length control of Meta Description is crucial. Search engines usually grab the summary of the page content as the description of search results, and through the use oftruncatecharsWe can ensure that the meta description is of moderate length, avoiding being cut off by search engines ruthlessly, thus optimizing the display effect of search results.

Moreover, these filters can effectively enhance the aesthetic beauty of the website.They ensure visual consistency of text of different lengths in page layout, avoiding overlong text from stretching the layout or destroying the carefully designed visual aesthetics.For example, in a card layout, the fixed length of the article title or summary can make the overall visual effect more professional and harmonious.

At the initial stage of template development, we can also use these filters to generate simulated data, making it convenient to test the actual display effect of text of different lengths on the page, ensuring that the final design can meet the challenges of various content lengths.

Tackle the rich text challenge: handle text containing HTML tags

In the process of content creation, we often use rich text editors to enter content, which often contains rich HTML tags such as paragraphs, links, images, and bold text. If we directly use such text containing HTML tagstruncatecharsortruncatewordsIt may destroy the original HTML structure, causing the page to display混乱 even functionally abnormal. For example, an unclosed<div>tags or<a>tag may cause the entire page layout to be chaotic.

To solve this problem, Anqi CMS template engine provides a special filter for processing HTML content:truncatechars_htmlandtruncatewords_htmlThese two filters can intelligently identify and retain the structural integrity of HTML tags while performing text extraction, ensuring that the page can still be correctly rendered after extraction.

truncatechars_htmlExample:

{{ archive.Content|truncatechars_html:100|safe }}

truncatewords_htmlExample:

{{ archive.Content|truncatewords_html:20|safe }}

It should be emphasized that when you usetruncatechars_htmlortruncatewords_htmlWhen processing variables containing HTML content, it is usually necessary to use `

Related articles

What is the role of the `safe` filter in the AnQi CMS template and when should it be used?

As a professional deeply familiar with the operation of Anqing CMS, I know the importance of template security and the correct presentation of content for a website.In the Anqi CMS template system, the `safe` filter plays a key role, concerning the security and display effect of the website. ### Automatic Escaping Mechanism of AnQiCMS Template AnQiCMS template system draws on the syntax characteristics of the Django template engine, one of its core design philosophies is security.

2025-11-06

How to use the `stampToDate` tag to format timestamps in the Anqi CMS template?

In website content management, the accuracy and aesthetics of time presentation are crucial for user experience.Whether it is the publication date of the article, the update time of the product, or the submission time of the comments, a clear and consistent date format can significantly improve the readability and professionalism of the content.AnQi CMS is an efficient and flexible content management system, deeply understanding this, and provides a powerful and simple tool for template developers - the `stampToDate` tag, which is specifically used to format timestamps into various custom date and time display formats.

2025-11-06

How to use `for` loop and `if` conditional judgment tags in Anqi CMS template?

As an experienced Anqi CMS website operation personnel, I am very clear about the core role of templates in content presentation.A flexible and efficient template can not only enhance the user experience but also help us achieve accurate content placement and management.In the Anqi CMS template system, the `for` loop and `if` conditional judgment tags are the two cornerstones for building dynamic and interactive web pages.They make content no longer static text blocks, but can intelligently display according to data changes.

2025-11-06

How to use the `tagDataList` tag to display documents under a specified Tag in the AnQi CMS template?

As an experienced CMS website operations manager for a leading security company, I know that high-quality content and convenient user experience are the key to attracting and retaining users.Tags (Tag) serve as an important dimension for content organization, not only helping users quickly find the content they are interested in, but also an indispensable part of internal link optimization and SEO strategy.

2025-11-06

How to use `join` and `split` filters to handle strings and arrays in AnQi CMS template?

As an experienced CMS website operation person in Anqi, I am well aware of the importance of flexible data handling in content management and display.The AnQi CMS template engine provides a rich set of filters to help us achieve this goal, among which the `join` and `split` filters are particularly powerful in handling string and array data, allowing our content display to be more dynamic and accurate.

2025-11-06

How to configure and display the `hreflang` tag in the Anqi CMS template?

As a website operator who deeply understands the operation of Anqi CMS, I am very clear about the importance of multilingual websites in today's global market and how to enhance the international visibility of the website through refined SEO strategies, such as the `hreflang` tag.The flexibility of AnQi CMS in multilingual support and template customization provides a solid foundation for us to achieve these goals.

2025-11-06

How to implement user group management and VIP paid content settings in AnQi CMS?

How to implement user group management and VIP paid content settings in AnQi CMS?As an experienced website operator, I am well aware that fine-grained user management and flexible content monetization capabilities are crucial for the success of a website.AnQiCMS (AnQiCMS) provides strong support in this aspect, allowing website operators to build differentiated user services and effectively realize the monetization of content value through its user group management and VIP system.

2025-11-06

How to use the `dump` filter to debug variable structure in AnQi CMS template?

As a senior CMS website operation personnel in a safety enterprise, I am well aware of the importance of quickly understanding data structures in template development and content optimization for debugging and accurate content presentation.Although AnQiCMS's template engine is syntactically similar to Django's template engine, providing rich tags and filters, but upon further examination of the provided documentation, it can be found that there is no explicit list of a filter named `dump`.

2025-11-06