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

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