How to truncate long text content and display an ellipsis?

Calendar 👁️ 69

In daily website operation, we often encounter such situations: the content of the article detail page is rich, but in order to keep the layout neat on the list page or recommendation module, it is necessary to display a concise version of the content, which is usually to cut a part of the text and add an ellipsis at the end.AnQi CMS knows the importance of content display and provides very convenient and powerful tools to handle such needs.

Let's take a look at how to elegantly implement the truncation of long text content and display an ellipsis in Anqi CMS, making the website interface both beautiful and professional.

The need and value of content truncation

In many content display scenarios, such as the article list on the homepage, the article summary on the special page, the recommended content in the sidebar, or the SEO meta description (Description), we need to control the display length of the text.The long text takes up too much space, disrupts the page layout, and affects the first impression of the user;And a short text carefully truncated with an ellipsis can convey information more efficiently, attracting users to click and view the full content.This not only optimizes the user experience, but also helps enhance the overall visual appeal and readability of the page.

The solution of AnQi CMS: Text Truncation Filter

The AnQi CMS template system is based on the Django template engine syntax and provides various built-in "filters" (Filters) to help us easily process content. In response to the need for text truncation, there are several practical filters available: truncatechars/truncatewordsand their corresponding HTML safe versionstruncatechars_htmlandtruncatewords_html.

1. Truncate by character:truncatechars

This filter will truncate text based on the number of characters you specify. Whether Chinese or English, it will accurately calculate the number of characters and add an ellipsis at the truncation point....It should be noted that the ellipsis itself is also included in the number of characters you have set.

How to use:

{{ 您的文本变量|truncatechars:数字 }}

Example:Suppose we have a text{{ archive.Description }}And we want to extract the first 20 characters:

{{ archive.Description|truncatechars:20 }}

Ifarchive.DescriptionIs "This is a very long document description that needs to be truncated for display. The output might be: "This is a very long document..."

When to use:When you need to strictly control the pixel width of displayed text, or when dealing with Chinese content,truncatecharsit is very useful because it does not distinguish between words, it truncates by character count only.

2. Truncate by word:truncatewords

withtruncatecharsdifferent,truncatewordsIt truncates text based on the number of words. It tries to maintain the integrity of words and adds an ellipsis after the last complete word.Similarly, ellipses are also counted in the number of words you set.

How to use:

{{ 您的文本变量|truncatewords:数字 }}

Example:Assumed text variable{{ archive.Description }}Yes"This is a very long description for an article that needs to be truncated, we want to take the first 10 words:

{{ archive.Description|truncatewords:10 }}

It is possible that the output will be: “This is a very long description for an article that…”

When to use:When dealing with English or other space-separated languages,truncatewordsit usually provides a more natural and fluent reading experience, avoiding words being abruptly cut in half.

3. Handle HTML content:truncatechars_htmlandtruncatewords_html

Many times, our content (such as a part of the article text) may contain HTML tags, such as<b>bold,<a>links,<p>Paragraphs and the like. If used directlytruncatecharsortruncatewordscould lead to HTML tags being incorrectly truncated, thereby destroying the page structure and even causing display anomalies.

To solve this problem, Anqi CMS providestruncatechars_htmlandtruncatewords_htmlThese enhanced filters. They can intelligently close all unclosed HTML tags while truncating text, ensuring that the output HTML structure is complete and valid.

How to use:

{{ 您的HTML文本变量|truncatechars_html:数字|safe }}
{{ 您的HTML文本变量|truncatewords_html:数字|safe }}

Please note that when you are dealing with content containing HTML, whether or not you are using a truncation filter, you should always add at the end|safefilter.|safeThe purpose is to inform the template engine that this content is safe, and it does not need to be escaped as HTML entities, but should be parsed and displayed as HTML directly.

Example:Assume{{ archive.Content }}Contains HTML code: “

This is a paragraph.ImportantContent that includes bold andlinks, needs to be truncated.

”, we hope to truncate the first 25 characters while maintaining the HTML structure:

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

The output might be: “

This is a paragraph.ImportantContent that includes bold andlinks...

Please note that even if it is truncated,<b>and<a>the tag is also closed correctly.

When to use:Any text content that may contain HTML tags, such as automatically extracted abstracts from the main text, classification descriptions, and single-page content, should be given priority to use with the_htmlSuffix truncation filter.

Specific application in Anqi CMS template.

In Anqi CMS, these filters can be applied to almost anywhere text needs to be displayed, especially when used with list tags.

For example, in your article list template (usually{模型table}/list.htmlIn brackets, you may usearchiveListTags to get the document list:

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
    <li>
        <a href="{{ item.Link }}">
            <h5>{{ item.Title }}</h5>
            {# 截取文章描述,显示前100个字符 #}
            <div>{{ item.Description|truncatechars:100 }}</div>
            {# 如果描述可能包含HTML,使用以下方式 #}
            {# <div>{{ item.Description|truncatechars_html:100|safe }}</div> #}
            <div>
                <span>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
                <span>阅读量:{{ item.Views }}</span>
            </div>
        </a>
    </li>
    {% empty %}
    <li>
        当前没有可用的文章。
    </li>
    {% endfor %}
{% endarchiveList %}

In the sidebar recommendation module of the article detail page, if you need to display a brief title:

{% archiveList relatedArchives with type="related" limit="5" %}
    {% for item in relatedArchives %}
    <li>
        <a href="{{ item.Link }}">
            <h6>{{ item.Title|truncatechars:15 }}</h6> {# 截取推荐文章标题的前15个字符 #}
        </a>
    </li>
    {% endfor %}
{% endarchiveList %}

You can also truncate the description or content when calling the category details or single page details:

{# 假设在分类列表页,需要截取分类描述 #}
{% categoryDetail categoryDescription with name="Description" %}
<p>{{ categoryDescription|truncatewords_html:30|safe }}</p>

{# 在单页面模板中,可能需要截取部分内容作为摘要 #}
{% pageDetail pageContent with name="Content" %}
<div class="page-summary">{{ pageContent|truncatechars_html:200|safe }}</div>

Practical suggestions and precautions

  • Choose an appropriate truncation length:There is no universal length for a "**". It depends on your design layout, target language, and content type.You need to test repeatedly, view the effect on different devices, and find a balance that can keep the page tidy and provide enough information to attract users to click.
  • The content type determines the filter:Remember, if your text content may contain HTML tags, be sure to use_htmlsuffix filter (such astruncatechars_html), and add|safe. For plain text,truncatecharsortruncatewordsit is enough.
  • Maintain consistency:In different areas of the website, applying unified truncation rules for similar content helps improve overall professionalism and user experience.
  • Testing and adjustment:Even if the length is set, it is recommended to publish some test content on the actual website and check the display effect. Different fonts, sizes, and layouts will affect the final visual effect.

By reasonably utilizing the text truncation filter provided by Anqi CMS, you can easily control the presentation of website content, providing visitors with a cleaner, more efficient, and professional browsing experience.


Frequently Asked Questions (FAQ)

Q1: The numeric parameter in the filter, does it include or exclude the ellipsis (...) length?

A1: In the text truncation filter of Anqi CMS (such astruncatecharsandtruncatewords), the number you setIs includedThe length of the ellipsis. For example, if you settruncatechars:10Then the final content displayed (including the ellipsis) will not exceed 10 characters in total.

Q2: How will it be if my content is too short to be truncated?

A2: If the original content is not long enough to reach the truncation length you set, then the content willWill not be truncatedAnd it will not show an ellipsis. The filter will only output this short text as is, without any modification.

Q3: Where can I find more detailed documentation and examples of these filters?

A3: You can find detailed descriptions of all filters in the official template development document of Anqi CMS. Specifically, you can check the 'Template Creation' category under 'Tags and Usage' as well as the 'More Filters' document (corresponding to your document collectiondesign-tag.mdandtag-filters.md)。There are parameters, detailed usage methods, and more code examples provided for each filter.

Related articles

How to avoid XSS attacks and safely display HTML content when outputting?

In website content management, ensuring the safe display of information, especially in preventing cross-site scripting (XSS) attacks, is an important issue that every content creator and website administrator must face.XSS attacks exploit vulnerabilities in websites, injecting malicious code into web pages. When other users visit the web page, the malicious code will execute on the user's browser, potentially stealing user information, hijacking sessions, or even tampering with web content, posing serious harm to the website and users.Fortunately, AnQiCMS has fully considered content security from the beginning of its design, providing us with multiple protective measures

2025-11-08

How to configure URL rewrite rules in AnQi CMS to optimize link display?

The website link, like the door number of a website, a clear and regular door number is not only convenient for visitors to remember and share, but also a key to understanding the structure of the website content, improving the efficiency of inclusion and ranking for search engines.This technique of optimizing dynamic links to look like static files is called 'pseudo-static'.The Aanqi CMS thoroughly understands this, providing users with powerful and flexible static configuration capabilities, aimed at helping websites perform better in search engines while improving the user browsing experience.The value of pseudo-static: Why can't it be ignored?in website operation

2025-11-08

How to display Markdown formatted content on a front-end page (including mathematical formulas and flowcharts)?

AnQi CMS provides users with powerful and flexible content management capabilities, among which the support for Markdown format greatly improves the efficiency of content creators.Whether it is necessary to display complex mathematical formulas in technical articles or to present clear flowcharts in product documents, Anqi CMS can help you beautifully present these contents on the frontend page. To achieve this goal, we need to follow several steps, from backend settings to frontend template adjustments, to ensure that the content is correctly parsed and rendered.### First step: Enable Markdown editor in the background First

2025-11-08

How to filter and display a list of documents with specific titles or categories in content management?

Today, as content management is increasingly becoming the core competitiveness of corporate websites, AnQiCMS (AnQiCMS) helps us easily manage a large amount of content with its flexible and efficient features.When you need to accurately filter and display a list of documents with specific titles, categories, or attributes, AnQiCMS provides intuitive and powerful template tags to make this process simple and efficient.### Core Tool: `archiveList` Tag Overview To display the document list on the website front-end, we mainly use AnQiCMS's core template tags

2025-11-08

How to batch generate and display images in Webp format in AnQi CMS?

Website performance is one of the key factors that determine user experience and search engine rankings.Among various optimization methods, image optimization plays a vital role.WebP is a modern image format that boasts excellent compression performance and almost lossless visual quality, and is gradually becoming the new standard for website optimization.How can we efficiently generate and display WebP images in the Anqi CMS management website?AnQi CMS provides very convenient and powerful functional support in this aspect, allowing you to easily achieve the WebPization of website images without delving into technical details

2025-11-08

How to automatically compress images based on size and display them on the front-end?

In website operation, images are an important element to attract visitors and convey information.However, large, unoptimized images often become the 'killer' of website loading speed, not only affecting user experience, but also possibly dragging down search engine rankings.Luckyly, AnQiCMS (AnQiCMS) provides very intelligent and practical image processing functions that can help us easily cope with these challenges, making images clear and fast when displayed on the front end.### Smart compression, goodbye to manual adjustment of large images Have you ever encountered such a situation: in order to maintain image quality

2025-11-08

How to configure and display thumbnails with different processing methods (such as cropping, scaling)?

##驾驭安企CMS缩略图:精细化的配置与灵活的展示,打造视觉冲击力 在网站运营中,图片无疑是吸引用户、提升内容质量的关键元素。While thumbnails, as the first visual touchpoint of website content, their display effect directly affects users' desire to click and the overall beauty of the page.AnQi CMS knows this and provides us with flexible thumbnail configuration and display capabilities, helping us easily manage and present high-quality image content.### Core Configuration

2025-11-08

How to display detailed information of the currently logged-in user (such as username, avatar, VIP status)?

In Anqi CMS, displaying the detailed information of the currently logged-in user, such as username, avatar, and VIP status, is a key step to enhance user experience and build a personalized website.AnQi CMS with its flexible template engine allows us to easily implement these features.This article will introduce how to display this information on your website front-end. ## Retrieve basic information of the currently logged-in user The Anqi CMS template system provides the `userDetail` tag, which is the core tool for retrieving various information of the currently logged-in user.This tag can directly retrieve the user data of the current session

2025-11-08