Template optimization: What is the difference between the `slice` filter and the `truncatechars` filter? When should you choose which one?

Calendar 👁️ 57

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,

Related articles

AnQiCMS development: Application scenarios of the `slice` filter in handling list pagination or displaying summaries?

In AnQiCMS template development, the `slice` filter is a very practical tool that allows us to perform precise slicing operations on strings (text) or arrays (lists).Mastering its usage can help you gain more flexible control when handling content display.The basic syntax of the `slice` filter is `{{obj|slice:"from:to"}}`.Here the `obj` is the string or array variable you want to process, and `from` and `to` define the start and end positions

2025-11-08

Batch processing content: How to use `slice` to dynamically truncate strings of different lengths in a loop?

In website content operation, we often encounter situations where we need to display content in bulk, such as article lists, product introduction summaries, etc.In order to ensure the beauty of the page and the clarity of information presentation, we often need to truncate the titles or descriptions of these contents so that they can display different lengths in different areas or under different conditions.AnQiCMS provides powerful template tags and filters, making this requirement simple and flexible.

2025-11-08

How to assign the result of a `slice` filter to a new variable for subsequent use?

In AnQiCMS template development, we often need to process displayed data in various ways, such as truncating a segment of text, or extracting specific items from a list.The `slice` filter is born for this, it can help us accurately slice a part of the string or array.However, it is not enough to simply extract data, how to conveniently assign the extracted results to a new variable for repeated use in the subsequent parts of the template or for more complex logic processing, this is the key to improving template development efficiency and code readability.### `slice` filter basics

2025-11-08

How to avoid Chinese garbled or incomplete truncation caused by the `slice` operation in AnQiCMS template?

When using AnQiCMS for website content development, you may sometimes encounter the situation where, when using the `slice` filter in the template to process Chinese content, the content is truncated and incomplete, which undoubtedly affects user experience and the accuracy of content presentation.Even though the underlying design of the system aims to avoid garbled characters, it is particularly important to understand its mechanism due to the characteristics of Chinese multi-byte characters and the expected display effects.

2025-11-08

What result will the `slice` filter return when operating on an empty string or array?

In AnQi CMS template development, we often need to perform fine-grained control and processing of content.Among them, the `slice` filter is a very practical tool that allows us to extract the specified part from a string or array (usually referred to as a slice in Go language).This feature is very convenient when displaying article summaries, partial elements in pagination lists, or processing dynamic data.

2025-11-08

How to use the `slice` filter to get all elements of the array except the first and last?

When managing and displaying content in Anqi CMS, the flexibility of the template is the key to improving website operation efficiency.The built-in Django template engine syntax provides many practical filters, allowing us to handle various data in a concise and efficient manner.Today, let's delve deeply into a very practical filter——`slice`, which can help us accurately cut a specific part of an array (or called slice in the Go language environment), especially on how to get all elements except the first and last one.Content display is the core of website operation, whether it is an article list

2025-11-08

What is the impact of the `slice` filter on performance when handling large strings or large arrays?

Performance considerations for the `slice` filter in AnqiCMS when handling large strings or large arrays The `slice` filter is a very convenient feature in the AnqiCMS template engine, allowing users to extract specified length data segments from strings or arrays.Whether it is to extract an abstract from a long article or to select a portion of elements from a large data list, `slice` can provide flexible control.

2025-11-08

How to get the actual character length of a string (including Chinese) in Anqi CMS template?

When making website templates, we often need to control the display length of text to ensure that the page layout is beautiful and information is conveyed efficiently.For example, limit the number of characters in the article summary, ensure that the text in the navigation menu is not too long, or perform character count verification before submitting the form.The AnQi CMS template engine provides a very practical filter called `length`, which can easily obtain the actual character length of strings, arrays, or key-value pairs, and has good support for Chinese.

2025-11-08