How to slice a string or array elements within a specified range using the `slice` filter?

Calendar 👁️ 82

AnQiCMS template engine provides a rich set of filters, giving you great flexibility in displaying content. Among them,sliceA filter is a very practical tool that can help you accurately extract elements within a specified range of strings or arrays. Whether you want to display an article summary, limit the number of images, or process other data segments, it can come in handy.

sliceThe principle of the filter.

sliceThe syntax of the filter is concise and clear:{{ obj|slice:"from:to" }}. Here,objIt can be the string or array variable you need to operate, and"from:to"it defines the range you want to extract.

UnderstandingsliceThe key points of the filter are as follows:

  1. 0-based indexinglike many programming languages,slicefilters from0Start calculating the index of the element. That is, the index of the first element is0, the second one is1and so on.
  2. Left-closed, right-open interval:sliceThe range extracted is 'left-closed, right-open'. This means the starting index isfromThe element at this position will be included in the result, while the end indextoThe element at this position will not be included.
  3. Flexible ellipsis rule:
    • If omittedfrom(For example)":to") will start from the beginning (index0) will start cutting from.
    • If omittedto(For example)"from:"), will start fromfromand continue to the end.
    • IffromandtoAll of them are omitted (for example":"or not usingslicethe parameter), it means to cut the entire string or array (equivalent to copying a copy).
  4. Negative index: You can also use negative indices, which indicate counting from the end. For example,-1represents the last element,-2represents the second-to-last element, and so on.

Next, let's see through specific examplessliceHow filters work in strings and arrays.

String slicing: Flexible control of displayed content

When you need to extract a portion of content from a longer text,slicethe filter is very efficient.

Suppose you have a string"Hello AnQiCMS World!":

  • cut from the specified position to the end: If you only want to get the content from index6to the end (i.e.,"AnQiCMS World!"), you can write it like this:{{ "Hello AnQiCMS World!"|slice:"6:" }}The result will be:AnQiCMS World!

  • Cut from the beginning to the specified position: If you only want to get the content from the beginning to the index5that is"Hello"), you can write it like this:{{ "Hello AnQiCMS World!"|slice:":5" }}The result will be:Hello

  • cut the specified range: If you want to get the content from the index6to index13that is"AnQiCMS"), you can write it like this:{{ "Hello AnQiCMS World!"|slice:"6:13" }}The result will be:AnQiCMS

  • using negative indices: If you want to get the last word of a string (i.e."World!"), you can use negative indices:{{ "Hello AnQiCMS World!"|slice:"-7:" }}(starting from the seventh character from the end). The result will be:World!Or, if you want to get all content except the last character:{{ "Hello AnQiCMS World!"|slice:":-1" }}The result will be:Hello AnQiCMS World

It is worth mentioning that AnQiCMS is developed based on the Go language and has good support for UTF-8 encoded characters. Therefore, when usingsliceWhen filtering a string containing Chinese characters, there is no need to worry about garbled characters or incomplete truncation. Each Chinese character is treated as an independent 'character' for indexing.

Extract array (or list): accurately extract data fragments

sliceThe filter processes arrays (or lists) in a manner similar to string slicing, but the object being operated on is the elements of the array.

Suppose you have an array containing numbers.[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]we cansplitThe filter simulates generating an array like this:{% set numList = "1,2,3,4,5,6,7,8,9,10"|split:"," %}

Now, we can performnumListThis array is subjected to a slicing operation:

  • cut from the specified position to the end: If you want to get the content from the index3The elements from the beginning to the end (i.e.,[4, 5, 6, 7, 8, 9, 10]):{{ numList|slice:"3:"|join:"," }}(Note:join:","To simply display the array elements as a comma-separated string,sliceThe operation itself returns a new array.) The result will be:4,5,6,7,8,9,10

  • Cut from the beginning to the specified position: If you want to get from the start to the index5that is[1, 2, 3, 4, 5]):{{ numList|slice:":5"|join:"," }}The result will be:1,2,3,4,5

  • cut the specified range: If you want to get the content from the index3to index7that is[4, 5, 6, 7]):

Related articles

How to search and replace specific keywords in the `replace` filter of the Anqi CMS template?

In the daily content management and template design of AnQi CMS, we often encounter scenarios where we need to search and replace specific content in strings.Whether it is to unify brand names, filter sensitive words, or adjust the display format of some text, manually modifying a large amount of content is undoubtedly cumbersome and inefficient.Fortunately, AnQi CMS provides a very practical template filter——`replace`, which can help us easily implement these string operations.### `replace` filter

2025-11-08

How does the `repeat` filter output a string repeated a specified number of times?

During the process of website content creation, there are times when we have the need to output a specific string multiple times, such as for visual separation, placeholder content, and quick generation of list items.In the AnQiCMS template system, the `repeat` filter provides a very practical function that can help us complete this task efficiently.This filter, as the name implies, repeats a string according to the number we specify, thus saving the trouble of manual copying and pasting, greatly enhancing the efficiency and flexibility of template writing.###

2025-11-08

How do the `removetags` and `striptags` filters remove specified or all HTML tags when processing HTML content?

In the daily content operation of AnQi CMS, we often encounter situations where we need to handle HTML content.To display plain text summaries in specific scenarios, or to standardize content output and enhance security, removing HTML tags is a common requirement.AnQi CMS provides two very practical template filters: `removetags` and `striptags`. They each have unique purposes and application scenarios, let us delve into how they help us efficiently clean HTML content.###

2025-11-08

How to use the `random` filter in Anqie CMS template to randomly return a character or value from a string or array?

In AnQi CMS template development, sometimes we hope to add a touch of dynamism and surprise to the website content, so that visitors can see different elements each time they refresh the page.This is a very practical tool, the `random` filter.It can help us randomly select one from a set of predefined data to display, whether it is randomly selecting characters from a string or randomly selecting a value from an array (or list), it can be easily achieved.

2025-11-08

How `split` and `make_list` filters split a string into an array by a specified delimiter or character?

In Anqi CMS template development, flexibly handling string data is an indispensable skill for building dynamic pages.Sometimes, we need to split a long string into a data list using a specified character or string as a delimiter (which is what we commonly call an array);At other times, we may need to process each character of the string independently.AnQi CMS provides two very practical filters: `split` and `make_list`, which can help us easily meet these needs.###

2025-11-08

How does the `stringformat` filter customize the formatted output of any variable like Golang's `fmt.Sprintf()`?

In content operation, the way content is presented often determines the first impression and reading experience of users.Sometimes, simple variable output cannot meet our needs for fine-grained data formatting display, such as retaining fixed decimal places for numbers or adding specific text before output.AnQi CMS provides powerful content rendering capabilities for template developers and content operators, and the `stringformat` filter is a key tool for achieving refined output.It is like the `fmt.Sprintf()` function in Go language, which can format the output of any variable according to custom specifications

2025-11-08

How to get the thumbnail version of the image according to the image address using the `thumb` filter in the Anqi CMS template?

In website content management, the effective use of images is crucial for improving user experience and page loading speed.AnQiCMS deeply understands this, providing powerful image processing functions, among which the `thumb` filter is a tool that helps us easily obtain the thumbnail version of images.Why thumbnails are so important?Imagine if all the images on your website loaded in their original high-definition large size, how heavy the page would become!

2025-11-08

How do the `trim`, `trimLeft`, and `trimRight` filters remove spaces or specific characters from the beginning or end of a string?

In website operation and content management, we often encounter the need for string processing, especially in data entry, content display, or API interaction.For example, the user may have mistakenly entered multiple spaces before and after the text box, or some data may have been sourced with unnecessary specific characters.These seemingly minor issues may affect the layout and aesthetics of the content, even causing functional abnormalities.The AnQi CMS template engine provides a series of powerful filters to help us easily deal with these string cleaning tasks.Today, let's get to know the three very practical filters: `trim`

2025-11-08