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

Calendar 👁️ 73

When using AnQiCMS to manage website content, we often encounter the following scenarios: In order to make the article content more aesthetically pleasing, various HTML tags are used to enrich the visual effects, such as paragraphs (<p>), and images (<img>), link (<a>)bold(<strong>However, on the article list page or in the related recommendation module, we often need to display the abstract or part of the content of these articles, but we cannot directly display the whole long article.

At this time, a common practice is to cut off the fixed length text at the beginning of the article.If directly simply to string truncation containing HTML tags, such as truncating the first 100 characters, the result is often not satisfactory.Because this rough cutting method may truncate HTML tags, causing rendering errors on the page, resulting in unclosed tags, chaotic styles, and even destroying the entire page layout.This not only affects the user experience, but may also cause compatibility issues with browsers.

To handle the need for elegantly and safely extracting article content with HTML tags, Anqi CMS provides a very practical template filter——truncatechars_html.

Why choosetruncatechars_html?

truncatechars_htmlThe core value of the filter lies in its ability to intelligently process HTML structures. It does not simply count characters like ordinary string truncation, but instead willparse HTML tagsIt will truncate the visible text to a specified length (excluding the characters of the HTML tags themselves) andautomatically close all unclosed HTML tagsThus ensuring that the output HTML code remains complete and valid.This means that you do not have to worry that truncated HTML content will destroy the layout or style of the page, it will try to maintain the semantic and visual integrity of the content.

How to use it in Anqi CMS templatetruncatechars_html?

In the AnQi CMS template system, usetruncatechars_htmlVery intuitive. You just need to apply it as a filter to the content variable you want to extract and specify the desired character length.

Its basic syntax is:{{ 变量名|truncatechars_html:长度|safe }}.

For example, on the article list page, you may need to display the abstract of each article. Suppose your article content is stored inarchive.Contenta variable, and you want to extract the first 120 visible characters as the abstract:

{# 假设我们正在遍历一个文章列表 archives #}
{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
    <div class="article-item">
        <h2><a href="{{ item.Link }}">{{ item.Title }}</a></h2>
        <div class="article-summary">
            {# 安全地截取文章内容的前120个可见字符,并保持HTML结构完整 #}
            {{ item.Content|truncatechars_html:120|safe }}
        </div>
        <a href="{{ item.Link }}" class="read-more">阅读更多</a>
    </div>
    {% endfor %}
{% endarchiveList %}

Here, item.ContentIs the detailed content of the article, which may contain such as<p>这是文章的<strong>第一段</strong>内容。</p><img src="/image.jpg" alt="图片描述">this HTML.

  1. truncatechars_html:120Will tell the system to截取前120个visible characters(HTML tags themselves are not counted in length), and intelligently close any tags that are opened at the cut-off point.
  2. |safeThe filter isindispensablebecause of.truncatechars_htmlThe output is actually processed HTML code. The Anqi CMS template engine, for safety, defaults to escaping all output content (such as replacing<Convert&lt;)。如果不加|safeThe HTML tags after truncation will be displayed as plain text, rather than being parsed by the browser, thereby losing the original style.

truncatechars_htmlexample of the working principle

Assuming you have the following HTML content:

<p>这是一段很长的文本,其中包含<strong>加粗</strong>和<a href="#">链接</a>,我们希望截取它的部分内容,同时保持格式。</p>
<p>第二段内容,可能也会被截取到。</p>

If you use{{ original_html_content|truncatechars_html:50|safe }}to cuttruncatechars_htmlit will calculate the visible characters, and then it may output something like this:

<p>这是一段很长的文本,其中包含<strong>加粗</strong>和<a href="#">链接</a>,我们希望截取它的部分内容,同时保持格式...</p>

It can be seen that although it is truncated after the link, but<a>and<strong>/<p>the tags are closed correctly, and an ellipsis is added at the end, (...It ensures the validity of HTML and the neatness of the page.

Application scenarios in practice

  • List of articles/New summary:In the list of articles on blogs and news websites, display a brief summary of each article to guide users to click and read the full text.
  • Product list/Introduction:On e-commerce product list pages, display the beginning part of the product detailed description while maintaining the style and link availability.
  • Search results page:Search engine internal search results, providing a preview of relevant content fragments.
  • Related recommendation module:At the bottom or sidebar of the article, other related articles are recommended, and their summaries are displayed.

By flexible applicationtruncatechars_htmlA filter that can greatly enhance the display effect and user experience of the Anqi CMS website, ensuring that even abstract content is presented in a professional and beautiful manner.


Frequently Asked Questions (FAQ)

1.truncatechars_htmlandtruncatecharsWhat is the difference? truncatecharsIs used for extracting plain text content, it simply truncates by character count without considering HTML tags.If used for content containing HTML, it is easy to truncate tags, causing the page to display incorrectly andtruncatechars_htmlIt will intelligently recognize HTML tags, ensuring that all opened tags are properly closed while extracting visible characters, thus outputting a valid HTML snippet.

2. Why do you need to addtruncatechars_htmlafter|safeFilter?The template engine of AnQi CMS defaults to escaping all output content for security reasons to prevent cross-site scripting attacks (XSS).truncatechars_htmlAlthough it will output a valid HTML fragment, but if it is not added|safefilter, the template engine will escape it again, for example, by converting<p>displayed as&lt;p&gt;.|safeIt explicitly tells the template engine: This content is safe, please parse and display it directly as HTML.

3. If my content is plain text, I can usetruncatechars_html?Can.truncatechars_htmlIt is also effective for plain text content, it treats it as HTML without tags and truncates it to the specified length. However, for plain text, it is more recommended to usetruncatecharsThe filter, as it is lighter and does not require HTML parsing, is more efficient. It is usually only needed when the content may contain HTML tags.truncatechars_html.

Related articles

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 truncate the title of the article and automatically add an ellipsis in the AnQiCMS template?

In AnQi CMS template design, in order to ensure the beauty of the page and the uniformity of the 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.

2025-11-07

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

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

How to batch remove all specific interfering characters or HTML entities from AnQiCMS article content?

It is crucial to maintain the purity and readability of content in website content operation.Whether it is content imported from outside, text processed by collection tools, or redundant characters inadvertently introduced during daily editing, these interfering factors may affect user experience and search engine optimization effects.AnQiCMS provides an efficient and powerful built-in tool to help you batch clean up various interfering characters or HTML entities from the article content, ensuring that your website content always maintains a high-quality state.### The necessity of understanding content cleaning As the accumulation of website content continues

2025-11-07

The `cut` filter removes characters from a string, does it remove all matches or just the first match?

In AnQi CMS template creation, we often need to process strings, such as removing specific characters or spaces.At this point, the `cut` filter comes into play. This practical feature helps us finely adjust the content displayed on the page to ensure that the final effect meets expectations. The most common question about the `cut` filter is: When used to remove characters from a string, is it only removing the first match, or all matches?By going through the documentation and actual testing of Anqi CMS, we can clearly tell everyone

2025-11-07