In website operation, the presentation of article descriptions or abstracts is crucial for user experience and search engine optimization (SEO).An average-length, concise summary that not only attracts visitors to click but also helps search engines better understand the content of the page.However, manually controlling the length of each article abstract is time-consuming and prone to errors.幸运的是,AnqiCMS 提供了强大的模板过滤器功能,能够帮助我们自动化这一过程,确保网站内容展示的统一性和美观性。

Why do we need to truncate the article description or abstract?

Our website often needs to display the description or summary of articles, especially in article lists, search results, or special topic pages.If these descriptions are too long, they may cause page layout to become chaotic and affect the reading experience; if too short, they may not effectively convey the main theme of the article.Moreover, search engines will also truncate the page description according to the preset character length when displaying search results. 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 exactly the weapon to solve this problem.By using simple template code, we can easily achieve smart extraction of article descriptions or summaries, and automatically add ellipses to make the content display more professional and uniform.

AnqiCMS 的模板过滤器:内容的美容师

在 AnqiCMS 的模板文件中,变量通常以双花括号{{ 变量名 }}of the form appears. And the filter, as the name implies, is a tool for 'filtering' or 'processing' these variables. Its usage is to add a pipe symbol after the variable name|An example of this is to append the filter name and optional parameters, for example{{ 变量 | 过滤器名称: 参数 }}.

AnqiCMS built-in multiple practical filters, the one used for truncating strings and adding an ellipsis is,truncatechars/truncatewordsand its corresponding HTML versiontruncatechars_html/truncatewords_htmlThese filters can not only truncate text to a specified length but also intelligently add “…” at the truncation point, saving the trouble of manual concatenation.

Core Tool: String Truncate Filter

  1. truncatechars: 长度(Character slicing)This filter will truncate the string to the specified character count. Note that the 'length' parameterContains the number of characters occupied by the ellipsis itselfIt is suitable for scenarios that require strict control of the number of characters, such as each article summary on the list page must be of fixed length.

  2. truncatewords: 数量(Sliced by words)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 the text for English or other languages separated by spaces.Similarly, it will also automatically add an ellipsis.

  3. truncatechars_html: 长度andtruncatewords_html: 数量(Processing content with HTML)If your article description or abstract content itself contains HTML tags (such as bold, links, etc.), and you wish to retain the structural integrity of these tags when truncating, then_htmlThe suffix filter is your **choice. It will intelligently identify and close HTML tags to prevent page structure from becoming chaotic due to truncation.

Practice Application: Extract Article Description or Abstract

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

Scene one: Extract pure text description

We usually use in the article list page,archiveListLabels 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 '...' will be automatically added at the end.If the description itself is less than 100 characters, it will not be truncated or have an ellipsis added.

Scene two: Extract the article content as a summary

Sometimes, we may not have a separateDescriptionfield, or hope to directly extract part from the articleContenta field to extract part as a summary. The article content usually contains rich HTML tags, at this time it is necessary to usetruncatechars_htmla filter and combinesafeFilter to ensure correct HTML rendering.

{# 在文章详情页或者其他需要展示文章内容摘要的地方 #}
{% 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(or}currentArticle) content even if it includes<strong>/<a>such HTML tags,truncatechars_htmland can maintain the integrity of these tags when truncating.|safeThe filter tells the template engine that this HTML code is safe and can be output directly without escaping, thus avoiding displaying<p>...</p>such raw tags.

Choose the appropriate cutting method

  • truncatecharsvstruncatewords: If you are more concerned about the visual width of the display area and want to strictly control the number of characters, thentruncatecharsis a good choice. If the content is mainly in English, and you hope that the summary is more semantically complete,truncatewordswould be better because it won't truncate in the middle of a word.
  • _htmlthe use of suffixes: Just your description or summary content may contain any HTML tags, be sure to use filters with_htmlsuffix and combine|safeFilter to prevent page display errors or security issues.

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

Common Questions (FAQ)

问:截取长度是否包含省略号的字符?答:是的,在使用Englishtruncatecharsortruncatechars_htmlThe number length you specify for the filter includes the automatically added ellipsis (i.e., “…”). For example, if you settruncatechars:100The text output (including ellipses) can be at most 100 characters.

Q: If my article description is shorter than the specified length, will an ellipsis be added?答:Will not.AnqiCMS's extract filter is intelligent.It will truncate and add an ellipsis only when the length of the original content exceeds the value you specified.If the length of the original content is less than or equal to the specified length, the content will be displayed in full without an ellipsis.

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