How to truncate long text content and add an ellipsis at the end to optimize list display?

AnQiCMS (AnQiCMS) provides a powerful and flexible template system, with built-in text filters that can help us easily solve this problem.By skillfully using these filters, we can not only optimize the display of the list, but also maintain the conciseness and efficiency of the code.

Understand the importance of text truncation

Imagine if every article in your list page showed a full several-hundred-word introduction, the page would become very long, and users would need to scroll for a long time to browse a limited amount of content, which would undoubtedly greatly reduce reading interest. By truncating long text content to a fixed length and adding an ellipsis at the end, we can:

  • Improve visual consistency:Ensure that the length of each item's brief introduction in the list is similar, making the page layout more neat.
  • Optimize the reading experience:Users can quickly scan the title and concise introduction to decide whether to click to view the details.
  • Avoid layout misalignment:Prevent excessively long text from stretching the container, causing the layout of page elements to become chaotic.
  • Highlight core information:Compel the editor to extract the most attractive content within a limited number of characters.

AnQiCMS Solution: Text Truncation Filter

The template engine of AnQi CMS provides various text filters that can process variable content.Among them, the filter specifically used to truncate text and automatically add ellipses is the key to solving the problem of list display.

Typically, you will bearchiveList(Document List Tag) orpageList(Single page list tag) processed in the loopitem.Title(Title),item.Description(Description) oritem.Content(Content) and other text fields. Its basic usage format is{{ 变量 | 过滤器名称: 参数 }}.

1. Truncate by character count:truncatechars

If you want to truncate text based on the exact number of characters, you can usetruncatecharsFilter. It calculates the specified number of characters from the beginning of the text, truncates them, and then automatically adds an ellipsis at the end....).

For example, we want to truncate the article description to 80 characters:

{{ item.Description|truncatechars:80 }}

Handle special cases of HTML content:truncatechars_html

Whenitem.Descriptionoritem.ContentMay contain HTML tags (e.g., formatted text generated by rich text editors), use directlytruncatecharsThe HTML tags may be truncated if they are incomplete, which may destroy the HTML structure of the page. To avoid this, Anqi CMS providestruncatechars_htmlFilter. It can intelligently process HTML tags and try to maintain the integrity of the HTML structure when extracting text.

At the same time,truncatechars_htmlThe processed content is still HTML, to ensure that the browser parses it correctly, you need to cooperate|safewith the filter to prevent the template engine from escaping the HTML characters in it.

{# 假设 item.Description 包含 HTML 标签 #}
{{ item.Description|truncatechars_html:120|safe }}

2. Cut by the number of words:truncatewords

In some scenarios, especially on English websites, cutting by words may be more in line with reading habits.truncatewordsThe filter will truncate text based on the number of words and add an ellipsis at the end. It will try to avoid truncating in the middle of words.

For example, we want to truncate the article description to 20 words:

{{ item.Description|truncatewords:20 }}

Handle special cases of HTML content:truncatewords_html

WithtruncatecharsSimilarly, when the text contains HTML tags, it should also be used:truncatewords_htmlFilter to intelligently retain HTML structure, and it also needs to be combined|safeFilter.

{# 假设 item.Content 包含 HTML 标签 #}
{{ item.Content|truncatewords_html:30|safe }}

Actual application example

Assume you are designing a list page for articles, hoping each article displays the title and a brief description.When the article title is too long, it needs to be truncated. The description may contain rich text content and also needs to be truncated.

in your list template file (for examplearchive/list.htmlorindex/index.html), there may be the following code snippet:

{% archiveList articles with type="page" limit="10" %}
    {% for item in articles %}
    <div class="article-card">
        <a href="{{ item.Link }}" class="card-link">
            {% if item.Thumb %}
                <div class="card-thumb">
                    <img src="{{ item.Thumb }}" alt="{{ item.Title|truncatechars:40 }}">
                </div>
            {% endif %}
            <div class="card-content">
                <h3 class="card-title">{{ item.Title|truncatechars:50 }}</h3> {# 标题截取为50个字符 #}
                <p class="card-description">{{ item.Description|truncatechars_html:150|safe }}</p> {# 描述截取为150个字符,并安全渲染HTML #}
                <div class="card-meta">
                    <span>发布时间:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
                    <span>阅读量:{{ item.Views }}</span>
                </div>
            </div>
        </a>
    </div>
    {% else %}
    <p>暂时没有文章内容。</p>
    {% endfor %}
{% endarchiveList %}

{# 页面底部的分页导航 #}
{% pagination pages with show="5" %}
    <div class="pagination-nav">
        {% if pages.PrevPage %}<a href="{{ pages.PrevPage.Link }}" class="prev-page">&laquo; 上一页</a>{% endif %}
        {% for pageItem in pages.Pages %}
            <a href="{{ pageItem.Link }}" class="page-number {% if pageItem.IsCurrent %}active{% endif %}">{{ pageItem.Name }}</a>
        {% endfor %}
        {% if pages.NextPage %}<a href="{{ pages.NextPage.Link }}" class="next-page">下一页 &raquo;</a>{% endif %}
    </div>
{% endpagination %}

Through the above code, the titles and descriptions in the article list will be uniformly truncated to the specified length regardless of the original length, and ellipses will be automatically added. At the same time, it ensures the correct display of rich text content, greatly enhancing the visual effects and user experience of the page.

Optimization Suggestions and Precautions

  1. Reasonable Setting of Truncation Length:The length of the cut is not the shorter, the better.It needs to be decided based on the design of your website, the type of content, and the amount of information you want to provide.Suggest testing on different devices to ensure good presentation on both PC and mobile.
  2. Maintain consistency across the entire site:Once the slicing rule of a content type in the list is determined, it should be maintained consistently throughout the entire site to avoid different pages using different slicing lengths, which helps to form a unified brand image and user experience.
  3. UnderstandingtruncatecharsWithtruncatewordsThe difference:
    • truncatecharsOn the character level it is more accurate, but may truncate words in English text. For Chinese, one character counts as one character, so the impact is not great.
    • truncatewordsRespects word boundaries, making it more natural in English text, but may not be as concise.truncatecharsPrecise control.
  4. Use with caution|safe: |safeThe filter tells the template engine that the content you output is safe HTML and does not require escaping. If the content source is not trustworthy, use it directly|safeMay bring XSS (Cross-Site Scripting) risk. But in the background of the safe CMS, the content published is usually controllable, with_htmlfilter usage can safely render rich text.

With these techniques, you can flexibly manage the list display of long text content in the AnQi CMS, providing users with a better browsing experience.


Frequent Questions (