In website operation, the way content is displayed has a significant impact on user experience and the efficiency of information transmission.Whether it is the introduction of the article list, the summary of the product description, or other text content that needs to be previewed, reasonable control of the display length and the addition of an ellipsis can not only maintain the neatness and beauty of the page, but also guide users to click and 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 is it necessary to truncate content and add an ellipsis?

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

  • Improve page aesthetics:A uniform abstract length can make the page layout more regular and improve visual comfort.
  • Optimizing user experience: Users can quickly scan multiple pieces of information, get a general understanding of the content, and then decide whether to delve deeper.
  • Improve loading speed:Reduce the amount of text loaded on the page initially, especially important for users on mobile devices or with poor network conditions.
  • Beneficial for SEO:A clear summary can help search engines better understand the page content and avoid a large amount of repetitive or redundant content on the list page.

AnqiCMS provides a直观且功能强大的content extraction tool in the template layer, whether it is plain text or content with complex HTML structure, it can handle it easily.

AnqiCMS content extraction filter

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

1. Extracting plain text content:truncatecharsandtruncatewords

When you need to extract plain text content without HTML tags, these two filters are your best choice.

  • truncatechars:length(By character cut)This filter will cut the string according to the number of characters you specifylength. If the length of the original string exceedslength, the extra part will be truncated and an ellipsis will be added at the end.... 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(Word-wise truncation)This filter will sort by the number of wordscountTo extract a string. It will try to truncate at word boundaries, which is particularly useful when dealing with English content, as it avoids cutting off the middle of a word.Likewise, if the content is truncated, it will be added at the end......

    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 a website, many content fields, such as article text, product details, etc., usually contain rich HTML tags (such as<strong>/<em>/<a>/<img>etc.). Use directlytruncatecharsortruncatewordsExtracting such content may break the HTML structure and cause the page to display incorrectly.

To elegantly handle the extraction of HTML content, AnqiCMS providedtruncatechars_htmlandtruncatewords_htmlTwo intelligent filters. They can intelligently close incomplete HTML tags while extracting content, thus ensuring that the HTML structure after extraction remains intact.

Important reminder:When you use_htmlBe sure to add it at the end of the filter when processing HTML content|safeFilterThe AnqiCMS template system, for security reasons, defaults to HTML-encoding all output content. If not added|safeEven though_htmlThe filter correctly closes the tags, and the browser will also display these HTML tags as plain text instead of parsing them.

  • truncatechars_html:length(Extract characters and retain HTML structure)This filter is compatible withtruncatecharsSimilar, extract by character count, but it ensures that all truncated HTML tags are properly closed.

    Example:Assumearticle.ContentIs<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(Extract words and retain HTML structure)This filter is compatible withtruncatewordsSimilar, extract by word count, and intelligently close HTML tags.

    Example:Assumearticle.ContentIs<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>

Practical Exercise: Applying Content Extraction in Templates

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

Scenario 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 brief 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 usearchiveListTag to get the list of articles, then extract from each article'sDescriptionField usagetruncatechars:150Ensure the consistency of the abstract length by cutting.

Scenario two: The 'expand/collapse' or first load part of the document detail page content

Sometimes, we may wish to display only a part of the content on the article detail page when it is first loaded, and then provide a button for the user to click to view the full content, or to only display 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 usetruncatechars_html:500YesContentfield for extraction. SinceContentfields usually contain HTML tags, we must use|safeA filter to ensure that HTML is 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 length of the excerpt.

Some practical suggestions

  1. select filters based on actual requirements:If the content is confirmed to be plain text, usetruncatecharsortruncatewordsmore efficient. If the content may contain HTML,Make sureUsetruncatechars_htmlortruncatewords_html.
  2. do not forget|safe:the truncation filter for handling HTML content (_htmlAdd it after the)at the end,|safeFilter, otherwise your HTML tags will be output as is and not parsed by the browser.
  3. Consider truncating the length: