How to safely extract strings or HTML content and add an ellipsis in AnQiCMS templates?

Calendar 👁️ 83

When operating a website, we often need to display article summaries, product descriptions, or user comments and so on.This text, if not processed, will be displayed directly, and long text may disrupt the page layout, affecting the overall aesthetics and information transmission efficiency.At this time, it is particularly important to properly truncate the content and add an ellipsis.

AnQiCMS as an efficient and customizable content management system, its powerful template engine developed based on the Go language provides us with a simple and intelligent solution.By using built-in filters, we can easily implement flexible extraction of string or HTML content, automatically adding ellipses to ensure that the content is concise and complete while maintaining good page structure.

Extract ordinary text content: balancing brevity and readability

For text content without any HTML tags, AnQiCMS provides two convenient filters to meet different truncation needs:truncatecharsandtruncatewords.

1.truncatechars: Truncate by character count

This filter is very suitable when you need to strictly control the display length of text. It will truncate the string according to the specified number of characters and add an ellipsis within this length....This means that if you set a cut-off of 10 characters, the content displayed, including the ellipsis, can be no more than 10 characters long. It should be noted that,truncatecharsWhen truncating, a word may be "cut off" because it only counts character numbers.

Usage example:Assuming your article descriptionitem.DescriptionIs a plain text, you want to display at most 30 characters:

<p>{{ item.Description|truncatechars:30 }}</p>

Ifitem.DescriptionThe content is 'AnQiCMS is an enterprise-level content management system based on Go language, with powerful functions and easy deployment.' It may be displayed as 'AnQiCMS is an enterprise-level content management system based on Go language, with powerful functions...'

2.truncatewords: Truncate by word count

When you pay more attention to the semantic integrity of the content and hope that the truncated text does not appear with "half a word" when it is done,truncatewordsThe filter comes into play. It will truncate according to the number of words you specify and ensure that each word is complete.Of course, the filter effect will be very natural in an English-speaking environment.For Chinese content, since Chinese does not have clear word separators, the effect may not be astruncatecharsIt is more accurate and meets expectations to truncate directly by word count.

Usage example:If you want a summary of an English articleitem.DescriptionShow the first 15 words:

<p>{{ item.Description|truncatewords:15 }}</p>

Ifitem.DescriptionIs “AnQiCMS is an enterprise-level content management system developed based on Go language, powerful and easy to deploy.”, it may be displayed as “AnQiCMS is an enterprise-level content management system developed based on Go language, powerful and easy…”

Extract content containing HTML: Prioritize safety and structure

It is a tricky problem to directly cut characters or words from content containing HTML tags.Simplistically cutting off may destroy the integrity of HTML tags, causing the page display to be chaotic, and even possibly introducing security risks.AnQiCMS provides filters specifically designed for HTML content, which can intelligently handle tags to ensure that the HTML structure is still valid after extraction.

1.truncatechars_html: Safely extract HTML by character

This filter is compatible withtruncatecharsSimilar, but it intelligently identifies and maintains the structure of HTML tags when extracting.No matter how many characters you extract, it ensures that all opened tags are closed correctly, avoiding page rendering issues due to mismatched tags.This is very useful for article text, rich text editor generated introductions, and other scenarios.

Important reminder:While usingtruncatechars_htmlortruncatewords_htmlAfter extracting HTML content, be sure to add it to the variable output|safeFilter. This is because the AnQiCMS template engine, for security reasons, defaults to escaping all output content (such as<will be escaped to&lt;)。If not processed_htmlThe content processed by the filter|safeThe browser will display your HTML tags as plain text, rather than rendering them.|safeTell the template engine explicitly that this content is safe, it does not need to be escaped, and can be output directly as HTML.

Usage example:Suppose the content of your articlearchive.ContentContains rich HTML format, you want to display the first 100 characters:

<div class="summary">{{ archive.Content|truncatechars_html:100|safe }} <a href="{{ archive.Link }}">阅读更多</a></div>

2.truncatewords_html: Safely split HTML by words

withtruncatewordssimilar,truncatewords_htmlIt will cut the content containing HTML according to the word count, while also intelligently maintaining the integrity of HTML tags. Similarly, it is also suitable for languages with clear word delimiters such as English, and also needs to be配合|safefilter usage.

Usage example:If you wish to view the product detailsproduct.DescriptionDisplay the first 20 words while retaining the HTML format:

<div class="product-brief">{{ product.Description|truncatewords_html:20|safe }} <a href="{{ product.Link }}">查看详情</a></div>

**Practical and Practical Suggestions

  • Choose the appropriate truncation method:For plain text descriptions, choosetruncatecharsortruncatewords. For rich text content with HTML format, always usetruncatechars_htmlortruncatewords_html, to avoid breaking the page structure.
  • Remember|safeFilter:At any time, whenever you usetruncatechars_htmlortruncatewords_htmlA filter to process HTML content must be used immediately afterwards|safeOtherwise, the browser will display the original HTML tags instead of the rendered effect.
  • Uniform length truncation:In different areas of the website, try to maintain consistency in the length of extracted content.For example, the summaries of all articles on the list page are truncated to 80 characters, making the page look neater and more professional.
  • Add 'Read More' link:After extracting the content, it is usually necessary to add a "Read More" or "View Details" link at the end to guide users to access the full content and enhance the user experience.

By flexibly using these content extraction filters provided by AnQiCMS, you will be able to better manage and present website content, providing visitors with a beautiful and efficient browsing experience.


Frequently Asked Questions (FAQ)

  1. truncatecharsandtruncatewords_htmlWhat is the core difference? truncatecharsIt is a filter used to truncate plain text, it simply counts characters and may truncate words.truncatewords_htmlIt is used to extract text containing HTML tags, it will intelligently recognize and maintain the HTML structure, and extract it by word count. Most importantly,truncatewords_htmlThe processed content must be matched with|safeThe filter to correctly render HTML.

  2. Why did I usetruncatechars_htmlbut the content on the page still displayed<p>/<a>such tags?This is usually because you forget to add the output content after|safeThe filter. The AnQiCMS template engine defaults to escaping all variable outputs for HTML to prevent XSS attacks. When you usetruncatechars_htmlAfter processing HTML content, if lacking|safeThe filter, the escape mechanism will convert HTML tags to the corresponding entity characters (such as<p>becomes&lt;p&gt;),causing the browser to display it as plain text. Plus|safeIt will tell the template engine that this content is safe and should be rendered directly as HTML.

  3. Can I customize the style or content of the ellipsis?Currently, the built-in truncation filter of AnQiCMS uses by default...As an ellipsis. These filters are mainly for handling truncation logic and HTML structure, and do not provide direct parameters to modify the specific content or CSS style of the ellipsis.If you have specific style requirements, you may need to perform additional processing on the text container after it has been cropped, through front-end JavaScript or CSS rules.

Related articles

How to debug template in AnQiCMS and view the structure and value of variables (using dump filter)?

When developing website templates, we often encounter such confusion: what data does a variable in the template contain?What is its structure? What is the type? And what is the specific value?If these questions cannot be answered quickly, the debugging process will become extremely繁琐and time-consuming.Fortunately, AnQiCMS has provided us with a powerful and convenient debugging tool——`dump` filter, which can help us easily reveal the true face of variables.AnQiCMS developed in Go language, using a template engine syntax similar to Django

2025-11-08

How to generate random text of a specified length as placeholder content in AnQiCMS template?

## Generate random text of a specified length as placeholder content in AnQiCMS template During website development and content operation, we often encounter scenarios where we need to fill in placeholder content (Placeholder Content).Whether it is designing a new template, testing page layout, or giving an initial preview when the content is not fully ready, placeholder text can help us quickly build prototypes, intuitively evaluate the visual effects, and do not need to wait for the real content to be filled in.

2025-11-08

How does AnQiCMS filter or replace external links in content to standardize display?

External links contained in website content, if not managed properly, may have a negative impact on the website's search engine optimization (SEO) effect, user experience, and even the quality of the content.AnQiCMS as a comprehensive content management system, provides a series of powerful and flexible tools to help you effectively filter or replace external links in the content, ensuring the standardized display of website content.

2025-11-08

How to retrieve and display details of a specific user group (such as VIP level) in AnQiCMS template?

In AnQiCMS, managing users and content, we often encounter the need to display different information based on the user's identity (such as VIP level).The powerful template engine and user group management function of AnQiCMS makes it very intuitive and efficient to achieve this goal. Today, let's discuss how to retrieve and flexibly display detailed information of specific user groups in the AnQiCMS template, such as the name of the VIP level.

2025-11-08

How to format a timestamp into the display format of "Year-Month-Day" in AnQiCMS?

In daily website operations, the display format of dates is crucial to user experience.A clear, consistent, and easy-to-understand date format that allows visitors to easily obtain information and enhance the professionalism of the website.For users of AnQiCMS, we often encounter data stored in the form of timestamps for content publishing time, update time, and so on. How to convert these long strings of numbers into a friendly display format such as 'Year-Month-Date' is an indispensable part of content presentation.

2025-11-08

How can simple mathematical arithmetic operations be performed in the AnQiCMS template to display the result?

Handling arithmetic operations in AnQiCMS templates is an important link to the dynamic and personalized display of website data.No matter whether you need to calculate the total price of goods, display discount information, or make conditional judgments based on certain values, AnQiCMS's powerful template engine can provide flexible support.Thanks to its Django template engine features, simple mathematical arithmetic operations can be performed directly in the template without complex code logic.### Directly perform expression calculation in the template AnQiCMS template engine supports double braces `{{ }}`

2025-11-08

How to split a string into an array by a specified separator and iterate and display it in the template in AnQiCMS?

In website operations and content management, we often encounter such scenarios: a certain field in the background stores multiple related information, such as multiple keywords of an article, various functional tags of a product, or multiple aliases of an author.This information is usually connected into a string with commas, semicolons, or other specific symbols.When it is necessary to display this information one by one or perform style processing in the website front-end template, it is necessary to split this string into independent items and then traverse and display them one by one.AnQiCMS provides a powerful and flexible template engine, its syntax style is similar to

2025-11-08

How to remove specific characters or spaces from a string in AnQiCMS template?

In website content management, string processing is inevitable and crucial.In order to maintain the beauty of the page, keep the standardization of data output, or for SEO optimization, we often need to make fine adjustments to text content, such as removing extra spaces, punctuation marks, or other specific characters.AnQiCMS provides a flexible and powerful template engine, allowing us to easily implement these string operations in front-end templates.

2025-11-08