How to truncate long text content and add an ellipsis (...)

Calendar 👁️ 84

In the daily management of website content, we often encounter such situations: a brief introduction of an article, a product description, or the title of a list item, if the content is too long, it not only occupies too much page space but may also destroy the beauty of the overall layout.Especially on small screen devices like mobile phones, overly long text can severely affect user experience.How gracefully can these texts be truncated and supplemented with common ellipses (…) to make the information complete and tidy, which is a very practical skill in content operation.

AnQi CMS as an efficient content management system, fully understands the users' demand for flexible content display.Its powerful template engine provides a series of built-in filters (Filters) that can help us easily implement text truncation and ellipsis addition, ensuring that website content can present **status** in any scenario.

Precise character truncation: truncatecharsFilter

If you need to truncate text based on the exact number of characters, for example, to strictly control the abstract of each article to be within 50 characters, thentruncatecharsThe filter is your ideal choice.It starts counting characters from the beginning of the text, truncates when it reaches the specified length, and automatically adds an ellipsis at the end.includethis ellipsis included.

The usage is very intuitive, just add it to the text variable you want to process|truncatechars:数字And then. For example, if you want to display the first 50 characters of each article in the article list as a summary:

{{ item.Description|truncatechars:50 }}

This willitem.DescriptionContent truncated to ensure the displayed string (including ellipsis) does not exceed 50 characters, making the list page look more tidy.

Natural word truncation:truncatewordsFilter

Sometimes, simply truncating by character count may cause a word to be cut in half, affecting the reading experience. If your content places more emphasis on semantic integrity and you hope that the truncation point can be more naturally at the end of a word, thentruncatewordsThe filter would be a better choice. It would truncate the text based on the number of words, avoiding the text being cut off abruptly, making the truncated content more readable.

For example, you want the article title to display a maximum of 10 words in a certain area:

{{ item.Title|truncatewords:10 }}

It will intelligently search for the end of the 10th word to truncate and add an ellipsis at the end, to avoid incomplete words like 'Anqi CM...' and make the content more fluent and natural.

Coping with complex HTML:truncatechars_htmlwithtruncatewords_html

In Anqi CMS, many contents are entered through rich text editors, which means they contain rich HTML tags (such as<p>,<strong>,<img>Directly using text containing HTML tagstruncatecharsortruncatewordsMay destroy its structure, causing abnormal display of the page or even confusion.

To solve this problem, Anqi CMS provides a special filter for processing HTML content:truncatechars_htmlandtruncatewords_htmlThey intelligently close all truncated HTML tags while truncating text, ensuring that the final output HTML code is complete and valid.

A very important reminder:When you use these two filters to process HTML content,Make surecooperate|safeto use the filters together.|safeThe function is to inform the template engine that this part of the content is safe HTML code that does not need to be escaped, otherwise the browser will display the HTML tags as plain text.

For example, you want to truncate the content of an article with rich formatting into an abstract while ensuring that HTML tags are not broken:

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

Or truncate by word:

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

This ensures that even if the HTML tags in the original text are truncated, these filters will guarantee that<div>/<span>etc. tags can be closed correctly without affecting the overall layout and style of the page.

Tip and Practical Suggestions

  • Flexible choice:For plain text content (such asDescription), you can choose according to your needstruncatecharsortruncatewords. For rich text content (such asContentPlease make sure to usetruncatechars_htmlortruncatewords_html.
  • Don't forget|safe:We would like to emphasize again, when dealing with HTML content,|safeIt is indispensable, as it ensures that your HTML code is correctly parsed by the browser.
  • Test different lengths:In practice, it is recommended that you try different truncation lengths in the test environment to find the best display effect for your website design and content style.
  • Combined with the Anqi CMS backend settings:In the Anqi CMS backend content settings, you can set a default thumbnail or automatically extract a summary for documents.Although these features provide convenience, using these filters directly in the template will provide you with greater flexibility when fine-grained text control is needed in specific template areas.

By skillfully using these text truncation filters, you can not only maintain the beauty of the CMS website layout, but also improve the user reading experience, making information communication more efficient. Whether it is an article list, product display, or other content sections, it can present a professional and engaging effect.


Frequently Asked Questions (FAQ)

1. How many characters does a Chinese character count as when truncating?

In AnQi CMS'struncatecharsandtruncatechars_htmlIn the filter, a Chinese character is usually counted as a character (rune).This means that the length you set will directly correspond to the number of Chinese characters displayed, without any deviation due to multibyte encoding.

2. Why does truncating HTML content sometimes cause tag breaks or page styles to become chaotic?

This is usually because it was forgotten or incorrectly used when handling variables containing HTML content|safea filter. When there is none|safeAt this time, the template engine treats HTML tags as plain text and escapes them, causing the browser to fail to correctly parse and render. At the same time, even if|safeIf the truncated length is too short, it may also cause some complex nested HTML structures to fail to close perfectly, although_htmlThe series filter will try to process, but it is still recommended to set a reasonable truncation length.

3. Will the ellipsis (...) added during truncation occupy the truncation length I set?

Yes, whether it istruncatecharsOrtruncatewordsA series of filters, the ellipsis (usually three dots) automatically added to the end of the text will be counted in the total length you set. For example, if you set|truncatechars:50The final content displayed (including ellipses) will be 50 characters in length.

Related articles

How to safely display HTML content retrieved from a database on the frontend without escaping?

In website operation, we often need to display some content with rich formatting, such as mixed text and images on article detail pages, HTML tables on product introduction pages, or interactive codes embedded in custom pages.This content is usually stored in a database and rendered on the front-end page.However, many content management systems (including the familiar AnQiCMS) by default, for website security, will escape the HTML content retrieved from the database, resulting in the front-end displaying the original HTML code rather than the expected effect.

2025-11-09

How to format a timestamp into a readable date in the template (such as: 2023-01-01)?

<ctrl94>thought Here's a thinking process that leads to the article above: 1. **Understand the Goal:** The user wants an article about formatting timestamps in AnQiCMS templates. I need to act as

2025-11-09

How to customize parameter filtering for an article or product list?

In daily website operations, we often encounter such needs: we hope that users can quickly filter out the content they are interested in based on the different attributes of articles or products.For example, on a real estate website, users may want to filter for 'two bedrooms and one living room' 'school district' housing;On a product showcase website, users may want to find 'red' new T-shirts.AnQiCMS (AnQiCMS) provides a powerful and flexible custom parameter function, which can help us easily achieve this refined content filtering

2025-11-09

How to implement pagination in the content list?

When managing website content, especially when the amount of content increases, a straightforward and efficient pagination feature becomes particularly important.It not only allows visitors to find the information they need faster, improves the browsing experience, but also avoids performance issues caused by loading too much content on a single page.In Anqi CMS, implementing the pagination function of the content list is flexible and direct, and it can be configured to completion in just a few steps.The Anqi CMS adopts the Django template engine syntax, allowing you to control the display logic of content through clear tags.Add pagination to your content list, we will mainly use two core tags

2025-11-09

How to automatically convert URL strings in text to clickable links?

In daily content operations, we often need to mention various URLs in articles, product descriptions, or page introductions.If these URLs are displayed as plain text, users will need to manually copy and paste them to access, which undoubtedly will greatly reduce their reading experience and the interactivity of our website.How can we automatically make the URL strings in these texts clickable?In AnQi CMS, this implementation is very simple, no complex code development is required, just use its powerful template filter function to easily handle it.

2025-11-09

How to perform basic arithmetic operations in the template?

In Anqi CMS template design, it can flexibly handle data, perform simple calculations, and is an indispensable part of creating dynamic and functional websites.You may find that in addition to displaying the content itself, it is also necessary to perform some basic arithmetic operations at the template level, such as calculating the total price of goods, displaying the discounted price, or dynamically adjusting the style of elements based on numerical values.The AnQi CMS template engine (similar to Django syntax) provides us with intuitive and powerful arithmetic calculation capabilities, allowing these requirements to be easily implemented in the template.###

2025-11-09

How to convert a string to uppercase, lowercase, or title case?

In website content operation, the way content is presented often determines the overall impression of users on the website.Whether it is to maintain brand style consistency or to improve the readability of text, flexible case conversion of strings is a basic and important operation.AnQiCMS (AnQiCMS) understands this, and it has built-in simple and easy-to-use filters (Filters) in its powerful template engine, allowing you to easily perform string transformations such as uppercase, lowercase, and capitalization without complex programming.We will introduce in detail how to use the Anqi CMS template

2025-11-09

How to display a default value when a variable is empty?

In website operation, we often encounter such situations: a content field may not be filled in for various reasons, such as the author of the article, image description, or specific parameters of a product.If the template outputs a blank directly when displaying this content, it not only affects the aesthetics but may also confuse the user.At this time, how to display a friendly default value when a variable is empty has become a very practical skill.The AnQi CMS template system, with its flexible and powerful features, provides us with various methods to elegantly solve this problem

2025-11-09