How to get the first or last element in the list of 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 articles as headlines, or highlighting a popular product.In AnQiCMS templates, flexibly obtaining the first or last element of the list is the key to meeting these requirements.It is fortunate that AnQiCMS provides a variety of intuitive and efficient methods to handle these scenarios, making content display more vivid.

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

Using loop built-in variables to dynamically identify

The first method is to useforLoop built-in special variablesforloop.Counterandforloop.Revcounter.forloop.CounterIt will increase by 1 each time the loop occurs, indicating which element is currently being processed;forloop.RevcounterThen counting from the last element of the list backwards, the value indicates how many elements away from the end the current element isforloop.Revcounteris 1).

This method is especially suitable for when you need to apply special styling 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 == 1Exactly points to the first element in the loop,forloop.Revcounter == 1This indicates the last element. The advantage of this method is that you can complete the processing and recognition of all elements in a single loop, making the code structure clear.

UsefirstandlastThe filter is directly obtained

When your need is just to get the first or last element of the list without traversing the entire list, AnQiCMS provides a more direct filter:firstandlast.These filters can be directly applied to list variables, returning the element you need.It is best to check if the list is empty before using these filters to avoid potential errors.

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 use{% set %}Label to assign values to the elements obtained, making it easier to use in subsequent code.

With the help ofsliceFilter for flexible slicing

If your scenario requires more granular control or you want to get any segment of elements from the list,sliceThe filter will be very useful. It allows you to 'slice' the list by specifying start and end indices. To get the first element, you can useslice:Using a negative index, you can get the last element by coordinating with the starting index.

It is worth noting that,sliceThe filter returns a list (array) containing the element even if only one element is extracted, rather than the element itself. Therefore, you may need to further cooperatefirstFilter to get the individual element.

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