Does the `slice` filter support negative indices to start cutting from the end?

Calendar 👁️ 68

In Anqi CMS template development, we often need to flexibly extract and display strings or data lists, only presenting a part of them.sliceThe filter is created for this purpose, it allows us to precisely control the length of the content. And forsliceThe filter supports negative indices, which means it can start from the end, and the answer is affirmative. This feature greatly enhances the flexibility and convenience of our templates when handling dynamic content.

sliceBasic usage of the filter

First, let's briefly review.sliceBasic syntax of the filter. It usually starts with{{ 变量 | slice:"from:to" }}in the form of, wherefromandtoare optional numbers used to specify the start and end positions.

  • from:: Indicates from the specifiedfromposition, and continues to the end of the string or array. For example:{{ "AnQiCMS"|slice:"2:" }}It will outputQiCMS(Starting from index 2, the third character).
  • :to: It means to extract from the beginning of the string or array to the specifiedtoposition (excluding the element at that position). For example:{{ "AnQiCMS"|slice:":5" }}It will outputAnQiC(From the beginning to index 5, not including index 5).
  • from:to: indicates a clear range, starting fromfromposition totoposition (not including)tothe element at that position). For example:{{ "AnQiCMS"|slice:"1:4" }}It will outputnQi(From index 1 to index 4, not including index 4 characters).

These usages apply equally to strings and arrays (or Go language slices)

Negative indices: a tool for extracting from the end.

sliceThe real strength of the filter lies in its support for negative indices. Negative indices provide a convenient way toendstart counting from a string or an array.

  • -1represent the last element.
  • -2represents the second-to-last element, and so on.

Let's look at how negative indices work with some specific examples:

  1. Extract a specific part starting from the endIf you want to get the last few elements of a list, negative indices are very convenient. Suppose we have a list of numbers:[1, 1, 2, 3, 5, 8, 13, 21, 34, 55].

    • To get the last element:{{ simple.multiple_item_list|slice:"-1:"|join:"," }}You will get55This means to cut from the last element to the end.
    • To get the last three elements:{{ simple.multiple_item_list|slice:"-3:"|join:"," }}You will get21,34,55.
    • The same for strings:{{ "你好世界"|slice:"-1:" }}You will get.
  2. Cut all content except the last N elements.The opposite of taking from the end, you can also exclude the last element by using negative indices.

    • Get all content except the last element:{{ simple.multiple_item_list|slice:":-1"|join:"," }}You will get1,1,2,3,5,8,13,21,34.
    • Get all content except the last three elements:{{ simple.multiple_item_list|slice:":-3"|join:"," }}You will get1,1,2,3,5,8,13.
    • For strings:{{ "你好世界"|slice:":-1" }}You will get你好世.
  3. Combine positive and negative indices for more complex slicing sliceThe filter also supports combining positive and negative indices to define a more flexible range for extraction.

    • For example, to start from the second element (index 1) of the list and continue to the second-to-last element (not including the second-to-last):{{ ["A", "B", "C", "D", "E"]|slice:"1:-1"|join:"," }}It will outputB,C,D.

Whether it is from the beginning, from the end, or combined with positive and negative indices to define the range of truncation,sliceThe filter can meet our needs, making it more intuitive and efficient to process data in the template.

Application scenarios in practice

The one with negative indexsliceThe filter has many practical scenarios in website content operation:

  • Displaying N summaries of the latest comments or dynamics: Assuming the backend returns all comments, you might only want to display the latest 3 comments in the homepage or detail page sidebar. Use|slice:"-3:"to easily achieve this.
  • Get the last picture in the image list: If a content model returns multiple images and you only need to display the last one as a cover at a specific position,|slice:"-1:"it can be put to use.
  • Extract the end part of the article title or descriptionIn some designs, it may be necessary to display or process the specific end part of the title separately, negative indices can accurately specify.
  • Displaying partial information in the composite documentFor example, on the product comparison page, you may only be concerned with a few key parameters. You can use negative indices to quickly locate and display them.

Tip

  • While usingsliceRemember that the filtering logic is 'left closed right open', that isfromthe elements at this position will be included, whiletothe elements at this position will not be included.
  • If the specified index exceeds the actual length of the string or array,sliceThe filter usually does not cause an error, but returns an empty value or truncates as much content as possible within the valid range, making it more robust when handling dynamic or uncertain length data.
  • Chinese and English strings are uniform in index calculation, that is, a Chinese character is counted as one character for indexing.

In conclusion, in AnQi CMSsliceFilter, especially its support for negative indices, provides template developers with powerful content truncation capabilities.Mastering this feature can help us control the display of page content more flexibly and efficiently, thereby enhancing the user experience and content presentation quality of the website.


Frequently Asked Questions (FAQ)

1.sliceDoes the filter only apply to strings, or also to arrays (slice/list)? sliceThe filter is not only applicable to strings, but also to arrays (or slices in Go language). Whether it is text content or a collection of data, you can use itsliceTo perform the slicing operation.

2. What happens if the specified negative index is out of the length of the string or array?WhensliceThe system usually handles the case where the negative index used in the filter exceeds the actual length of the original string or array intelligently.It will not cause an error, but will return the result based on the actual available range.For example, if you try to slice an array of only 5 elements starting from the 10th position from the end, it may return an empty array or start slicing from the beginning of the array iffromThe index is positive and within range).

3.slicein the filterfromandtoThe index is inclusive or exclusive? sliceThe filter's index is 'left closed right open'. This meansfromThe starting position specified by the parameter isincludewhile in the extracted result,toThe ending position specified by the parameter isDo not includewhile in the extracted result. For example,"AnQiCMS"|slice:"1:4"It will take the characters at indices 1, 2, and 3, but not the character at index 4.

Related articles

How to ensure the integrity of the sliced result when截取中文字符串 using the `slice` filter (to avoid half characters)?

In Anqi CMS template development, the `slice` filter is a commonly used tool for handling strings and arrays.It can help us conveniently extract a part of the content, whether it is several elements of a list or a specified segment of a long text.However, when it comes to cutting Chinese character strings, if you are not familiar with the underlying working principle, you may encounter a common and annoying problem: the cutting result appears as 'half a character' or garbage code.

2025-11-07

How to accurately slice an array in the AnQiCMS template?

During the template development process of AnQi CMS, we often need to flexibly handle the data displayed on the page, especially when the data is presented in the form of a list or sequence.Imagine that you are designing a product list page, where you need to select the top 5 most popular products from an array of dozens of products to display at the top of the page; or, you may need to truncate a long string from the content of an article detail page to use as a summary.

2025-11-07

How will the `length_is` filter handle non-string or numeric types when comparing lengths?

AnQiCMS provides rich template filters to help us flexibly handle and display data.Among them, the `length_is` filter is often used to determine whether the length of the variable meets expectations.However, during use, one may encounter a question: What will the system do if we pass non-string or non-numeric data to the `length_is` filter for length comparison?This is not just a technical detail, but also about how we avoid potential errors in template design and ensure the accuracy of data display.

2025-11-07

How to use the `length_is` filter to determine if the character length of a user comment meets the specified requirements?

In the daily operation of AnQi CMS, we often need to manage user-generated content, especially user comments, which directly affect the activity and professionalism of the website.Content length control is one of the common requirements, for example, we hope that the comments are not too short to seem perfunctory, nor too long to affect the reading experience.Anqi CMS's flexible template engine provides a variety of powerful filters that can help us easily implement these seemingly complex validation logic.

2025-11-07

How to use the `slice` filter to extract specific parts of parameters or paths from a long URL?

In the world of AnQi CMS templates, flexible data handling is the key to improving website user experience and SEO performance.Sometimes, we need to extract a specific part from a long URL, such as path parameters, product ID, or simply display a part of the URL to keep the page concise.At this time, the `slice` filter is an extremely useful tool that can help us accurately cut any segment of a string or array.

2025-11-07

How to split a comma-separated keyword string configured in the AnQiCMS backend into an iterable keyword list?

In AnQiCMS (AnQiCMS) daily content operations, we often need to display related keywords on articles or product detail pages.These keywords not only help search engines understand the content of the page, but also guide users to discover more relevant information.In most cases, we will enter these keywords in a text box on the backend, separated by commas, for example: "website operation, SEO optimization, content marketing.

2025-11-07

What are the different splitting behaviors when the delimiter is empty or not present?

In AnQi CMS template development, the `split` filter is a very practical tool that can help us split strings into arrays according to the specified delimiter, which is very convenient when dealing with list data, tag content, or any structured text.However, when the delimiter is an empty string or does not exist in the target string, the behavior of the `split` filter shows some clever characteristics, understanding these characteristics is crucial for precise template control and avoiding potential errors.

2025-11-07

What are the main differences and application scenarios between the `make_list` filter and the `split` filter when splitting strings into arrays?

In AnQi CMS template development, it is often encountered that a string needs to be split into multiple parts for further processing or dynamic display.To meet this requirement, AnQiCMS template engine provides two very useful filters, `make_list` and `split`.Although they can both convert strings to arrays, there are obvious differences in their core functions, splitting logic, and applicable scenarios in actual use.Understanding these differences can help us handle content more efficiently and accurately.

2025-11-07