In daily website operation, we often encounter such situations: the content of the article detail page is rich, but in order to keep the layout neat on the list page or recommendation module, it is necessary to display a concise version of the content, which is usually to cut a part of the text and add an ellipsis at the end.AnQi CMS knows the importance of content display and provides very convenient and powerful tools to handle such needs.

Let's take a look at how to elegantly implement the truncation of long text content and display an ellipsis in Anqi CMS, making the website interface both beautiful and professional.

The need and value of content truncation

In many content display scenarios, such as the article list on the homepage, the article summary on the special page, the recommended content in the sidebar, or the SEO meta description (Description), we need to control the display length of the text.The long text takes up too much space, disrupts the page layout, and affects the first impression of the user;And a short text carefully truncated with an ellipsis can convey information more efficiently, attracting users to click and view the full content.This not only optimizes the user experience, but also helps enhance the overall visual appeal and readability of the page.

The solution of AnQi CMS: Text Truncation Filter

The AnQi CMS template system is based on the Django template engine syntax and provides various built-in "filters" (Filters) to help us easily process content. In response to the need for text truncation, there are several practical filters available: truncatechars/truncatewordsand their corresponding HTML safe versionstruncatechars_htmlandtruncatewords_html.

1. Truncate by character:truncatechars

This filter will truncate text based on the number of characters you specify. Whether Chinese or English, it will accurately calculate the number of characters and add an ellipsis at the truncation point....It should be noted that the ellipsis itself is also included in the number of characters you have set.

How to use:

{{ 您的文本变量|truncatechars:数字 }}

Example:Suppose we have a text{{ archive.Description }}And we want to extract the first 20 characters:

{{ archive.Description|truncatechars:20 }}

Ifarchive.DescriptionIs "This is a very long document description that needs to be truncated for display. The output might be: "This is a very long document..."

When to use:When you need to strictly control the pixel width of displayed text, or when dealing with Chinese content,truncatecharsit is very useful because it does not distinguish between words, it truncates by character count only.

2. Truncate by word:truncatewords

withtruncatecharsdifferent,truncatewordsIt truncates text based on the number of words. It tries to maintain the integrity of words and adds an ellipsis after the last complete word.Similarly, ellipses are also counted in the number of words you set.

How to use:

{{ 您的文本变量|truncatewords:数字 }}

Example:Assumed text variable{{ archive.Description }}Yes"This is a very long description for an article that needs to be truncated, we want to take the first 10 words:

{{ archive.Description|truncatewords:10 }}

It is possible that the output will be: “This is a very long description for an article that…”

When to use:When dealing with English or other space-separated languages,truncatewordsit usually provides a more natural and fluent reading experience, avoiding words being abruptly cut in half.

3. Handle HTML content:truncatechars_htmlandtruncatewords_html

Many times, our content (such as a part of the article text) may contain HTML tags, such as<b>bold,<a>links,<p>Paragraphs and the like. If used directlytruncatecharsortruncatewordscould lead to HTML tags being incorrectly truncated, thereby destroying the page structure and even causing display anomalies.

To solve this problem, Anqi CMS providestruncatechars_htmlandtruncatewords_htmlThese enhanced filters. They can intelligently close all unclosed HTML tags while truncating text, ensuring that the output HTML structure is complete and valid.

How to use:

{{ 您的HTML文本变量|truncatechars_html:数字|safe }}
{{ 您的HTML文本变量|truncatewords_html:数字|safe }}

Please note that when you are dealing with content containing HTML, whether or not you are using a truncation filter, you should always add at the end|safefilter.|safeThe purpose is to inform the template engine that this content is safe, and it does not need to be escaped as HTML entities, but should be parsed and displayed as HTML directly.

Example:Assume{{ archive.Content }}Contains HTML code: “

This is a paragraph.ImportantContent that includes bold andlinks, needs to be truncated.

”, we hope to truncate the first 25 characters while maintaining the HTML structure:

{{ archive.Content|truncatechars_html:25|safe }}

The output might be: “

This is a paragraph.ImportantContent that includes bold andlinks...

Please note that even if it is truncated,<b>and<a>the tag is also closed correctly.

When to use:Any text content that may contain HTML tags, such as automatically extracted abstracts from the main text, classification descriptions, and single-page content, should be given priority to use with the_htmlSuffix truncation filter.

Specific application in Anqi CMS template.

In Anqi CMS, these filters can be applied to almost anywhere text needs to be displayed, especially when used with list tags.

For example, in your article list template (usually{模型table}/list.htmlIn brackets, you may usearchiveListTags to get the document list:

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
    <li>
        <a href="{{ item.Link }}">
            <h5>{{ item.Title }}</h5>
            {# 截取文章描述,显示前100个字符 #}
            <div>{{ item.Description|truncatechars:100 }}</div>
            {# 如果描述可能包含HTML,使用以下方式 #}
            {# <div>{{ item.Description|truncatechars_html:100|safe }}</div> #}
            <div>
                <span>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
                <span>阅读量:{{ item.Views }}</span>
            </div>
        </a>
    </li>
    {% empty %}
    <li>
        当前没有可用的文章。
    </li>
    {% endfor %}
{% endarchiveList %}

In the sidebar recommendation module of the article detail page, if you need to display a brief title:

{% archiveList relatedArchives with type="related" limit="5" %}
    {% for item in relatedArchives %}
    <li>
        <a href="{{ item.Link }}">
            <h6>{{ item.Title|truncatechars:15 }}</h6> {# 截取推荐文章标题的前15个字符 #}
        </a>
    </li>
    {% endfor %}
{% endarchiveList %}

You can also truncate the description or content when calling the category details or single page details:

{# 假设在分类列表页,需要截取分类描述 #}
{% categoryDetail categoryDescription with name="Description" %}
<p>{{ categoryDescription|truncatewords_html:30|safe }}</p>

{# 在单页面模板中,可能需要截取部分内容作为摘要 #}
{% pageDetail pageContent with name="Content" %}
<div class="page-summary">{{ pageContent|truncatechars_html:200|safe }}</div>

Practical suggestions and precautions

  • Choose an appropriate truncation length:There is no universal length for a "**". It depends on your design layout, target language, and content type.You need to test repeatedly, view the effect on different devices, and find a balance that can keep the page tidy and provide enough information to attract users to click.
  • The content type determines the filter:Remember, if your text content may contain HTML tags, be sure to use_htmlsuffix filter (such astruncatechars_html), and add|safe. For plain text,truncatecharsortruncatewordsit is enough.
  • Maintain consistency:In different areas of the website, applying unified truncation rules for similar content helps improve overall professionalism and user experience.
  • Testing and adjustment:Even if the length is set, it is recommended to publish some test content on the actual website and check the display effect. Different fonts, sizes, and layouts will affect the final visual effect.

By reasonably utilizing the text truncation filter provided by Anqi CMS, you can easily control the presentation of website content, providing visitors with a cleaner, more efficient, and professional browsing experience.


Frequently Asked Questions (FAQ)

Q1: The numeric parameter in the filter, does it include or exclude the ellipsis (...) length?

A1: In the text truncation filter of Anqi CMS (such astruncatecharsandtruncatewords), the number you setIs includedThe length of the ellipsis. For example, if you settruncatechars:10Then the final content displayed (including the ellipsis) will not exceed 10 characters in total.

Q2: How will it be if my content is too short to be truncated?

A2: If the original content is not long enough to reach the truncation length you set, then the content willWill not be truncatedAnd it will not show an ellipsis. The filter will only output this short text as is, without any modification.

Q3: Where can I find more detailed documentation and examples of these filters?

A3: You can find detailed descriptions of all filters in the official template development document of Anqi CMS. Specifically, you can check the 'Template Creation' category under 'Tags and Usage' as well as the 'More Filters' document (corresponding to your document collectiondesign-tag.mdandtag-filters.md)。There are parameters, detailed usage methods, and more code examples provided for each filter.