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.