How to truncate the title or abstract of an article and display it with an ellipsis?

Calendar 👁️ 89

In website content operation, the title and introduction are important elements to attract visitors to click and understand the details.Especially on list pages, recommendation spots, or the homepage, the limited space requires us to refine and trim the content.In order to maintain the neat and beautiful appearance of the page while fully conveying the core information, truncating overly long article titles or summaries and ending with an ellipsis “…” is a commonly used optimization strategy.AnQiCMS (AnQi CMS) provided us with flexible and powerful tools to meet this requirement.

Why should the title and summary be truncated?

Imagine if each title on your website's list page varied in length, with some even taking up two or three lines. This would not only make the page look disorganized but would also significantly reduce the efficiency and experience of browsing. There are several core benefits to truncating titles and summaries:

  • Maintain uniform page layout:Ensure that the content is presented in a neat style in different display areas (such as article lists, hot recommendations, related articles, etc.) to avoid page element jumps or misalignments caused by uneven content length.
  • Improve reading efficiency:Users can quickly scan multiple titles and summaries, quickly judge whether the content meets their interests, and improve the efficiency of information acquisition.
  • Optimize the mobile experience:On smaller mobile devices, concise titles and summaries can better adapt to limited display space, enhancing readability.
  • Focus on core information:Encourage content creators to distill the most critical information in the title and summary, allowing readers to grasp the key points at a glance.

The truncation tool in AnQiCMS: A powerful filter

AnQiCMS template engine provides a series of built-in filters (Filters), which can help us process data in various ways, including formatting, conversion, and truncation. To implement the truncation of article titles and summaries with an ellipsis, we mainly usetruncatecharsandtruncatewordsFilters of these families.

These filters are all|Connected by symbols after the variables to be processed, followed by the filter name and parameters.

Understand the four truncation filters and their application scenarios

AnQiCMS provides four main truncation filters to meet different content types and truncation requirements:

  1. truncatechars(truncating plain text by characters)

    • Function:This filter will truncate text based on the number of characters you specify.No matter if it is Chinese or English, it will count each character as a unit and add an ellipsis after reaching the specified length.
    • Application scenario:When you need to precisely control the display length of plain text titles or summaries, such as in navigation menus, tags, and other places with strict length restrictions.
    • Example: {{ article.Title|truncatechars:20 }}If the title exceeds 20 characters, it will be truncated and an ellipsis will be displayed.
    • Note:If the truncation position is exactly in the middle of a Chinese character or an English word, it may cause incomplete display.
  2. truncatewords(Truncate pure text by word)

    • Function:This filter will truncate text based on the number of words you specify and add an ellipsis after the last complete word. It is moretruncatecharsMore "intelligent", it will not truncate words in progress, thus maintaining the semantic integrity of English content.
    • Application scenario:Mainly used for truncating English titles or summaries, which can avoid ugly displays like 'this is a lo...'.
    • Example: {{ article.Description|truncatewords:15 }}If the introduction exceeds 15 words, it will be truncated.
    • Note:This is invalid for Chinese content because Chinese does not have the concept of 'word'.
  3. truncatechars_html(Character-truncate HTML content while retaining tag structure)

    • Function:withtruncatecharsSimilar, it also truncates by character count, but it can intelligently handle content containing HTML tags.It ensures that all opened HTML tags are properly closed while truncating, thus avoiding layout chaos due to incomplete tags.
    • Application scenario:When your profile content may contain bold, links, and other small HTML tags, this filter can help you maintain these styles when truncating.
    • Example: {{ article.Description|truncatechars_html:80|safe }}Indicates a brief description that includes HTML. If it exceeds 80 characters (HTML tags are not counted in the character count), it will be intelligently truncated.
    • Note:When using this filter to process HTML content,Mandatory to add at the end of the filter chain|safeFilter.|safeIt will tell the AnQiCMS template engine that this content is safe HTML and should be rendered directly without escaping.
  4. truncatewords_html(Truncate HTML content by word, retaining tag structure)

    • Function:Combined withtruncatewordsandtruncatechars_htmladvantages, truncate English HTML content by word count and retain complete HTML tag structure.
    • Application scenario:Applicable to English summaries containing a small amount of HTML tags.
    • Example: {{ article.Description|truncatewords_html:20|safe }}.
    • Note:It also needs to be配合|safeFilter usage, not applicable to Chinese content.

Practice in AnQiCMS template: taking the article list as an example

In AnQiCMS, you can use the article list (usually usingarchiveListtags) or the article detail page (usingarchiveDetailApply these filters in the template label. Below we show an example of how to apply these truncation filters in a real template:

Suppose you have a template for an article list that needs to display the article title and summary:

{# 使用 archiveList 标签获取文章列表 #}
{% archiveList articles with type="list" limit="10" %}
    {% for article in articles %}
    <div class="article-item">
        <a href="{{ article.Link }}" class="article-link">
            {# 文章标题:按字符截断,最多显示30个字符 #}
            <h3 class="article-title">
                {{ article.Title|truncatechars:30 }}
            </h3>
            {# 文章简介:按字符截断HTML内容,最多显示80个字符,并确保HTML标签正常显示 #}
            <p class="article-description">
                {{ article.Description|truncatechars_html:80|safe }}
            </p>
        </a>
        {# 文章发布时间,使用 stampToDate 过滤器格式化 #}
        <span class="article-date">{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
    </div>
    {% else %}
    <p class="no-articles">抱歉,目前没有找到任何文章。</p>
    {% endfor %}
{% endarchiveList %}

In this code block:

  • {{ article.Title|truncatechars:30 }}It will truncate the article titlearticle.Titleto a maximum of 30 characters.
  • {{ article.Description|truncatechars_html:80|safe }}It will truncate the article summaryarticle.DescriptionTruncated to a maximum of 80 characters. Since the introduction may contain HTML (such as bold text), we usetruncatechars_htmlto intelligently handle tags, and use|safeMake sure the HTML code is correctly parsed and displayed by the browser.

In this way, even if your article title or summary content is long, it can be displayed in a unified, tidy, and easy-to-read form on the page.

Caution when using these truncation filters

  1. Selection of Chinese content:It is recommended to use Chinese titles and descriptions first fortruncatecharsortruncatechars_html. Because Chinese does not have the concept of 'words' like English, truncatewordsThe series filter does not work effectively.
  2. Rendering of HTML content:When processing content that may contain HTML tags (such as summaries generated by rich text editors), usetruncatechars_htmlortruncatewords_htmlIs the correct choice. But remember, at the end of these filters.Must be added.|safe Otherwise, the browser will display the truncated HTML tags as plain text, rather than rendering their effects.
  3. Truncation length test: The appropriate truncation length depends on your website design and layout.It is recommended to perform multiple tests on the actual template, observe the effects of different lengths, and choose the value that best balances beauty and information transmission.
  4. The ellipsis is automatic: The AnQiCMS truncation filter will automatically add an ellipsis (...) after truncating the content, so you do not need to add it manually.

Summary

In AnQiCMS, by using flexible applicationstruncatechars/truncatewordsAnd its HTML version filter, we can easily implement the elegant truncation and ellipsis display of article titles and summaries.This can greatly enhance the beauty and consistency of the website interface, and it can also optimize the user's reading experience, helping your content stand out among numerous pieces of information.Mastery of these filters will make your website operations more efficient and professional.


Frequently Asked Questions (FAQ)

  1. Ask: Can the ellipsis displayed after truncation be customized in style or content?

    • Answer: The AnQiCMS built-in truncation filter automatically adds "..." as an ellipsis.The template engine at this level does not support customizing the style or content of the ellipsis directly.If your design requirements are high, you may need to consider performing a secondary processing of truncated text through JavaScript on the front end to achieve this.
  2. Ask: If my article title or introduction is already quite short and does not reach the set truncation length, will an ellipsis still be displayed?

    • Answer: No. These truncation filters of AnQiCMS are very smart.They will only truncate and add an ellipsis when the actual length of the content exceeds the truncation length you set.If the content itself meets the length requirement, it will be displayed in full without any ellipsis

Related articles

How to display the custom parameter list in the article content on the front page?

AnQiCMS as an efficient and customizable content management system provides powerful content model features, allowing us to add various custom fields to articles according to different business needs.These custom parameters not only make the article content more rich and structured, but also allow for personalized display on the front page, greatly enhancing the flexibility and user experience of the website.Today, let's delve into how to flexibly display these custom parameter lists in the AnQiCMS front page.

2025-11-07

How to use the `pagination` tag to build standard pagination navigation in the template?

When the content of a website becomes richer, a clear and efficient pagination navigation system is crucial for improving user experience.The AnQiCMS template system provides a powerful `pagination` tag that allows us to easily build standard, beautiful pagination navigation.Next, we will delve deeper into how to use this tag in templates.

2025-11-07

How to display the number of comments for each article on the article list page?

In website operation, the article list page is not only the entrance of content, but also a window for users to understand the activity level of the website.When users see that every article is accompanied by a comment count, this not only effectively enhances the interactivity and attractiveness of the article, but also brings positive social proof to the website, encouraging more readers to participate in discussions.For users who use AnQiCMS, displaying the number of comments for each article on the article list page is a very direct and practical feature.

2025-11-07

How to ensure that the website displays a custom prompt to users when it is in "shutdown" status?

In website operation, we sometimes encounter situations where we need to temporarily close the website, such as for system maintenance, major upgrades, data migration, or dealing with unexpected security events.For any reason, directly allowing users to access a blank page or an error page will severely affect user experience and even damage the brand image.At this time, it is particularly important to clearly display a friendly prompt message to visitors.

2025-11-07

How to use logical tags like `if` and `for` in templates to control conditional and repeated display of content?

In website content management, displaying dynamic and diverse content is the key to improving user experience and website attractiveness.AnQiCMS (AnQiCMS) provides a powerful template system, drawing inspiration from the Django template engine syntax, allowing you to easily control the display of content through logical tags.Among them, the `if` tag is used for conditional judgment, while the `for` tag is used for loop iteration, they are the foundation for building flexible and variable web pages.

2025-11-07

How to safely display rich text content containing HTML tags on the front-end page?

In website operation, we often need to display rich content that includes images, links, bold text, and so on, which is known as rich text content.But it is a practical and careful task to safely display these rich text with HTML tags on the front-end page.AnQi CMS as an efficient content management system, fully considers this point, and provides us with a clear solution.

2025-11-07

How to dynamically display the current year or current time in a template?

In website operation, we often need to dynamically display the current year or time, such as displaying the latest copyright year at the bottom of the website, or marking the generation time of the page accurately in articles.AnqiCMS provides flexible and powerful template functions, making these operations very simple.Next, we will discuss how to implement this requirement in the AnqiCMS template.

2025-11-07

How to reflect the high concurrency characteristics of the Go language in the front-end page loading speed?

In today's fast-paced online world, website loading speed has become a core factor in user experience and search engine rankings.Nobody likes to wait for a slow page, and search engines tend to rank websites that respond quickly higher.How can you make your website lightning fast?For users of AnQiCMS, the answer is hidden in its powerful Go language underlying architecture, especially the high concurrency features that Go language boasts.

2025-11-07