How to truncate a long string (such as an article summary) to a specified length and display an ellipsis in the AnQiCMS template?

Calendar 👁️ 58

In website content operation, the display length of article abstracts or content introductions often needs to be carefully controlled.Long content can affect page layout and user experience, while a concise summary with an ellipsis can effectively guide users to click and read more details.AnQiCMS provides flexible template tags and filters, allowing us to easily implement this feature.

In AnQiCMS templates, we often usearchiveListtags to loop through article lists, or througharchiveDetailTag to get the details of a single article. Whether in any case, the summary of the article is usually stored inDescriptionthe field. For example, in the article list, we use{{item.Description}}To get the abstract of each article; on the article detail page, it is{{archive.Description}}. Now, our goal is to truncate these long strings and add an ellipsis at the end.

The AnQiCMS template system provides a very convenient filter to meet this requirement. The most core tool istruncatecharsfilter.

UsetruncatecharsThe filter extracts plain text strings

truncatecharsThe filter can truncate a string to the length you specify and automatically add an ellipsis “…” at the end. This length includes the total number of characters, including the ellipsis.

Its usage is very intuitive:

{{ 变量 | truncatechars:长度 }}

For example, if you want to truncate the article abstract to 50 characters:

<p>{{ item.Description | truncatechars:50 }}</p>

so ifitem.DescriptionThe content exceeds 50 characters and will be truncated, with an ellipsis added after the 47th character, with a total length of 50. If the content itself is less than 50 characters,truncatecharsIt will not perform any operation, output as is.

Processing a long string containing HTML:truncatechars_html

Many times, the abstract of an article may not be plain text, but contains<strong>/<em>/<a>Rich text content of HTML tags. If the string containing HTML is used directlytruncatecharsIt may cause HTML tags to be truncated, thus destroying the page structure or style.

To elegantly handle this situation, AnQiCMS provides.truncatechars_htmlFilter. This filter will intelligently identify and retain the integrity of HTML tags, ensuring that the final output HTML is still valid while extracting strings.

Its usage is similar to.truncatecharssimilar:

{{ 变量 | truncatechars_html:长度 }}

For example:

<p>{{ item.Description | truncatechars_html:100 | safe }}</p>

Here, | safeFilters are also crucial.truncatechars_htmlIt will produce a string containing HTML tags, and| safeTell AnQiCMS template engine that this is a safe HTML fragment that can be rendered directly without performing HTML entity encoding.This ensures that the HTML content after extraction is displayed correctly.

Practical Application and **Practice

Applying the above filters to your template will allow you to flexibly control content display.

1. List page article summary extraction

On the homepage or category list page of the website, it is often necessary to display brief summaries of multiple articles.

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
    <div class="article-card">
        <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
        {# 假设 item.Description 包含 HTML,并截取为 120 个字符 #}
        <p class="article-summary">{{ item.Description | truncatechars_html:120 | safe }}</p>
        <a href="{{ item.Link }}" class="read-more">阅读更多</a>
    </div>
    {% endfor %}
{% endarchiveList %}

2. Summary extraction at the top of the detail page

In some article detail pages, you may wish to display a brief summary before the main content of the article.

{% archiveDetail archive with name="Description" %}
<div class="post-intro">
    {# 假设 archive.Description 可能包含简单HTML,并截取为 150 个字符 #}
    <p>{{ archive | truncatechars_html:150 | safe }}</p>
</div>
{% endarchiveDetail %}

{# 文章主体内容 #}
<div class="post-content">
    {% archiveDetail articleContent with name="Content" %}
    {{ articleContent | safe }}
    {% endarchiveDetail %}
</div>

3. Intelligent judgment, avoid unnecessary ellipses.

Sometimes, the abstract of the article is already very short and does not require truncation. To avoid adding an ellipsis even when the content is very short, we can combinelengthFilters andiftags for conditional judgment.

{% set raw_summary = item.Description %}
{% if raw_summary|length > 80 %} {# 判断原始字符串长度是否超过 80 #}
    <p>{{ raw_summary | truncatechars_html:80 | safe }}</p>
{% else %}
    <p>{{ raw_summary | safe }}</p> {# 如果不长,则原样输出 #}
{% endif %}

This handling method is more user-friendly and can enhance the user's reading experience.

Summary

Bytruncatecharsandtruncatechars_htmlThese powerful filters, the AnQiCMS template performs very flexible and efficient in handling long string truncation and ellipsis display. According to the nature of your content (plain text or rich text), choose the appropriate filter and combine with| safeAnd with condition judgment, it can easily realize diversified content display needs, making your website interface more tidy and professional.


Frequently Asked Questions (FAQ)

  1. Question:truncatecharsandtruncatechars_htmlWhat are the essential differences between filters? Answer: truncatecharsThe filter is mainly used to truncate plain text strings, it simply truncates by character count without considering any existing HTML tags. If your content contains HTML, usetruncatecharsIt may cause the label to break, destroying the page structure.truncatechars_htmlIt is specifically designed to handle strings containing HTML tags, it intelligently recognizes and tries to maintain the integrity of HTML tags during extraction, ensuring that the output HTML is still valid to avoid display anomalies on the page.

  2. Ask: Is the ellipsis “…” included in truncation length? Answer:Yes, you are intruncatecharsortruncatechars_htmlThe length set in the filter (for exampletruncatechars:50of50The total number of characters including the automatically added ellipsis “…”This means that if you set the length to 50, the actual number of characters displayed will be 47, plus 3 ellipses.

  3. Ask: I am running a multilingual website, English content usestruncatecharsWhen cutting, words are often cut off, is there a better method? Answer:AnQiCMS provides for English and other languages that use words as the basic unit of content,truncatewordsandtruncatewords_htmlFilters. They work in a way thattruncatecharsandtruncatechars_htmlSimilar, but not truncated by character count, but by word count, which can avoid cutting a word in half and make the reading experience more natural. Chinese content, due to the lack of clear word delimiters, usually usestruncatecharsThe series filter is more suitable.

Related articles

How to judge whether a variable is empty in AnQiCMS template and set a default display value?

During the development of website templates, it is often encountered that the variable value may be empty.If not properly handled, the front-end page may appear with unattractive blank areas, even displaying some default placeholders (such as `nil` or `null`), which undoubtedly affects user experience and the professionalism of the website.AnQiCMS (AnQiCMS) provides a powerful and flexible template engine that can help us elegantly determine whether variables are empty and set appropriate default display values.

2025-11-07

How to dynamically display the Title, Keywords, and Description information of the website homepage in AnQiCMS template?

In website operation, the Title (title), Keywords (keywords), and Description (description) of the homepage are the first impression given to users on the search engine results page (SERP) and are also the key for search engines to understand the core content of the website.They not only affect the website's search engine optimization (SEO) effect, but also directly relate to whether users will click to enter your website.AnQiCMS as a feature-rich enterprise-level content management system provides a straightforward and powerful way to manage these important SEO elements. Next

2025-11-07

How to display all the Tag tags belonging to the current article in AnQiCMS template?

Flexible display of article tags in AnQiCMS templates Tags are a highly effective content organization method in website content operation.They can not only help users find relevant content faster, enhance the browsing experience of the website, but also have an indispensable positive effect on search engine optimization (SEO).AnQiCMS as a feature-rich enterprise-level content management system naturally also provides powerful tag management and call functions, allowing us to easily display all tags associated with the current article on the article detail page.

2025-11-07

How to get and display related article lists according to Tag ID in AnQiCMS template?

In a content management system, Tag (tag) plays an important role.They can not only help us flexibly organize content, but also associate articles with similar themes across different categories, and can effectively improve the website's internal link structure and user experience.When a user is interested in a specific topic, by clicking on a Tag, they can easily view all related articles.AnQiCMS provides a set of intuitive and powerful template tags that allow you to easily retrieve and display these related article lists based on Tag ID.

2025-11-07

How to remove specific HTML tags from an HTML string in the AnQiCMS template (such as `<i>`, `<span>`)?

In AnQiCMS template development, we often encounter content coming from rich text editors, or imported from external sources, which may contain some HTML tags that we do not want to display at specific locations.For example, in the summary section of the article list, we may only want to display plain text, or we may need to remove specific tags such as `<i>`, `<span>`, etc. to maintain the consistency of the page style.

2025-11-07

How to convert newline characters in multi-line text to the HTML `<br>` tag for display in AnQiCMS templates?

In AnQiCMS content management, we often enter multi-line text with line breaks, such as article content, product descriptions, or contact addresses.However, when this content is displayed on the website front-end, we may find that the original clear line breaks are missing, and all the text is squeezed into a single line.This not only affects the reading experience of the content, but may also be inconsistent with our original design intention.Why is this happening?

2025-11-07

How to calculate the number of elements in a string (such as an article title) or an array (such as a tag list) in AnQiCMS templates?

In AnQi CMS template design, we often need to make accurate statistics of the content on the page, whether it is to dynamically display the number of data or to make conditional judgments based on the number, mastering how to calculate the number of elements in a string or array is particularly important.AnQiCMS's powerful template engine provides a concise and efficient method to handle these requirements.

2025-11-07

How to automatically convert a URL string into a clickable hyperlink and set `nofollow` in the template of AnQiCMS?

In the daily operation of AnQi CMS, we often need to display external links in the website content.These links, if they are just simple text, not only affect the user experience, but also cannot effectively convey information.At the same time, in order to follow the **practice** of search engine optimization (SEO), especially for links pointing to external sites, we usually want to add the `rel="nofollow"` attribute to avoid unnecessary "weight loss" or passing unnecessary trust.AnQi CMS provides a simple and efficient method to solve this problem.### Core Function Revelation

2025-11-07