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

Calendar 👁️ 63

In AnQiCMS, the template is the key to building dynamic content, allowing us to flexibly display data.In the process of template development, it is often necessary to perform string or list (usually a slice in Go templates, which can be understood as an array) truncation operations.AnQiCMS provides powerfulslicefilter to handle such needs.

Deep understandingsliceBasic usage of the filter.

sliceThe filter is mainly used to extract elements from strings or lists within a specified range. Its basic syntax is{{obj|slice:"from:to"}}of whichobjis the data you want to operate on,fromIs the starting index (inclusive),tois the end index (not included).

For example, if you have a list containing numbers from 1 to 10 and you want to extract indices 3 to 6 (i.e., the fourth to the seventh numbers), you can do it like this:

{% set my_list = "1,2,3,4,5,6,7,8,9,10"|split:"," %}
{{ my_list|slice:"3:7"|join:"," }}

The output of this code will be4,5,6,7This indicates:sliceThe filter follows the convention of slicing operations in most programming languages when handling positive indices: the starting index is included in the result, while the ending index is not.

Unveiling negative index: A convenient operation starting from the end

However,sliceThe filter has a not very obvious but very practical feature - it supports negative indices.This means we can count from the end of the data without relying on the exact length, and perform the slicing operation.This provides great convenience when dealing with data of uncertain length or dynamic changes.

When using negative indices,-1represents the last element of the data,-2Representing the second-to-last element, etc. This method greatly simplifies the logic of operating on data from the end, especially when we need to perform 'reverse slicing'.

How to use negative index for reverse truncation?

Mastering the use of negative indices can allow you to achieve more efficient and flexible data extraction in the AnQiCMS template. Here are some common scenarios for negative index extraction and their applications:

  1. Get the last N elements of the dataIf you want to get the last few elements of a list or string, you can use-N:This format. It will start from the N-th element from the end and go all the way to the end.

    {% set my_list = "1,1,2,3,5,8,13,21,34,55"|split:"," %}
    {# 获取列表的最后3个元素 #}
    {{ my_list|slice:"-3:"|join:"," }} {# 输出: 21,34,55 #}
    
    {% set my_string = "AnQiCMS是一个优秀的内容管理系统" %}
    {# 获取字符串的最后5个字符 #}
    {{ my_string|slice:"-5:" }} {# 输出: 管理系统 #}
    
  2. Exclude the N elements from the end of the data.The opposite of getting the last element, if you need to truncate from the beginning of the data but exclude the last N elements, you can use:-Nformat.

    {% set my_list = "1,1,2,3,5,8,13,21,34,55"|split:"," %}
    {# 排除列表的最后3个元素 #}
    {{ my_list|slice:":-3"|join:"," }} {# 输出: 1,1,2,3,5,8,13 #}
    
    {% set my_string = "AnQiCMS是一个优秀的内容管理系统" %}
    {# 排除字符串的最后5个字符 #}
    {{ my_string|slice:":-5" }} {# 输出: AnQiCMS是一个优秀的内容 #}
    
  3. Truncate the elements from the Nth to the Mth from the endBy combining the use of negative indices, you can precisely control the range of slicing starting from the end of the data. For example, to get the fifth element from the end to the second element from the end (excluding the second element from the end).

    {% set my_list = "1,1,2,3,5,8,13,21,34,55"|split:"," %}
    {# 获取倒数第5个到倒数第2个元素(不含倒数第2个) #}
    {{ my_list|slice:"-5:-2"|join:"," }} {# 输出: 8,13,21 #}
    

    Please note that the logic here is stillfromto includeto(excluding).slice:"-5:-2"means fromlen-5starting at the position,截取到len-2to the position before.

Universality of strings and arrays

sliceThe negative index feature of the filter is not only applicable to lists (slices), but also to string data as well.It is also worth mentioning that it can correctly handle strings containing Chinese characters, where each Chinese character is treated as a unit for indexing and slicing, which is very friendly for the development of multilingual websites. For example,"你好时间"|slice:"1:3"It will output.好世Perfectly handles Chinese characters.

Application scenarios in practice

In daily AnQiCMS content operations, negative index of thesliceThe filter can help us quickly achieve various needs. For example:

  • Display the latest comments/dynamics:Quickly display the latest N comments or user dynamics in the sidebar of the article detail page.
  • Extract a brief summary:When the content of the article is too long and it is necessary to display an abstract that does not include the last few words or sentences, you can use:-NExclude the end content.
  • Product list display:On the homepage or other important positions, only display the latest few products listed, or remove some less important information at the end.

By reasonable applicationsliceThe negative index feature of the filter allows you to control the display of data in AnQiCMS templates more flexibly and efficiently, thereby enhancing the user experience of the website.


Frequently Asked Questions (FAQ)

Q1:sliceCan the index in the filter be a decimal?A1: No.sliceThe index in the filter (includingfromandto) must be an integer. If you try to use a decimal, the system will report an error or fail to parse correctly.

Q2: What will happen if I try to use a negative index that exceeds the length of the data? For example, a list with only 5 elements, I useslice:"-10:"what will you get?A2:sliceThe filter usually performs intelligent error handling when processing negative indices out of range.

  • IffromThe absolute value of a negative index is greater than the length of the data, it will start cutting from the beginning of the data (equivalent tofrom:0) For example,"1,2,3,4,5"|split:","|slice:"-10:"You will get1,2,3,4,5.
  • IftoThe absolute value of a negative index is greater than the length of the data, it will truncate to the end of the data. For example,"1,2,3,4,5"|split:","|slice:":-10"You will get an empty string or an empty list.Overall,it will try to return a valid result rather than reporting an error directly.

Q3:sliceFilters andtruncatechars/truncatewordsWhat is the difference between these string truncation filters?A3:sliceThe filter is based on the index position for precise extraction, it does not care about the extraction

Related articles

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

In AnQi CMS template development, we often need to flexibly handle the displayed content, such as extracting key parts from a paragraph of text or simply displaying several items from the list.At this point, the `slice` filter is very practical.It can help us accurately extract a segment of content from the middle of a string or array (a slice in Go language).

2025-11-08

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 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

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