In daily website operation, we often encounter such situations: the content of the article detail page is rich, but the list page or recommendation module needs to display a concise version of the content for the sake of layout, usually by truncating part of the text and adding an ellipsis at the end.The auto CMS understands 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 truncate long text content and display an ellipsis in the 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 topic 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 may occupy too much space, disrupt the page layout, and affect the user's first impression; while the short text, carefully truncated with ellipses, can convey information more efficiently and attract users to click and view the full content.This not only optimizes the user experience, but also helps enhance the overall visual aesthetics and readability of the page.

The solution of Anqi CMS: Text Truncation Filter

The template system of Anqi CMS is based on Django template engine syntax and provides a variety of built-in "filters" (Filters) to help us easily process content. In order to meet the needs of text truncation, there are mainly the following practical filters:truncatechars/truncatewordsand their corresponding HTML safe versionstruncatechars_htmlandtruncatewords_html.

1. Character truncation:truncatechars

This filter will truncate the text based on the number of characters you specify. It will accurately calculate the number of characters regardless of Chinese or English, and add an ellipsis at the truncation point....English version: Note that the ellipsis itself is also included in the character count you set.

Usage:

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

Example:Assuming we have a piece of text{{ archive.Description }}English version: 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 the displayed text, or when dealing with Chinese content,truncatecharsit is very useful because it does not distinguish between words, but truncates by the number of characters.

2. Truncate by word:truncatewords

Withtruncatecharsdifferent,truncatewordsThis is to truncate the text based on the number of words.It will try to maintain the integrity of the word and add an ellipsis after the last complete word.Similarly, the ellipsis is also counted in the number of words you set.

Usage:

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

Example:assuming a text variable{{ archive.Description }}This is a very long description for an article that needs to be truncated.

{{ archive.Description|truncatewords:10 }}

输出结果可能是:“This is a very long description for an article that…”

When to use:When dealing with English or other languages separated by spaces between words,truncatewordsit usually provides a more natural and smooth reading experience, avoiding words being abruptly cut in the middle.

3. Handle HTML Content:truncatechars_htmlandtruncatewords_html

Many times, our content (such as a part of the article text) may contain HTML tags, for example<b>Bold,<a>Link,<p>Paragraphs and the like. If used directlytruncatecharsortruncatewords, it may cause HTML tags to be 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 smartly close all unclosed HTML tags while truncating text, ensuring that the output HTML structure is complete and valid.

Usage:

{{ 您的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 function of auto is to tell the template engine that this content is safe and does not need to be escaped as HTML entities, and is displayed directly as HTML.

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

This is a paragraphImportantContent, including bold andlinkagewhich needs to be truncated.

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

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

The output may be: “

This is a paragraphImportantContent, including bold andlinkage

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 abstracts extracted from the main text automatically, classification descriptions, and single-page content, should be given priority to use with_htmlThe truncation filter of the suffix.

Specific application in the Anqi CMS template.

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

For example, in your article list template (usually){模型table}/list.html)in,you might 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 generic “**” length.This depends on your design layout, target language, and content type.You need to test repeatedly, view the effects on different devices, and find a balance point that can keep the page neat 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 filters (such astruncatechars_html),and add|safe. For plain text,truncatecharsortruncatewordsis sufficient.
  • Maintain consistency:In different areas of the website, applying unified truncation rules to similar content helps enhance the overall professionalism and user experience.
  • Test and adjust: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 Auto CMS, you can easily control the way website content is presented, offering visitors a cleaner, more efficient, and professional browsing experience.


Common Questions (FAQ)

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

A1: In the text truncation filter of the security CMS (such astruncatecharsandtruncatewords),the number you setIs containedThe length of the ellipsis. For example, if you settruncatechars:10, then the total length of the content displayed at the end (including the ellipsis) will not exceed 10 characters.

Q2: If my content itself is very short and not enough to be truncated, what will happen?

A2: If the length of the original content is not enough to reach the truncation length you set, then the content willWould not be truncatedNeither would an ellipsis be displayed. The filter will output this short text as is, without any modification.

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

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