In website content operation, we often encounter such situations: the article list page needs to display the abstract of the content, the product detail page needs to show a brief introduction, or in some special modules, we need to extract a part from 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 user reading experience and attract them to click and 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.幸运的是,AnQiCMS 深知这些需求,在模板系统中内置了一系列强大且灵活的过滤器,能够帮助我们轻松完成长字符串和HTML内容的截取与省略号显示,而且无需编写复杂的代码。

AnQiCMS template engine provides core filters including:

  • truncatechars: Suitable for plain text content, truncating based on the specified number of characters.
  • truncatewords: 适用于纯文本内容,根据指定的单词数量进行截取。
  • truncatechars_html: 专门用于包含HTML标签的内容,按字符数量截取,同时智能地保持HTML结构的完整性。
  • truncatewords_html: Similarly used to include HTML content, truncating by word count and ensuring proper closure of HTML tags.

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

For truncation of plain text content:truncatecharsandtruncatewords

When we need to handle article titles, brief descriptions, etc., which do not contain any HTML tags and are plain text,truncatecharsandtruncatewordsit is an ideal choice.

截取字符数:truncatechars

This filter calculates characters from the beginning of the string, truncates to the 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 handling Chinese content,truncatecharsIt counts characters based on the actual number of Chinese characters, with one Chinese character counted as one character, which is very intuitive.

Truncated 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, since Chinese does not have clear space separation between words like English,truncatewordsthe continuous Chinese characters are regarded as a "word". For example,"你好世界"|truncatewords:1will be"你好世界",because it is considered a complete word. Therefore, when processing Chinese, it is usually recommended to usetruncatecharsto achieve a more accurate extraction effect.

for extracting HTML content:truncatechars_htmlandtruncatewords_html

In many cases, our article content, product details description, etc. may contain rich HTML tags, such as paragraphs, bold, images, etc. Directly usingtruncatecharsortruncatewordsMay cause HTML tags to be truncated, thereby destroying the page layout and even causing display errors. AnQiCMS provides with_htmlThe filter with the suffix to solve this problem, it will intelligently close all unclosed HTML tags while cutting the content, ensuring the integrity of the page structure.

Truncate HTML content by character count:truncatechars_html

This filter will truncate the string based on character count and close all open HTML tags at the truncation point. To ensure the browser correctly parses the truncated HTML content, it is usually necessary to use in conjunction with|safeFilter usage, tells 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_htmlis similar,truncatewords_htmlIt will truncate HTML content based on the number of words, and will also intelligently close HTML tags. Similarly, in order to ensure that the HTML content is displayed correctly, it needs to be used in conjunction with|safefilters.

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

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

Important reminder:When usingtruncatechars_htmlandtruncatewords_htmlThe filter must be added at the end of the pipeline operation|safeThis is because AnQiCMS's template engine defaults to escaping all output as HTML entities to prevent XSS attacks. And these_htmlThe filter produces exactly the HTML code that needs to be directly parsed by the browser, if it is missing|safeThe HTML tags after truncation will be displayed as plain text instead of being rendered by the browser.

Actual application scenarios

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

  • Article list page: InarchiveListYou can use it when outputting articles in a loop of tagsitem.Description|truncatechars:100oritem.Content|truncatewords_html:50|safeto display the article summary and keep the list page tidy.
  • Product showcase pageIn the product overview section,product.Detail|truncatechars_html:150|safePreview the detailed description of the product.
  • Sidebar or recommended moduleWhen you need to display long titles of popular articles or recommended content,article.Title|truncatechars:25it can ensure that the title will not overflow.

Through the flexible use of these built-in filters, AnQiCMS users can better control the way content is presented, significantly improving the website's user experience and visual effects.


Common Questions and Answers (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, it will be cut off directly. The total number of characters, including ellipses, will not exceed the value you set.truncatewordsIt will truncate by word count, trying to maintain word integrity and cut after the last complete word.

  • If your content is plain text and you need to control the final display text length precisely (e.g., cards with fixed heights), choosetruncatecharsis more suitable.
  • If your content is plain text and you want the semantics of the extracted text to be more complete (not wanting words to be cut), thentruncatewordsthis is a better choice.
  • When handling Chinese content, as Chinese characters do not have a natural space separation,truncatewordscontinuous Chinese characters are treated as a single "word", which may lead to inaccurate extraction. In this case, it is more recommended to usetruncatechars.

2. Why do I have to usetruncatechars_htmlortruncatewords_htmlinstead of ordinarytruncatechars?

This is because ordinarytruncatecharsortruncatewordsThe filter will treat HTML tags as plain text when calculating length or words, and will truncate directly.This will result in incomplete closing of HTML tags, thus destroying the structure and style of the page, causing layout disorder, and even displaying errors._htmlsuffix filters (such astruncatechars_html)则会自动地识别HTML标签,在截取文本内容的同时,确保所有打开的HTML标签(如<b>/<p>/<i>等)in the cutting point is properly closed, 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 to AnQiCMS.truncatechars/truncatewords/truncatechars_htmlandtruncatewords_htmlFilter, the default ellipsis generated is three dots ("...") 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 may require operations such as string replacement.In most cases, using the default ellipsis is sufficient to meet the content display requirements.