How to truncate a string and add an ellipsis (...) in AnQiCMS templates?

Calendar 👁️ 64

In website content management, we often need to present a long text (such as an article abstract, product description) in a concise way on the page, which can not only save space but also improve the user's browsing efficiency.If long text is not processed and displayed directly in the list, it may lead to a chaotic page layout and affect the user experience.The template engine of AnQiCMS (AnQiCMS) provides flexible and powerful filter (Filters) functions that can help us easily implement string truncation and automatically add ellipses.

String slicing in AnQiCMS template: principle and method

The template engine of AnqiCMS is similar to Django syntax, it processes and formats template variables through 'filters'. Filters use the pipe character|Connected to the variable, it can conveniently operate on data types such as strings, numbers, etc.For string truncation, AnQiCMS has built-in a variety of practical filters that can meet the needs of different scenarios.

Basic Concept: Filters and Template Variables

In AnQiCMS templates, you will see something like{{ 变量 }}This syntax is used to output content. And when we need to handle this变量When content needs special processing, filters can be introduced, for example{{ 变量|过滤器名称:参数 }}.

Next, we will introduce several commonly used string truncation filters.

Exact control of character count:truncatechars

When you need to limit a long text precisely to a certain number of characters and want to automatically add an ellipsis to the part that exceeds,truncatecharsThe filter is a good choice. It will truncate according to the number of characters you specify and add “…” at the truncation point. It is worth noting that these three ellipses are also counted in the total character count.

  • How to use: {{ obj|truncatechars:数字 }}
  • Example:Assumedescriptionthe value of the variable is"AnQiCMS 是一个基于 Go 语言开发的企业级内容管理系统,致力于提供高效、可定制、易扩展的内容管理解决方案。"If you need to cut the first 15 characters:{{ description|truncatechars:15 }} Output Result: AnQiCMS 是一个基于 Go...Please note that both Chinese characters and English characters are counted as single characters here.

Cut by word:truncatewords

If you prefer to maintain the integrity of the text and avoid breaking words in the middle, thentruncatewordsThe filter would be more appropriate. It will truncate according to the number of words you specify, and add an ellipsis after the last complete word, and the ellipsis will not be counted in the word count.

  • How to use: {{ obj|truncatewords:数字 }}
  • Example:Continue using the abovedescriptionVariable:{{ description|truncatewords:5 }} Output Result: AnQiCMS 是一个基于 Go 语言开发...(It will try to keep the first 5 words and add an ellipsis at the end.)

Process HTML content:truncatechars_htmlwithtruncatewords_html

In website content operation, we often encounter content generated by rich text editors with HTML tags. If used directly,truncatecharsortruncatewordsExtracting content of this type may lead to the destruction of the HTML structure, disordered page layout, and even abnormal display.

To solve this problem, AnQiCMS providedtruncatechars_htmlandtruncatewords_htmlThese filters are specifically designed to handle HTML content.They will intelligently retain the complete HTML tags while extracting text, ensuring the correctness of the page structure.

  • truncatechars_html:Extract text containing HTML based on the number of characters while retaining the HTML structure.

    • How to use: {{ obj|truncatechars_html:数字 }}
    • Example:Assumecontentthe value of the variable is"<p>这是一段<b>重要的</b>内容。</p><span>请注意查收。</span>" {{ content|truncatechars_html:10|safe }}(Note: When outputting HTML content, it is usually necessary to add}|safeFilter to prevent HTML tags from being escaped)Output Result: <p>这是一段<b>重要的</b>内容...</p>(The filter will close any open tags to ensure HTML validity.)
  • truncatewords_html:Extract text containing HTML based on the number of words, while preserving the HTML structure.

    • How to use: {{ obj|truncatewords_html:数字 }}
    • Example:Continue using the abovecontentVariable:{{ content|truncatewords_html:3|safe }} Output Result: <p>这是一段<b>重要的</b>...</p>(It will recognize word boundaries while keeping the tags closed.)

Case Study: Optimize Page Content Display

Suppose you are building an article list page, each article needs to display a brief description or abstract. The article'sDescriptionThe field may come from the background text input, whereasContentThe field is the full content generated by the rich text editor, which includes HTML.

{# 在文章列表循环中 #}
{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
    <article class="article-item">
        <h2 class="article-title"><a href="{{ item.Link }}">{{ item.Title }}</a></h2>

        {# 展示简洁描述,使用 truncatechars 避免过长 #}
        <div class="article-description">
            {{ item.Description|truncatechars:120 }}
        </div>

        {# 如果没有 Description,但有 Content,可以尝试截取 Content 的部分内容作为摘要 #}
        {% if not item.Description and item.Content %}
        <div class="article-teaser">
            {# 对 HTML 内容进行截取,确保标签不被破坏,并加上 |safe 防止转义 #}
            {{ item.Content|truncatewords_html:60|safe }}
        </div>
        {% endif %}

        <div class="article-meta">
            <span>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
            <span>浏览量:{{ item.Views }}</span>
        </div>
    </article>
    {% empty %}
    <p>暂时没有文章。</p>
    {% endfor %}
{% endarchiveList %}

By flexibly using these filtering tools, you can ensure that the website presents content elegantly across different devices and layouts, enhancing user experience.

Summary

AnQiCMS template filters provide us with very convenient string processing capabilities.Whether it is a precise cut to the number of characters or an intelligent cut based on words, or even a friendly handling of rich text HTML content, it can be easily realized through simple filter syntax.Reasonably utilizing these features will make your website content display more professional, neat, and more in line with user reading habits.


Frequently Asked Questions (FAQ)

1. Can you customize the ellipsis style or content after truncation (for example, changing “…” to “Read more”)?

AnQiCMS built-in truncation filter (such astruncatechars)The ellipsis style provided is fixed and cannot be customized directly through filter parameters. If you need text like sliceFilter to extract a fixed-length string (without an ellipsis) and then useifCheck if the original string length exceeds, if it does, then concatenate a custom text or link to the end of the truncated string.But this method requires you to handle character length calculation yourself, relatively complex.

2. Why does the page layout become messy after I extract content with HTML tags?

This is usually because you have usedtruncatecharsortruncatewordsThis filter does not recognize HTML structure to process rich text content.They indiscriminately truncate HTML tags, causing the labels on the page to close incorrectly, thereby causing layout chaos.Be sure to use for content containing HTMLtruncatechars_htmlortruncatewords_htmlfilters, which intelligently retain the integrity of HTML tags, ensuring that the page structure is not affected.

3. Can I apply multiple slicing filters to a variable?

AnQiCMS template filters support chained calls (for example{{ item.Title|lower|truncatechars:10 }}), but it is usually different types of filters (such as first convert to lowercase and then cut off). For the cutting function itself, you should choose the filter that best meets your needs (such astruncatecharsortruncatewords_html),Instead of trying to apply multiple extraction filters at the same time. Because different extraction logic (character-based, word-based, whether to handle HTML) can produce different results, and applying them simultaneously may lead to unexpected behavior or errors.

Related articles

How to display a message form on the AnQiCMS website and support the display of custom fields?

Today, with the increasing importance of digital operation, the website message board is not only an important bridge for user interaction with the website, but also a key channel for collecting user feedback and understanding market demand.AnQiCMS (AnQiCMS) fully understands this need, providing flexible and powerful form display and custom field support, allowing you to easily create an interactive platform that meets business requirements. ### Step 1: Configure the custom fields of the comment form To give the comment form more personalized information collection capabilities, we need to configure it first in the Anqi CMS backend.

2025-11-07

How to control specific content to be visible only to the VIP user group in AnQiCMS?

In content operation, it is a common strategy to present some high-quality content exclusively to VIP users.This can not only enhance user stickiness and promote user conversion, but it is also an important way to realize content monetization.AnQiCMS provides a complete user group management and content permission control function, allowing you to easily implement the need for specific content to be visible only to VIP user groups. ### Backend Settings: Distinguishing Users and Content To make VIP exclusive content visible, you first need to make two key configurations in the AnQiCMS backend: user group management and content permission settings.

2025-11-07

How to display the contact information of the website, such as phone, address, email, in AnQiCMS templates?

The contact information of the website, like a business card, is an important channel for visitors to understand and trust the website.Whether it is to hope that customers call to consult or to make it convenient for them to communicate through email, or to guide them to the physical store, clear and accurate contact information is indispensable.In AnQiCMS, displaying this information is a very intuitive and flexible thing, which allows us to not only manage uniformly but also display at different positions on the website according to our needs.

2025-11-07

How does AnQiCMS ensure that uploaded images are automatically converted to WebP format to optimize loading speed?

In today's fast-paced digital world, website loading speed directly affects user experience and search engine rankings.Especially images, they are often the main culprits in slowing down website speed.Large image files not only consume more server bandwidth, but also extend the page rendering time, leading to visitor loss. 幸运的是,AnQiCMS understands this and provides us with an elegant solution through intelligent image processing: automatically converting uploaded images to WebP format to optimize website loading speed. WebP is a modern image format developed by Google

2025-11-07

How to automatically filter or process external links in AnQiCMS article content?

In daily website content operation, we often encounter situations where external links need to be cited in articles.These external links are handled well, they can enrich the content and provide references, but if not managed properly, they may also affect the SEO performance or user experience of the website.AnQiCMS is a content management system that focuses on efficiency and SEO, providing practical automated solutions in this aspect, helping us better manage external links in the article content.### Core options in the background content settings The core mechanism of AnQiCMS handling external links in articles

2025-11-07

How to automatically wrap long text for display in AnQiCMS templates?

During the operation of the AnQiCMS website, we often encounter scenarios where we need to display a large amount of text content, such as the main content of article detail pages, detailed descriptions of product introductions, or long introductions on category pages.These long texts, if not handled properly, may cause page layout to be disordered and affect the user's reading experience.Fortunately, AnQiCMS's powerful template engine provides various flexible ways to manage and display these long texts, including automatic line breaks and content truncation.AnQiCMS's template system has adopted the syntax of Django template engine, allowing us to use double curly braces

2025-11-07

How does AnQiCMS control the special display style of articles by setting the Flag attribute?

In Anqi CMS, the Flag attribute of the article is a very practical feature, which allows us to tag articles with special "labels" to display them uniquely on the website front-end.This mechanism greatly enhances the flexibility and diversity of content display, allowing website operators to easily control the display style and position of articles based on the importance, characteristics, or promotion needs of the content.What is the article Flag attribute? In simple terms, the Flag attribute is like a special "mark" that is attached to the article, it is not a category of the article

2025-11-07

How to judge if a variable is empty in the template and display a default value?

During the presentation of web content, we often encounter such situations: a variable may be empty due to data loss, user failure to fill in, or other reasons.If you directly output these empty variables in the template, it may result in blank spaces on the page, affecting the appearance, or even cause layout errors, and may even expose unnecessary debugging information.It is particularly important to set a suitable default value for these variables that may be empty to ensure the completeness of website content display and the smoothness of user experience.The AnqiCMS uses a template engine syntax similar to Django

2025-11-07