How to extract the article summary and add an ellipsis in AnQiCMS template?

Calendar 👁️ 60

In website operation, how to make the article list page both beautiful and informative is a common concern.We usually do not display the full content of the article on the list page, but instead use a brief 'abstract' to attract readers to click.To maintain the neat and professional appearance of the page, these summaries often need to be automatically truncated when exceeding a certain length and appended with an elegant ellipsis.

AnQiCMS as a powerful content management system provides flexible tools in the template to help us meet this requirement.Below, let's discuss in detail how to extract the article abstract and display an ellipsis in the AnQiCMS template.

Source of the abstract content:DescriptionField priority,ContentField secondary,

In AnQiCMS, every article has two important content fields that can be used as the source of the abstract:

  1. Description(Document summary)This is the most ideal source for a summary. When publishing articles in the background, there is usually a 'Document Summary' input box where you can manually fill in a concise text as a summary of the article.The official documentation of AnQiCMS also recommends keeping the document summary within 150 characters.If you do not fill in manually, the system will automatically fromContentExtract the first 150 characters as the default description. This field is typically plain text, or it may contain a small amount of simple HTML tags.

  2. Content(Document Content)This is the complete content of the article, which may contain rich pictures, videos, and various HTML structures. WhenDescriptionthe field is empty, we can take fromContentExtracting a part as a summary. ButContentThe field is rich text, and directly extracting it may damage the HTML structure, causing the page to display abnormally, so it needs to be handled specially.

After understanding these two sources, our strategy is to use them firstDescriptionfield when it is empty, then fromContentfield to intelligently extract.

Extract pure text summary:truncatecharsFilter

When you are sureDescriptionFields are plain text when you can usetruncatecharsa filter to truncate content by character count and automatically add an ellipsis.

Usage:In article loop (usuallyarchiveListwithin the labelforloop) you can call it like this:

{{ item.Description|truncatechars:长度 }}

Among them,长度Is the total number of characters you want to display in the summary, this length includes the characters occupied by the ellipsis ("...").

Example:If you want to display a maximum of 100 characters in the summary:

<p>{{ item.Description|truncatechars:100 }}</p>

Ifitem.DescriptionThis is an article about AnQiCMS template creation, it is very detailed, and I hope it can help everyone.This is just a test summary, let's see how the truncation effect is.This is just a test abstract, see the effect of truncation in this form...

Process a summary containing HTML:truncatechars_htmlFilter

When your summary content comes fromContenta field (it is rich text), orDescriptionif the field may contain HTML tags, use it directlytruncatecharsIt may truncate unclosed HTML tags, causing the page layout to be confused. At this time,truncatechars_htmlThe filter comes into play. It can intelligently extract HTML content while ensuring that all tags are properly closed, thus maintaining the integrity of the page structure.

Usage:

{{ item.Content|truncatechars_html:长度|safe }}

Here are two points to note:

  1. truncatechars_html:长度This filter will truncate HTML content to a specified character length and intelligently close all open HTML tags.
  2. |safeThis is a crucial step! The AnQiCMS template engine defaults to HTML-escaping all output content to prevent XSS attacks.This means, if you do not add|safeThe HTML tag (such as<p>,<strong>) will be displayed as plain text and not parsed by the browser. Add|safeAfter that, the template engine will consider this content safe, thus rendering it in HTML format.

Example:If you wish to extract up fromContentto get the most 150 characters as a summary:

<div>{{ item.Content|truncatechars_html:150|safe }}</div>

Even ifitem.ContentIt is a complex HTML snippet,truncatechars_htmlAlso be careful when cutting, to ensure the integrity of such tags,<p>...</p>/<strong>...</strong>and correctly add ellipses.

Extract by word:truncatewordsandtruncatewords_htmlFilter (optional)

In addition to truncating by characters, AnQiCMS also provides a summary truncation filter based on words, which is especially useful for English or other languages separated by spaces, as it can prevent truncating a word in the middle, making the summary reading more natural.

  • truncatewordsUsed for plain text content,截取 by word count.{{ item.Description|truncatewords:20 }}(Extract 20 words)
  • truncatewords_htmlUsed to include HTML content, truncating by word count while maintaining HTML structure.{{ item.Content|truncatewords_html:25|safe }}(Truncate to 25 words and safely render HTML)

Practical Application: Build an Intelligent Summary Display Logic

To achieve **effect, we usually combine the above methods to build an intelligent summary display logic: priority displayDescriptionField, ifDescriptionis empty, thenContent截取字段并安全渲染,最后再加入一个默认文本作为最终的备选。

以下是一个完整的模板代码片段,展示了如何在archiveListImplement this logic in the loop:

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
    <article class="article-item">
        <a href="{{ item.Link }}" class="article-thumb">
            {# 优先显示文章缩略图,如果没有则显示默认图 #}
            {% if item.Thumb %}
                <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
            {% else %}
                <img src="/public/static/images/default-thumb.png" alt="默认图片">
            {% endif %}
        </a>
        <div class="article-info">
            <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
            <div class="article-meta">
                <span>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
                <span>阅读量:{{ item.Views }}</span>
            </div>
            <p class="article-summary">
                {% if item.Description %}
                    {# 优先使用 Description 字段,并截取为 120 字符 #}
                    {{ item.Description|truncatechars:120 }}
                {% else %}
                    {# 如果 Description 为空,则从 Content 截取 150 字符并确保 HTML 安全 #}
                    {{ item.Content|truncatechars_html:150|safe|default:"暂无内容" }}
                {% endif %}
            </p>
            <a href="{{ item.Link }}" class="read-more">阅读更多 &raquo;</a>
        </div>
    </article>
    {% empty %}
    <p>抱歉,目前没有可供展示的文章。</p>
    {% endfor %}
{% endarchiveList %}

In this code block:

  • We first checkitem.DescriptionIf there is content. If there is, we usetruncatecharsCut it.
  • Ifitem.DescriptionIf it is empty, we use insteaditem.Contentthrough.truncatechars_htmlPerform HTML safe truncation and add|safeThe filter ensures that the content is parsed correctly.
  • Finally,|default:"暂无内容"As a fallback, ensure even ifContentIf the content is cut and still empty (such as the article content is too short or there is no content at all), it can also display a friendly prompt.

By using the above method, you can flexibly extract the article abstract in the AnQiCMS template and display it in a beautiful and secure way on the list page, greatly enhancing the user's browsing experience.


Frequently Asked Questions (FAQ)

Q1: What is the character count of the truncated string including the ellipsis?A1: Yes, when you usetruncatecharsortruncatechars_htmlWhen filtering, the length you set will include the characters occupied by the automatically added ellipsis (“…”).For example, if you set the truncation length to 100, the total number of characters displayed in the summary (including the ellipsis) will be 100.

Q2: Why is it necessary to truncate HTML content?|safeFilter?A2

Related articles

How to implement safe output of HTML tags in article content to avoid XSS attacks?

In AnQiCMS, we not only pursue efficient and flexible content management, but also regard website security as a core element.In daily content creation and template development, a seemingly simple HTML tag output actually hides potential security risks, the most common of which is cross-site scripting (XSS) attack.Understanding how AnQiCMS processes HTML output and mastering security practices is crucial for building a robust and reliable website.How does AnQiCMS handle HTML content output?In AnQiCMS template rendering mechanism

2025-11-07

How to determine if a variable is empty in AnQiCMS template and display default content?

In website content operation, data integrity and the elegance of display are crucial.We often encounter such situations: some fields of data may be missing for various reasons, such as an article may not have an illustration, a product may not have a detailed description, or a custom field may not be filled in.If the template code does not perform the corresponding null value judgment, it may result in blank pages on the page, affecting the aesthetics, or may even cause template rendering errors, affecting the user experience.AnQiCMS with its efficient architecture based on the Go language and similar to Django

2025-11-07

How to display a custom page template independently on a specific page (such as About Us)?

Hello! When using AnQi CMS to build a website, we often encounter such needs: some specific pages, such as 'About Us', 'Contact Us', or some special topic pages, need to have a completely different layout and design from other pages on the website.Luckyly, AnQi CMS provides a very flexible solution for this, allowing you to easily specify independent custom templates for these pages.AnQi CMS with its efficient features based on the Go language and support for Django template engine syntax, brings great convenience and customizability to content display

2025-11-07

How to get and display the Tag list of articles in the front-end template of AnQiCMS?

AnQiCMS as an efficient and flexible content management system, provides a wealth of features to help operators manage and display website content.Among them, the Tag tag function of the article is an important factor for optimizing content organization, improving user experience and SEO effects.Understand how to obtain and display these tags in front-end templates, which is crucial for building a website with comprehensive functions.### In AnQiCMS backend management tags Before delving into the front-end template, let's briefly review how tags work in the AnQiCMS backend

2025-11-07

How to display a list of website friend links in the front-end template?

In website operation, friendship links are not only a bridge between websites, but also an important strategy to enhance website authority, increase external traffic, and optimize search engine rankings.Reasonably configure and display friendship links, which can effectively improve the website's SEO performance and provide users with more valuable external resources.AnQiCMS as an efficient content management system, fully considers this need, and provides a simple and intuitive way to manage and display friend links in the front-end template.### Backend Management: Setting and Maintaining Friend Links Display Friend Links on the Front-end Page

2025-11-07

How to display a user comment list on the front end and support review status display?

User comments are an important manifestation of website vitality, they not only enhance the interactivity of content but also provide valuable reference for other visitors.AnQi CMS understands the importance of comment management, providing simple and powerful features that allow you to flexibly display comment lists on the website front end and clearly identify the review status of comments.The core of displaying the comment list on the front-end: `commentList` tag To display user comments on your website's front-end page, you need to use the `commentList` template tag provided by AnQiCMS

2025-11-07

How to dynamically display the website's logo image in the template of AnQiCMS?

The website's logo is the core of the brand image, it not only enhances the professionalism of the website, but also facilitates users in quickly identifying and remembering your brand.For AnQiCMS users, dynamically displaying the logo image in the website template is a basic and important operation.Luckyly, AnQiCMS provides a very convenient way to achieve this, allowing you to easily manage and display the website logo without writing complex code.### Website Logo Management: Backend settings are crucial Display the Logo on your AnQiCMS website

2025-11-07

How to insert Markdown formatted text in website content and render it correctly as HTML?

In AnQiCMS, inserting Markdown formatted text and rendering it correctly to HTML is an important way for content operators to improve efficiency and produce high-quality pages.AnQiCMS has built-in support for Markdown editing and rendering, allowing you to enjoy the simplicity and efficiency of Markdown while ensuring that the final page output is beautiful and structured HTML.### Enable Markdown Editor To start using Markdown in AnQiCMS, you first need to ensure that the editor feature is enabled

2025-11-07