How to safely truncate a long text containing HTML tags in AnQiCMS template?

Calendar 81

In AnQiCMS template design, we often encounter scenarios where we need to display long text content, such as abstracts on article list pages, brief introductions of product details, and so on.If this long text content is displayed directly, it may cause the page to be long, affecting user experience and layout aesthetics.Therefore, truncating long text is a common requirement.

However, when this long text content contains HTML tags, simple character truncation may cause problems. For example, a<p>这是一段<b>重要的</b>文本</p>such content, if truncated at<b>If the label is in the middle, it may cause the HTML structure to be destroyed, resulting in abnormal display of the page.At this point, we need a safe way to truncate long text that contains HTML tags.

AnQiCMS provides a powerful and flexible template engine, its syntax is similar to Django templates.In this engine, we can take advantage of built-in filters (filters) to elegantly solve this problem.Among them, there is a truncation filter specifically designed to handle text containing HTML, which can intelligently truncate the content while maintaining the integrity of the HTML tags to avoid chaos in the page structure.

Understand HTML safe truncation filter

In the AnQiCMS template, there are two core truncation filters that can help us safely handle long text:truncatechars_htmlandtruncatewords_htmlThey are ordinarytruncatecharsandtruncatewordsThe main difference is that they are "HTML sensitive", trying to recognize and close incomplete HTML tags to avoid rendering errors caused by truncation.

  • truncatechars_html:长度This filter will truncate text according to the specified character count.It calculates the visible characters (excluding the characters of the HTML tags themselves) and tries to ensure that all open HTML tags are properly closed when truncating.If content is truncated, it is usually followed by “…”.
  • truncatewords_html:单词数This filter then truncates the text according to the specified word count.Similar to character truncation, it also pays attention to the integrity of the HTML structure and performs necessary tag closures when truncating.

Why can't it be used directly?truncatecharsTruncate HTML content?

OrdinarytruncatecharsThe filter simply calculates characters from the beginning and stops once it reaches the specified length.It does not distinguish between visible text and HTML tags, nor does it attempt to close incomplete tags after truncation.truncatecharsTruncate<b>重要的</b>, it may result in a<b>重要This result causes all subsequent text on the page to become bold, or other unexpected style issues. And_htmlThe suffix filter will avoid this situation.

Apply HTML safe truncation in AnQiCMS template

We take common article content as an example,archiveDetailThe tag is used to obtain document details, among which,ContentThe field usually contains text with HTML formatting.

Assuming we need to display a short preview of the article content on a list page or in an abstract area, limited to 100 characters. The steps are as follows:

  1. Get the document content:First, you need to usearchiveDetailtags to get the article'sContentfield. For the convenience of subsequent operations, we can assign it to a variable, such asarticleContent.

    {% archiveDetail articleContent with name="Content" %}
    

    orarchiveListuse it directly in the loopitem.Content.

    {% for item in archives %}
        {# 这里可以直接访问 item.Content #}
    {% endfor %}
    
  2. Apply the truncation filter and ensure safe output:In the AnQiCMS template, any content containing HTML should be used when outputting:|safeA filter to prevent the template engine from escaping HTML tags to plain text.This is particularly important for truncating HTML content because we want the browser to parse these tags normally.

    toarticleContentTruncate to 100 characters and safely output:

    {{ articleContent|truncatechars_html:100|safe }}
    

    If you prefer to truncate by word count, for example, truncate to 30 words:

    {{ articleContent|truncatewords_html:30|safe }}
    

Complete example scenario: Display HTML formatted summary on the article list page

Assume the loop name of your article list isarchivesYou want each article to display a summary of up to 150 characters and retain the basic format such as bold and links:

`twig {% 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-meta">
        <span>发布日期: {{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
        <span>浏览量: {{ item.Views }}</span>
    </div>
    <div class="article-summary">
        {# 安全地截断HTML内容,并使用|safe避免转义 #}
        {{ item.Content|truncatechars_html:150|safe }}
        <a href="{{ item.Link

Related articles

Only delete the specified HTML tags in AnQiCMS article content, which filter should be used?

When using AnQiCMS for content operations, we often encounter situations where we need to refine the processing of HTML tags in article content.For example, during the import or copy and paste process, some unnecessary, format-inconsistent tags may be brought in, which may affect the page layout, SEO performance, and even introduce security risks.In order to meet the requirement of "only deleting the specified HTML tags from the content of AnQiCMS articles", we need to use the specific filter provided by the template engine.In AnQiCMS template system

2025-11-08

How to completely remove all tags from HTML content in the AnQiCMS template?

In website content operation, we often encounter such needs: to extract plain text from richly formatted content, such as displaying abstracts on article list pages, or providing clean text for SEO meta description tags.AnQiCMS provides a powerful and flexible template engine, allowing us to easily remove tags from HTML content with built-in filters.

2025-11-08

How to batch replace keywords or links in the entire site's content and display them immediately?

In website operation, we often encounter situations where we need to adjust a large amount of content, whether it is to adapt to new brand strategies, unify website terminology, fix broken links, or better optimize SEO, these all require batch updating of keywords or links throughout the entire site.Manually modifying one by one not only takes time and effort, but is also prone to errors.The AnqiCMS provides a very practical feature that allows you to easily deal with such challenges: batch replacement of keywords or links in the entire site content, and ensure that changes take effect immediately.This ability is crucial for the daily operation and maintenance of the website

2025-11-08

How to use the pseudo-static function of AnQi CMS to optimize URL display and improve SEO effect?

In website operation, the URL (Uniform Resource Locator) plays a vital role.A clear, meaningful, and easy-to-understand URL not only improves user experience but is also an indispensable part of search engine optimization (SEO).The traditional dynamic URL often contains parameters and numbers that are difficult to understand, while the pseudo-static URL, through rewriting technology, makes it look as simple and standardized as a static HTML page, thus gaining the favor of search engines and users.AnQiCMS (AnQiCMS) knows the impact of URL structure on website SEO

2025-11-08

How to avoid AnQiCMS from destroying the tag structure when truncating HTML text?

In content management, in order to maintain the neatness and loading efficiency of the website page, we often need to truncate articles, product descriptions, or other long text content, and only display part of the abstract.However, if the content itself contains HTML tags, simple character truncation often breaks the structure of these tags, causing the page display to become chaotic and even affecting the layout and functionality of the website.For example, the content of a `<p>This is an <b>important</b> paragraph</p>`, if it is simply truncated to `<p>This is an <b>important</b`

2025-11-08

How does AnQiCMS render Markdown formatted article content to HTML?

AnQiCMS boasts its efficient content management capabilities, is favored by users, especially in handling text content, providing flexible and diverse options.For users accustomed to using Markdown format, AnQiCMS also provides comprehensive support, able to seamlessly render Markdown formatted article content into user-friendly HTML pages.To understand how AnQiCMS achieves this transformation, we can explore from three aspects: content creation, system configuration, and template rendering.

2025-11-08

Can I control whether Markdown content in AnQiCMS templates is automatically converted to HTML?

In website content management, we often need to balance the writing efficiency of content and the final presentation effect.Markdown with its concise syntax greatly enhances the speed of content creation.But the question that follows is: do we always want the content to be automatically converted to HTML when it enters the template?Or in some specific scenarios, we want to maintain the original Markdown format, or manually control the conversion process?

2025-11-08

How to call and safely display the `Content` field that contains HTML on the AnQiCMS document detail page?

On a website built with AnQiCMS, the core of the document detail page is often the main content of the article, namely the `Content` field.This field carries a wealth of information, ranging from simple text to complex text and image layouts, multimedia embedding, and even custom code segments.Therefore, how to correctly and safely display these contents containing HTML format in the template is a key skill that every AnQiCMS user needs to master.AnQiCMS when designing template rendering, fully considers the security of the content.

2025-11-08