How to use a filter to truncate the specified character length of an article description or abstract and automatically add an ellipsis?

Calendar 👁️ 59

In website operation, the presentation of article descriptions or summaries is crucial for user experience and Search Engine Optimization (SEO).A well-balanced, concise summary that not only attracts visitors to click but also helps search engines better understand the page content.However, manually controlling the length of each article summary is time-consuming and prone to errors.Luckyly, AnqiCMS provides powerful template filter functions that can help us automate this process, ensuring the uniformity and beauty of website content display.

Why is it necessary to truncate the article description or abstract?

Our website often needs to display article descriptions or summaries, especially on article lists, search results, or special pages.If these descriptions are too long, it may cause page layout confusion and affect reading experience;If it is too short, it may not effectively convey the main theme of the article. Moreover, when search engines display search results, they will also cut the page description according to the preset character length, and if it is too long, it will be automatically truncated, affecting the display effect.

AnqiCMS based on Django style template engine, its built-in filter function is the tool to solve this problem.By using simple template code, we can easily achieve intelligent extraction of article descriptions or summaries, and automatically add ellipses to make the content display more professional and unified.

AnqiCMS template filter: the beautician of content

In AnqiCMS template files, variables are usually enclosed in double curly braces{{ 变量名 }}The form appears. And a filter, as the name implies, is a tool for 'filtering' or 'processing' these variables. Its usage is to add a vertical line after the variable name|,followed by the filter name and optional parameters, for example{{ 变量 | 过滤器名称: 参数 }}.

AnqiCMS is built-in with a variety of practical filters, among which is the one used to truncate strings and add an ellipsis,truncatechars/truncatewordsand its corresponding HTML versiontruncatechars_html/truncatewords_htmlThese filters can not only cut text to a specified length but also automatically add “...” at the cut-off point, saving the trouble of manual concatenation.

Core Tool: String Trimming Filter

  1. truncatechars: 长度(By character cut)This filter will truncate the string according to the specified number of characters. It should be noted that the "length" parameterThe number of characters occupied by the ellipsis itselfIt is suitable for scenarios where strict control of character numbers is required, such as when each article abstract on the list page must be of fixed length.

  2. truncatewords: 数量(Word-wise truncation)withtruncatecharsdifferent,truncatewordsThe string will be truncated according to the specified number of words, avoiding truncation in the middle of a word.This can maintain the semantic integrity of text in English or other languages separated by spaces.Similarly, it will also automatically add an ellipsis.

  3. truncatechars_html: 长度andtruncatewords_html: 数量(Handle HTML content)If your article description or summary content already includes HTML tags (such as bold, links, etc.), and you want to retain the structural integrity of these tags when extracting, then_htmlThe suffix filter is your **choice. They will intelligently identify and close HTML tags to prevent page structure chaos due to truncation.

Practical Application: Extracting Article Description or Summary

Suppose we are designing an article list page, which needs to display the title and brief introduction of each article. The brief introduction of the article is usually stored inDescriptionin the field.

Scene one: Extract pure text description

On the article list page, we usually usearchiveListTags to cyclically display articles. We can directly applyitem.DescriptionontruncatecharsFilter:

{# 假设这是文章列表页模板中的循环部分 #}
{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
    <div class="article-item">
        <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
        {# 截取描述为 100 个字符,并自动添加省略号 #}
        <p>{{ item.Description|truncatechars:100 }}</p>
        <a href="{{ item.Link }}" class="read-more">阅读更多</a>
    </div>
    {% empty %}
    <p>暂时没有文章。</p>
    {% endfor %}
{% endarchiveList %}

In this example,item.DescriptionThe content will be truncated to a maximum of 100 characters (including ellipsis), and an ellipsis will be automatically added at the end.If the description itself is less than 100 characters, it will not be truncated or ellipsis will not be added.

Scene two: Extract article content as a summary

Sometimes, we may not have a separateDescriptionfield, or you want to extract part of the article directlyContentas a summary. The content of the article usually contains rich HTML tags, at this point, it is necessary to usetruncatechars_htmla filter and combinesafeA filter to ensure that HTML is rendered correctly.

{# 在文章详情页或者其他需要展示文章内容摘要的地方 #}
{% archiveDetail currentArticle with name="Content" %}
    <div class="article-summary">
        {# 将文章内容截取为 200 个字符的摘要,保留HTML结构,并安全输出 #}
        {{ currentArticle|truncatechars_html:200|safe }}
    </div>
{% endarchiveDetail %}

{# 或者在文章列表页循环中,使用 item.Content #}
{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
    <div class="article-item">
        <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
        {# 将文章内容截取为 150 个字符的摘要,保留HTML结构,并安全输出 #}
        <div class="summary-from-content">{{ item.Content|truncatechars_html:150|safe }}</div>
        <a href="{{ item.Link }}" class="read-more">阅读更多</a>
    </div>
    {% empty %}
    <p>暂时没有文章。</p>
    {% endfor %}
{% endarchiveList %}

Here, item.Content(orcurrentArticleThe content within the brackets even includes<strong>/<a>such as HTML tags,truncatechars_htmlcan also maintain the integrity of these tags when cut out.|safeThe filter tells the template engine that this HTML code is safe and can be output directly without escaping, thereby avoiding displaying<p>...</p>such raw tags.

Select the appropriate truncation method

  • truncatecharsvstruncatewords: If you are more concerned about the visual width of the display area, and want to strictly control the number of characters, thentruncatecharsIt's a good choice. If the content is mainly in English and you hope the abstract to be more semantically complete,truncatewordsit would be better, as it will not break a word in the middle.
  • _htmlThe use of suffixes.: Just make sure that your description or summary content may contain any HTML tags, and you must use a filter with_htmlsuffix and combine|safeA filter to prevent abnormal display or security issues on the page.

By flexibly using these filters, AnqiCMS users can easily manage the display of all articles' descriptions and summaries on the website, ensuring that the website presents content in an elegant and consistent layout on any device, thereby enhancing the overall website quality and user experience.

Frequently Asked Questions (FAQ)

Ask: Does the truncated length include the characters of the ellipsis?Answer: Yes, when usingtruncatecharsortruncatechars_htmlWhen filtering, the number length you specify includes the automatically added ellipsis (i.e., “…”). For example, if you settruncatechars:100The final output text, including ellipses, is at most 100 characters.

Ask: If my article description is shorter than the specified length, will an ellipsis be added?Answer: No. The extraction filter of AnqiCMS is intelligent.Only when the length of the original content exceeds the value specified, will it be truncated and an ellipsis will be added.If the length of the original content is less than or equal to the specified length, the content will be displayed in full and no ellipsis will be added.

Ask: How to extract the content of an article containing HTML tags as a summary without destroying the structure?Answer: To safely and correctly extract content containing HTML tags, you should usetruncatechars_htmlortruncatewords_htmlFilter. Since the content processed by these filters is still HTML, you need to use the filter immediately afterwards|safeFilter to indicate the template engine

Related articles

Besides `stampToDate`, which filters can format time values into a specified date format?

In AnQi CMS template development, we often need to display the time values stored in the database, such as the publication time and update time of articles, in the date and time format we expect.The `stampToDate` filter is undoubtedly one of the most commonly used and powerful tools, which can flexibly convert Unix timestamps to various date formats.

2025-11-08

How to combine custom parameters (such as "area", "house type") for multi-condition filtering on the article list page?

In AnQi CMS, to implement multi-condition filtering on the article list page, such as filtering based on custom parameters such as "area" and "house type", it requires us to cleverly combine the system-provided "content model" feature with the "document parameter filtering tag" ("archiveFilters") and "document list tag" ("archiveList") of the front-end template.The entire process can be divided into several core steps, let's take a detailed look together.### Core Function: Customize Content Model and Parameters Basic Implementation of Multi-Condition Filtering

2025-11-08

How to implement search through URL parameters (such as `q=keyword`) on the article list page and display the results?

It is crucial to provide users with a convenient and accurate content search experience in website content operation.When the number of articles on the website continues to grow, a practical search function can greatly enhance user satisfaction and the efficiency of content access.AnqiCMS as an efficient content management system provides a flexible way to implement the URL parameter search function for the article list page, allowing visitors to directly search and view related content by adding parameters such as `q=keywords` to the URL.

2025-11-08

How to dynamically add a website name suffix or custom delimiter in the page title (Title)?

The page title (Title) is the 'front door' of a website on the search engine results page. It not only can intuitively tell users the content of the page, but it is also an important indicator for search engines to evaluate the relevance and authority of the page.An optimized page title that can significantly improve click-through rates and the website's search engine ranking.In AnQiCMS, you can flexibly control the way page titles are generated, especially by dynamically adding the website name suffix and custom delimiters to achieve a unified brand image and better SEO effect.### AnQiCMS in TDK

2025-11-08

How to perform addition or other arithmetic operations on numbers or strings in the template?

In website template development, we often need to perform some basic arithmetic operations, such as calculating the sum, adjusting values, or comparing values based on specific conditions.AnQiCMS (AnQiCMS) boasts an efficient architecture based on the Go language and a flexible template engine inspired by the Django style, providing users with an intuitive and powerful way to perform arithmetic operations such as addition of numbers or strings in templates.

2025-11-08

How to set a default display value for a possibly empty variable, string, or object?

In website content management, the integrity and consistency of data are crucial.However, in actual operation, we often encounter situations where certain variables, strings, or objects may be empty.If the template does not handle these null values properly, the front-end page may appear blank, disordered, or even report errors, severely affecting user experience.AnQiCMS provides various flexible and powerful template tags and filters, helping us elegantly handle potential null values to ensure the stability and beauty of website content.The AnQi CMS template system borrows the syntax from Django

2025-11-08

How to use a filter to remove specific characters (such as spaces) from the beginning, end, or any position of a string?

String cleaning practical guide in AnQiCMS: Efficiently remove filters for specific characters During the operation of a website, we often encounter situations where we need to clean and format string data.Whether it's the extra spaces typed by users or redundant characters carried in when importing content from external sources, these subtle details may affect the neatness of website content and the user experience.AnQiCMS (AnQiCMS) provides a multifunctional and easy-to-use template filter that can help us easily deal with these string cleaning needs.

2025-11-08

How to use a filter to automatically find URLs in text and convert them into clickable HTML links?

In website operation, we often encounter such needs: in the content or description of the article, some URLs or email addresses may be included, but they are just plain text, and users cannot click to access directly.Manually adding HTML links to each URL is inefficient and prone to errors, especially when the volume of content is large.AnQiCMS (AnQiCMS) understands this pain point and provides powerful built-in filters to help us easily automate the conversion of URLs in text, making website content more friendly and convenient.### Automated Link

2025-11-08