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