How to truncate the first N characters of an AnQiCMS article title and add an ellipsis at the end?

Calendar 👁️ 63

In website operation, we often encounter such needs: In order to make the page layout beautiful, present information concisely, or improve search engine friendliness, it is necessary to truncate article titles and add an ellipsis at the end when the title is too long.AnQiCMS (AnQiCMS) flexible template system and rich built-in filters make this operation very simple and efficient.

AnQi CMS adopts a template engine syntax similar to Django, one of its core advantages lies in the powerful "tags (tags)" and "filters (filters)" mechanism.Tags are used to retrieve data from the database or implement logic control, while filters allow us to perform secondary processing on these data, such as formatting dates, truncating strings, etc.Understand and make good use of these tools and you can easily meet various content display needs.For title truncation in this scenario, Anqi CMS provides a very convenient filter that allows us to accurately control the display length of the title.

Core function implementation:truncatecharsFilter

To implement the truncation of article titles and add an ellipsis, we mainly use the built-in Anqi CMS template.truncatecharsA filter that truncates strings to a specified character length and automatically adds an ellipsis at the end of the truncated string if the original string exceeds this length....)

truncatecharsThe basic usage format of the filter is:{{ 变量名|truncatechars:N }}. Here,变量名It is the title of the article you get from the AnQi CMS backend, andNwhich represents the number of characters you want to截取 from the title.NIt should be noted that,NThe value will include automatically added ellipses.

How to apply: actual operation steps

In Anqi CMS templates, whether it is the article list page, home recommendation position, or other places that need to display article titles, as long as you can get the article title variable, you can apply ittruncatecharsfilter.

Apply title truncation on the article list page

On the article list page, we usually usearchiveListTags to cyclically display article data. Within the loop, the title of each article is usually accessed through{{ item.Title }}Get it. Suppose we want to truncate the article title to the first 30 characters and add an ellipsis at the end, we can write the template code like this:

{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
    <li>
        <a href="{{item.Link}}">
            {# 截取文章标题的前30个字符,并添加省略号 #}
            <h5>{{item.Title|truncatechars:30}}</h5>
            <div>{{item.Description|truncatechars:80}}</div> {# 描述同样可以截取 #}
            <div>
                <span>{% categoryDetail with name="Title" id=item.CategoryId %}</span>
                <span>{{stampToDate(item.CreatedTime, "2006-01-02")}}</span>
                <span>{{item.Views}} 阅读</span>
            </div>
        </a>
    </li>
    {% empty %}
    <li>
        当前列表没有任何内容。
    </li>
    {% endfor %}
{% endarchiveList %}

In this code block,{{item.Title|truncatechars:30}}This line completes the title truncation work. Ifitem.TitleThe actual length exceeds 30 characters, for example,

Apply title truncation in other scenarios

In any corner of the website, as long as you pass through, except for the article listarchiveDetailtags,categoryDetailLabels or other ways to obtain the title of the article (or any other string that needs to be truncated), can be used flexiblytruncatecharsFilter. For example, if you need to display a short title summary on the article detail page, you can use it as well:

{# 获取当前文章的完整标题 #}
{% archiveDetail currentArchiveTitle with name="Title" %}
{# 显示截取后的标题摘要 #}
<p>摘要:{{ currentArchiveTitle|truncatechars:20 }}</p>

It should be noted that on the article detail page, the full title is usually displayed, but if you have specific design requirements, such as displaying the title of 'related articles' in the sidebar, the operation of truncation is very useful.

Advanced consideration: Handling content with HTML tags

In some cases, the title (or summary) of the article may contain HTML tags. If used directlytruncatecharsPerforming a cut may destroy the HTML structure, causing the page to display abnormally. Anqi CMS also provides a special filter for this:

  • truncatechars_html:N: For strings containing HTML tags,截取 according to character count, while preserving the integrity of the HTML tags to prevent structural damage.
  • truncatewords_html:N: Similarly applicable to strings containing HTML tags, but it is truncated by word count, suitable for English content.

Although the topic is about title truncation, the title is usually plain text, but understanding these filters for HTML content can provide more convenience and safer guarantees when processing rich text fields such as article descriptions.

Summary

The template filter of Anqi CMS provides great convenience for website operators. Through simpletruncatecharsFilter, we can easily implement the fixed-length truncation of article titles and automatically add ellipses, which not only helps to maintain the neat layout of the page but also makes the presentation of content more in line with user reading habits.Flexibly utilizing these powerful built-in functions will elevate the content management and display of your website to a new level.

Frequently Asked Questions (FAQ)

  1. Question:truncatecharsCan the ellipsis generated by the filter be customized in style or content?Answer:truncatecharsThe ellipsis within the filter is fixed to the English "…" symbol and cannot be customized directly via parameters. If your design requires a different ellipsis style or text, you may need to first obtain the full title, then use conditional judgment and string concatenation in the process (for example, usingsliceThe filter extracts a part and then manually concatenates a custom ellipsis to achieve more complex custom effects.

  2. Question: When truncating Chinese string,truncatecharsIs it calculated by bytes or by the actual number of characters (Chinese characters)?Answer: In the Anqi CMS template,truncatecharsThe filter calculates the actual number of Chinese characters when cutting a Chinese string. For example,{{ "你好世界"|truncatechars:2 }}It will display as "Hello…", rather than being truncated by bytes, which can cause garbled characters. This ensures the accuracy and display effect of truncating mixed Chinese and English content.

  3. Ask: If my article title contains some HTML tags,truncatecharswill it break these tags?Answer:truncatecharsThe filter is designed for extracting plain text, if the title variable accidentally contains HTML tags, using it directly may cause the tags to be truncated, thereby breaking the HTML structure. To safely extract strings containing HTML tags, it is recommended to usetruncatechars_html:NFilter. It will intelligently close HTML tags while extracting, ensuring that the page structure is not affected.

Related articles

In AnQiCMS, what is the difference in usage scenarios between the `safe` filter and the `autoescape off` tag?

In AnQiCMS template development, we often encounter the need to display content containing HTML tags.For the security of the website, the AnQiCMS template engine defaults to automatically escaping all output variables.This means that if you directly output a text containing HTML tags such as `<strong>` or `<em>`, these tags will not be parsed as styles by the browser, but will be displayed as raw text.

2025-11-08

Why does my AnQiCMS template still escape HTML code even though I used `safe`?

When using AnQiCMS for website content creation and template customization

2025-11-08

What potential security risks should be considered when outputting HTML using the `safe` filter?

In AnQiCMS template development, the `safe` filter is a very useful tool that allows us to directly output some content containing HTML tags to the page, rather than escaping the HTML tags as well.This is crucial for displaying details of articles generated by rich text editors, custom HTML modules, and other scenarios, as it ensures the correct rendering of the style and structure of the content.However, like all powerful tools, the use of the `safe` filter also comes with some potential security risks that should not be overlooked.

2025-11-08

How to safely display HTML content generated by the rich text editor in AnQiCMS templates?

In website operation, we often need to handle content from rich text editors, which usually contains richly formatted HTML code.However, when displaying these HTML contents on a website template, security is the primary consideration.If not properly handled, malicious code (such as XSS attacks) may be injected, thereby damaging the website and users.The AnQi CMS is a highly efficient, customizable, and secure enterprise-level content management system that has fully considered content security issues from the outset.

2025-11-08

How to safely extract from an article summary containing HTML tags without damaging the HTML structure?

In website operation, the abstract of the article plays a vital role.It is not only the first window to attract visitors to click, but also an important basis for search engines to understand page content, index, and rank.A good abstract can quickly convey the core information of the article, enhance user experience, and help with SEO performance.However, when the content of the article itself contains rich HTML tags (such as images, links, bold, paragraphs, etc.), how to safely extract a summary from these contents while avoiding destroying the HTML structure has become a common challenge.

2025-11-08

How to convert all English characters to uppercase or lowercase in the AnQiCMS template?

In the display and management of website content, maintaining uniformity in text formatting is a key factor in improving user experience and maintaining brand image.Especially the capitalization of English characters, sometimes it is necessary to unify it according to design or business needs.AnQiCMS as an efficient and flexible content management system fully considers these needs, and provides us with a quick and easy method for English character case conversion through its powerful template function.

2025-11-08

How to remove the specified characters or extra spaces from the AnQiCMS string?

In website content operations, we often encounter situations where we need to process strings, such as cleaning up user input data, standardizing display content, or removing unnecessary characters and extra spaces from text.These seemingly minor operations can significantly improve the neatness and professionalism of website content.As an AnQiCMS user, you will find that the system provides powerful and flexible template filter functions that can easily meet these string processing needs.

2025-11-08

How to replace the old keyword with a new keyword in the AnQiCMS template?

When operating website content on AnQiCMS, we often encounter situations where we need to make minor adjustments to the website text content.Sometimes it's a change in brand words, sometimes it's the correction of typos, or adjusting the copy temporarily to cater to specific marketing activities.When these modifications need to be reflected at specific locations on the website front-end template rather than the global database, AnQiCMS provides a flexible and efficient solution.### Understand the need for keyword replacement within templates The AnQiCMS backend usually provides the "site-wide content replacement" function, which is powerful and convenient

2025-11-08