How to determine whether to truncate text and add an ellipsis (...) in AnQiCMS templates based on content length?

Calendar 78

In AnQiCMS website content operation, how to elegantly handle long text content so that it is both beautiful and complete on the page, which is the key to improving user experience.Especially on the list page, card display, or introduction area, overly long text often leads to layout errors, affecting the overall visual effect.AnQiCMS's powerful template engine provides various flexible ways to solve this problem, the most commonly used being the feature of text truncation and adding an ellipsis.

AnQiCMS's template system draws on the syntax of the Django template engine, built-in a series of practical filters (Filters), which can help us easily implement intelligent text truncation.With these features, you can flexibly decide whether to truncate the content based on its actual length, and automatically add an ellipsis (…) after truncation to optimize the display of the website content.

Understand the core text truncation filter

In the AnQiCMS template, the implementation of text truncation mainly depends on the following core filters:truncatechars/truncatewordsAnd the versions they handle HTML contenttruncatechars_htmlandtruncatewords_html.

  1. truncatecharsTruncated by character countThis filter will truncate text according to the specified character count.No matter the text is Chinese, English, or other symbols, it will count each character one by one, truncate after reaching a specified length, and automatically add an ellipsis at the end.It is noteworthy that the specified length includes the characters of the ellipsis itself.

    • Usage example:{{ 变量名|truncatechars:长度 }}
    • Features: Simple and direct, suitable for scenarios with strict character count limitations, but may truncate English content in the middle of words.
  2. truncatewordsTruncated by word countThis filter is designed for English content, it will truncate text according to the specified word count. It ensures the integrity of each word, and it will not be liketruncatecharsThat is truncated in the middle of the word. An ellipsis is also automatically added after the truncation.

    • Usage example:{{ 变量名|truncatewords:长度 }}
    • Features: Maintain the integrity of English words to make truncated text more readable. For Chinese content, since there is no clear concept of 'word', the effect may not be as good astruncatechars.
  3. truncatechars_htmlandtruncatewords_htmlTruncate HTML contentIf your content contains HTML tags, such as formatted text in article details, use them directlytruncatecharsortruncatewordsIt may damage the HTML structure, causing tags not to close, which may lead to display errors on the page. At this time,truncatechars_htmlandtruncatewords_htmlThey come into play. While truncating text, they intelligently handle HTML tags to ensure that the truncated HTML structure remains valid and avoid page chaos.

    • Usage example:{{ 变量名|truncatechars_html:长度|safe }}or{{ 变量名|truncatewords_html:长度|safe }}
    • Important reminderBe sure to add at the end when using these two filters|safeThe filter. This is because AnQiCMS (and most modern template engines) defaults to escaping output content to prevent XSS attacks. If not added|safeEven though_htmlThe filter retains the HTML structure, escaping will also convert<h1>tags to&lt;h1&gt;, causing the text to be displayed instead of parsing the HTML.|safeTell the template engine that this part of the content is safe and does not need to be escaped.

Actual application scenarios and code examples

Let us look at some common examples to see how to apply these truncation functions in the AnQiCMS template.

Scenario one: Limit the display length of the article title.On the list page, to make the title uniform, the length is usually limited.

<a href="{{ item.Link }}" title="{{ item.Title }}">
    {{ item.Title|truncatechars:25 }} {# 如果标题超过25个字符,将截断并添加... #}
</a>

Scenario two: truncating the article summary or abstractThe article summary usually needs to be limited to a certain number of words to guide users to click and view the details.

<p>
    {{ item.Description|truncatechars:120 }} {# 截断简介,保留120个字符,并添加... #}
</p>

Scenario three: Preview part of the article with HTML format.Sometimes it is necessary to display a formatted excerpt of the article's main content on the list page or in related article recommendations.

<div class="article-preview">
    {# 截断文章内容,保留50个单词,并确保HTML结构正确 #}
    {{ item.Content|truncatewords_html:50|safe }}
</div>

Scenario four: dynamically judge the length, truncate only when necessary.If you want to display an ellipsis only when the text is truly long, you can combinelengtha filter to make the judgment:

{% if item.Title|length > 30 %}
    <span title="{{ item.Title }}">{{ item.Title|truncatechars:30 }}</span>
{% else %}
    <span>{{ item.Title }}</span>
{% endif %}

In this example, we first judge whether the actual length of the title exceeds 30 characters. If it does, then truncate; otherwise, output as is.

Useful tips and precautions

  • Testing is the key.Before applying any truncation filter in practice, it is recommended to thoroughly test in the development environment to ensure that the truncation effect meets expectations, especially for Chinese and content containing HTML.
  • Choose the appropriate lengthThe setting of truncation length should be determined according to the page design, content type, and reading habits of the target audience, to avoid too much truncation causing information loss, or too little truncation causing the effect to be not obvious.
  • The uniqueness of Chinese content:truncatewordsPrimarily for English, as it relies on spaces to distinguish 'words'. For Chinese content, due to the lack of a natural word separator,truncatewordsIt may treat the entire sentence as a 'word' or judge according to punctuation, the effect may not be as good astruncatecharsdirectly. Therefore, when dealing with Chinese,truncatecharsit is usually a safer choice.
  • HTML content with|safe: It is emphasized again, any truncation filter with a_htmlsuffix needs to be added immediately after it|safeThe filter, otherwise the HTML tags will be escaped as text, not parsed by the browser.

Summary

AnQiCMS's template engine considers the details of content display carefully, throughtruncatechars/truncatewordsCombined with its HTML version|safeFilters that can help you easily achieve intelligent text truncation.This not only effectively enhances the beauty and layout of the website page, but also optimizes the reading experience for users, presenting your content in the most suitable form to visitors.In content operation, using these template functions will greatly improve work efficiency and the professionalism of website content.


Frequently Asked Questions (FAQ)

  1. truncatecharsandtruncatewordsWhat are the differences in Chinese content? truncatecharsIt is truncated by character count, applicable to both Chinese and English, it accurately calculates the length of each character (including Chinese characters), and truncates after reaching the specified number.truncatewordsIt is truncated by word count, mainly designed for English because it relies on spaces or punctuation marks to distinguish words. For continuous Chinese text,truncatewordsIt may be considered as a long 'word' that cannot be truncated as expected, or the truncation point may not be in line with Chinese reading habits. Therefore, it is usually recommended to usetruncatecharsTo achieve more precise and controllable truncation effects.

  2. Why are you usingtruncatechars_htmlortruncatewords_htmlIt needs to be added when|safeFilter?AnQiCMS's template engine, to prevent potential cross-site scripting (XSS) attacks, defaults to escaping all output variable content. This means that if your variable contains<h1>Such HTML tags are converted by default to&lt;h1&gt;thereby displayed as plain text rather than being parsed by the browser as a title.truncatechars_htmlandtruncatewords_htmlAlthough internally it tries to preserve the HTML structure, it is still affected by the template engine's escaping mechanism when the output is finally generated. Therefore, add|safeThe filter tells the template engine that this part of the content is known and safe HTML, which does not need to be escaped and can be parsed directly by the browser, thus ensuring that formatted text is displayed correctly.

  3. Can the ellipsis displayed after text truncation be customized? For example, can it be replaced with "[View More]"??Built-in in AnQiCMStruncatecharsandtruncatewordsThe filter uses a fixed ellipsis (…) as the truncation mark, and there is no direct parameter to modify this default mark in the current document. If you need to customize the truncation mark, you can combinelengthFilters and condition judgments can be manually implemented. You can determine if the actual length of the text exceeds your expected length.If it exceeds, manually truncate the text and append your custom marker at the end. For example:

    {% set max_length = 50 %}
    {% set original_text = item.Description %}
    {% if original_text|length > max_length %}
        {{ original_text|truncatechars:max_length|replace:"..."," [查看更多]" }} {# 先截断,再替换默认省略号 #}
    {% else %}
        {{ original_text }}
    {% endif %}
    

    Please, replace manually...Maybe not as goodtruncatecharsThe internal implementation handles ellipsis characters intelligently. A more precise approach is to first cut the required length of the string, and then manually judge whether to add a custom marker.

    {% set max_chars = 50 %}
    {% set my_content = item.Description %}
    {% if my_content|length > max_chars %}
        {{ my_content|slice:("0:" + (max_chars - 6)) }}... [更多] {# 假设" [更多]"占6个字符 #}
    {% else %}
        {{ my_content }}
    {% endif %}
    

    This manual concatenation method can provide greater flexibility, but it requires you to manage length calculations more finely, especially when the content includes HTML, which can become complex.

Related articles

What is the default return value when the `integer` and `float` filters fail to convert in the AnQiCMS template?

When building a website on Anqi CMS, we often need to flexibly handle and display data in the template.These, `integer` and `float` filters are very commonly used tools when converting values to integers or floating-point numbers.However, have you ever thought about how the system will handle when these filters receive a value that cannot be recognized as a number?In other words, what default values will these filters return if the conversion operation fails?Understanding this is crucial for us to write robust and predictable template logic.###

2025-11-09

In AnQiCMS template, how to judge whether a string can be successfully converted to a numeric type and perform conditional processing?

In AnQi CMS template creation, we often encounter situations where we need to process strings entered by users or retrieved from the database.One common requirement is to determine whether a string can be successfully converted to a numeric type and to perform different conditional processing based on the result.This is crucial for data display, calculation, and even simple form validation.The AnQi CMS template engine (based on Go language's Pongo2) provides a rich set of filters (filters) and logical tags, allowing us to flexibly meet this requirement. Below

2025-11-09

In AnQiCMS template, how to judge and display the 'In stock' or 'Out of stock' status based on the product inventory (`Stock`) quantity?

It is crucial to clearly communicate the inventory status of products to users in website operations, especially for sites involving product display.This not only optimizes the user experience, reduces invalid consultations, but also effectively guides the user's purchase decision.AnQiCMS as a flexible and efficient content management system, implements the display of "in stock" or "out of stock" status according to the product inventory quantity in the template, which is very intuitive. AnQiCMS template system adopts a syntax similar to Django, which allows us to control the display of page content through concise tags and variables.When processing product information

2025-11-09

How to display different content in the AnQiCMS template based on the value of the `item.Status` field (such as approved, in review)?

In website content operation, the review status of the content is a very important link.Whether it is a comment submitted by the user, a forum post, or an article or product information released by the website administrator, it often needs to be reviewed before it can be displayed to the public.AnQiCMS provides a flexible template mechanism that allows us to easily display different content on the front-end page based on the review status of the content (such as "approved" or "in review"), thereby providing users with clearer and more accurate feedback.AnQiCMS template syntax is similar to the Django template engine

2025-11-09

What are the respective application scenarios of the `striptags` and `removetags` filters when cleaning HTML code in AnQiCMS templates?

In AnQiCMS template design, we often encounter situations where we need to clean up or simplify the HTML code in the content.This is not just for beauty, but also to ensure the correct display of content, improve page loading efficiency, and even prevent potential security risks.The Aqie CMS provides two very practical filters: `striptags` and `removetags`.Although they are all related to the removal of HTML tags, each has a clear application scenario.### `striptags`

2025-11-09

How can AnQiCMS templates safely display user-submitted rich text content to prevent potential XSS attacks?

During website operations, displaying rich text content submitted by users, such as article comments, forum posts, or blog content, is an unavoidable requirement.However, there may be malicious scripts hidden in these contents, and if they are displayed without precautions, it may lead to cross-site scripting (XSS) attacks, posing potential threats to website visitors.AnQiCMS (AnQiCMS) has fully considered this security risk in its design and provides a series of mechanisms through its template engine to help us safely handle this type of rich text content.

2025-11-09

How to control the automatic escaping of HTML tags with the `autoescape` tag in AnQiCMS templates?

In the AnQiCMS template system, our daily content display core is inseparable from the handling of HTML tags.To ensure the security of the website, AnQiCMS defaults to automatically escaping variables output in templates.This mechanism effectively prevents the injection of malicious code, such as common cross-site scripting attacks (XSS).However, in some scenarios, we may need to display rich text content that includes HTML tags, at this point we need to understand how to flexibly control this automatic escaping function.### Automatically Escaped

2025-11-09

How to check if the article content in the AnQiCMS template contains specific keywords and display conditions based on this?

In website content operation, we often need to flexibly adjust the display of the page according to the actual content of the article.For example, if an article mentions a specific product or event, we may want to highlight related purchase links or promotional information on the page;If the content of the article involves sensitive topics, it may be necessary to add additional disclaimers.This requirement for conditional display based on article content can be fully realized in the AnQiCMS template.AnQi CMS uses a template engine syntax similar to Django

2025-11-09