How to add special styles to specific items when displaying in a list, based on the count in a for loop?

Calendar 👁️ 65

In website content display, we often need to highlight specific items in the list visually, whether to attract user attention or to enhance the level of content.For example, you may want to add a "pin" tag to the latest few articles released, or make the odd and even rows of the list display different background colors to enhance readability.AnQiCMS (AnQiCMS) flexible template engine, which provides strong support for achieving these fine-grained controls.

AnQiCMS's template system borrows the syntax of the Django template engine, which means you can control the display logic of content through concise and intuitive tags. Among them,forThe loop tag is the most commonly used tool for handling list data, and its built-in counter function is the core of our implementation of special styling for list items.

Core function analysis: for loop and counter

In the Anqi CMS template, when we usearchiveList/categoryListGet the content list with tags and iterate over it,forLoops provide some very useful built-in variables that help us understand the current state of the loop. The most critical one isforloop.Counterandforloop.Revcounter.

forloop.CounterThis variable is used to record the current number of loops, it starts from1and increments. This means that when you traverse the first item in the list,forloop.CounterThe value is 1; the second item is 2, and so on.

forloop.Revcounter: withforloop.CounterOn the contrary,forloop.RevcounterStart from the total number of items in the list and decrement until 1. This is very useful when you need to count from the end of the list or process the last item.For example, if the list has 10 items, the first item is theforloop.RevcounterIs 10, the last one is 1.

Understood these two counters, we can add the style we want to specific items in the loop through conditional judgment.

Practical exercise: Add style to specific items

Next, we will demonstrate how to巧妙地利用several common scenarios in the Anqi CMS templateforto add special styles to list items using a loop counter.

Scenario one: Highlight the first item in the list

Assume you have a list of articles and you want the first article in the list to have a special background color or a 'new' badge.

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
    <li class="{% if forloop.Counter == 1 %}highlight-first{% endif %}">
        <a href="{{ item.Link }}">
            <h3>{{ item.Title }}</h3>
            <p>{{ item.Description }}</p>
        </a>
    </li>
    {% empty %}
    <li>暂无文章</li>
    {% endfor %}
{% endarchiveList %}

In this code block,{% if forloop.Counter == 1 %}Determine if the current item is the first item in the loop. If so, add a name ofhighlight-firstThe CSS class. You just need to define the style of this class in your CSS file, for example:

.highlight-first {
    background-color: #ffe0b2; /* 柔和的橙色背景 */
    border-left: 5px solid #ff9800; /* 左侧边框 */
    padding-left: 15px;
}

This way, the first article in the list will automatically apply this special style.

Scene two: Implement row coloring or looping style in the list

In order to improve the readability of long lists, or to add different background patterns to each item, we often use alternating row coloring or cycling through a set of styles. At this point,cycleTags make it particularly convenient and elegant.

cycleTags allow you to select a value in order from a set of predefined strings in each iteration.

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
    <li class="{% cycle 'even-row' 'odd-row' %}">
        <a href="{{ item.Link }}">
            <h3>{{ item.Title }}</h3>
            <p>{{ item.Description }}</p>
        </a>
    </li>
    {% empty %}
    <li>暂无文章</li>
    {% endfor %}
{% endarchiveList %}

Here, {% cycle 'even-row' 'odd-row' %}It will output on the first iteration.even-rowThe second outputodd-rowThe third time backeven-rowThis is a loop. You can define styles separately in CSSeven-rowandodd-rowFor example:

.even-row {
    background-color: #f9f9f9;
}
.odd-row {
    background-color: #ffffff;
}

If you need more looping styles, such as a carousel with three different colors, just add more parameters in thecycletag:{% cycle 'color-a' 'color-b' 'color-c' %}.

Scenario three: Add styles based on location range or specific numbers

Sometimes, you may need more complex conditions, such as adding styles to the first three articles, or adding an ad style every five items.

{% archiveList archives with type="list" limit="15" %}
    {% for item in archives %}
    <li class="
        {% if forloop.Counter <= 3 %}highlight-top3{% endif %}
        {% if forloop.Counter % 5 == 0 %}ad-slot{% endif %}
    ">
        <a href="{{ item.Link }}">
            <h3>{{ item.Title }}</h3>
            <p>{{ item.Description }}</p>
        </a>
        {% if forloop.Counter % 5 == 0 %}
            <div class="ad-content">广告内容</div>
        {% endif %}
    </li>
    {% empty %}
    <li>暂无文章</li>
    {% endfor %}
{% endarchiveList %}

This code combines multipleifconditions:

  • {% if forloop.Counter <= 3 %}Will add to the first three items in the listhighlight-top3Class.
  • {% if forloop.Counter % 5 == 0 %}Then it will judge whether the current item is the 5th, 10th, 15th... item (i.e., the counter can be divided by 5), and add it toad-slotClass, at the same time<li>Insert an advertisement content insidediv.

This flexible conditional judgment allows you to accurately control the style and content insertion of any item in the list according to your business needs.

Combine actual needs, flexible application

In AnQi CMS, style differentiation for list items should not be limited to the above examples. You can exercise creativity based on the actual website design and operation strategy:

  • Hot RecommendationsCombine the reading volume or recommended attributes of the article to display special icons or styles in the top few positions.
  • New content released.Utilizeforloop.CounterMark the latest few articles released.
  • Product promotion.In the product list, add a promotional tag style for products in a specific price range.
  • Content interlaced: In addition to adding styles, you can also insert advertisements, recommended content, or other hints at specific locations as shown in the example.

Always recommend separating style definitions (CSS) from structure (HTML template), by dynamically adding or removing CSS class names in the template, to maintain the cleanliness and maintainability of the template. Anqi CMS providesforloop.CounterandcycleThese tools make these operations effortless.

Summary

The powerful template engine of AnQi CMS combined with its built-in.forA loop counter that provides an effective way to control the style of specific items when displayed in a list.Whether it is simple alternating line color or complex conditional trigger style, it can be easily achieved through intuitive tag syntax.Apply these functions flexibly to greatly enhance the visual appeal and user experience of your website content.


Frequently Asked Questions (FAQ)

Q1: Whyforloop.CounterWhy does it start counting from 1 instead of 0?

A1: In many programming languages, the index of an array or list usually starts from 0. However, in Anqi CMS (and many other template engines such as Django, Liquid)forCounting in a loop,forloop.CounterIt is designed to better comply with human intuitive counting habits, starting from 'the 1st', 'the 2nd', and so on.This makes it more intuitive and convenient to handle needs such as 'the first item', 'the second item', etc. in templates, without the need for additional +1 or -1 conversions.

Q2: Besides,classAttribute, can I directly modifystyleAttribute to apply styles?

A2: Theoretically, you can usestyleThe attribute is directly embedded in the HTML tag with CSS styles, for example<li style="background-color: yellow;">...</li>This is not recommended as it violates the practice of separating style from structure, which makes template code bloated, difficult to read, and maintain.When you need to modify the style, you must modify each template file that contains inline styles.Compared to, usingclassProperties defined in an external CSS file can make your code more modular, easy to manage, and improve the loading efficiency and SEO performance of your website.

Q3: How do I add a special style to the last item in the list?

A3: To add a special style to the last item in the list, you can useforloop.RevcounterThe variable. Whenforloop.Revcounteris 1, it means that the current loop has reached the last item in the list. For example:

<li class="{% if forloop.Revcounter == 1 %}highlight-last{% endif %}">
    <!-- 列表内容 -->
</li>

Or, ifforthere is no loop after{% empty %}block, and you are sure that there is at least one item in the list, you can also use `forloop.

Related articles

How to use filters in a template to format displayed numbers and strings (such as decimal places, case conversion)?

In website content presentation, the aesthetics and readability of the data are as important as the quality of the content itself.AnQiCMS (AnQiCMS) provides powerful filter (Filters) functions at the template level, allowing us to easily format numbers and strings displayed on the page, thereby enhancing user experience and the professionalism of page information. ### Filter: A process in data processing We can imagine a filter as a series of processes that handle data.Raw data is like unprocessed raw materials, after the processing of the filter, it can be shaped into what we need

2025-11-09

How to correctly display HTML rich text content in article content using the `safe` filter?

In website content operation, rich text content plays a vital role.It allows us to enrich the expression of the article with various formats such as images, links, bold, italic, and more, enhancing the reading experience.AnQiCMS (AnQiCMS) provides a powerful backend editor, making it easy for us to create various wonderful content.However, when this rich text content is finally displayed on a website page, sometimes you may find that the original beautiful formatting and links have become raw HTML code strings. Why is that?

2025-11-09

How to display both subcategories and the list of articles under the category on a category page?

When operating the AnQiCMS website, we often encounter such a need: on a category page, we not only want to display the list of articles under the category but also clearly list all its subcategories to facilitate users in making more detailed navigation.The Anqi CMS, with its flexible template engine and rich built-in tags, can fully help us easily achieve this goal. ### Understanding AnQi CMS Category Page and Template Mechanism In AnQi CMS, each category (whether it is an article category or a product category) can be associated with an independent template file. Generally speaking

2025-11-09

How to manage and display category Banner images and thumbnails?

In website operation, the category page is an important link in guiding users to browse and deepen the brand impression.To configure a unique banner image and thumbnail for the category page, it can not only enhance the visual appeal of the website, but also allow users to intuitively understand the category content, effectively optimizing the user experience.AnQi CMS provides flexible and easy-to-operate functions in this regard, helping us manage and display these visual elements efficiently.

2025-11-09

How to implement the automatic display of content collected on the website front end?

How to automatically display the collected content on the website front-end is a concern for many content operators.AnQiCMS (AnQiCMS) is an efficient and flexible content management system that provides a complete solution from content entry to front-end display.It goes through a powerful content model, flexible template tags, and a friendly SEO mechanism, making this process simple and efficient.Next, we will explore how to use the various functions of AnQiCMS to automatically and beautifully display the valuable content you collect on the website's front-end.###

2025-11-09

How to prevent HTML tags from being automatically escaped when content is displayed?

When using Anqi CMS to manage website content, you may encounter a seemingly small but annoying problem: the formatted HTML code entered in the background editor is displayed as plain text on the front page, even presented directly in the form of angle brackets, losing the original style and layout.This not only affects the appearance of the page, but also discounts the carefully arranged content.Why is that, and how should we solve it?###

2025-11-09

How can you reference and overwrite the base master template (extends) in a template to unify the display style?

In the world of AnQiCMS, building a website with a unified appearance, easy to manage, and efficient to update is a common pursuit of each content operator and developer.Imagine if each page of the website needed to be designed individually for the header, footer, and sidebar, then the amount of work required to modify the logo, navigation menu, or copyright information would be enormous.Luckyly, AnQiCMS cleverly utilizes the template inheritance mechanism, allowing us to easily achieve a unified display style while maintaining flexible content updates

2025-11-09

How to define macro functions in templates to reuse commonly used content display code snippets?

In the development of website content management system templates, we often encounter situations where we need to repeatedly write the same or similar code snippets to display specific types of content.For example, each article card in the blog article list, each product feature item on the product detail page, although their content is different, their structure and style are highly similar.If you copy and paste this code manually every time, not only is it inefficient, but you also have to repeat the laborious work in multiple places when you need to make modifications, which is very prone to errors.AnQiCMS (AnQiCMS) is an efficient content management system, its template engine supports similar

2025-11-09