In AnQiCMS template development, we often need to process displayed data in various ways, such as truncating a paragraph of text or extracting specific items from a list.slice
sliceFiltering Basics: How to Accurately Extract Data
sliceThe filter is a powerful tool provided by AnQiCMS template engine, used to extract specified elements from strings (string) or arrays (slice/list). Its basic usage is very intuitive:{{ obj|slice:"start:end" }}.
objThis is the source data you want to perform the cut operation on, which can be a string variable or an array variable."start:end"This is a critical string parameter that defines the start and end positions of the cut.start: represents the starting index of the cut. The element at this position isincludingin the result. If omittedstart[for example]":end")will start cutting from the beginning of the data.end:represents the end index of the cut. The element at this position isdoes not includein the result. If omittedend[for example]"start:")will start cutting fromstartand continue cutting to the end of the data.- The index can be a positive number or a negative number. A positive index starts counting from 0 (the first element is 0). A negative index indicates counting from the end, for example
-1Represents the last element,-2Represents the second-to-last element.
Let's understand through some simple examplessliceThe basic working way of the filter:
{# 截取字符串的前三个字符 #}
{# "AnQiCMS"的索引是0,1,2,3,4,5,6。截取到索引3(不包含)就是0,1,2 #}
{{ "AnQiCMS"|slice:":3" }} {# 结果: AnQ #}
{# 截取字符串的第二个到第四个字符(索引1到4,不包含索引4) #}
{# 索引1是'n',索引2是'Q',索引3是'i' #}
{{ "AnQiCMS"|slice:"1:4" }} {# 结果: nQi #}
{# 截取数组的倒数第二个到末尾 #}
{# 假设 intList 是一个包含数字的数组,如 [1, 2, 3, 4, 5]。负数索引-2对应数字4 #}
{{ intList|slice:"-2:"|join:", " }} {# 结果: 4, 5 #}
tosliceThe result is assigned to a new variable:setandwithtags
In AnQiCMS template syntax, we can utilize{% set %}and{% with %}these tags to create new variables. ForsliceThe result after filter processing, the most commonly used and recommended way in most scenarios is to use{% set %}.
{% set %}The tag allows you to declare a new variable and assign a value anywhere in the template.The scope of this variable is local, starting from the point of definition to the end of the template file, unless it is overridden by the same variable name.{% set variableName = value %}.
{% with %}Tags are used to define temporary variables within a specific code block. These variables are only valid in the{% with %}and{% endwith %}is valid. Although it can also achieve assignment, it is usually used in most scenarios.{% set %}provides greater flexibility because the variables it defines can be accessed in a larger part of the template.
CombinesliceFilter, we can save the truncated data to a new variable like this:
`twig