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

Calendar 👁️ 74

In content management, in order to maintain the neatness and loading efficiency of the website pages, we often need to truncate articles, product descriptions, or other long text content to display only part of the summary.However, if the content itself contains HTML tags, simple character truncation often breaks the structure of these tags, leading to chaotic page display and even affecting the layout and functionality of the website.<p>这是一个<b>重要</b>的段落</p>If the content is simply truncated to<p>这是一个<b>重要</b, this will leave an unclosed tag, thereby disrupting the structure of all subsequent HTML.

AnQiCMS is well aware of this pain point and provides a dedicated solution for content processing to ensure that it can intelligently recognize and close tags when truncating HTML text, thereby elegantly presenting the content summary while maintaining the integrity of the page structure.

Understand the challenge of HTML truncation

The traditional text truncation method is usually performed by character or word. When encountering<p>Lorem <b>ipsum</b> dolor</p>such an HTML segment, if the truncation point falls on<p>Loor<b>ipswill result in<b>or<p>Tags are not closed. This not only makes the page look unprofessional, but may also cause various front-end rendering issues, such as style chaos, loss of content, and even affect SEO optimization.Therefore, for the content generated by rich text editors, we cannot simply perform string splitting.

AnQiCMS's intelligent solution: HTML truncation filter

AnQiCMS template engine built-in powerful filters, wheretruncatechars_htmlandtruncatewords_htmlIt is specially designed to handle HTML content.They are not just simply cutting strings, but also intelligently parsing HTML structures, ensuring that all open HTML tags are properly closed while truncating text, thereby avoiding structural damage.

  • truncatechars_html: This filter allows you to specify a character count, AnQiCMS will try to truncate the content within this character limit and ensure that the truncated HTML tags are closed.
  • truncatewords_html: Similarly, this filter allows you to specify a word count.AnQiCMS will truncate the content within the word count limit and ensure the integrity of the HTML structure.

These filters are the ideal choice for processing rich text content summaries, allowing content operators to worry about manually adjusting HTML tags, just focusing on the length control.

How to elegantly apply these filters in the template

While usingtruncatechars_htmlortruncatewords_htmlWhen filtering, it is important to apply it to variables containing HTML content, and since these filters output processed HTML fragments, it is usually also necessary to|safeThe filter is used to prevent the template engine from escaping HTML content again, causing tags to be displayed as plain text.

Assuming you are displaying article summaries on an article list page, and the summary content (such asarchive.Descriptionorarchive.Content) may contain HTML tags.

Example 1: Truncate HTML content by character count

If you want to truncate the article content to a maximum of 150 characters (including HTML tags, but the actual visible characters will be fewer), and ensure that the HTML structure is complete:

{# 假设 articleContent 变量中包含了文章的富文本内容 #}
{% archiveDetail articleContent with name="Content" %}
<div class="article-summary">
    {{ articleContent|truncatechars_html:150|safe }}
    <a href="{{ archive.Link }}">阅读更多</a>
</div>

In this example,articleContentwill be truncated, and if the truncation point is within<div>or<strong>the tag, AnQiCMS will automatically add a closing tag todiv.article-summaryensure that the internal HTML is valid.

Example two: Truncate HTML content by word count

If your content is better suited for word truncation, for example, if you want to display the first 30 words:

{# 假设 productDescription 变量中包含了产品的详细描述,可能带有 HTML #}
{% pageDetail productDescription with name="Description" %}
<div class="product-teaser">
    {{ productDescription|truncatewords_html:30|safe }}
    <a href="{{ page.Link }}">查看详情</a>
</div>

productDescriptionAfter being truncated, it will still ensure the correct closure of HTML tags.

Key reminder:|safeUse of filters

|safeThe filter is crucial. The AnQiCMS template engine defaults to prevent cross-site scripting attacks (XSS) by escaping all variable content output to the page.This means if your content is<p>Hello</p>, without adding|safeMay be displayed as&lt;p&gt;Hello&lt;/p&gt;. When usingtruncatechars_htmlAfter the filter is processed, we hope to get a parseable HTML, therefore|safeClearly tell the system: "This content is safe HTML, please output directly without escaping."

Summary

provided by AnQiCMStruncatechars_htmlandtruncatewords_htmlFilter, is a powerful assistant for content operators when processing rich text content summaries.They completely solve the problem of structural damage that may occur when truncating HTML text by intelligent recognition and closing HTML tags, greatly enhancing the stability and user experience of content display.|safeUsing it, you can easily achieve a content summary display that is both beautiful and robust.


Frequently Asked Questions (FAQ)

1. If you use a filter at the end of content that includes HTML tagstruncatecharsortruncatewordsFilter, rather than_htmlWhat will happen?

If you incorrectly use a filter on content that contains HTML tagstruncatecharsortruncatewordsSuch a plain text truncation filter, the system will treat it as a normal string for truncation and will not parse or process HTML tags.This is likely to cause the tag to be cut off in the middle, leaving an unclosed tag.<b>重要</b>May be truncated to<b>重.This way, the page structure will be destroyed, causing subsequent HTML elements to display abnormally, style chaos, and even possibly affect the page function._htmlA filter at the end.

2. Why do you need to addtruncatechars_htmlortruncatewords_htmlPlus after the filter,|safeFilter?

The AnQiCMS template engine, for security reasons, defaults to automatically escaping all content from variables output to the page, which will<to&lt;etc. althoughtruncatechars_htmlandtruncatewords_htmlThe filter can generate a structurally complete HTML fragment, but if it is not added|safeThe filter, these generated HTML tags (such as<p>/<div>The character )is escaped, causing it to be displayed on the page as is&lt;p&gt;Instead of being a real paragraph.|safeThe filter explicitly tells the template engine: This content is processed and safe HTML, please output it as is without escaping, to ensure that the truncated HTML can be rendered correctly on the page.

Can I customize the ellipsis (…) displayed after truncation?

Currently, AnQiCMS built-in thetruncatechars_htmlandtruncatewords_htmlThe filter uses the standard ellipsis “…” to indicate that content has been truncated.In the parameters of the filter itself, there is no direct option to modify or customize this ellipsis character.This is to maintain the consistency and conciseness of display, usually in web design, the ellipsis has already become a widely accepted symbol to represent content truncation.

Related articles

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

In AnQiCMS template design, we often encounter scenarios where it is necessary to display long text content, such as the abstract on the article list page, and the brief introduction of product details.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 long text content contains HTML tags, simple character truncation may cause problems.For example, a content like this `\u003cp\u003eThis is an important\u003cb\u003e text\u003c/b\u003e\u003c/p\u003e`

2025-11-08

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 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

How to prevent AnQiCMS template from automatically escaping HTML tags and output the original content directly?

When using AnQiCMS to build a website and design a template, you may encounter a common problem: when outputting some content in the template, the tags that were originally expected to be displayed as HTML are automatically converted to plain text, for example, `<p>This is a paragraph</p>` becomes `&lt;p&gt;This is a paragraph&lt;/p&gt;`.This loses the original style and structure of the content.Understanding this problem and knowing how to handle it is very important for template developers.Why does the AnQiCMS template automatically escape HTML tags?

2025-11-08