In the operation of a website, the way content is presented has a crucial impact on user experience and the efficiency of information communication.Whether it is the summary of the article list, the abstract of the product description, or other text content that needs to be previewed, reasonable control of the display length and the use of ellipsis can not only keep the page neat and beautiful but also guide users to click to view more details.AnqiCMS as an efficient and flexible content management system, provides a variety of powerful template tags and filters, making the control of content length extremely simple and intelligent.

Why do you need to cut content and add an ellipsis?

Imagine if every article in your website's article list displayed the full content directly, the page would become overly long and it would be difficult for users to browse quickly. Appropriate content truncation can bring many benefits:

  • Improve page aesthetics:A consistent abstract length makes the page layout more uniform, enhancing visual comfort.
  • Optimize user experience:Users can quickly scan multiple pieces of information, get a general understanding of the content, and then decide whether to delve deeper into reading.
  • Improve loading speed:Reduce the amount of text loaded initially on the page, which is particularly important for mobile devices or users with poor network conditions.
  • Beneficial for SEO:A clear summary helps search engines better understand the page content and avoids a large amount of repetitive or redundant content on list pages.

AnqiCMS provides an intuitive and powerful content snippet tool at the template level, which can easily handle both plain text and content with complex HTML structures.

AnqiCMS Content Extraction Filter

AnqiCMS's template system (similar to Django's template engine) includes a series of practical filters, specifically designed for string truncation. Among them, the one most relevant to controlling display length is...truncatechars/truncatewordsand its HTML friendly versiontruncatechars_htmlandtruncatewords_html.

1. Extracting plain text content:truncatecharsandtruncatewords

These two filters are your best choice when you need to extract plain text content without HTML tags.

  • truncatechars:length(Character slicing)This filter will slice the string according to the number of characters you specifylengthto slice the string. If the length of the original string exceedslength, the extra part will be truncated and appended at the end...Ellipsis. Please note,lengthThe parameter includes the final ellipsis character.

    Example:Assumearticle.TitleIs 'How to truncate a string in AnqiCMS template and add an ellipsis to control the display length?'

    <p>{{ article.Title|truncatechars:20 }}</p>
    

    Output effect: 如何在AnqiCMS模板中截取...

  • truncatewords:count(Sliced by words)This filter will be based on the number of wordscountExtract the string.It will attempt to truncate at word boundaries, which is especially useful when handling English content, as it avoids truncating the middle of a word....Ellipsis.

    Example:Assumearticle.DescriptionIs “AnQiCMS is a powerful and flexible content management system designed for ease of use.”

    <p>{{ article.Description|truncatewords:8 }}</p>
    

    Output effect: AnQiCMS is a powerful and flexible content...

2. Handle content containing HTML tags:truncatechars_htmlandtruncatewords_html

In the website, many content fields, such as article body, product details, etc., usually contain rich HTML tags (such as<strong>/<em>/<a>/<img>). Directly usingtruncatecharsortruncatewordsExtracting this content may disrupt the HTML structure, causing the page to display incorrectly.

To elegantly handle the extraction of HTML content, AnqiCMS providestruncatechars_htmlandtruncatewords_htmlTwo smart filters. They can intelligently close incomplete HTML tags while extracting content, thus ensuring the HTML structure extracted remains intact.

Important reminder:When you use_htmlPlease ensure to add at the end when filtering HTML content by the terminator filter|safeFilter.AnqiCMS template system defaults to HTML-encoding all output content for security reasons. If not|safe, even_htmlThe filter correctly closes the tags, and the browser will also display these HTML tags as plain text, rather than parsing them.

  • truncatechars_html:length(Extract characters and retain HTML structure)This filter is similar totruncatechars, but it ensures that all truncated HTML tags are properly closed.

    Example:Assumearticle.ContentYes<strong>AnQiCMS</strong> 是一个<em>高效</em>、可定制的内容管理系统,致力于提供******解决方案。

    {% set intro_content = article.Content|truncatechars_html:30|safe %}
    <div>{{ intro_content }} <a href="{{ article.Link }}">阅读更多</a></div>
    

    Output effect: <strong>AnQiCMS</strong> 是一个<em>高效</em>、可定... <a href="...">阅读更多</a>

  • truncatewords_html:count(Split by words while retaining HTML structure)This filter is similar totruncatewordsSimilar, split by word count, and smartly close HTML tags.

    Example:Assumearticle.ContentYes<strong>AnQiCMS</strong> is a <em>powerful</em>, customizable CMS solution.

    {% set intro_content = article.Content|truncatewords_html:5|safe %}
    <div>{{ intro_content }} <a href="{{ article.Link }}">Read More</a></div>
    

    Output effect: <strong>AnQiCMS</strong> is a <em>powerful</em>, customizable... <a href="...">Read More</a>

Practice: Applying content truncation in templates

Now, let's combine the actual template tags of AnqiCMS and see how to flexibly use these extraction functions in document lists and detail pages.

Scene One: The article list page displays a concise summary

On the article list page, we usually want each article to display only the title and a short description, and provide a 'Read More' link.

<div class="article-list">
    {% archiveList articles with type="page" limit="10" %}
        {% for item in articles %}
        <article class="article-item">
            <h2><a href="{{ item.Link }}">{{ item.Title }}</a></h2>
            <div class="article-meta">
                <span>发布日期: {{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
                <span>浏览量: {{ item.Views }}</span>
            </div>
            <div class="article-summary">
                {# 截取纯文本描述,并添加阅读更多链接 #}
                <p>{{ item.Description|truncatechars:150 }} <a href="{{ item.Link }}">阅读更多</a></p>
            </div>
        </article>
        {% empty %}
        <p>暂时没有文章内容。</p>
        {% endfor %}
    {% endarchiveList %}

    {# 分页导航,如果需要的话 #}
    {% pagination pages with show="5" %}
        {# 分页链接代码略 #}
    {% endpagination %}
</div>

In this example, we usearchiveListtags to get the article list, thenDescriptionfield usagetruncatechars:150truncate each article to ensure the consistency of the summary length.

Scene two: Expand/collapse or initially loaded part of the document detail page

Sometimes, we may wish to display only a part of the content on the article detail page when it first loads, and then provide a button for users to click to view the full content, or to display only a part of the formatted content in some special modules.

{% archiveDetail currentArticle %}
    <div class="article-detail">
        <h1>{{ currentArticle.Title }}</h1>
        <div class="article-content">
            {# 截取包含HTML的内容,注意使用 |safe 过滤器 #}
            {% set fullContent = currentArticle.Content %}
            {% set truncatedHtmlContent = fullContent|truncatechars_html:500|safe %}

            <div id="display-content">
                {{ truncatedHtmlContent }}
                {% if fullContent|length > 500 %}
                    <a href="javascript:void(0);" id="toggle-content">查看完整内容</a>
                {% endif %}
            </div>
            {# 实际操作中,可以使用JavaScript来切换完整内容和截取内容,这里仅为示意 #}
        </div>
    </div>
{% endarchiveDetail %}

Here, we usearchiveDetailRetrieve the detailed content of the current document and utilizetruncatechars_html:500ForContentfields for truncation. SinceContentfields usually contain HTML tags, we must use|safeA filter to ensure that HTML can be parsed and displayed correctly.At the same time, we determine whether to display the 'View Full Content' button by judging the length of the original content and the extracted length.

some practical suggestions

  1. Select the filter according to actual requirements:Use if the content is definitely plain text:truncatecharsortruncatewordsMore efficient. If the content may contain HTML,Be sure toUsetruncatechars_htmlortruncatewords_html.
  2. Do not forget|safe:Extract filter for processing HTML content 【en】_htmlAfter the ), remember to add 【en】|safeThe filter, otherwise your HTML tags will be output as is, not parsed by the browser. 【en】
  3. Consider cutting the length: