How to safely truncate the article content using the `truncatechars_html` filter without destroying the HTML structure for website SEO?

Calendar 👁️ 66

In website operation, we often need to display the concise content of articles in article lists, search result summaries, or social media shares.This concise content should not only attract the attention of users, but also ensure that the complex HTML structure behind it is not destroyed, in order to avoid affecting the page layout and user experience.For search engine optimization (SEO), a clean and effective code structure is crucial.

AnQiCMS (AnQiCMS) is an enterprise-level content management system developed based on the Go language, deeply understanding the pain points and needs of website operations.It not only provides multi-site management, flexible content model, multilingual support, as well as powerful SEO tools such as pseudo-static and 301 redirect, but also pays great attention to the details of content display. Among them,truncatechars_htmlThe filter is designed as a practical feature to solve the integrity issue of HTML structure during content truncation.

Content truncation and HTML structure: The hidden challenge of SEO operation.

Imagine if your article content is rich in images, links, bold text, and even complex layout tags, and you simply truncate it as plain text by character count. The result is likely to be truncated HTML tags causing page chaos, for example, a<div>The label was truncated without a corresponding</div>Closing this may affect the display of subsequent content. This may not only provide a bad experience for visitors but may also pose obstacles for search engine crawlers in crawling and understanding the page, which may affect the ranking performance of your website in search results.

On the search engine results page (SERP), if the website summary (meta description) is not displayed in full or displays garbled text due to damaged HTML tags, it will undoubtedly greatly reduce the willingness of users to click.Similarly, if the summaries of each article on the article list page are disordered due to HTML structure damage, it may also discourage users.Therefore, how to safely and elegantly extract content containing HTML is a common pursuit of website SEO and user experience.

AnQiCMS's elegant solution:truncatechars_htmlFilter

To perfectly solve this challenge, AnQiCMS introduced in its powerful template engine,truncatechars_htmlFilter. This filter is designed to handle strings containing HTML tags, it can intelligently identify and close truncated tags, ensuring that the output HTML structure is always complete and valid.This means, even if your article content is cut off halfway<div>or<strong>tag, truncatechars_htmlIt will automatically close it correctly, thus avoiding page chaos.

This filter is especially suitable for the following scenarios:

  • Summary display on the article list pageLet each article preview remain beautiful within a fixed length.
  • Meta description on the search results pageEnsure that the summary information displayed in search engines is clear and无损.
  • Social media sharing copywritingPresent a high-quality, structured article snippet within a limited number of characters.

How to use in AnQiCMS templatetruncatechars_html

In AnQiCMS, you can use syntax similar to the Django template engine to manipulate content.truncatechars_htmlUsing filters with variables is very simple.

Assuming you have an article objectitemItsContentThe field contains a complete article with HTML formatting. If you want to extract the first 120 characters as a summary on the article list page and ensure the HTML structure is safe, you can use it like this:

<div class="article-summary">
    {{ item.Content|truncatechars_html:120|safe }}
</div>

Here120Is the number of target characters you want to extract (including ellipsis).|safeThe filter is a crucial step, it tells the template engine that you are sure.truncatechars_htmlThe output of the filter is safe HTML that can be rendered directly by the browser without escaping. If missing|safeThe browser may display the captured HTML code as plain text, rather than rendering it as actual page elements.

In addition to truncating by character, AnQiCMS also providestruncatewords_htmlA filter with similar functionality, but it truncates based on word count while also safely preserving HTML structure.In some languages or content styles, it may be more natural to cut words.

Why is this crucial for website SEO?

In SEO optimization, details determine success or failure. A filter that can safely capture HTML content, which seems to be just a technical detail, actually has a profound impact:

  1. Enhancing user experience: A clean page layout and a clear summary can effectively attract users and reduce the bounce rate.
  2. Optimize search results displayAvoid unnecessary HTML tags or truncation errors in search summaries to improve click-through rates.
  3. Ensure accessibility of the page.: A damaged HTML structure may cause the page to display abnormally on different browsers or devices, affecting user access.
  4. Maintain code health.: Continuously output valid HTML helps search engines efficiently crawl and understand your website content, improving inclusion efficiency.

AnQiCMS is committed to providing a simple and efficient system architecture to help enterprises carry out content marketing, SEO optimization and other activities. Throughtruncatechars_htmlSuch detailed features, Anqi CMS not only simplifies the complexity of content operations, but also provides a strong guarantee for your website's SEO performance in an invisible way.

Frequently Asked Questions (FAQ)

1.truncatecharsandtruncatechars_htmlWhat is the difference?

truncatecharsThe filter is used to interceptPlain textA string that does not consider whether the string contains HTML tags, may directly truncate the tags, causing the HTML structure to be destroyed. Andtruncatechars_htmlFilter is specifically used for extractingContaining HTML tagsThe string will intelligently parse HTML, ensuring that even if the content is truncated, all opened HTML tags will be correctly closed, thus ensuring the integrity and validity of the output HTML structure.

2. My article content is in Markdown format, usingtruncatechars_htmlwill there be any problems?

There will be no problem. In AnQiCMS, when you enable the Markdown editor and save the content, the system will usually convert Markdown to HTML first.Therefore, when you call the article content in the template and usetruncatechars_htmlWhen a filter is applied, it is actually processing content that has already been converted to HTML. For example, when calling the document content fieldContentWhen enabled, if Markdown rendering is turned on, it will first render as HTML, thentruncatechars_htmland then safely truncate this HTML.

3. Usetruncatechars_htmlWhy do we need to add it afterwards|safeFilter?

The AnQiCMS template engine defaults to HTML-escaping all output variable content, which is a security mechanism to prevent cross-site scripting attacks (XSS).truncatechars_htmlThe filter will generate a string with HTML tags, if you do not add|safeThe filter will also escape these HTML tags as plain text (for example<p>Will become&lt;p&gt;), causing them not to be rendered correctly by the browser. Add|safeThe filter explicitly tells the template engine that you trusttruncatechars_htmlThe generated HTML content is safe and can be directly displayed as HTML.

Related articles

Array concatenation into a string: Application scenarios of the `join` filter in AnQiCMS templates?

In website content management, we often encounter the need to display a set of data, such as multiple tags, multiple image URLs, or custom multiple-choice content, in a unified string format.AnQiCMS (AnQiCMS) boasts its efficient architecture based on the Go language and a flexible template engine similar to Django, providing great convenience for content display.Today, let's delve deeper into a very practical tool for handling such needs - the `join` filter.What is the `join` filter? In the AnQi CMS template world

2025-11-08

What is the difference between the `make_list` filter and the `split` filter? When should `make_list` be used to split strings?

In AnQi CMS template development, we often need to process string data, such as splitting a long string into multiple independent parts for traversal, display, or further logical judgment.Anqi CMS provides a variety of filters (Filters) to help us complete these tasks, among which `make_list` and `split` are two commonly used string splitting tools.Although they can all convert strings to lists (or arrays), there are obvious differences in their functional focus and usage scenarios.

2025-11-08

`split` filter: How to split a long string into an array by a specific delimiter?

In the powerful functions of AnQi CMS, the flexibility of content display has always been our focus.Sometimes, you may need to enter a long string of information in a field on the back end, such as multiple keywords for an article, multiple parameters for a product specification, or a list of skills for a team member.This information is usually connected by specific delimiters (such as commas, semicolons, or pipes).However, when you want to display this information individually on the front page, even to style each part differently, the problem arises: how can you conveniently split this long string into independent items?

2025-11-08

What are the limitations of the `first` and `last` filters when getting the first and last elements of a string/array?

In Anqi CMS template design, the `first` and `last` filters are two concise and practical tools designed to help us quickly obtain the first or last character of a string, as well as the first or last element of an array.They perform well in handling simple data structures, but in practical applications, if their internal mechanisms are not well understood, they may encounter some unexpected behaviors.Firstly, let us understand their core functions. For string type data, `first` will return the first character, and `last` will return the last character

2025-11-08

Template content shows: How does the `truncatewords` filter truncate text by word count?

In the presentation of website content, we often need to condense lengthy text information to meet different layout requirements, such as displaying article summaries on list pages, brief descriptions on product cards, etc.This not only makes the page look neater, but also helps visitors quickly grasp the core information.AnQiCMS provides flexible template filters for this type of need, where the `truncatewords` filter is your powerful assistant for truncating text by word count.### A clever and concise summary, making the content clear at a glance

2025-11-08

How to get a specific digit from a number: Advanced usage of the `get_digit` filter in AnQiCMS template?

In AnQiCMS template development, flexible handling and displaying data is the key to enhancing website functionality and user experience.When faced with a sequence of numbers, such as product numbers, order numbers, or some kind of identification code, sometimes we do not need the entire number, but rather a specific digit at a certain position.At this time, the `get_digit` filter has become a very practical tool.It can help us extract the required part from the numbers accurately, providing more possibilities for the dynamic display of templates and logical judgment.

2025-11-08

What is the role of the `index` filter in processing string searches?

In the AnQiCMS template world, efficiently processing and displaying content is the core.Whether it is to dynamically adjust the page display based on user input or quickly locate key information in complex text, mastering the template function can greatly improve the operation efficiency of your website content.Today, let's delve into a very practical tool for string searching—the `index` filter.### `index` filter: 'Locate Expert' string Imagine you have a long article content or a list with multiple tags

2025-11-08

How to replace a specific keyword with another in AnQiCMS template?

In the flexible template system of AnQiCMS, dynamic content processing is an indispensable part of daily operation.Sometimes, we may need to replace a specific keyword in a string when displaying content, such as displaying a brand name uniformly or adjusting the presentation of certain text without modifying the original data.AnQiCMS's template engine provides a concise and efficient method to complete this task, among which the `replace` filter is our powerful assistant.###

2025-11-08