How to truncate a long string and automatically add an ellipsis (...)?

Calendar 👁️ 62

In website operation, we often encounter situations where we need to display a piece of text, but we cannot let it be too long, in order not to affect the page layout or reading experience.If the content of the article title, abstract, or product description exceeds the expected length, the usual practice is to truncate part of it and add an ellipsis at the end to indicate that the content has not ended.For AnQiCMS users, achieving such an effect is not complex, thanks to its flexible and powerful template engine, we have a variety of built-in filters (Filters) that can easily handle it.

The AnQiCMS template engine is designed to be very practical, allowing developers and operators to process variables with simple syntax, including the string truncation and ellipsis addition we are discussing today.These filters can help us efficiently manage the display of content on the front end, enhancing user experience and page cleanliness.

How to truncate a plain text string and add an ellipsis

For plain text content without any HTML tags, AnQiCMS provides two very convenient filters to handle:truncatecharsandtruncatewords.

  1. Character-based truncation:truncatecharsAs the name implies,truncatecharsThe filter will truncate the string based on the number of characters you specify.It also counts the ellipsis automatically added at the end (usually 3 characters) in the total length.This means that if you specify a truncation of 20 characters, the final content displayed (including the ellipsis) will not exceed 20 characters.

    Usage: {{ 你的变量|truncatechars:长度 }}

    For example, assume your article titlearchive.TitleIs 'AnQi CMS: A high-efficiency enterprise-level content management system, helping you easily manage website content.' If you want to display it in a maximum of 15 characters, you can write it like this: {{ archive.Title|truncatechars:15 }}

    The result after processing might be: "AnQi CMS: an efficient..."

  2. Extract by word:truncatewordswithtruncatecharsdifferent,truncatewordsThe filter attempts to cut strings at word boundaries, which can prevent a word from being abruptly cut in the middle, making the text more natural and smooth to read in the English context.It will also count the ellipsis within the specified number of words.

    Usage: {{ 你的变量|truncatewords:单词数量 }}

    Assuming you have a description in English.archive.DescriptionIs "AnQiCMS is a powerful and flexible content management system developed with Go language, offering efficient solutions for SMEs." If you need to display the first 10 words, you can do so by doing this: {{ archive.Description|truncatewords:10 }}

    The result may be: 'AnQiCMS is a powerful and flexible content management system developed with Go language...'

How to extract a string containing HTML content and add an ellipsis

In many website content management scenarios, the summary or product description of an article may contain images, links, bold text, and other HTML tags. If used directly,truncatecharsortruncatewordsHandling this content may cause HTML structure to be broken, resulting in pages displaying disorganized or incomplete.

In order to avoid this situation, AnQiCMS kindly provides a special filter for processing HTML content:truncatechars_htmlandtruncatewords_html.

  1. Cut HTML by characters:truncatechars_htmlThis filter is compatible withtruncatecharsIt has a similar function, but it will intelligently identify and close incomplete HTML tags.This ensures that the output HTML structure is still valid when extracting strings containing HTML tags.At the same time, ellipses are also counted in the specified character length.

    Usage: {{ 你的HTML变量|truncatechars_html:长度|safe }}

    Please note when using_htmlThe suffix filter processes HTML content,Make sureadding at the end|safefilter.safeThe filter tells the AnQiCMS template engine that this content is safe HTML code, which does not require additional escaping and should be parsed directly as HTML.

    For example, ifarchive.Contentinclude<p>这里是<b>一段长长的文本,其中包含<i>各种有趣的</i>内容</b>。</p>And you want to truncate to a maximum of 30 characters:{{ archive.Content|truncatechars_html:30|safe }}

    The result after processing might be:<p>这里是<b>一段长长的文本,其中包含<i>各种...</i></b></p>As you can see, the HTML tags are properly closed.

  2. Truncate HTML by word:truncatewords_htmlwithtruncatewordsSimilar, but it is suitable for content containing HTML tags and will strive to cut at word boundaries and the correct HTML tag structure. It also requires|safeA filter to correctly parse HTML.

    Usage: {{ 你的HTML变量|truncatewords_html:单词数量|safe }}

    For example, ifarchive.ContentIs<p>AnQiCMS is a <b>powerful and flexible</b> content management system.</p>Would you like to extract the first 5 words:{{ archive.Content|truncatewords_html:5|safe }}

    The result after processing might be:<p>AnQiCMS is a <b>powerful and...</b></p>

Actual application scenarios and tips

In AnQiCMS template development, these truncation filters are a tool for optimizing content display. They are usually used for:

  • Summary of article list page:Unify the summary length to make the page layout more tidy.
  • Brief description of the product list page:Quickly browse the highlights of the product to attract users to click.
  • Any scenario that requires a brief display of text:Avoid long text from occupying too much space.

Tip:

  • Choose the appropriate filter:For plain text, choose.truncatecharsortruncatewords; For content containing HTML, please use.truncatechars_htmlortruncatewords_htmland always cooperate with.|safe.
  • Consider language features:For Chinese content,truncatecharsIt is usually more commonly used because it does not have the concept of 'word'; and for English content,truncatewordsit often provides a more natural effect in extracting text.
  • Test effect:In practical application, it is best to test the effect of truncation on content of different lengths to ensure that it meets your design and user experience requirements.

Master these string slicing filters, and you'll be able to present content in AnQiCMS more flexibly and efficiently, easily creating website pages that are both beautiful and practical.


Frequently Asked Questions (FAQ)

Q1: Why does the page display incorrectly or tags are not closed when I extract HTML content?A1: This is likely because you are usingtruncatecharsortruncatewordsProcess content containing HTML tags. These filters do not have the ability to recognize and process HTML structure, which may cause tags to be truncated in the middle. Please usetruncatechars_htmlortruncatewords_htmlPlease ensure that it is added in the output|safeFilter, for example{{ 你的HTML变量|truncatechars_html:长度|safe }}.|safeThe filter indicates that the template engine should render the content as raw HTML instead of escaping it.

Related articles

What are the similarities and differences between the `stampToDate` and `date` filters in handling time formatting and their applicable scenarios?

In Anqi CMS template development, we often need to display time data in a user-friendly format.The system provides two very practical tools for handling time: the `stampToDate` function and the `date` filter.Although they can all help us format time, there are some key similarities and differences as well as applicable scenarios, understanding these can make our template development more efficient and accurate.## `stampToDate`: A timestamp handler In AnQi CMS

2025-11-08

How to format a Unix timestamp into a readable date and time string?

In website content management, the way time is presented is crucial to user experience.Although the system may prefer a unified and efficient Unix timestamp format for background data processing, for visitors, a string of random numbers is obviously not as intuitive and easy to understand as AnQi CMS knows this and provides a simple and powerful tool to solve this problem.### Unix timestamp: The 'time language' in the database Unix timestamp, in short

2025-11-08

Can the `divisibleby` filter be used to implement alternating row colors or other conditional styles in a loop?

In the daily operation of website content, how to make the list data more readable and visually attractive is a key factor in improving user experience.AnQiCMS (AnQiCMS) offers a flexible template engine, providing rich possibilities for content display.Today, let's talk about a very practical template filter——`divisibleby`, and see how it helps us achieve alternate row coloring or other conditional styles in loops.## Get to know the `divisibleby` filter AnQi CMS template system

2025-11-08

How to determine if a number can be evenly divided by another number in AnQiCMS templates?

In web content display, we often encounter situations where we need to adjust the layout or display logic of content based on the characteristics of some numbers.For example, we may need to insert an advertisement every few articles, or make even and odd rows of the table display different background colors, or perform special operations when the list loops to a specific position.In the AnQiCMS template system, based on the Django template engine syntax, it provides a very practical filter that can easily meet this requirement.This filter is `divisibleby`

2025-11-08

How does the `truncatechars_html` filter safely truncate HTML content without breaking the tag structure?

In website operation, we often need to display an abstract of a large amount of content on a page, such as the article list on the homepage, a brief introduction on the product details page, or recommended content for a module.These summaries must be able to attract readers to click and maintain the neat and beautiful layout of the page.However, when the content itself contains rich HTML formatting (such as bold, italic, images, links, etc.), simply truncating the character length often leads to a headache: the HTML tag structure is destroyed, causing the page to display incorrectly and even affecting the overall style.Imagine

2025-11-08

How to convert the first letter or the first letter of each word in an English string to uppercase in AnQiCMS?

In daily website content management, we often need to finely control the display format of English strings, such as capitalizing the first letter of the article title or making each word of the product name start with uppercase to enhance the professionalism and unity of the content.AnQiCMS (AnQiCMS) fully understands the importance of these subtle details to the website's image, and therefore provides convenient and powerful string processing functions in template design, allowing you to easily meet these formatting needs.The Anqi CMS uses a template engine syntax similar to Django

2025-11-08

What are the limitations of the `lower` and `upper` filters when dealing with case conversion (such as Chinese)?

In AnQiCMS template development, the `lower` and `upper` filters are commonly used tools for handling text case conversion.They are designed to help us quickly standardize the display of text, such as converting the irregular content entered by users to lowercase or uppercase to maintain consistent page style or meet certain data processing requirements.However, when using these convenient filters, we may encounter some "edge" cases that they cannot handle, especially when it comes to non-English characters, such as Chinese.### `lower` and `upper`

2025-11-08

How to ensure that single quotes, double quotes, and backslashes are correctly escaped in HTML output?

During website operation and template creation, we often need to output dynamic content to the HTML page.This is a common but often overlooked question: How to ensure that special characters such as single quotes, double quotes, and backslashes in the content do not破坏 the page structure or cause security issues when output to HTML?Don't worry, AnQiCMS provides very friendly built-in mechanisms and flexible tools in this aspect, which help us handle it easily.### AnQiCMS's default security mechanism: automatic escaping AnQiCMS has taken full consideration of content security in its design

2025-11-08