How to truncate a string and add an ellipsis (...) to limit the display length in AnQiCMS template?

Calendar 👁️ 55

In AnQiCMS template development, we often need to refine the content displayed on the website, such as article titles, summaries, or abstracts of a text.If content is too long, it not only affects the beauty of the page, but may also reduce the reading experience of users.AnQiCMS's powerful template engine provides a simple and efficient way to solve this problem, allowing us to easily extract strings and automatically add ellipses (…), thereby elegantly limiting the display length of content.

AnQiCMS's template system adopts a syntax similar to the Django template engine, which is flexible and easy to use.When handling string slicing, the built-in 'filter' function is mainly relied upon.These filters are like little tools that can process the content of variables and then output the processed results.

Smartly using AnQiCMS string truncation filter

AnQiCMS provides us with four main and very practical string truncation filters, each catering to different scenarios:

  1. truncatechars: Truncate by character count (ignoring the integrity of words)This filter will truncate the string according to the number of characters you specify.It should also take into account the ellipsis (...) that is automatically added.If the cut-off position is exactly in the middle of a word, it will also be cut off directly.Usage: {{ 变量 | truncatechars:长度 }} Example:Assumearchive.TitleThe content is “AnQiCMS is a powerful enterprise-level content management system”.{{ archive.Title|truncatechars:15 }} output: AnQiCMS是一个功...You can see that the word "function" has been cut off.

  2. truncatewords: Cut by word count (keep the integrity of the word)withtruncatecharsdifferent,truncatewordsWill try to maintain the integrity of the words.It will truncate the number of words you specify and add an ellipsis at the end.This filter works very effectively when processing English content because it recognizes spaces between words.truncatecharsSimilar.Usage: {{ 变量 | truncatewords:单词数量 }} Example:Assumearchive.DescriptionThe content is 'AnQiCMS is a powerful enterprise content management system developed using Go language.'{{ archive.Description|truncatewords:8 }} output: AnQiCMS is a powerful enterprise content management system...

  3. truncatechars_html: Safely truncate HTML content by character countIf the content to be truncated may contain HTML tags, use it directlytruncatecharsIt could cause the label to be truncated, thereby destroying the HTML structure of the page, causing a display mess.truncatechars_htmlThe filter can solve this problem well. It will intelligently close unclosed HTML tags during extraction, ensuring that the extracted content is still valid HTML.Usage: {{ 变量 | truncatechars_html:长度 | safe }} Important reminder:Since this filter processes HTML content, it must be added when outputting|safeA filter to inform the template engine that the content is safe, does not require escaping, and thus the HTML tags can be rendered correctly.

  4. truncatewords_html: Safely truncate HTML content by word count.withtruncatechars_htmlsimilar,truncatewords_htmlUsed to truncate HTML content while maintaining the integrity of the HTML structure. Similarly, it also needs to be配合 in the output|safefilter usage.Usage: {{ 变量 | truncatewords_html:单词数量 | safe }}

Example in actual application

Now, let's demonstrate how to apply these filters to AnQiCMS templates in a real scenario, for example, displaying article titles and summaries on a document list page:

We need to display multiple articles in a loop, and the title and summary of each article need to be limited in length.

{# 假设我们正在循环一个名为 archives 的文档列表 #}
<ul class="article-list">
    {% for item in archives %}
    <li class="article-item">
        <h3 class="article-title">
            <a href="{{ item.Link }}">
                {# 截取标题,限制为30个字符,并自动添加省略号 #}
                {{ item.Title|truncatechars:30 }}
            </a>
        </h3>
        <div class="article-summary">
            {# 截取简介(假设可能包含少量HTML),限制为100个字符,并安全地处理HTML #}
            {{ item.Description|truncatechars_html:100|safe }}
        </div>
        <a href="{{ item.Link }}" class="read-more">阅读更多</a>
    </li>
    {% empty %}
    <li class="no-content">暂无相关文章。</li>
    {% endfor %}
</ul>

In this example, we usedtruncatecharsMake sure the title is not too long and that the synopsis has been usedtruncatechars_htmland|safeTo avoid HTML tags from being destroyed. This way, no matter how long or complex the original content is, the page can maintain a neat and beautiful appearance.

By flexibly using these string truncation filters provided by AnQiCMS, we can easily control the length of page content, greatly enhancing the visual experience and professionalism of content presentation.


Frequently Asked Questions (FAQ)

  1. Ask: After truncation, do I want to display an ellipsis, but only want pure truncation? Can it be implemented?Answer: AnQiCMS built-intruncatecharsandtruncatewordsThe series filter is designed to automatically add ellipses. If you really do not need ellipses, you can consider usingsliceThe filter performs pure string truncation. For example:{{ 变量|slice:":30" }}It will truncate the first 30 characters without an ellipsis. But this requires you to judge the original string length yourself, and add an ellipsis manually if needed.

  2. Question: When handling Chinese content,truncatewordsThe filter effect is not noticeable, what are some alternatives?Answer:truncatewordsThe filter mainly identifies spaces between English words to extract. Since Chinese does not have a natural word separator, when used directly on pure Chinese content, its performance will be different andtruncatecharsVery similar, both are cut by character number. Therefore, it is usually recommended to use it directly when dealing with Chinese content.truncatecharsortruncatechars_htmlTo cut by character number, which can better control the display length.

  3. Ask: Why do we need to extract HTML content besidestruncatechars_htmlortruncatewords_html, we also need to add|safeFilter?Answer: AnQiCMS template engine, for security reasons, defaults to escaping all output content to prevent XSS attacks. This means that like<p>/<a>Such HTML tags will be escaped into&lt;p&gt;/&lt;a&gt;Thus, they are displayed as plain text rather than actual HTML structure. When you use_htmlThe filter in the series captures the content containing HTML, and if you want these HTML tags to be correctly parsed and rendered by the browser, you need to explicitly add|safeFilter, tell the template engine: "This content has been processed, it is safe, please do not escape, and output HTML directly."

Related articles

How to format a timestamp (timestamp) into a readable date format for display in AnQiCMS?

In the process of website operation, the effective display time of content publishing or updating is crucial for improving user experience and the readability of content.If time information is presented in the original timestamp format, it is often difficult for ordinary users to understand.AnQiCMS provides a straightforward and flexible way to help you convert these digital timestamps into easily readable date and time formats.### How AnQiCMS handles timestamps AnQiCMS typically uses standard Unix Timestamp format for storing content time information

2025-11-08

How to use a `for` loop to iterate over data and display content in AnQiCMS templates?

In AnQiCMS template development, we often need to display a series of dynamic content, such as the latest article list, product categories, navigation menu items, and even custom parameters.At this point, the 'for loop' has become the core tool for us to traverse these data and display it on the web page.Understand and master the `for` loop, which will greatly enhance the flexibility and development efficiency of the template.### Core Grammar: The Foundation of Data Traversal The `for` loop syntax in AnQiCMS templates is concise and intuitive, borrowing the style of the Django template engine.

2025-11-08

How to use the `if` tag for conditional judgment to control content display in AnQiCMS templates?

How to use the `if` tag for conditional judgment to control content display in AnQiCMS templates?When building website templates, we often need to display or hide specific content blocks based on different conditions.For example, the image will be displayed only when the article has a thumbnail, or the welcome message will be displayed only after the user logs in.In the AnQiCMS template system, the `if` tag is a powerful tool for implementing conditional judgments.It uses a syntax similar to the Django template engine, concise and expressive, making the content display logic clear and easy to understand

2025-11-08

How to dynamically retrieve and display the contact information of the website in AnQiCMS?

In today's digital age, a website's contact information is more than just cold numbers or addresses; it is a bridge for users to build trust and communicate with the company.Efficiently and accurately display this information on the website, and be able to update it flexibly as needed, which is crucial for any website operator.AnQiCMS as an enterprise-level content management system provides a very intuitive and powerful solution in this aspect, allowing you to easily manage these key information without touching complex code.This article will introduce how to configure and dynamically obtain the contact information of the website in AnQiCMS

2025-11-08

How to safely output HTML code in the template without escaping in AnQiCMS?

When using AnQiCMS for website template development or content display, you may encounter situations where you need to output HTML code directly on the page, only to find that the code is automatically escaped, for example, the `<p>` tag becomes `&lt;This often confuses those who are new to it.In fact, this is the default measure taken by the AnQiCMS template engine for website security.### Understanding the default security mechanism of AnQiCMS templates The AnQiCMS template engine design has drawn inspiration from

2025-11-08

How to automatically wrap long text to a specified length in AnQiCMS template?

In the presentation of website content, the way long texts are displayed is often a key factor affecting user experience and the beauty of the page.When we need to display a long text content, such as an article summary, product description, or detailed introduction, in a more readable and layout-adaptive way, AnQiCMS's template function provides a powerful and flexible solution.AnQiCMS uses syntax similar to Django template engine, with various built-in filters (Filters) that can help us easily format text.

2025-11-08

How to automatically parse a URL string into a clickable HTML link in AnQiCMS template?

In AnQiCMS template development, we often encounter the need: the URL string contained in the content should be automatically converted into a clickable HTML link to enhance user experience and page interactivity.Manually adding links is undoubtedly cumbersome and unrealistic, fortunately AnQiCMS provides powerful template filters that can help us easily achieve this function.AnQiCMS template engine supports Django-like syntax, which includes a series of practical filters that can process variable content.For automatic parsing of URL strings

2025-11-08

How to define and use temporary variables in AnQiCMS templates to simplify content display?

When developing templates in AnQiCMS, we often encounter situations where we need to process some complex data or reuse a certain calculation result.To make the template code more concise, readable, and maintainable, AnQiCMS provides a powerful mechanism for defining and using temporary variables, mainly through the `with` and `set` tags.Reasonably utilizing them can greatly enhance our content display efficiency and flexibility. ### Simplified Content Display: Why do we need temporary variables?

2025-11-08