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 may only care about a part of these data, such as the latest few articles, or a specific number of elements at the end of the list.This is, AnQiCMS built-in thesliceThe filter function is particularly powerful and convenient. It allows us to flexibly extract elements from an array or string within a specified range.This article will introduce how to use AnQiCMS templatesliceFilters, especially how to efficiently get the last N elements of an array.
UnderstandingsliceFilter
AnQiCMS's template engine is similar to Django, providing a rich set of filters to handle data.sliceOne of the filters is, its basic syntax is{{ obj|slice:'from:to' }}.
Among them,objrepresents the array (or slice) or string variable you want to operate onfromandtospecifies the start and end positions of the cut.fromIs included as the starting index,toIs not included as the ending index. It should be noted that the index starts from 0. For example,slice:"0:3"Will extract the elements at indices 0, 1, and 2.
sliceThe filter also supports negative indices, which is the key to implementing the retrieval of 'the last N elements.' Negative indices start counting from the end of the array,-1representing the first element from the end,-2represent the second to last, and so on.
Get the "last N elements" of the array
To get the last N elements of the array, we can usesliceThe negative index feature of the filter. The specific method is tofromthe parameter to-N(where N is the number of elements you want to retrieve), andtothe parameter can be omitted. Whentothe parameter is omitted, sliceThe filter will automatically truncate to the end of the array.
For example, if you want to get the last 3 elements of the array, the syntax is.{{ obj|slice:'-3:' }}.
If the original array length is less than N,sliceThe filter returns all available elements without error, which makes it very robust when handling arrays of uncertain length.
Practice exercise: Get the last N articles of the latest article list
Assuming we have a througharchiveListThe article list obtained by the tag, and we hope to extract the latest 5 articles from this list for display.
First, for the sake of demonstration, we usesetLabel a list containing 10 articles:
{# 模拟一个包含10篇文章的数组 #}
{% set all_articles = "文章1,文章2,文章3,文章4,文章5,文章6,文章7,文章8,文章9,文章10"|split:"," %}
{# 现在,我们尝试获取这个 all_articles 数组的后 5 篇文章 #}
{% set last_five_articles = all_articles|slice:"-5:" %}
<div>
<h3>最近的 5 篇文章:</h3>
<ul>
{% for article in last_five_articles %}
<li>{{ article }}</li>
{% endfor %}
</ul>
</div>
Run the above code, and you will see the output result:
最近的 5 篇文章:
- 文章6
- 文章7
- 文章8
- 文章9
- 文章10
This provesslice:"-5:"Successfully retrieved the last 5 elements of the array.
In a real project, you can combine it like thisarchiveListTag to get the latest articles:
{% archiveList all_articles with type="list" limit="20" order="id desc" %} {# 获取最新的20篇文章 #}
{% if all_articles %}
{# 从这20篇文章中,进一步获取后5篇(即最旧的5篇,因为order="id desc"是从新到旧排序) #}
{# 如果all_articles是按id desc(最新在前)排序的,那么取后N个元素实际上是取最旧的N个。
如果想取最新的N个,通常是直接调整limit参数,或者在前端展示时重新排序。
这里我们假设原始需求是获取“列表顺序中的后N个元素”,即使在id desc的情况下,
也只是演示slice的功能。
#}
{% set recent_articles = all_articles|slice:"-5:" %}
<div>
<h3>最新列表中的后 5 篇文章:</h3>
<ul>
{% for article in recent_articles %}
<li><a href="{{ article.Link }}">{{ article.Title }}</a></li>
{% endfor %}
</ul>
</div>
{% else %}
<p>没有找到任何文章。</p>
{% endif %}
{% endarchiveList %}
Please note that,archiveList,order="id desc"It means that the latest articles are at the top. If you want to get the "latest 5 articles", just uselimit="5"Generally more direct and effective.slice:"-5:"The scenario is more about an already obtained and sequentially fixed array, where you need to extract a fixed number of elements from the end.For example, you may first filter out a complex article list based on other conditions, and then you need to extract data from the end of this complex list.
Points to note
- The starting point of negative indices:Negative index
-NIt indicates starting from the Nth element from the end of the array to the end. For example, in an array containing 10 elements,-1Point to the last element (index 9),-5Point to the fifth element from the end (index 5). - Handle empty arrays or insufficient length:If attempting to get a number of elements
NGreater than the actual length of the array,sliceThe filter does not throw an error, but rather returns all the available elements in the array. For example, an array with only 2 elements uses|slice:'-5:'It will still return these 2 elements. fromandtoThe closed and open interval:Remember,sliceoffromIt includes the starting position,toIt does not include the end position. Usually, we omit the next N elements.toLet it default to the end of the array.- String and array:
sliceThe filter is not only applicable to arrays (slice), but also to strings.When a string is used, it will be truncated by character (not by byte), even Chinese characters can be processed correctly. For example{{ "你好世界"|slice:"-2:" }}It will return "world" correctly.
BysliceThe filter combined with negative index allows AnQiCMS template developers to easily extract the last N elements from an array or list, which is very practical when displaying the latest content, related recommendations, or brief summaries.Mastering this skill can effectively enhance the flexibility and efficiency of template development.
Frequently Asked Questions (FAQ)
Question:
sliceCan the filter be used to get the first N elements of the array?Answer: Of course. You canfromis set to0or omitted,tois set toNFor example,{{ obj|slice:":5" }}Will get the first 5 elements of the array (indices 0 to 4).**Question: If I want to start from the middle of the array