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

Calendar 👁️ 77

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

Related articles

Can the `removetags` filter remove specified tags from HTML content (such as `<i>`)?

In AnQiCMS (AnQiCMS) such a flexible content management system, handling HTML content is a common task in daily operations.Sometimes, we want to remove certain tags from the content without completely stripping all HTML structure, in order to maintain consistency in the page display or meet design specifications.At this time, the `removetags` filter has become a very practical tool.### Understanding the `removetags` filter The `removetags` is an embedded filter provided by the Anqi CMS template engine

2025-11-08

How to remove all HTML tags from dynamically generated HTML content?

In website content management, we often encounter a common requirement: to extract pure text information from dynamically formatted content.The reasons behind this are diverse, such as the need to generate concise and clear meta descriptions (Meta Description) for search engines, to display unformatted summaries on list pages, or simply to obtain clean plain text content for data analysis.AnQi CMS as a flexible and efficient content management system, fully considering these scenarios, through its powerful template engine and built-in filters

2025-11-08

How does the `yesno` filter handle boolean or null values and customize the display of 'Yes/No/Unknown'?

In AnQi CMS template development, how to display boolean (true/false) states or handle unknown (empty) values in an intuitive and concise manner is an important aspect for improving user experience and code readability.The `yesno` filter is designed for this purpose, it can simplify complex logical judgments into a single line of code, and allows you to customize the output results, such as displaying as "yes/no/unknown".### `yesno` filter: Smart converter for boolean and null values In a content management system, we often encounter situations where we need to display whether a project is enabled or a feature is turned on

2025-11-08

What is the use of the `addslashes` filter in JavaScript or JSON data output?

In website content management, especially when we want to insert dynamic data into JavaScript code or construct JSON formatted output, handling special characters is a non-negligible aspect.The AnQiCMS template engine provides a rich set of filters to help us elegantly handle such issues, with the `addslashes` filter being a practical tool specifically designed for this kind of scenario.The purpose of the `addslashes` filter explained

2025-11-08

Does the `first` and `last` filter return a single Chinese character when processing Chinese string?

In Anqi CMS template development, we often use various filters (filters) to format or extract data.The `first` and `last` filters are among the most common ones, used to get the first or last element from a string or array.Many friends who use AnQi CMS may be curious, when we process data containing Chinese characters, such as article titles or content snippets, will these two filters return single Chinese characters?The answer is: **Yes, the `first` and

2025-11-08

How to encode URL parameters to ensure the correctness and security of the link?

In the daily operation of Anqi CMS, we often need to deal with various website links, which not only need to be beautiful and SEO-friendly, but more importantly, they must work correctly and safely.Among these, encoding URL parameters is a seemingly trivial but crucial link, which is directly related to the integrity and user experience of our website links.Why is URL parameter encoding so important?Imagine if your website had a search function, and users entered keywords containing spaces, special characters, or even Chinese characters, such as "Anqi CMS"}

2025-11-08

What is the difference between the `urlencode` and `iriencode` filters in URL escaping?

In the daily content operation and website development of Anqi CMS, we often need to handle URL links to ensure that they are both secure and effective, and can be correctly parsed by browsers and search engines.This is an indispensable part of URL escaping (also known as encoding).Our Anqi CMS provides us with two very practical filters: `urlencode` and `iriencode`, both of which can help us with URL escaping, but their purposes and processing methods are different in actual application.###

2025-11-08

How does AnQiCMS automatically identify URL links in text and convert them into clickable `<a>` tags?

During content creation and publication, we often encounter situations where we need to cite external sources or share relevant links.If these URLs are in plain text form, users not only need to manually copy and paste them, but it will also affect the reading experience and the professionalism of the website.Anqi CMS knows this pain point, and therefore integrated the intelligent URL automatic recognition and conversion function from the beginning of the system design, making your content publishing more efficient and convenient, and improving the user experience accordingly.### Intelligent recognition, automatic conversion: Say goodbye to manual operation AnQi CMS through its powerful template engine

2025-11-08