In AnQiCMS template, how to implement `slice` to extract a segment of content from a string?

Calendar 👁️ 76

In Anqi CMS template development, we often need to flexibly handle the displayed content, such as extracting key parts from a paragraph or simply displaying a few items from the list. At this time,sliceThe filter is very practical. It helps us extract a segment of content precisely from a string or array (a slice in Go language).

UnderstandingsliceThe principle of the filter.

sliceThe role of the filter in the AnQi CMS template, as the name implies, is to "slice" — it allows us to take out the piece we want from the whole, whether it's a long text description or a neatly arranged data list.sliceCan extract a part from the specified start and end positions.

Its basic syntax is very intuitive:{{ 变量 | slice:"起始位置:结束位置" }}.

The 'starting position' and 'ending position' are both based on zero-indexing. This means that the position of the first character or the first element is 0, the second is 1, and so on.

  • Starting position (from)Indicates the starting index of the substring. The character or element at this position is included in the result.
  • End position (to): indicates the index at which the extraction ends. The character or element at this positionNotis included in the extraction result, but up to the one before it.

By omitting the index before or after the colon, we can also achieve extracting from the beginning to a specified position, or from a specified position to the end.

Actual application example

Let's see through several specific examples.sliceThe application of filters in different scenarios:

1. Extracting the specified part of a string

Suppose we have a string."欢迎使用安企CMS,这是一个强大的内容管理系统!"We want to extract the segment 'AnQi CMS' from it.

{# 假设有一个变量 myString 存储了这段文字 #}
{% set myString = "欢迎使用安企CMS,这是一个强大的内容管理系统!" %}

{# 从索引4开始,到索引9结束(不包含索引9的字符),即“安企CMS” #}
{{ myString | slice:"4:9" }}
{# 显示结果:安企CMS #}

It is important to note that if the string contains ChinesesliceThe filter counts and truncates based on characters rather than bytes, which makes it very convenient to handle multilingual content. For example"你好时间",slice:"1:3"It will correctly cut"好世".

2. Cut from the beginning or end of the string

If we want to get the first few characters of a string, or the last few characters, we can also omitslicePart of the parameter:

{% set myString = "欢迎使用安企CMS,这是一个强大的内容管理系统!" %}

{# 截取前五个字符:从索引0到索引5(不包含5) #}
{{ myString | slice:":5" }}
{# 显示结果:欢迎使用安企 #}

{# 截取从索引12开始到字符串末尾的所有字符 #}
{{ myString | slice:"12:" }}
{# 显示结果:一个强大的内容管理系统! #}

{# 截取字符串的最后一个字符(使用负数索引从末尾开始计数) #}
{# 注意:直接使用负数索引作为起始位置时,如果负数索引的绝对值大于字符串长度,可能会返回空。更稳妥的做法是先获取长度再计算。
   不过,文档中的示例 `slice:"-1:"` 和 `slice:":-1"` 似乎表明它支持从尾部开始的切片操作,但需要注意具体行为。
   对于单个字符,如`{{ "Test"|slice:"-1:" }}`,会返回`t`。
#}

3. Extract elements from an array (or list) at specified positions

sliceThe filter also applies to arrays. Suppose we have a list of numbers[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]We want to extract the third to the seventh numbers:

{% set numbers = simple.multiple_item_list %} {# 假设这是一个数字数组 [1,1,2,3,5,8,13,21,34,55] #}

{# 从索引2开始(第三个数字),到索引7结束(不包含第七个,即到第六个) #}
{{ numbers | slice:"2:7" | join:", " }}
{# 显示结果:2,3,5,8,13 #}

join:", "Is another commonly used filter, which concatenates array elements with commas and spaces into a string for easy display.

Several usessliceTips:

  • Zero-based index: Remember that all indices start from 0.
  • Left closed, right open: The start position is included in the result, the end position is not included.
  • Omitting indices:":N"Means from the beginning to N-1;"N:"Indicates from N to the end.
  • Out of bounds: If the specified start or end position exceeds the actual length of the string or array,sliceFilters are usually handled gracefully, only capturing the valid part, or returning an empty value without causing template rendering errors.
  • The start is greater than the end.: If the specified starting index is greater than or equal to the ending index,sliceit will return an empty string or an empty array.

MastersliceFilter, allowing us to more flexibly control the presentation of content in the AnQi CMS template, whether it is to extract abstracts, display partial data, or perform more complex string processing, it is a very handy tool.


Frequently Asked Questions (FAQ)

1.sliceWhat is the filter cutting in Chinese by character or by byte?

sliceThe filter is in the Anqi CMS template bycharacterExtracted. This means that even a Chinese character may occupy multiple bytes in memory, sliceThe filter also treats it as a separate character for counting and truncation, which is consistent with our daily reading habits and greatly simplifies the template processing of Chinese content.

2. IfsliceWhat happens if the start or end position specified by the filter exceeds the actual length of the string/array?

When the specified index exceeds the actual length,sliceThe filter will intelligently perform the trimming.If the starting position exceeds the length, or the end position exceeds the length but can still extract a valid part, it will return the valid part as much as possible.slice:"5:15"It will cut off from index 5 to the end of the string; if you tryslice:"15:20"Since the starting position is out of range, it will return an empty string or an empty array without causing an error.

3.sliceCan the filter be used to truncate a string containing HTML tags while ensuring the integrity of the tags?

sliceThe filter is based on character or array index to截取,it does not know if the content contains HTML tags.Therefore,if used directlysliceExtracting a string containing HTML tags may cause the tags to be truncated, which can破坏 the structure or style of the page. If you need to safely extract content containing HTML tags, it is recommended to use something liketruncatechars_htmlortruncatewords_htmlSuch filters can intelligently handle HTML structures and avoid truncating tags.

Related articles

How does the `slice` filter handle string or array index out of bounds situations?

In Anqi CMS template development, the flexibility of data display is crucial for building dynamic and user-friendly websites.The `slice` filter is a powerful and practical tool that helps us accurately extract part of the string or array content.However, when performing such operations, we are bound to encounter index out of bounds situations, that is, attempting to access a position beyond the data range.Fortunately, the `slice` filter of Anqi CMS has considered these edge cases and provided a set of elegant solutions.

2025-11-08

How to use `slice` to get the last N elements of an array in AnQiCMS template?

In AnQiCMS template development, we often need to handle list or array type data, such as article lists, product lists, and so on.Sometimes, we might only be concerned with a part of these data, such as the latest few articles, or a specific number of elements at the end of the list.At this time, the `slice` filter built into AnQiCMS is particularly powerful and convenient.It allows us to flexibly extract elements from an array or string within a specified range.This article will thoroughly introduce how to use the `slice` filter in AnQiCMS templates

2025-11-08

How to get only the first N characters of a string using the `slice` filter?

In website content display, we often need to truncate a part of the long text as a preview, abstract, or to ensure the neat layout of the page.For example, it is crucial to control the text length precisely when displaying the article summary on the article list page or setting `meta description` content for search engine optimization (SEO).AnQiCMS (AnQiCMS) powerful template engine provides a variety of flexible filters to help us easily meet these needs.

2025-11-08

How to extract elements from a specified range in AnQi CMS template?

In the powerful template system of Anqi CMS, we often need to precisely control the display of content.Whether it is an article list, product album, or custom data model, data is often presented in the form of an array.Sometimes, we may only need to display a part of the array, such as only showing the latest three records, or picking out a few images from a picture list.At this point, the `slice` filter provided by AnQi CMS comes in handy, as it helps us elegantly extract elements within a specified range from the array

2025-11-08

Does Go template's `slice` filter support negative indices? How to use it to slice in reverse order?

In AnQiCMS, templates are the key to building dynamic content, allowing us to flexibly display data.In the process of template development, it is often encountered that string or list (usually slice in Go template, which can be understood as an array) truncation operations need to be performed.AnQiCMS provides a powerful `slice` filter to handle such needs.### Deeply understand the basic usage of `slice` filter The `slice` filter is mainly used to extract specified elements from strings or lists

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

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

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