In website content operation, we often encounter such needs: in order to keep the page layout neat and the reading experience smooth, it is necessary to truncate the long text (whether it is plain text or content containing HTML tags) and add an ellipsis at the end.AnQiCMS provides very practical template filters that can help us accurately complete this task, while ensuring that the content is displayed beautifully without destroying the HTML structure.

Understanding the requirements of截取的需求 & AnQiCMS's solution

Imagine, in a list of articles, the summaries of each article vary in length. If the full content is displayed directly, the page will look disorganized.In the search results page, we need to control the number of characters in the abstract to adapt to the display rules of the search engine.AnQiCMS uses a syntax similar to Django template engine, which includes a series of powerful filters that can easily handle these text truncation issues.These filters are particularly good at handling not only plain text but also smartly processing content with HTML tags, thus avoiding page rendering errors caused by truncation and unclosed tags.

Extraction for plain text content

For plain text content without any HTML tags, AnQiCMS provides two main ways to truncate: by character count and by word count.

  1. 截取字符数:truncatecharsWhen you need to strictly control the total number of characters in the content,truncatecharsFilter is your first choice.It will start counting from the beginning of the text, once it reaches the number of characters you set, it will truncate the text and add three dots (…) at the end as an ellipsis.This setting includes the ellipsis in the character count.

    For example, if you want the title of the article to display a maximum of 15 characters in the list, you can use it like this:{{ item.Title|truncatechars:15 }}Ifitem.TitleIt is “Anqi CMS: How to accurately截取 strings or HTML content and add an ellipsis”, which may be displayed as “Anqi CMS: How to accurately截…”.

  2. Truncated by word count:truncatewordsIf your content is mainly in English or separated by spaces into words, and you are more concerned with maintaining the integrity of the words,truncatewordsThe filter would be more appropriate. It counts words until the number of words you set is reached. Andtruncatecharssimilarly, an ellipsis will be added at the end if the content is truncated.

    For example, if an English description is{{ item.Description|truncatewords:5 }},内容是 “AnQiCMS is a powerful and flexible CMS platform.“,它可能会显示为 “AnQiCMS is a powerful and flexible…“。“auto”翻译成“English”}]

For intelligent extraction of HTML content

Directly truncating content containing HTML tags often leads to unclosed tags, which can destroy the page layout and even cause security issues. AnQiCMS is well aware of this and therefore provides a special intelligent truncation filter for HTML content:

  1. Truncate HTML by character count:truncatechars_htmlThis filter is similar totruncatecharsSimilar, it also truncates by character count, but its intelligence lies in its ability to recognize and preserve the integrity of HTML tags.This means that even if the truncation point falls in the middle of a tag, it will ensure that the tag is properly closed, thus avoiding page chaos.Similarly, an ellipsis will be added if the content is truncated.

    When used, since the content contains HTML, we usually also need to cooperate with|safeFilter.|safeIt will inform the template engine that this content is safe and does not need to be HTML escaped.

    For example, a document'sContentfield includes formatted HTML content:{{ archive.Content|truncatechars_html:100|safe }}If yourContentYes<p>这是一个<b>很长很长</b>的段落,其中包含各种<em>格式化</em>的文本。</p>,truncatechars_htmlWould ensure it during slicing.<p>/<b>/<em>Ensure that these tags are correctly closed, output similar.<p>这是一个<b>很长很长</b>的段落,其中包含各种<em>格式化</em>...</p>The content.

  2. Slicing HTML: by word count.truncatewords_htmlWithtruncatewords类似,这个过滤器按单词数截取 HTML 内容,并同样会智能地处理 HTML 标签的闭合问题。When processing English HTML content, it can better maintain the integrity of semantics.|safeFilter.

    For example:{{ archive.Description|truncatewords_html:20|safe }}

Actual application scenarios and **practice

These exquisite slicing tools can play a role in every corner of the website:

  • 文章/产品列表摘要:在文章或产品列表页,使用truncatecharsortruncatewords截取标题和简述,让列表看起来更整齐。
  • Category Description:在分类页面顶部,如果分类描述过长,可以用truncatechars_htmlPerform reasonable truncation and provide an 'View More' option.
  • SEO TDK (Title, Description, Keywords):Although TDK usually has dedicated setting fields, if you need to dynamically generate them from content, the truncation filter can help you control the length to adapt to the character limits imposed by search engines on meta description and title.
  • Navigation menu or sidebar brief prompt:In areas where brief text prompts are required, these filters ensure that the text will not overflow the layout.

When using these filters, there are a few points to note:

  • Consideration of length:The length of the excerpt should be determined according to the actual layout (PC, mobile) and content type (title, description). For example, mobile devices usually require a shorter summary.
  • |safeImportance:Process any content containing HTML (such as rich text editors generated)ContentorDescriptionwhen dealing with fields), make sure to add_htmlthe cut filter after|safe,otherwise the browser will display HTML tags as plain text instead of parsing them.
  • Ellipsis behavior:The ellipsis is added only when the content is actually truncated. If the original content length is already less than or equal to the set truncation length, no ellipsis is added.

Example: Extract the title and description from the article list page

Suppose we have an article list that needs to display the article title and a brief description.

<div class="article-list">
    {% archiveList archives with type="page" limit="10" %}
        {% for item in archives %}
        <div class="article-item">
            <h3 class="article-title">
                <a href="{{ item.Link }}">{{ item.Title|truncatechars:30 }}</a> {# 标题截取为30个字符 #}
            </h3>
            <div class="article-description">
                {# 描述可能包含HTML,截取为120个字符,并确保HTML安全显示 #}
                {{ item.Description|truncatechars_html:120|safe }}
            </div>
            <p class="article-meta">
                <span>发布日期: {{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
                <span>浏览量: {{ item.Views }}</span>
            </p>
        </div>
        {% empty %}
        <p>目前还没有文章。</p>
        {% endfor %}
    {% endarchiveList %}

    {# 如果需要分页,可以添加分页标签 #}
    {% pagination pages with show="5" %}
        <div class="pagination-controls">
            {# ... 分页链接代码 ... #}
        </div>
    {% endpagination %}
</div>

Through the flexible use of these excerpt filters provided by AnQiCMS, you can easily manage and display website content, ensuring a high-quality reading experience under various layouts.


Common Questions (FAQ)

Q1: If the length of the original content does not reach the截取length, will an ellipsis be added?A1: EnglishAnQiCMS's truncation filter will only add an ellipsis to the actual truncated content.If the number of characters or words in the original content is less than or equal to the length you set for truncation, the content will be displayed in full and no ellipsis will appear.

Q2: Can you customize the ellipsis style or content added after truncation (such as displaying characters other than “…”)?A2: Currently built-in in AnQiCMS.truncatechars/truncatewordsThis HTML version filter is the default, using three English periods “…” as an ellipsis, and it cannot be customized directly through parameters.If you have more advanced customization needs, you may need to perform additional data processing or use JavaScript to implement it.

Q3: If I forget to use_htmla filter (for example, onlytruncatechars) or forget to add|safeWhat will happen?A3: If I only usetruncatecharsIt may cause HTML tags to be incorrectly truncated, resulting in a chaotic page layout, because ordinary character truncation does not understand HTML structure. If you forget to add it after truncation|safeThe browser will display HTML tags as plain text in the content, for example, you will see<p>这是<b>一段文字</b>...</p>This is rather than the parsed style. More seriously, if the content contains malicious scripts, it is not|safeThe content will be safe due to the default HTML escaping mechanism, but if used incorrectly|safewithout being_htmlThe processing of filters may introduce cross-site scripting (XSS) risks. Therefore, when handling HTML content, it is imperative to use_htmlfilters and|safe.