How does the `slice` filter implement the function of extracting elements from the end of an array?

Calendar 👁️ 86

In the template development of AnQiCMS,sliceThe filter is a very practical tool that allows us to flexibly extract a portion of the string or array content.But do you know?It can also realize a particularly clever function——to extract elements from the end of an array or list, which is very convenient when it comes to displaying the latest data or removing old data.sliceHow does the filter implement this feature through negative indices.

UnderstandingsliceBasic usage of the filter.

As the name implies,sliceThe filter is used for "slicing" data, which can extract the part you need from a longer sequence (such as a string, array, or list). Its basic syntax is{{ obj|slice:"from:to" }}.

Here, fromandtoRepresent index positions:

  • from: Indicates the start index (including the element at this position).
  • to: Indicates the end index (not including the element at this position).

For example, if you have a string"AnQiCMS模板制作"To truncate the first 5 characters, you can use this:

{{ "AnQiCMS模板制作"|slice:"0:5" }}
{# 显示结果: AnQiCMS #}

For arrays,sliceThe filter is also effective. Suppose we have a list of numbers[1, 2, 3, 4, 5]To get the elements from index 1 to index 3 (not inclusive), you would typically go throughsplitThe filter converts the string to an array and then performs the operation:

{{ "1,2,3,4,5"|split:","|slice:"1:4"|join:","}}
{# 显示结果: 2,3,4 #}

As you can see,sliceThe filter follows the 'left closed right open' principle, which means the range to be截取包含fromelements corresponding to the index, but does not includetoelements corresponding to the index.

sliceThe secret of the filter from the end: negative indices

When we need to operate from the end of the sequence,slicethe negative index of the filter comes into play. A negative index indicates counting down from the end, for example-1it means the last element,-2represents the second-to-last element, and so on.

By cleverly combining negative indices, we can achieve various needs for截取 from the end:

1. Get the last N elements

If you want to get the last N elements of an array or string, you can setfromto a negative number, andtothen you can omit it (indicating the end of the sequence):

{# 假设我们有一个列表:["A", "B", "C", "D", "E"] #}
{{ "A,B,C,D,E"|split:","|slice:"-2:"|join:","}}
{# 显示结果: D,E  —— 获取最后2个元素 #}

{# 如果想获取最后3个元素 #}
{{ "A,B,C,D,E"|split:","|slice:"-3:"|join:","}}
{# 显示结果: C,D,E #}

Here-2:Start from the second-to-last element and continue to the end of the sequence.

2. Get all elements except the last N elements.

If you need all elements but want to exclude the last N, you cantoto a negative number, andfromThen it can be omitted (indicating from the beginning of the sequence):

{# 假设我们有一个列表:["A", "B", "C", "D", "E"] #}
{{ "A,B,C,D,E"|split:","|slice:":-2"|join:","}}
{# 显示结果: A,B,C  —— 排除最后2个元素 #}

{# 如果想排除最后3个元素 #}
{{ "A,B,C,D,E"|split:","|slice:":-3"|join:","}}
{# 显示结果: A,B #}

Here:-2It indicates starting from the beginning and cutting off to the second-to-last element (but not including the second-to-last element).

3. From a specific position at the end to the end (not including).

This usage is slightly complex, but very flexible. You can specify starting from the Mth element from the end, to the element before the Nth from the end:

{# 假设我们有一个列表:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #}
{{ "1,2,3,4,5,6,7,8,9,10"|split:","|slice:"-5:-2"|join:","}}
{# 显示结果: 6,7,8  —— 从倒数第5个元素 (6) 开始,到倒数第2个元素 (9) 之前结束 #}

In the above example,-5Point to6,-2Point to9So the cut is6,7,8.

Application scenarios in practice

Understood the negative index

Related articles

How to extract elements within a specified range from an array or string in Anqi CMS template?

In AnQiCMS template development, we often need to finely control the displayed content, such as extracting part of the information from a long text, or displaying only the first few elements from a list.Fortunately, AnQiCMS uses a Django-like template engine that provides a very useful tool - the `slice` (slicing) filter, which can help us easily meet these needs.The `slice` filter is a very flexible feature that is not only applicable to string (text) but also to array (list) data

2025-11-08

How does the `join` filter behave when processing non-array objects (such as strings)?

In Anqi CMS template development, the `join` filter is a very practical tool, mainly used to concatenate elements of an iterable object (such as an array or list) into a single string with a specified separator.However, when we apply the `join` filter to non-array objects, especially strings, its behavior may be different from what we initially imagine, but understanding its working principle can help us use it more flexibly.### The basic functionality of `join` filter review First, let's review the most common uses of the `join` filter

2025-11-08

How to concatenate array elements in an Anqi CMS template with a custom character into a string?

In AnQi CMS template design, we often encounter situations where we need to display list-type data, such as multiple tags of an article, multiple image links on a product details page, or multiple options stored in a custom field.Directly outputting these array-shaped data to the page will often show a similar format like `["Label one", "Label two", "Label three"]`, which clearly does not meet the aesthetic and reading habits of users.At this point, we need to find a method to separate each element of the array with a custom character (such as a comma

2025-11-08

How does the `split` filter split a string into an array of characters?

When using AnQiCMS for website content creation and template development, string processing is a common requirement.Sometimes, we need to split a complete string into smaller parts, such as breaking it down into an array of characters.This article will delve into the powerful `split` filter feature in AnQiCMS and provide practical examples.

2025-11-08

How to determine whether an array or string in an Anqicms template contains a specific keyword?

In AnQi CMS template development, we often need to dynamically display information based on specific attributes or keywords of the content.For example, determine whether an article title contains a certain product name, or check whether a document's tag list contains a hot keyword.This can not only make the website content more targeted, but also improve user experience and SEO effect.The AnQi CMS template engine provides powerful and flexible features to meet these needs.Among them, it is easy to determine whether an array or string contains a specific keyword by using the built-in `contain` filter.

2025-11-08

Can the `contain` filter be used to check if a Map (key-value pair) contains a specific key?

AnQiCMS with its efficient and customizable features brings many conveniences to content management.In the daily operation of websites, we often need to dynamically adjust the page content in templates based on the existence of data.Among them, it is a common requirement to judge whether a specific key exists in the data of key-value pair (Map) type.Today, let's delve into whether and how the `contain` filter in AnQiCMS templates can be used to check for the existence of keys in a Map.

2025-11-08

How to calculate the number of times a keyword appears in a string or array in the Anqi CMS template?

In content operation, precisely mastering the use of keywords on the page plays a crucial role in SEO strategy, content quality assessment, and user experience optimization.AnQiCMS (AnQiCMS) is a flexible and efficient content management system with a powerful template engine built-in with many practical features, including a filter that can help us easily calculate the number of times keywords appear.Next, we will introduce how to use these features to count the frequency of keywords in the Anqi CMS template.### Deeply understand `count`

2025-11-08

The `count` filter calculates the number of times a keyword appears in an array, is it a partial match or a complete match?

In Anqi CMS template development, the `count` filter is undoubtedly a very practical tool for processing data, which can help us quickly count the frequency of a specific keyword in the data.However, when using this filter, many users may be puzzled: when it handles string and array data of different types, is the keyword matching method 'partial matching' or 'exact matching'?This is crucial for accurately presenting content data.

2025-11-08