How to truncate a string to a specified length or word count and add an ellipsis at the end?

Calendar 👁️ 57

In AnQi CMS, as an experienced website operator, we are well aware of how to improve user experience through precise content display.In many content management scenarios, the control of the text length of article summaries, product descriptions, or list page previews is a key factor in ensuring the page is neat and beautiful, and information is efficiently conveyed.To avoid long text affecting the layout while maintaining the continuity of content, it is a very practical skill in AnQiCMS template development to truncate strings to a specified length or word count and automatically add an ellipsis at the end.

AnQiCMS's template engine provides powerful filter functions, which can conveniently format and process output variables. For the need of string truncation, we mainly usetruncatecharsandtruncatewordsThese two filters.

Truncate string by character length and add an ellipsis

When we want to limit the display of a text content to a fixed number of characters, we can usetruncatecharsThe filter will truncate the string according to the number of characters you specify. If the length of the original string exceeds the specified number, it will automatically add an ellipsis (...) at the end of the truncation, clearly indicating that the content has been omitted.

For example, you need to display the introduction of each article on the article list page, but in order to maintain the unity of the page layout, it is hoped that the introduction will be displayed for a maximum of one hundred characters. At this point, you can apply it in the template like thistruncatecharsFilter:

{{ item.Description|truncatechars:100 }}

In this example,item.DescriptionRepresented the introduction of the article. Through|truncatechars:100,AnQiCMS will automatically truncate the introduction to a maximum of one hundred characters and intelligently add an ellipsis at the end. If the introduction itself is less than one hundred characters, it will be displayed in full without adding an ellipsis.

String is truncated by word count and an ellipsis is added

Different from character truncation, sometimes we prefer to control the length of text by word count, which is especially common in English or other languages based on words, as it can better maintain the integrity of semantics.truncatewordsThe filter is designed for this purpose. It calculates the number of words in a string and truncates according to the number you specify, and also automatically adds an ellipsis at the end.

If you have a product description field and you want to display a short description containing twenty words on the product list page, you can use it like this in the template.truncatewords:

{{ product.Description|truncatewords:20 }}

Hereproduct.DescriptionRepresents product description.|truncatewords:20Ensure that the description content is no more than twenty words and add an ellipsis when necessary.

Handle content that includes HTML tags.

In the operation of actual websites, many content fields (such as article text, rich text editor-generated summaries) may contain HTML tags. If used directly,truncatecharsortruncatewordsTo truncate this type of content may damage the HTML structure, causing the page to display abnormally. To solve this problem, AnQiCMS also provides an optimized filter for HTML content:truncatechars_htmlandtruncatewords_html.

These filters intelligently parse the HTML structure when extracting HTML strings, ensuring that all open HTML tags are properly closed while truncating text, thus avoiding page chaos caused by unclosed tags. When outputting such extracted content, it is usually necessary to use in conjunction with|safefilter.

For example, to extract a segment of a paragraph containing HTML and limit it to two hundred characters while maintaining the HTML structure:

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

Similarly, if you want to truncate HTML content by word count:

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

By these filters, you can flexibly control the display length of AnQiCMS website content, whether it is plain text or rich HTML content, it can be presented to the user in an elegant and structurally complete way, thus optimizing the visual effects of the page and the user reading experience.When engaging in content operation and template design, it is beneficial to use these string truncation functions, which will greatly enhance the professionalism and attractiveness of your website content.

Frequently Asked Questions

Ask: Will an ellipsis be displayed if my text content is shorter than the set truncation length? Answer: No. These extraction filters of AnQiCMS are very smart.If the length of the original content (whether in characters or words) does not exceed the limit you set, the filter will output the text as is and will not add an ellipsis at the end.An ellipsis will only appear when the content is actually truncated to indicate to the reader that the content is incomplete.

Ask: Can I use multiple filters consecutively on the same template variable? Answer: Yes, AnQiCMS template engine supports chained filter calls.You can pass multiple filters through|Symbols are connected together, they will process the variables in order from left to right. For example, you may want to convert the text to lowercase before truncating it:{{ item.Title|lower|truncatechars:50 }}.

Question:truncatechars_htmlandtruncatewords_htmlCan the filter handle all complex HTML structures? For example, nested ones?div/scriptTags, etc.? Answer:_htmlThe series filter aims to maintain the integrity of the HTML structure as much as possible, especially good at handling common text format tags (such as<b>/<i>/<a>/<p>However, for very complex or HTML structures containing embedded scripts, although they strive to close tags to prevent rendering errors on the page, overly complex HTML content may still cause slight differences in display when forced to be truncated.Therefore, for content that includes complex interactions or scripts, it is recommended to preprocess it or consider not extracting it before, to ensure that the function is not affected.

Related articles

How to escape HTML special characters when outputting in a template to prevent XSS attacks?

As an experienced CMS website operation person in the safety industry, I know the importance of content security for website operations, especially in preventing cross-site scripting (XSS) attacks.In Anqi CMS, the template engine provides powerful tools to ensure the safety of the output content.Ensure the safety of template output: HTML special character escaping Cross-site scripting (XSS) attacks are a common security vulnerability in web applications. Attackers inject malicious client-side scripts into websites, causing browsers to execute these scripts when users browse the web.These scripts may steal user sessions

2025-11-06

How to generate random text or placeholder content for layout testing in templates?

As a senior CMS website operation personnel, I am well aware that it is crucial to carry out layout testing efficiently during the website design and development stage.When the content is not fully ready, we often need to fill in placeholder content to check the layout, style, and responsiveness of the template.AnQi CMS provides a very practical built-in tag that can help us easily generate random text.

2025-11-06

How to implement content switching and display in multilingual websites?

As an experienced website operator, I am well aware of the importance of multilingual websites in expanding the international market and enhancing the global brand influence.AnQiCMS (AnQiCMS) is a system designed specifically for enterprise-level content management, which provides us with powerful and flexible tools for building and managing global websites with built-in multilingual support.In Anqi CMS, implementing the content switching and display of a multilingual website is not just a simple text translation, but also a systematic process of content organization, template adaptation, and SEO optimization.###

2025-11-06

How to display the contact information of the website in the template, such as phone number, email, and WeChat QR code?

As an expert in Anqi CMS content management and website operation, I fully understand the importance of displaying contact information externally.This is not only a bridge for users to communicate with you, but also a key link to enhance the professionalism and credibility of the website.In AnQi CMS, integrate this key information into the website template, which is flexible and efficient.

2025-11-06

How to split a string into an array with a specified separator?

As an experienced expert who deeply understands the operation of AnQiCMS, I know that the flexibility of content creation and display is crucial for attracting and retaining users.AnQiCMS is a powerful template engine that provides a variety of tools for fine-grained control over the presentation of content, including string processing functionality.Today, let's delve into how to use the built-in functions in the AnQiCMS template to split a string into an array according to a specified delimiter, making it easier for you to display dynamic content flexibly.### In AnQiCMS

2025-11-06

How to concatenate the elements of an array into a string using a specified character?

As an experienced soldier in the field of Anqing CMS content management, I know that how to efficiently handle and display data in daily operations is the key to improving website user experience and content value.AnQi CMS provides us with great flexibility with its powerful template engine.Today, we will delve deeply into a very common requirement in content display: how to concatenate multiple elements in an array into a string with a specified character.This is crucial for scenarios such as aggregating display keywords, image lists, or handling multi-select custom fields.

2025-11-06

How to remove specified characters or spaces from the beginning, end, or any position of a string?

As an experienced CMS website operation personnel for a security company, I know the importance of content quality and data cleanliness for user experience and SEO optimization.In the daily content publishing and maintenance work, we often encounter the need to clean up strings, such as removing unnecessary spaces and special characters to ensure the standardization and aesthetics of the content.

2025-11-06

How to convert English string to uppercase, lowercase, or capitalize each word?

As an experienced CMS website operation personnel for an enterprise, I know the importance of the refinement of content presentation in attracting and retaining users.When handling website content, the format of the text often determines its professionalism and readability.AnQi CMS provides a powerful and flexible template engine that can help us easily achieve various text format conversions, such as converting English strings to uppercase, lowercase, or capitalizing the first letter of each word.

2025-11-06