How to extract a part of a long string or HTML content and display an ellipsis at the end?

Calendar 👁️ 67

In website content operation, we often encounter such situations: on the article list page, we need to display the summary of the content, on the product detail page, we need to show a brief introduction, or in some special modules, we need to extract a part of the long text or content containing HTML tags, and add "…" at the end to prompt the user that the content is not complete.This can not only effectively save page space and keep the layout neat, but also enhance the reading experience and attract users to click to view the full content.

To achieve such a function, if it is manually intercepted each time, it will undoubtedly consume a lot of time and effort.Fortunately, AnQiCMS is well aware of these needs, built-in a series of powerful and flexible filters in the template system, which can help us easily complete the truncation and ellipsis display of long strings and HTML content, and no complex code needs to be written.

The core filters provided by AnQiCMS template engine include:

  • truncatechars: Suitable for plain text content, truncating based on the specified number of characters.
  • truncatewords: Suitable for plain text content, truncating according to the specified word count.
  • truncatechars_html: Specifically used for containing HTML tags, it truncates by character count while intelligently maintaining the integrity of the HTML structure.
  • truncatewords_htmlThe same is used for content containing HTML tags, it should be truncated by word count and ensure the correct closure of HTML tags.

All these filters automatically add an ellipsis (...) at the end of the truncated content, making the display more professional and friendly.

For the truncation of plain text content:truncatecharsandtruncatewords

When we need to process article titles, brief descriptions, etc., which do not contain any HTML tags and are plain texttruncatecharsandtruncatewordsis the ideal choice.

截取字符数:truncatechars

This filter calculates characters from the beginning of the string, truncates after a specified number of characters, and adds an ellipsis at the end.It is worth noting that it counts the three characters of the ellipsis itself when counting.

{# 假设有一个纯文本变量 `article.Title`,内容为 "AnQiCMS是一款高效、可定制、易扩展的内容管理系统。" #}

{# 截取前10个字符,包括省略号 #}
{{ article.Title|truncatechars:10 }}
{# 预期输出: AnQiCMS是... #}

{# 截取前20个字符 #}
{{ article.Title|truncatechars:20 }}
{# 预期输出: AnQiCMS是一款高效、可定制、易扩展的... #}

When processing Chinese content,truncatecharsCounts characters according to the actual number of Chinese characters, one Chinese character counts as one character, which is very intuitive.

Truncate by word count:truncatewords

If you prefer to split content by words (separated by spaces),truncatewordsit would be a better choice. It will truncate after a specified number of words and add an ellipsis at the end.

{# 假设有一个纯文本变量 `article.Description`,内容为 "AnQiCMS is an enterprise-grade content management system developed using Go language." #}

{# 截取前5个单词 #}
{{ article.Description|truncatewords:5 }}
{# 预期输出: AnQiCMS is an enterprise-grade content... #}

For Chinese content, as Chinese does not have clear space separation between words like English,truncatewordsit considers continuous Chinese characters as a 'word'. For example,"你好世界"|truncatewords:1the result would be"你好世界"It is considered a complete word. Therefore, when dealing with Chinese, it is usually recommended to usetruncatecharsto achieve more precise extraction.

for extracting HTML content:truncatechars_htmlandtruncatewords_html

In many cases, our article content, product details descriptions, etc., may contain rich HTML tags, such as paragraphs, bold, images, etc. Use directlytruncatecharsortruncatewordsIt may cause HTML tags to be truncated, thereby destroying the page layout and even causing display errors. AnQiCMS provides with_htmlSuffix filters are used to solve this problem, they intelligently close all unclosed HTML tags while extracting content, ensuring the integrity of the page structure.

Truncate HTML content by character count:truncatechars_html

This filter will truncate by character count and close all open HTML tags before the truncation point. To ensure the browser correctly parses the truncated HTML content, it is usually necessary to pair with|safeThe filter is used to inform the template engine that this content is safe and does not require additional HTML entity escaping.

{# 假设 `article.Content` 包含 HTML 内容,例如:
   `<p><b>AnQiCMS</b>是一个基于<i>Go语言</i>开发的企业级内容管理系统,致力于提供高效、可定制、易扩展的内容管理解决方案。</p><p>项目定位于服务中小企业、自媒体运营者和多站点管理需求的用户。</p>` #}

{# 截取前40个字符的HTML内容,并保持HTML结构 #}
{{ article.Content|truncatechars_html:40|safe }}
{# 预期输出可能类似 (具体截取点及省略号前内容会根据实际HTML结构调整,并确保闭合):
   <p><b>AnQiCMS</b>是一个基于<i>Go语言</i>开发的企业级内容管理系统,致力于提供高效、可定制、易扩展... </p>
#}

Truncate HTML content by word count:truncatewords_html

withtruncatechars_htmlsimilar,truncatewords_htmlIt then truncates the HTML content based on the number of words and also intelligently closes HTML tags. Similarly, to ensure the correct display of HTML content, it needs to be accompanied by|safefilter usage.

{# 假设 `article.Content` 内容同上 #}

{# 截取前15个单词的HTML内容,并保持HTML结构 #}
{{ article.Content|truncatewords_html:15|safe }}
{# 预期输出可能类似:
   <p><b>AnQiCMS</b>是一个基于<i>Go语言</i>开发的企业级内容管理系统,致力于提供高效、可定制、易扩展的内容管理... </p>
#}

Important reminder:While usingtruncatechars_htmlandtruncatewords_htmlWhen filtering, always add at the end of the pipeline operation|safeThis is because the AnQiCMS template engine defaults to escaping all output to prevent XSS attacks. And these_htmlThe filter produces exactly the HTML code that needs to be directly parsed by the browser, if it lacks|safeAfter the HTML tags are extracted, they will be displayed as plain text, rather than being rendered by the browser.

Application scenarios in practice

These filters are very practical in the template design of AnQiCMS:

  • Article list pageInarchiveListTags can be used in a loop to output articlesitem.Description|truncatechars:100oritem.Content|truncatewords_html:50|safeto display the article summary and keep the list page tidy
  • Product Display Page: In the product overview section, you can useproduct.Detail|truncatechars_html:150|safeto preview the detailed description of the product
  • Sidebar or recommendation moduleWhen it is necessary to display long titles of popular articles or recommended content,article.Title|truncatechars:25it can ensure that the title will not overflow.

By flexibly using these built-in filters, AnQiCMS users can better control the presentation of content, significantly enhancing the user experience and visual effects of the website.


Frequently Asked Questions (FAQ)

1.truncatecharsandtruncatewordsWhat is the difference between these filters, and how should I choose?

truncatecharsTruncate by character count, even if the truncation point is in the middle of a word, the total number of characters including the ellipsis will not exceed the value you set.truncatewordsIt will cut according to the number of words, trying to maintain the integrity of the words, and cut after the last complete word.

  • If your content is plain text and you need to control the final display text length (for example, a card with fixed height), selecttruncatecharsit is more appropriate.
  • If your content is plain text and you want the semantics of the extracted text to be more complete (you do not want words to be cut off), thentruncatewordsIs a better choice.
  • When processing Chinese content, since Chinese does not have a natural space separation,truncatewordsthe continuous Chinese characters will be considered as one 'word', which may lead to inaccurate extraction. In such cases, it is more recommended to usetruncatechars.

2. Why do I have to usetruncatechars_htmlortruncatewords_html instead of ordinarytruncatecharsWhat?

This is because ordinarytruncatecharsortruncatewordsThe filter will also treat HTML tags as plain text when calculating length or words, and will truncate them directly.This would result in incomplete HTML tag closures, thereby destroying the structure and style of the page, causing layout chaos, and even displaying errors. It includes_htmlsuffix filter (such astruncatechars_htmlIt will intelligently recognize HTML tags, while extracting text content, ensuring that all open HTML tags (such as<b>/<p>/<i>Correctly closed at the cut point, thus avoiding the destruction of the page structure and ensuring the correct rendering of the content.

3. Can the ellipsis displayed after truncation be customized to other symbols or text?

Currently built-in in AnQiCMStruncatechars/truncatewords/truncatechars_htmlandtruncatewords_htmlThe filter generates an ellipsis with three dots ("...") by default and does not support customizing the symbol or text of the ellipsis directly through parameters.If you need to customize, you may need to consider manually removing the default ellipsis after content truncation and adding the custom text you want.This will increase the complexity of the template, and it may require combining string replacement operations.In most cases, using the default ellipsis is sufficient to meet the content display requirements.

Related articles

How to safely output content containing HTML tags in a template and prevent them from being escaped by the browser?

In website operation, we often need to display information with rich formatting and media content, such as carefully edited article details, product introductions, or customized pages.This content often contains HTML tags, such as image tags `<img>`, link tags `<a>`, paragraph tags `<p>` and so on.However, if you directly output this content to a web page, you may find that it does not render as expected, but rather displays the HTML tags as plain text, greatly affecting the user experience and the beauty of the page.

2025-11-08

How to implement multi-condition filtering on a product list or article list page and display the filtered results?

In a content management system, providing users with flexible multi-condition filtering functions is a key factor in improving website usability and user experience.Whether it is an e-commerce website product list or a content portal article classification page, users hope to quickly locate the content they are interested in.AnQiCMS (AnQiCMS) with its powerful content model and template tag system allows you to easily meet this requirement and intuitively display the filtered results. ### 1.Establishing the foundation: defining content models and custom fields All filtering functions rely on data.

2025-11-08

How to display custom additional field content on the detail page?

One of the core strengths of AnQiCMS is its flexible content model feature.It allows us to add various unique custom fields to content based on different business scenarios, such as products, services, events, etc.These custom fields greatly enrich the expression of content, making our website content more professional and meet the needs.But with these additional fields, how can they be presented elegantly on the front-end detail page?

2025-11-08

How can AnQi CMS automatically replace keywords to display article or product content?

In content operations, we often need to ensure that specific keywords in articles or product descriptions are consistent, even automatically associated with related pages, which is crucial for SEO optimization and improving user experience.But manually modifying one by one takes time and is prone to errors, especially when the content of the website is massive, it is also a huge challenge.Anqi CMS knows this, and therefore provides us with a very practical feature, that is, the automatic replacement and display of keywords in articles or product content.This feature can intelligently identify the keywords or phrases you preset and automatically replace them with the specified text or link

2025-11-08

How to format user input plain text content (including newline characters) into HTML paragraphs and newline characters for display?

In website content management, we often encounter such needs: when users input a block of plain text content in the background, it often contains some natural paragraphs and line breaks. We hope that these paragraphs and line breaks are rendered correctly on the website front-end as HTML paragraph tags (`<p>`) and line break tags (`<br/>`), rather than being compressed into a blob or ignored by the browser.AnQi CMS provides a very convenient and powerful template filter to solve this problem, allowing plain text content to be presented elegantly on the web.

2025-11-08

How to convert timestamp data stored in the background into a readable date and time format for display?

When managing website content in Anqi CMS, we often encounter situations where we need to display dates and times.However, the time information stored in the background database is usually in the form of timestamps, which is very efficient for machine processing, but difficult for users to read directly.For example, you might see a string like `1609470335`, which represents a specific moment, but we want it to be displayed in a more friendly format like "2021 January 1 at 12:25:35".fortunately

2025-11-08

How to concatenate the elements of an array into a string separated by a specified delimiter for display?

When managing and displaying content in Anqi CMS, we often encounter situations where we need to merge a group of related information into a coherent text.For example, a product may have many characteristics, and we hope to display the list of these characteristics uniformly with commas or slashes.Or perhaps, an article is associated with multiple keyword tags, and we want to summarize these tags into a single line of text.At this time, the powerful template filter of Anqi CMS can be put to good use, especially the `join` filter, which can help us easily achieve this goal.### Understand the `join` filter

2025-11-08

How to perform basic arithmetic operations on numbers in templates and display the results?

In website operation, we often need to dynamically display some numerical information, such as total product price, percentage of article reading, discounted price, and so on.The template system provided by AnQi CMS is powerful, it adopts syntax similar to the Django template engine, allowing us to easily implement these requirements when displaying content, perform basic arithmetic operations directly in the template, and display the results.### Master basic arithmetic operations in templates The most direct way to write arithmetic expressions in Anqi CMS templates is within double curly braces `{{ }}`

2025-11-08