In AnQi CMS template development, we often need to control or truncate the displayed content to adapt to different layout requirements and optimize the user experience. At this time,sliceFilters andtruncatecharsThe filter has become our commonly used tool.Although they can all achieve text truncation, there is a significant difference in their functional focus and application scenarios.Understanding these differences can help us choose the appropriate filters more accurately, making template code more efficient and page display more reasonable.

truncatecharsFilter: A powerful assistant for content summarization

truncatecharsThe filter is mainly used to truncate strings to a specified number of characters and automatically add an ellipsis when the content exceeds the limit...This clearly indicates to the user that there is more content not displayed. Its core value lies in "cutting for display", especially suitable for scenarios where content preview or summary is needed.

The uniqueness of this filter lies in the character length you specifyincludeincluding the ellipsis. For example, if you set{{ "一段很长的文字内容"|truncatechars:10 }}So the output might be a long paragraph... The ellipsis (...) will also be counted within the 10 character length. When the original text length is less than or equal to the specified length,truncatecharsThe ellipsis is not added, but the text is output as is.Whether it is Chinese characters or English characters, they are counted as one character in length, which makes it very convenient to handle multilingual content.

In addition to the basictruncatechars,AnQi CMS also provides several variants to meet more detailed requirements:

  • truncatewords: Truncate strings by word count, trying to ensure the integrity of words.
  • truncatechars_html: Designed specifically for strings containing HTML tags, it intelligently retains the integrity of the HTML tags during extraction, avoiding destruction of page structure due to truncation.
  • truncatewords_html: Also used for HTML content, but it cuts by words and retains the HTML structure.

Application scenarios:

  • Article summary or list preview: Display a brief summary of the article on the article list page, prompting users to click to read the full text.
  • Product description snippet: Show the core selling points of the product on the product card, saving space.
  • Meta Description: Although it is usually automatically generated by CMS, if you need to control it manually in the template,truncatecharsEnsure that the output description length is moderate to avoid being cut off by search engines.
  • Optimization of display when the title is too long.: When a title may be too long in a specific area, it can be used to shorten it friendly.

Example:Suppose we have a paragraph of text.“安企CMS是一个基于Go语言开发的企业级内容管理系统,致力于提供高效、可定制、易扩展的内容管理解决方案。”

  • {{ "安企CMS是一个基于Go语言开发的企业级内容管理系统,致力于提供高效、可定制、易扩展的内容管理解决方案。"|truncatechars:15 }}Output:安企CMS是一个...(Including an ellipsis, a total of 15 characters)
  • {{ "AnQiCMS provides an efficient content management solution."|truncatechars:20 }}Output:AnQiCMS provides...
  • {{ "<p>AnQiCMS 是一个功能强大的平台。</p>"|truncatechars_html:15|safe }}Output:<p>AnQiCMS 是一个...</p>(reserved p tag)

sliceFilter: The Tool for Precise Data Slicing

sliceThe filter is more like a precise 'scalpel', used to extract specific elements from strings or arrays. Its operation is purely data slicing,No ellipsis will be added. Its behavior is very similar to the slicing operation in many programming languages (such as Python's[start:end]), which determines the range to be cut by specifying the start and end indices.

sliceThe parameter format is usually"start:end"of whichstartandendare based on the index of 0.

  • start:means from the starting index to the end.
  • :endmeans from the beginning to the index before the end (excluding)endthe element at the index).
  • start:endIndicates the substring from the start index to the index before the end index.

If the index exceeds the actual length of the string or array,sliceThe filter handles it gracefully, only returning the part within the valid range without throwing an error.

Application scenarios:

  • Fixed length data extractionFor example, extracting a fixed-length product code or user ID from a long string.
  • URL parameter processingWhen you need to extract a specific path segment or parameter value from a complex URL.
  • Array or list segmentation processing: If you need to split a large list into several small lists for display, or take the first N elements of the list without ellipsis.
  • Accurate retrieval of specific text fragmentsFor example, accurately retrieve the first 100 characters from the beginning of a document for some backend processing or frontend non-summarized display.

Example:Suppose we have a string.“AnQiCMS企业内容管理系统”and an array[1, 2, 3, 4, 5, 6, 7, 8].

  • {{ "AnQiCMS企业内容管理系统"|slice:":7" }}Output:AnQiCMS(From index 0 to 7 minus 1 equals 6 index)
  • {{ "AnQiCMS企业内容管理系统"|slice:"7:11" }}Output:企业内容(From 7 to 11 minus 1 equals 10 index)
  • {{ [1,2,3,4,5,6,7,8]|slice:"2:5"|join:"," }}Output:3,4,5(Array from index 2 to 5 minus 1 equals 4)

Guide to Core Differences and Selection

Feature truncatecharsFilter sliceFilter
Purpose Truncated for display, providing content preview or summary Precise data slicing, extracting elements at specific positions
Ellipsis Automatically added when content exceeds length...and,...count in total length Notadd any ellipsis
HTML processing there is_htmlVariants that can intelligently preserve HTML structure Does not distinguish between text and HTML, truncates based on character or array index in the original, may destroy HTML structure
Application scenario Article summary, product introduction, friendly display of long titles Fixed length data extraction, URL segment parsing, array subset acquisition
Focus point Maximum display lengthPrompt the user for more content Accurate index rangeNo additional embellishment

When to choosetruncatechars:When your goal isShorten a text to fit the display spaceand you hope touse an ellipsis to clearly indicate that the content is incompleteat that time, you should choosetruncatechars.For example, display the first few characters of each article in a blog post list, or truncate news titles when they are too long.truncatechars_htmlto ensure that the page structure is not destroyed.

When to chooseslice:When you needExtract a specific length or position segment from a string or arrayandDo not have any additional embellishments (such as ellipses)then,sliceThe filter is the more suitable choice. For example, extracting a specific field from a string of a fixed format, or extracting the first few elements from a dataset for special processing.

In short,truncatecharsIt is a 'user-friendly' filter, focusing on the visual presentation of content; whilesliceIt is more like a "developer-friendly" tool, focusing on precise data operations.According to your specific template needs, whether to emphasize the completeness of content display and user prompts, or to focus on the accurate extraction of data, choose your filter.

Frequently Asked Questions (FAQ)

  1. truncatecharsDoes the filter include ellipses when calculating length?Yes,truncatecharsThe filter will automatically add an ellipsis (to the calculated total length of the cut-out content,...This is included. This means that if you specify a cut of 10 characters, the final output text (including the ellipsis) will be 10 characters in length.

  2. Can I usesliceDoes the filter extract text containing HTML tags? Will it preserve the integrity of the tags? sliceThe filter will extract characters according to the index you specifyOriginal extractIt will not,Does not care whether the content is HTMLThis means that if the range you are cutting is exactly in the middle of an HTML tag, it will directly truncate the tag, thus breaking the HTML structure,