How to truncate the title of the article and automatically add an ellipsis in the AnQiCMS template?

Calendar 👁️ 57

In Anqi CMS template design, for the beauty of the page and the unity of layout, we often need to truncate the article title and automatically add an ellipsis after truncation.AnQiCMS provides a simple and efficient template filter to meet this requirement, making content display more flexible.

The core principle: Understanding AnQiCMS template filters

In the AnQiCMS template system, with its powerful Django-like template engine, we can conveniently use 'filters' to process and format data.These filters can process variables, such as changing case, formatting time, or what we are currently concerned with - truncating strings.

AnQiCMS provides character truncation and ellipsis addition for article titles,truncatecharsFilter. Its function is: when the number of characters in a string exceeds a specified length, it will automatically truncate the extra characters and add...an ellipsis. It is worth noting that,truncatecharsWhen calculating the character count, the automatically added ellipsis is included.

The basic syntax of the filter is as follows:{{ 变量 | 过滤器名称 : 参数 }}

Here, 变量It refers to the string you want to truncate (such as an article title),过滤器名称That istruncatecharswhile参数which is the maximum number of characters you want to keep.

Practice Exercise: Applying Title Truncation in Templates

Next, let's see how to truncate article titles in AnQiCMS templates through specific template code examples.

Scene one: Article list page title truncation

On the article list page of the website (such as the latest articles on the homepage, category article lists, etc.), the title usually needs to be kept within a certain length to avoid layout confusion. At this time,archiveListLabel collaborationtruncatecharsThe filter is an ideal choice.

Suppose we want to display article titles in a list and limit their length to 30 characters:

{# 假设我们正在循环输出文章列表,变量名为 archives #}
{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
    <li>
        <a href="{{item.Link}}">
            {# 对文章标题 item.Title 进行字符截断,并限制在 30 个字符以内 #}
            <h5>{{item.Title | truncatechars:30 }}</h5>
            <div>{{item.Description}}</div>
            {# ... 其他文章信息 ... #}
        </a>
    </li>
    {% empty %}
    <li>
        当前没有可展示的文章。
    </li>
    {% endfor %}
{% endarchiveList %}

In this example,item.TitleIs the article title we have obtained. Through| truncatechars:30The system will automatically check the title length, if it exceeds 30 characters, it will be truncated from the 27th character and appended with...The final length is 30 characters.

Scenario two: Truncation of a single article title (non-list scenario)

Although on the article detail page, the full title is usually displayed, under certain special layouts, such as page sidebars or custom modules, it is also possible to use the concise version of the current article title.truncatecharsfilter.

Assume that in a sidebar module, it is necessary to display the title of the current page article and limit it to 20 characters:

{# 获取当前文章的详情,假定变量 archive 已可用 #}
{# 如果 archive 未直接可用,可以使用 archiveDetail 标签获取,例如:
   {% archiveDetail currentArchive with name="Title" %}
   <h3>{{ currentArchive | truncatechars:20 }}</h3>
#}
<div>
    <h3>{{archive.Title | truncatechars:20 }}</h3>
    <p>{{archive.Description | truncatechars:50 }}</p>
</div>

here,archive.TitleRepresents the title of the current article. Similarly,| truncatechars:20Ensure the title is displayed within 20 characters and automatically adds an ellipsis.

Additional hint: Handle titles containing HTML.

Although the title of an article is usually plain text, if the content of your website or the 'title' of some special fields may contain HTML tags (for example, through custom field input), use it directlytruncatecharsIt may destroy the HTML structure. For this kind of situation, AnQiCMS providestruncatechars_htmlFilter. It intelligently tries to maintain the integrity of HTML tags during truncation, preventing unclosed tags.

At the same time, in order to ensure that the content containing HTML can be parsed correctly by the browser rather than displayed as plain text, it usually needs to be paired with|safefilter.

{# 假设 item.RichTitle 是一个可能包含 HTML 的标题 #}
<h5>{{item.RichTitle | truncatechars_html:50 | safe }}</h5>

In this example,truncatechars_html:50Truncates the title to 50 characters while preserving the HTML structure and adds an ellipsis.| safeThen tell the template engine that this content is safe HTML and does not need to be escaped.

Points to note

  • Choose an appropriate truncation length:The length of the truncation needs to be determined based on the actual page design and reading habits.Too short may not provide enough information, too long may lose the significance of truncation.It is recommended to perform more testing and adjustment in the actual environment.
  • Chinese character processing:AnQiCMS is developed based on the Go language, and its string processing naturally supports Unicode. This meanstruncatecharsThe filter correctly counts a Chinese character as one character when processing Chinese characters, and it will not truncate half of a Chinese character.
  • SEO considerations:Although truncating the article title is mainly for the beauty of the front-end display, but remember, the page'stitleTags (usually set through TDK tags) should contain a complete, search engine optimized title.The truncation in templates usually only affects local displays such as lists or cards, rather than the core SEO title of the page.

By reasonably using the AnQiCMS providedtruncatecharsA filter that allows us to easily implement automatic character truncation and ellipsis addition for article titles, thus optimizing the visual presentation and user experience of the website.


Frequently Asked Questions (FAQ)

  1. How to customize the ellipsis character that appears after truncation?...It can be set to other symbols, such as... [更多]? Answer:in the AnQiCMS providedtruncatecharsfilter, the ellipsis (...) is part of the built-in behavior, the documentation does not mention any parameters to directly configure or modify the default ellipsis character. If you need to customize the content after the ellipsis, you may need to use more complex template logic (such as using ifConditionally judge the length of the string, then manually concatenate the truncated content with a custom suffix), or consider using a custom template function to implement it, although this usually goes beyond the functionality provided by a simple filter.

  2. Ask: If my article title already contains HTML tags, can I use them directly?truncatecharsWill there be a problem if I truncate it? Answer:Yes, if the article title contains HTML tags (for example,<strong>我的标题</strong>Please use directlytruncatecharsThe filter may truncate tags directly based on character count, which can destroy the HTML structure and affect page rendering. To avoid this situation, AnQiCMS providestruncatechars_htmlThe filter tries to maintain the integrity of HTML tags when truncating. It is used intruncatechars_htmlit is usually necessary to coordinate with|safe

Related articles

How to use `split` and `join` filters to standardize user tag inputs?

In the daily content operation of AnQi CMS, the tags (Tag) submitted by users often face a common problem: the format is not unified.Some users are accustomed to separating with commas, some with semicolons, and even possibly with Chinese commas or even just spaces.These irregular inputs, if directly displayed on the website front-end, not only affect the aesthetics but may also reduce the usability of tags, for example, causing trouble when generating tag clouds or performing SEO optimization.

2025-11-07

How to combine a dynamically generated array (such as a tag list) into a string with a specified delimiter for display in a template?

In website content operation, we often need to display a series of related information in the form of a list to users, such as all tags of an article, multiple characteristics of a product, or a set of image URLs.AnQiCMS's template system usually provides these data in the form of a dynamic array (or sometimes called slices, lists).

2025-11-07

What are the main differences and application scenarios between the `make_list` filter and the `split` filter when splitting strings into arrays?

In AnQi CMS template development, it is often encountered that a string needs to be split into multiple parts for further processing or dynamic display.To meet this requirement, AnQiCMS template engine provides two very useful filters, `make_list` and `split`.Although they can both convert strings to arrays, there are obvious differences in their core functions, splitting logic, and applicable scenarios in actual use.Understanding these differences can help us handle content more efficiently and accurately.

2025-11-07

What are the different splitting behaviors when the delimiter is empty or not present?

In AnQi CMS template development, the `split` filter is a very practical tool that can help us split strings into arrays according to the specified delimiter, which is very convenient when dealing with list data, tag content, or any structured text.However, when the delimiter is an empty string or does not exist in the target string, the behavior of the `split` filter shows some clever characteristics, understanding these characteristics is crucial for precise template control and avoiding potential errors.

2025-11-07

What is the essential difference between the `truncatechars` and `truncatewords` filters, and how should one choose?

In AnQi CMS template development, in order to better display content summaries or control page layouts, we often need to truncate text.At this moment, the `truncatechars` and `truncatewords` filters come into play.They can all help us shorten long texts and add an ellipsis at the end, but there is an essential difference in their truncation logic. Understanding these differences is crucial for choosing and using them correctly.

2025-11-07

How to safely truncate text to a specified length for articles containing HTML tags using `truncatechars_html`?

When using AnQiCMS to manage website content, we often encounter such a scenario: to make the article content more beautiful in layout, various HTML tags are used to enrich the visual effects, such as paragraphs (`<p>`), images (`<img>`), links (`<a>`), bold (`<strong>`), and so on.However, on the article list page or in the related recommendation module, we often need to display the abstracts or parts of these articles, but we cannot directly display the entire long discourse. At this time

2025-11-07

Can the `truncatewords_html` filter correctly handle nested HTML tags while truncating, preventing page layout chaos?

In website operations, we often need to summarize long content to attract users to click and view the details.However, directly truncating rich text content containing HTML tags often leads to page structure chaos, for example, a `<p><b>important information</p>` truncated to `<p><b>important` such a missing tag, not only ruins the visual beauty of the page, but may also lead to the entire page layout disorder.This is undoubtedly one of the most headache issues for content operators. AnQi CMS understands this pain point.

2025-11-07

How to ensure that all unclosed HTML tags are properly closed after truncating `truncatechars_html`?

In website content operation, we often need to extract a part of the long text such as articles and product descriptions as a summary, used for list display or card preview.This can not only effectively save page space, but also attract users' attention and guide them to click to view the full content.However, when these long texts contain HTML tags, simple character truncation often leads to unclosed tags, thereby destroying the page layout and affecting the user experience.AnQiCMS (AnQiCMS) understands this pain point and has built the `truncatechars_html` filter into the template engine

2025-11-07