How to get the first or last element of a list in AnQiCMS template?

When building a website, we often encounter the need to pick out the most special one from a pile of content, such as displaying the latest article as the headline or highlighting a popular product.In the AnQiCMS template, flexibly obtaining the first or last element of the list is the key to meeting these requirements.Luckily, AnQiCMS provides various intuitive and efficient methods to handle these scenarios, making content display more vivid.

AnQiCMS's template system adopts a syntax similar to the Django template engine, which makes it very convenient for content developers to create templates. When we usearchiveList/categoryList/navListTags usually return an array (or a slice in Go language) object when they retrieve content lists from the background, which contains all the elements we need to display.Next, let's discuss how to easily get the first or last element we want in these lists.

Using the built-in loop variable to dynamically identify

The first method is to useforThe built-in special variable of the loopforloop.Counterandforloop.Revcounter.forloop.CounterIt will increment from 1 each time the loop runs, indicating which element is currently being processed; andforloop.RevcounterThen starting from the last element of the list, it represents how many elements the current element is away from the end (the last elementforloop.RevcounterThe value is 1).

This method is especially suitable for when you need to apply special styles or display different information to the first or last element while traversing the entire list.

For example, we want to find the first and last articles from the latest list:

{% archiveList recentArchives with type="list" limit="5" %}
    {% for item in recentArchives %}
        {% if forloop.Counter == 1 %}
            <div class="featured-item">✨ 热门头条:<a href="{{ item.Link }}">{{ item.Title }}</a></div>
        {% elif forloop.Revcounter == 1 %}
            <div class="last-item">⏳ 历史回顾:<a href="{{ item.Link }}">{{ item.Title }}</a></div>
        {% else %}
            <div>普通文章:<a href="{{ item.Link }}">{{ item.Title }}</a></div>
        {% endif %}
    {% empty %}
        <p>暂时没有文章内容可供展示。</p>
    {% endfor %}
{% endarchiveList %}

In this example,forloop.Counter == 1It precisely points to the first element in the loop, andforloop.Revcounter == 1This indicates the last element. The advantage of this method is that you can complete all element processing and recognition in one loop, making the code structure clear.

UsefirstandlastThe filter directly gets

When your need is simply to obtain the first or last element of the list without traversing the entire list, AnQiCMS provides a more direct filter:firstandlastThese filters can be directly applied to list variables to return the desired element.Before using these filters, it is best to check if the list is empty to avoid potential errors.

Assuming we need to display the latest product image and the oldest product name separately at the top of the page:

{% archiveList products with moduleId="2" order="id desc" limit="10" %}
    {# 获取第一个(最新)产品 #}
    {% set latestProduct = products|first %}
    {% if latestProduct %}
        <div class="highlight-product">
            <img src="{{ latestProduct.Logo }}" alt="{{ latestProduct.Title }}" class="product-banner">
            <h3>新品上市:{{ latestProduct.Title }}</h3>
        </div>
    {% endif %}

    {# 获取最后一个(最旧)产品 #}
    {% set oldestProduct = products|last %}
    {% if oldestProduct %}
        <div class="vintage-product">
            <p>经典回顾:{{ oldestProduct.Title }}</p>
        </div>
    {% endif %}
    
    {# 您可以继续在这里展示产品列表的其余部分 #}
    {% for item in products %}
        {% if item != latestProduct and item != oldestProduct %} {# 避免重复显示第一个和最后一个 #}
            <div class="product-item">
                <a href="{{ item.Link }}">{{ item.Title }}</a>
            </div>
        {% endif %}
    {% empty %}
        <p>没有找到任何产品。</p>
    {% endfor %}
{% endarchiveList %}

This method is more concise and efficient, especially suitable for scenarios where you only need to extract a specific element for independent display. Please note that we used{% set %}Label to assign values to the elements obtained, so that they can be used more conveniently in subsequent code.

WithsliceFilter for flexible slicing.

If your scenario requires finer-grained control, or you want to get any segment of elements in the list, thensliceThe filter is very useful. It allows you to 'slice' the list by specifying a start and end index. To get the first element, you can useslice:With the starting index, you can use negative indices to get the last element.

It should be noted that,sliceThe filter even if it extracts only one element, its return result is still a list (array) containing that element, rather than the element itself. Therefore, you may need to further cooperatefirstFilter to get a single element from it.

For example, we want to display the Logo of the first category, as well as