How to use `slice` to get the last N elements of an array in AnQiCMS template?

Calendar 👁️ 75

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 elementsNGreater 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)

  1. 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).

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

Related articles

How to get only the first N characters of a string using the `slice` filter?

In website content display, we often need to truncate a part of the long text as a preview, abstract, or to ensure the neat layout of the page.For example, it is crucial to control the text length precisely when displaying the article summary on the article list page or setting `meta description` content for search engine optimization (SEO).AnQiCMS (AnQiCMS) powerful template engine provides a variety of flexible filters to help us easily meet these needs.

2025-11-08

How to extract elements from a specified range in AnQi CMS template?

In the powerful template system of Anqi CMS, we often need to precisely control the display of content.Whether it is an article list, product album, or custom data model, data is often presented in the form of an array.Sometimes, we may only need to display a part of the array, such as only showing the latest three records, or picking out a few images from a picture list.At this point, the `slice` filter provided by AnQi CMS comes in handy, as it helps us elegantly extract elements within a specified range from the array

2025-11-08

How to accurately extract the specified position element of a string in Anqi CMS template?

In AnQiCMS template development, we often need to flexibly handle text content, such as extracting the first few words of a long description as a summary, or extracting a specific part of the filename.AnQiCMS's powerful template engine provides a variety of practical filters (filter) to meet these needs, among which the "slice" filter is a powerful tool for precise string truncation.It allows us to easily extract any segment of content we want from a string or array.

2025-11-08

Default display template file for article detail page

The Anqi CMS provides a flexible and powerful template mechanism for handling the display of website article detail pages, allowing content operators and developers to finely control the presentation of each article according to actual needs.Understanding the search logic of the default template file is the basis for efficient content management and personalized customization.Firstly, the template files of Anqi CMS are all stored in the `/template` directory and use `.html` as the file extension.

2025-11-08

How does the `slice` filter handle string or array index out of bounds situations?

In Anqi CMS template development, the flexibility of data display is crucial for building dynamic and user-friendly websites.The `slice` filter is a powerful and practical tool that helps us accurately extract part of the string or array content.However, when performing such operations, we are bound to encounter index out of bounds situations, that is, attempting to access a position beyond the data range.Fortunately, the `slice` filter of Anqi CMS has considered these edge cases and provided a set of elegant solutions.

2025-11-08

In AnQiCMS template, how to implement `slice` to extract a segment of content from a string?

In AnQi CMS template development, we often need to flexibly handle the displayed content, such as extracting key parts from a paragraph of text or simply displaying several items from the list.At this point, the `slice` filter is very practical.It can help us accurately extract a segment of content from the middle of a string or array (a slice in Go language).

2025-11-08

Does Go template's `slice` filter support negative indices? How to use it to slice in reverse order?

In AnQiCMS, templates are the key to building dynamic content, allowing us to flexibly display data.In the process of template development, it is often encountered that string or list (usually slice in Go template, which can be understood as an array) truncation operations need to be performed.AnQiCMS provides a powerful `slice` filter to handle such needs.### Deeply understand the basic usage of `slice` filter The `slice` filter is mainly used to extract specified elements from strings or lists

2025-11-08

How to avoid Chinese garbled or incomplete truncation caused by the `slice` operation in AnQiCMS template?

When using AnQiCMS for website content development, you may sometimes encounter the situation where, when using the `slice` filter in the template to process Chinese content, the content is truncated and incomplete, which undoubtedly affects user experience and the accuracy of content presentation.Even though the underlying design of the system aims to avoid garbled characters, it is particularly important to understand its mechanism due to the characteristics of Chinese multi-byte characters and the expected display effects.

2025-11-08