How to determine whether the current item is the first or last in a looped article list so that special styles can be displayed?

Calendar 👁️ 69

In website content management, it is often encountered that there is a need for the first or last element of an article list, product list, or other data list to have a special style, such as the first article title being particularly prominent, or the last product detail not having a bottom separator line.This not only helps to highlight the key points, but also makes the visual effects of the page more hierarchical.AnQiCMS (AnQiCMS) powerful template engine provides us with a simple and efficient way to meet these customized needs.

In the Anqi CMS template system, we usually use{% for ... in ... %}tags to loop display articles, products, or other data lists. ThisforThe loop tag can not only traverse data, but it also has several very practical variables that can help us easily judge the current element being looped to the number of elements in the list, or how many elements are left to the end of the list.

Identify the first element of the list usingforloop.Counter

To determine if the current element is the first in the list, we can useforloop.Counterthis built-in variable. Inforeach iteration of the loop,forloop.CounterIt will return a number starting from1which represents the current element's index. Therefore, whenforloop.Counter == 1it means we are processing the first element in the list.

For example, suppose you are iterating through a series of articles and you want to add a specialfirst-itemCSS class:

{% archiveList articles with type="list" limit="10" %}
    {% for item in articles %}
        <div class="article-item {% if forloop.Counter == 1 %}first-item{% endif %}">
            <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
            <p>{{ item.Description | truncatechars:100 }}</p>
            <span>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
        </div>
    {% empty %}
        <p>暂时没有文章发布。</p>
    {% endfor %}
{% endarchiveList %}

In the code above,{% if forloop.Counter == 1 %}Check if the current article is the first. If it is, it willdivAdd extra to the elementfirst-itemThis class name.

Utilize to identify the last element in the list:forloop.Revcounter

withforloop.Countersimilar,forloop.RevcounterThe variable returns how many elements are left in the list from the current element. Whenforloop.Revcounter == 1It means that the current element is the last one in the list.

If you want to add an article to the last one in the list.last-itemCSS class, in order to remove the bottom border, for example, the template can be written as:

{% archiveList articles with type="list" limit="10" %}
    {% for item in articles %}
        <div class="article-item {% if forloop.Revcounter == 1 %}last-item{% endif %}">
            <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
            <p>{{ item.Description | truncatechars:100 }}</p>
            <span>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
        </div>
    {% empty %}
        <p>暂时没有文章发布。</p>
    {% endfor %}
{% endarchiveList %}

In this way, only the last article element in the list will obtainlast-itemclass, you can control its style accurately through CSS.

Combined use: more complex style control

You can also use these two variables with{% if %}/{% elif %}/{% else %}Combine logic labels to achieve more complex style control, for example, applying different styles to the first, last, and middle elements:

{% archiveList articles with type="list" limit="10" %}
    {% for item in articles %}
        <div class="article-item
            {% if forloop.Counter == 1 %}first-item
            {% elif forloop.Revcounter == 1 %}last-item
            {% else %}middle-item
            {% endif %}">
            <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
            <p>{{ item.Description | truncatechars:100 }}</p>
            <span>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
        </div>
    {% empty %}
        <p>暂时没有文章发布。</p>
    {% endfor %}
{% endarchiveList %}

Once the conditional logic in the template adds a special class name to the corresponding HTML element, you just need to define the styles for these class names in your CSS file. For example:

/* style.css */
.article-item {
    padding: 10px;
    margin-bottom: 15px;
    border-bottom: 1px dashed #eee;
}

.article-item.first-item {
    background-color: #f9f9f9; /* 第一个元素背景色不同 */
    border-top: 2px solid #007bff; /* 顶部加粗边框 */
    padding-top: 20px;
}

.article-item.last-item {
    margin-bottom: 0; /* 最后一个元素移除底部外边距 */
    border-bottom: none; /* 最后一个元素移除底部边框 */
}

.article-item.middle-item {
    /* 中间元素的通用样式 */
}

This method has extremely strong versatility, it is not only suitable forarchiveListtags, but also for all the use offorloop to traverse data scenarios, for examplecategoryList/pageList/navListetc. By using it flexiblyforloop.Counterandforloop.RevcounterYou can fine-tune the style of each list display on the website, greatly enhancing the user experience and visual effects of the website.


Frequently Asked Questions (FAQ)

Q1: Does this method apply to allforloops?

A: Yes,forloop.Counterandforloop.RevcounterIs an Aanqi CMS template engine inforLoop built-in variables, they are in all typesforLoop are universal, no matter if you are traversing articles (archiveList), categories (categoryList), navigation items (navListThis JSON array contains objects with a "key" and a "value" field. The "value" field can be any data type, such as a string, number, or object. The "key" field is an integer that represents the position of the object in the array. To determine the current position of an element in the loop, you can use either the "key" field or the index of the element in the array. Whether it is a data list or any other data list, both methods can be used to determine the current loop position.

Q2: Can I apply special styles to even or odd items in the list?

A: Of course. You can still combineforloop.Counterto implement modulo operation. For example, to add style to even items (the 2nd, 4th, 6th items, etc.), you can use{% if forloop.Counter % 2 == 0 %}even-item{% endif %}; to add style to odd items, you can use{% if forloop.Counter % 2 != 0 %}odd-item{% endif %}.

Q3: If my article list may be empty, how can I avoid displaying incorrect styles or empty labels?

A: Safe CMS offorLoop tags support one{% empty %}branch. When the data you loop through is empty,{% empty %}and{% endfor %}The content between the quotes will be rendered, butforThe content within the loop will not be displayed. This can effectively avoid unnecessary HTML structures or style issues when there is no data, ensuring a clean page and a good user experience. For example:

{% archiveList articles with type="list" limit="10" %}
    {% for item in articles %}
        <!-- 这里是文章内容,如果列表不为空则显示 -->
    {% empty %}
        <p>暂无相关内容。</p> <!-- 如果列表为空,则显示这条消息 -->
    {% endfor %}
{% endarchiveList %}

Related articles

How to define and temporarily store variables in a template for easy content display and reuse?

When building a website, we often encounter situations where we need to repeat certain information or adjust content flexibly according to different contexts.If each time is hard-coded, it is not only inefficient but also quite麻烦 to maintain later.AnQiCMS (AnQiCMS) fully understands this, its template system provides various flexible ways to define and temporarily store variables in templates, thus achieving convenient display and efficient reuse of content.Why do you need to define and store variables in templates?

2025-11-08

How can AnQi CMS protect the copyright of original content through anti-crawling and watermark features when displayed?

On a day when digital content is increasingly abundant, the value of original content is self-evident, serving as the cornerstone for attracting users and building brand images on websites.However, the issues of content theft and malicious collection that follow also make countless creators and operators headache.Hardly written articles, carefully designed images, may be borrowed by others in a moment, even copied and pasted directly, which not only severely打击s the original enthusiasm, but also actually harms the intellectual property rights.For website operators, original content is the core competitiveness of the website.

2025-11-08

How to get and display the current year in a template for dynamic content such as copyright information?

When operating a website, we often need to display the current year in the footer copyright statement, for example, “© 2023 All Rights Reserved.”. With the passage of time, this year needs to be updated annually, and if manually modified, it is undoubtedly a repetitive and easily overlooked task.AnQi CMS fully considers this common demand and provides a very intuitive and powerful template tag that allows you to easily realize the dynamic display of years, keeping your website's copyright information always up to date.###

2025-11-08

How to retrieve and display the contact information configured on the website backend (such as phone number, address, social media links)?

It is crucial to display a company's contact information clearly and conveniently in website operations, as it not only enhances customer trust but also serves as a direct way for users to obtain services and consult.AnQiCMS (AnQiCMS) is a powerful content management system that provides intuitive backend configuration options and flexible template calling mechanisms, allowing you to easily manage and display this information.Next, we will explore how to configure and display your website's contact information in AnQiCMS, including phone number, address, social media links, and more.--- ## First Part

2025-11-08

How can AnQi CMS automatically replace keywords to display article or product content?

In content operations, we often need to ensure that specific keywords in articles or product descriptions are consistent, even automatically associated with related pages, which is crucial for SEO optimization and improving user experience.But manually modifying one by one takes time and is prone to errors, especially when the content of the website is massive, it is also a huge challenge.Anqi CMS knows this, and therefore provides us with a very practical feature, that is, the automatic replacement and display of keywords in articles or product content.This feature can intelligently identify the keywords or phrases you preset and automatically replace them with the specified text or link

2025-11-08

How to display custom additional field content on the detail page?

One of the core strengths of AnQiCMS is its flexible content model feature.It allows us to add various unique custom fields to content based on different business scenarios, such as products, services, events, etc.These custom fields greatly enrich the expression of content, making our website content more professional and meet the needs.But with these additional fields, how can they be presented elegantly on the front-end detail page?

2025-11-08

How to implement multi-condition filtering on a product list or article list page and display the filtered results?

In a content management system, providing users with flexible multi-condition filtering functions is a key factor in improving website usability and user experience.Whether it is an e-commerce website product list or a content portal article classification page, users hope to quickly locate the content they are interested in.AnQiCMS (AnQiCMS) with its powerful content model and template tag system allows you to easily meet this requirement and intuitively display the filtered results. ### 1.Establishing the foundation: defining content models and custom fields All filtering functions rely on data.

2025-11-08

How to safely output content containing HTML tags in a template and prevent them from being escaped by the browser?

In website operation, we often need to display information with rich formatting and media content, such as carefully edited article details, product introductions, or customized pages.This content often contains HTML tags, such as image tags `<img>`, link tags `<a>`, paragraph tags `<p>` and so on.However, if you directly output this content to a web page, you may find that it does not render as expected, but rather displays the HTML tags as plain text, greatly affecting the user experience and the beauty of the page.

2025-11-08