How to truncate strings or HTML content in templates and add ellipses?

Calendar 👁️ 71

When operating a website, we often encounter such situations: the abstract of an article is too long, causing the page layout to be disordered;The product description is detailed, but it seems redundant on the list page;Or maybe it's a title that's too long and takes up space for other elements.These seemingly minor issues may affect user experience and the overall aesthetics of the page.Fortunately, AnQiCMS (AnQiCMS) has provided us with very convenient and powerful template tags, which can easily solve the needs for content truncation and adding ellipses, making our website content display more proper and professional.

The AnQi CMS template engine is built-in with several very practical content extraction filters, which can work according to different needs (whether it is plain text or contains HTML, whether it is by word count or by word count). The core four filters are: truncatechars/truncatewords/truncatechars_htmlandtruncatewords_html.

Understand the Anqi CMS cropping tool

Before delving into the specific usage, we first need to clarify several concepts:

  1. Plain text content vs. HTML content:

    • Plain text contentThis indicates text that does not contain any HTML tags, such as article titles, brief descriptions, etc.
    • HTML contentThis refers to text that includes HTML tags, such as the main content of articles, formatted product details, etc.When extracting content from HTML, it is particularly important to avoid damaging the original tag structure, otherwise it may cause the page display to be abnormal.
  2. Character cut vs. Word cut:

    • Character cut: Strictly truncate according to the set character count, regardless of whether these characters are Chinese, English, or punctuation marks, they will be counted in the total.
    • Truncate by wordMainly for English content, it will cut according to word boundaries to ensure that each word cut is complete.For Chinese content, since there is no clear word concept, it usually falls back to character processing.

Understood the basics, we can then choose the appropriate filters to process different content.

How to use these tools

In AnQi CMS templates, the syntax of using filters is very intuitive:{{ 变量 | 过滤器: 参数 }}. Among them,|The symbol indicates that the value of the left variable is passed to the filter on the right, and:Symbols are used to pass parameters to the filter.

1. Extracting plain text content.

For text without HTML tags, we mainly use.truncatecharsandtruncatewords.

  • truncatechars: Cut by characters (including ellipsis)This filter will strictly cut according to the number of characters you specify and will automatically add an ellipsis "..." after the cut.It should be noted that these three characters of the ellipsis are also counted in the total length you set.

    Usage example:Assuming we have an article description variablearchive.DescriptionWe want to truncate the first 50 characters and add an ellipsis.

    <p>{{ archive.Description|truncatechars:50 }}</p>
    

    Effect:If the original description is "This is a very long article description that needs to be truncated here to ensure the neatness of the page." The truncated display may be: "This is a very long article description that needs to be truncated here to ensure the neatness of the page."

  • truncatewords: Cut by words (including ellipsis)This filter will truncate based on the number of words and add an ellipsis (...) at the end.It tries to maintain the integrity of the word. Similarly, the characters of the ellipsis are also counted in the set total length.

    Usage example:Assuming we have an English title variablearchive.Title, We want to cut the first 10 words.

    <h3>{{ archive.Title|truncatewords:10 }}</h3>
    

    Effect:If the original title is “AnQiCMS is a powerful and flexible content management system for enterprises.” It may be displayed as “AnQiCMS is a powerful and flexible content management system…”

2. Extracting HTML content (key point)

When we need to extract content containing HTML tags (such as a part of an article), we can directly usetruncatecharsortruncatewordsIt may damage the HTML structure, causing the page to display incorrectly. Anqi CMS provides a special filter for handling HTML content.truncatechars_htmlandtruncatewords_htmlThey can intelligently preserve the integrity of HTML tags.

Special reminder:After extracting HTML content, in order for the browser to correctly parse and render HTML, it must be used at the end.|safeFilter. Otherwise, the browser may display HTML tags as plain text.

  • truncatechars_html: Truncate HTML content by characters (retaining structure, including ellipsis)This filter trims HTML content by character count and intelligently closes all unclosed HTML tags to ensure the output HTML structure is valid.An ellipsis is included in the total length.

    Usage example:Assuming we have a body of text containing HTMLarchive.Contentwe want to extract the first 200 characters.

    <div class="article-summary">{{ archive.Content|truncatechars_html:200|safe }}</div>
    

    Effect:If the original content is<strong>这是一段重要的内容,包含<em>粗体和斜体</em>文字。非常长...</strong>the extracted content might look like:<strong>这是一段重要的内容,包含<em>粗体和斜体</em>文字。非常...</strong>(Note: during the extraction process,)<em>Tags are smartly closed)

  • truncatewords_html: Extract HTML content by word (retain structure, including ellipsis)withtruncatechars_htmlSimilar, but it truncates HTML content by word count, and also intelligently handles HTML tags. Ellipses are counted towards the total length.

    Usage example:Suppose we want to extractarchive.Contentthe first 40 words.

    <div class="article-snippet">{{ archive.Content|truncatewords_html:40|safe }}</div>
    

    Effect:If the original content is<ul><li>第一项</li><li>第二项</li><li>第三项,内容很长...</li></ul>the extracted content might look like:<ul><li>第一项</li><li>第二项</li><li>第三项,内容很长...</li></ul>(Retained when truncated)<ul>and<li>Label integrity)

Practical scenarios and **practice

In practical application, using these clipping tools flexibly can significantly improve the user experience and page cleanliness of the website

Related articles

How to convert string case or capitalize the first letter in SafeCMS?

In website content operation, the way text is presented often affects the user's reading experience and brand image.In order to unify brand style, improve the readability of the title, or highlight text in specific scenarios, it is a common requirement to convert strings to uppercase or capitalize the first letter.AnQiCMS (AnQiCMS) with its flexible Django template engine syntax, provides us with several concise and efficient methods for handling these string formatting tasks.These operations do not require complex backend code modifications, just apply the corresponding filters in the template file, and you can easily achieve it

2025-11-08

How to set custom URL aliases for articles, categories, and single pages?

On the day when content management is increasingly important, a clear and friendly URL address can not only help search engines better understand the content of the page, improve the SEO performance of the website, but also provide users with a better browsing experience, and even help in brand promotion.AnQiCMS understands this and provides a powerful and flexible custom URL alias feature, allowing you to easily set personalized addresses for articles, categories, single pages, and even tags on your website.Next, we will explore how to finely manage these URL aliases in AnQiCMS.### Core Premise

2025-11-08

How to customize URL rewrite rules in AnQi CMS to optimize SEO?

In website operation, the website structure is not just a string of characters for accessing pages, but also a key factor in the website's performance in search engines.A clear, meaningful, and search engine-friendly URL (Uniform Resource Locator) that can significantly improve the SEO effect of the website, helping the content to be discovered and understood more easily.AnQiCMS (AnQiCMS) knows this and therefore integrated powerful pseudo-static and URL customization features into the system design from the beginning, allowing website operators to flexibly configure URL rules to meet different SEO strategy needs.

2025-11-08

How to display the current year or a specified format of time in the template?

In website operation, it is often necessary to keep the web page content up-to-date or accurately display the time of specific events, whether it is the copyright year in the footer, the publication date of the article, or the update time of the product. These dynamic time information can make the website look more professional and active.AnQiCMS provides a very flexible and intuitive way, allowing you to easily display the current year or specify the format of time in templates. Next, we will explore two main methods together, allowing your AnQiCMS website to flexibly display various time information.## One

2025-11-08

How to convert newline characters in multi-line text to HTML tags in AnqiCMS?

In website content operation, we often need to input multi-line text in articles, product descriptions, or page content.However, when displaying text with line breaks directly on a web page, browsers often do not retain these line breaks as expected, instead rendering them as a single continuous line of text, which undoubtedly affects the reading experience and layout of the content.AnQi CMS understands this and provides very convenient built-in functions to help us easily convert newline characters in multi-line text to corresponding HTML tags, allowing the content to be perfectly presented on the front-end page.###

2025-11-08

How to automatically convert a URL string to a clickable link in a template?

In website content operation, we often encounter such situations: articles, introductions, or comments contain some URL strings that can be seen by users but cannot be directly clicked to jump, which not only affects user experience but also reduces the readability and practicality of the content.As an AnQiCMS user, you will find that the system provides us with a set of elegant and efficient solutions that can easily convert these ordinary URL strings into clickable links.AnQiCMS's template engine is powerful and flexible, it draws on the concise syntax of Django templates

2025-11-08

How to format numbers in Anqi CMS (such as retaining decimal places for floating-point numbers)?

In website operation, the way data is displayed is crucial to user experience.Whether it is product prices, statistics, or financial statements, clear and standardized number formats can not only enhance the professionalism of the website but also help users understand information more intuitively.AnQi CMS knows this need, and provides powerful number formatting functions in the template system, allowing us to easily control the decimal places of floating-point numbers, the display style of integers, and more customized presentations of numbers.### Why is Number Formatting So Important? Imagine a e-commerce website where the price of a product is displayed as "199"

2025-11-08

How to remove leading and trailing spaces or specified characters from a string?

In website content management, string formatting is often a problem we need to solve when displaying content and handling data.Especially in user input, data import, or system-generated content, strings may have extraneous spaces at the beginning and end, or specific characters may need to be removed to meet expected display effects or data standards.AnQiCMS as an efficient and flexible content management system, through its powerful template engine and rich filters, provides us with concise and powerful string processing capabilities, allowing such tasks to be easily completed at the template level.

2025-11-08