In AnQiCMS, templates are the key to building dynamic content, allowing us to flexibly display data.During template development, you often encounter scenarios where you need to perform truncation operations on strings or lists (usually slices in Go templates, which can be understood as arrays).sliceUse the filter to handle such needs.
Deep understandingsliceBasic usage of the filter
sliceThe filter is mainly used to extract specified elements from strings or lists. Its basic syntax is{{obj|slice:"from:to"}}where,objis the data you want to operate on,fromis the start index (inclusive),tois the end index (not included).
For example, if you have a list containing numbers 1 to 10 and you want to slice from index 3 to index 6 (that is, the fourth to the seventh number), 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:"," }}
This code's output will be4,5,6,7This indicatessliceThe 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.
Revealing Negative Index: A Convenient Operation Starting from the End
However,sliceThe filter has a not very noticeable but very practical feature—it supports negative indices.This means we can count from the end of the data without depending on the exact length and perform the cutting operation directly.This provides great convenience when dealing with data of uncertain or dynamic length.
When using negative indices,-1represents the last element of the data,-2Represents the second-to-last element, and so on. This method greatly simplifies the logic for operating on data from the end, especially when we need to perform a 'reverse slice'.
How to use negative indices for reverse slicing?
Mastering the usage of negative indices can enable you to achieve more efficient and flexible data slicing in AnQiCMS templates. The following are some common scenarios of negative index slicing and their applications:
Retrieve the last N elements of the dataIf you want to get the last few elements of a list or string,
-N:The format. This will start from the N-th element from the end and continue 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:" }} {# 输出: 管理系统 #}Exclude the N elements at the end of the data.In contrast to getting the last element, if you need to slice 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是一个优秀的内容 #}Slice elements from the Nth to the Mth from the endBy combining negative indices, you can precisely control the range of slicing 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 still
from(including) toto(excluding).slice:"-5:-2"means fromlen-5the position, and cut tolen-2English position before.
The versatility of strings and arrays.
sliceThe negative index feature of the filter is not only applicable to lists (slices), but also to string data.It is also worth mentioning that it can correctly handle strings containing Chinese characters. A Chinese character is treated as a unit for indexing and slicing, which is very friendly for the development of multilingual websites."你好时间"|slice:"1:3"It will output好世Perfectly handles Chinese characters.
Actual application scenarios
In daily AnQiCMS content operation, negative indices,sliceFilter can help us quickly achieve a variety of needs. For example:
- Show the latest comments/moments:In the sidebar of the article detail page, quickly display the latest N comments or user moments.
- Extract summary:When the article content is too long and it is necessary to display an abstract that does not include the last few words or sentences, you can
:-NExclude the end content. - Product list display:On the homepage or other important positions, only display a few recently listed products, or remove some less important information at the end.
By making reasonable use ofsliceThe 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.
Common Questions (FAQ)
Q1:sliceFilter index can be a decimal?A1: No.sliceFilter index (includingfromandto) must be an integer. If you try to use a decimal, the system will report an error or cannot parse it correctly.
Q2: What happens 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 be obtained?A2:sliceThe filter usually performs intelligent error handling when processing negative indices out of range.
- If
fromThe 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. - If
toThe 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"It will return an empty string or an empty list. In general, it will try to return a valid result instead of directly reporting an error.
Q3:slicefilters andtruncatechars/truncatewordsWhat is the difference between the filters that cut strings?A3:sliceThe filter is based on index position for precise truncation, it does not care about the truncation