In AnQiCMS template development, we often need to handle list or array type data, such as article lists, product lists, etc.Sometimes, we might be interested in only a part of these data, such as the latest few articles, or a specific number of elements at the end of the list.sliceThe filter is particularly powerful and convenient.It allows us to flexibly extract elements from a specified range within an array or string.sliceFilter, especially how to efficiently obtain the last N elements of an array.

UnderstandingsliceFilter

AnQiCMS's template engine is similar to Django, providing rich filters to handle data.sliceFilter is one of them, its basic syntax is{{ obj|slice:'from:to' }}.

Among them,objrepresents the array (or slice) or string variable you want to operate on.fromandtospecifies the start and end positions of the extraction.fromIs included as the starting index,toIs not included as the ending index. It is important to note that indexing starts from 0. For example,slice:"0:3"It will截取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.-1represents the last element.-2represent the second-to-last, and so on.

Get the 'last N elements' of the array

To get the last N elements of an array, we can usesliceThe negative index feature of the filter. Specifically, it is done by...fromparameter settings-N(where N is the number of elements you want to get), and...toThe parameter can be omitted. When...toThe 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 length of the original array is less than N,sliceThe filter will return all available elements without error, making it very robust when handling arrays of uncertain length.

Practice: Retrieve the last N articles in the latest article list

Suppose we have a way toarchiveListThe article list obtained by the tag, and we hope to extract the latest 5 articles from this list for display.

Firstly, for the sake of demonstration, we first usesetLabel a simulation of an array 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 is:

最近的 5 篇文章:
- 文章6
- 文章7
- 文章8
- 文章9
- 文章10

This provesslice:"-5:"Successfully retrieved the last 5 elements of the array.

In actual projects, you can combine it like thisarchiveListTags 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 inarchiveListin,order="id desc"means that the latest articles are displayed at the top. If you want to get the "latest 5 articles", you can directly uselimit="5"is usually more direct and effective.slice:"-5:"The scenario is more for a fixed and ordered array that has already been obtained, where you need to extract a fixed number of elements from the end.For example, you might first filter out a complex list of articles based on other conditions, and then need to extract data from the end of this complex list.

Precautions

  • The starting point of negative indices:negative indices-NStarts from the Nth element from the end and goes until the end of the array. For example, in an array with 10 elements,-1points to the last element (index 9),-5Point to the last fifth element (index 5).
  • Handle empty arrays or arrays with insufficient length:If you try to get more elementsNThan the actual length of the array,sliceThe filter will not raise an error, but will return all available elements in the array. For example, an array with only 2 elements using|slice:'-5:'will still return these 2 elements.
  • fromandtois: Remember,sliceoffromContains the starting position,toDoes not include the end position. For getting the next N elements, we usually omitto, making it default to the end of the array.
  • String and array: sliceThe filter applies not only to arrays (slice) but also to strings.When used with a string, it will truncate by character (not by byte), which can correctly handle Chinese characters.{{ "你好世界"|slice:"-2:" }}Will correctly return “world”.

PasssliceWith the filter combined with negative indices, template developers of AnQiCMS can very conveniently extract the last N elements from an array or list. This is very practical when displaying the latest content, related recommendations, or brief summaries.Master this skill to effectively enhance the flexibility and efficiency of template development.


Common Questions (FAQ)

  1. Q:sliceCan the filter be used to get the first N elements of an array?Answer: Of course. You can eitherfromset0or omit,tosetNFor example,{{ obj|slice:":5" }}Get the first 5 elements of the array (indices 0 to 4).

  2. **Question: If I want to select elements from the middle of the array