How to truncate long text content and add an ellipsis at the end to optimize list display?

Calendar 👁️ 64

In website operation, especially managing content-rich platforms, the display effect of list pages is crucial to user experience.Whether it is an article list, product overview, or news update, we hope the page is tidy and the information is clear at a glance.However, when the document content or description is too long, it often leads to chaos in the layout of the list, affecting the overall aesthetics and information acquisition efficiency.At this moment, it is particularly important to effectively truncate text and add an ellipsis.

AnQiCMS (AnQiCMS) provides a powerful and flexible template system, where built-in text filters can help us easily solve this problem.By skillfully using these filters, we can not only optimize the display of the list, but also maintain the conciseness and efficiency of the code.

Understanding the importance of text truncation

Imagine if every article on your article list page displayed a complete several-hundred-word introduction, the page would become very long, and users would need to scroll for a long time to view a limited amount of content, which would undoubtedly greatly reduce reading interest. By truncating the long text content to a fixed length and adding an ellipsis at the end, we can:

  • Improve visual consistency:Ensure that each item's introduction length is similar in the list, making the page layout more tidy.
  • Optimize the reading experience:Users can quickly scan the title and concise introduction to decide whether to click to view the details.
  • Avoid layout misalignment:Prevent long text from expanding the container, causing the layout of page elements to become chaotic.
  • Highlight the key information:Compel the editor to extract the most attractive content within a limited number of words.

AnQiCMS's solution: Text Extraction Filter

The Anqi CMS template engine provides various text filters that can process variable content.Among them, the filter specifically used for truncating text and automatically adding ellipses is the key to solving the problem of list display.

Generally, you will bearchiveList(Document list tag) orpageListPage list tag processing in the loopitem.Title(Title),item.DescriptionOr descriptionitem.ContentText field content such as. Its basic usage format is{{ 变量 | 过滤器名称: 参数 }}.

1. Truncate by character count:truncatechars

If you want to truncate text based on an exact character count, you can usetruncatecharsA filter that calculates the specified number of characters from the beginning of the text, truncates it, and automatically adds an ellipsis at the end (...)

For example, we want to truncate the article description to 80 characters:

{{ item.Description|truncatechars:80 }}

Handle special cases of HTML content:truncatechars_html

Whenitem.Descriptionoritem.ContentWhen it may contain HTML tags (such as formatted text generated by a rich text editor), use directlytruncatecharsIt may truncate incomplete HTML tags, thereby breaking the HTML structure of the page. To avoid this, Anqi CMS providestruncatechars_htmlA filter. It can intelligently process HTML tags, and when extracting text, it tries to maintain the integrity of the HTML structure as much as possible.

At the same time, due totruncatechars_htmlThe processed content is still HTML, to ensure that the browser parses it correctly, you need to use|safea filter to prevent the template engine from escaping the HTML characters.

{# 假设 item.Description 包含 HTML 标签 #}
{{ item.Description|truncatechars_html:120|safe }}

2. Extract by word count:truncatewords

In some cases, especially on English websites, extracting by words may be more in line with reading habits.truncatewordsThe filter will truncate text based on the number of words and add an ellipsis at the end. It will try to avoid truncating in the middle of a word.

For example, we want to truncate the article description to 20 words:

{{ item.Description|truncatewords:20 }}

Handle special cases of HTML content:truncatewords_html

withtruncatecharsSimilarly, when the text contains HTML tags, it should also be used.truncatewords_htmlA filter to intelligently retain HTML structure, and it also needs to be combined|safefilter.

{# 假设 item.Content 包含 HTML 标签 #}
{{ item.Content|truncatewords_html:30|safe }}

Actual application example

Suppose you are designing a list page of articles, hoping that each article will display the title and a brief description.The title is too long and needs to be truncated, the description may contain rich text content and also needs to be truncated.

In your list template file (for examplearchive/list.htmlorindex/index.html), there may be the following code snippet:

{% archiveList articles with type="page" limit="10" %}
    {% for item in articles %}
    <div class="article-card">
        <a href="{{ item.Link }}" class="card-link">
            {% if item.Thumb %}
                <div class="card-thumb">
                    <img src="{{ item.Thumb }}" alt="{{ item.Title|truncatechars:40 }}">
                </div>
            {% endif %}
            <div class="card-content">
                <h3 class="card-title">{{ item.Title|truncatechars:50 }}</h3> {# 标题截取为50个字符 #}
                <p class="card-description">{{ item.Description|truncatechars_html:150|safe }}</p> {# 描述截取为150个字符,并安全渲染HTML #}
                <div class="card-meta">
                    <span>发布时间:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
                    <span>阅读量:{{ item.Views }}</span>
                </div>
            </div>
        </a>
    </div>
    {% else %}
    <p>暂时没有文章内容。</p>
    {% endfor %}
{% endarchiveList %}

{# 页面底部的分页导航 #}
{% pagination pages with show="5" %}
    <div class="pagination-nav">
        {% if pages.PrevPage %}<a href="{{ pages.PrevPage.Link }}" class="prev-page">&laquo; 上一页</a>{% endif %}
        {% for pageItem in pages.Pages %}
            <a href="{{ pageItem.Link }}" class="page-number {% if pageItem.IsCurrent %}active{% endif %}">{{ pageItem.Name }}</a>
        {% endfor %}
        {% if pages.NextPage %}<a href="{{ pages.NextPage.Link }}" class="next-page">下一页 &raquo;</a>{% endif %}
    </div>
{% endpagination %}

By the above code, the titles and descriptions in the article list will be uniformly truncated to the specified length regardless of the original length, and ellipses will be automatically added. At the same time, it ensures the correct display of rich text content, greatly improving the visual effects and user experience of the page.

Optimization suggestions and precautions

  1. Reasonably set the截取 length:The length of the excerpt is not the shorter the better. It needs to be decided based on the design of your website, the type of content, and the amount of information you want to provide.It is recommended to test on different devices to ensure that it presents well on both PC and mobile ends.
  2. Maintain consistency across the entire site:Once a content type's truncation rule in the list is determined, it is best to maintain consistency across the entire site, avoiding different truncation lengths on different pages. This helps to establish a unified brand image and user experience.
  3. UnderstandingtruncatecharswithtruncatewordsThe difference is:
    • truncatecharsMore precise at the character level, but may truncate words in English text. For Chinese, one character counts as one character, so the impact is not great.
    • truncatewordsRespects word boundaries, which makes it more natural in English text, but it may not be as concisetruncatecharsPrecise control.
  4. Use with caution.|safe: |safeThe filter tells the template engine that the content you output is safe HTML and does not need to be escaped. If the content source is unreliable, use it directly|safeMay pose XSS (Cross-Site Scripting) risk. However, the content published on the back-end of AnQi CMS is usually controllable, and working with_htmlfiltering can safely render rich text.

By using these techniques, you can flexibly manage the display of long text content lists in Anqi CMS, providing users with a better browsing experience.


Common questions (

Related articles

How to safely output HTML tags in website content to avoid escaping?

In website content management, especially when content includes rich formats or user input, how to safely output HTML tags is a crucial issue.AnQiCMS (AnQiCMS) fully considered this from the beginning, its template engine defaults to escaping output variables to effectively prevent cross-site scripting attacks (XSS) and other security risks.### Understanding the Default Behavior of Template Engines The Anqi CMS template engine follows the syntax of mainstream frameworks like Django, one of its core concepts being 'Security First'

2025-11-08

How to embed mathematical formulas and flowcharts in a page and ensure correct rendering display?

In website operation, we often need to display some professional content, such as mathematical formulas involving scientific calculations, or complex flowcharts for business process descriptions.The traditional way of displaying this content is often inefficient, difficult to maintain, and also does not provide a good reading experience.AnQiCMS combines its powerful content management capabilities and support for Markdown to provide us with an elegant solution.By simply introducing some external libraries and enabling the Markdown editor, we can display the professional content correctly on the website page

2025-11-08

How to implement pagination navigation display for content list in AnQi CMS?

When using AnQiCMS to build a website, it is particularly important to have reasonable pagination navigation when displaying a large amount of content, such as article lists, product lists, etc.It not only enhances user experience, making it easier for visitors to browse and find content, but also helps search engines better crawl the website.AnQi CMS provides a very intuitive and powerful pagination tag, making it easy to display content list pagination.### Step 1: Prepare the content list data To implement pagination of the content list, you first need to use `archiveList`

2025-11-08

How to call and display the friendship link set in the background on the front end?

AnQiCMS (AnQiCMS) provides a set of intuitive and powerful content management features, among which the management of 'friend links' is an indispensable part of website operation. It not only promotes the SEO performance of the website but also provides users with convenient navigation.This article will give a detailed introduction on how to call and elegantly display the friendship links you set in the background. ### Friend link backend configuration Managing friend links in Anqi CMS is very simple.You just need to log in to the back-end, find the "Function Management" module in the left menu bar, click to enter "Friend Links". Here

2025-11-08

How to convert image addresses to thumbnail format for display?

In website operation, images play a crucial role.They can not only attract users' attention but also effectively convey information.However, very large images can severely affect website loading speed, thereby damaging user experience and search engine rankings.Therefore, converting the image address to a thumbnail format for display has become an indispensable part of optimizing website performance.AnQiCMS provides very convenient features in this aspect, it can automatically generate and manage thumbnail images for your website, and also provides flexible calling methods to help you easily meet the challenges of image optimization.### AnQiCMS

2025-11-08

How to display the background custom banner (Banner) image list in the template?

The banner image on the website is an important element to attract visitors' attention and display core information.In Anqi CMS, you can flexibly customize these banner images in the background and elegantly present them in various template positions on the website.Below, we will discuss in detail how to display the custom banner image list in the template, making your website more attractive. ### Configuration and Management of Background Banner Images In the Anqi CMS backend, the management of banner images is mainly divided into two cases: global homepage banners and specific content banners. 1.

2025-11-08

How to dynamically display different content blocks based on conditions (if tag)?

In Anqi CMS, the dynamic display of website content is the key to improving user experience and operational efficiency.You often encounter such needs: you want a certain content block to appear only under specific conditions, or to display different information for different situations.At this point, the powerful conditional judgment feature of Anqi CMS - the `if` tag, can be put to good use.The Anqi CMS template system adopts a syntax similar to the Django template engine, allowing you to implement logical judgments in templates in a straightforward manner.By flexibly using the `if` tag, you can easily control the display and hide of web elements

2025-11-08

How to use a loop (for label) to traverse and display a content list?

In Anqi CMS, whether it is displaying article lists, product catalogs, navigation menus, or friend links, we will frequently deal with content lists.To dynamically display this content on the website front-end, you can't do without powerful looping functions.Today, let's delve deeper into how to use the loop (`for` tag) in Anqi CMS templates to traverse and display your content list. ### The core syntax of the `for` tag: Bring content to life The Anqi CMS template syntax is similar to Django and Blade, very intuitive.When you need to handle a set of data

2025-11-08