How to alternate different CSS classes or styles while looping through list items?

Calendar 👁️ 50

In web design, to enhance visual aesthetics and user experience, we often encounter situations where we need to alternate different CSS classes or styles for list items (such as article lists, product lists, navigation menus, etc.).For example, make the background color of odd and even rows different, or apply a unique layout style every few items.AnQiCMS (AnQiCMS) provides a variety of simple and efficient methods to meet this requirement with its flexible template engine.

AnQi CMS uses a syntax similar to Django template engine, when processing data in loops, we can easily use built-in loop variables and tags to control the style of list items.The essence lies in using the index of items during the loop process, to assign different CSS classes through conditional judgment or specific tags.

Core function:forLoop withforloop.Counter

In the Anqi CMS template, when we use{% for item in items %}When traversing the list data with such a structure, the template engine will automatically provide some special loop variables, among which the most commonly used and crucial for style alternation isforloop.Counter.

forloop.CounterIndicates the current loop number, it starts from1and increases. This means that the first item in the loop,forloop.CounterThe value is 1; the second item is 2, and so on. Utilizing this feature, we can implement various complex alternating style logic.

Method one: utilizecycleTag efficient alternating CSS class

cycleThe tag is one of the most direct and elegant ways to implement style alternation in Anqi CMS templates.It can output a predefined list of strings in order in each loop, and it will automatically loop back to the first one when the list is exhausted.This is very suitable for alternating row styles or cycling through multiple styles in a fixed pattern.

Implement alternating row styles:

Assuming we want the odd rows of the list item to useodd-rowClass, even rows to useeven-rowClass.

{# 假设 archives 是通过 {% archiveList archives ... %} 获取的文档列表 #}
<ul class="article-list">
    {% for item in archives %}
    <li class="{% cycle 'odd-row' 'even-row' %}">
        <a href="{{ item.Link }}">{{ item.Title }}</a>
        <p>{{ item.Description }}</p>
    </li>
    {% endfor %}
</ul>

The corresponding CSS style can be defined as:

.odd-row {
    background-color: #f9f9f9;
    border-left: 3px solid #007bff;
}
.even-row {
    background-color: #ffffff;
    border-left: 3px solid #6c757d;
}

Implement a loop of multiple classes (N styles):

If we need to looply apply three or more different CSS classes,cycletags are also applicable.

<ul class="product-grid">
    {% for item in products %}
    <li class="product-item {% cycle 'style-one' 'style-two' 'style-three' %}">
        <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
        <h3>{{ item.Title }}</h3>
        <p>价格: {{ item.Price }}</p>
    </li>
    {% endfor %}
</ul>

the corresponding CSS styles:

.product-item.style-one {
    background-color: #e0ffe0;
    border: 1px solid #28a745;
}
.product-item.style-two {
    background-color: #e0e0ff;
    border: 1px solid #007bff;
}
.product-item.style-three {
    background-color: #fffde0;
    border: 1px solid #ffc107;
}

Method two: useforloop.Counterperform conditional judgment (odd/even styles)

AlthoughcycleLabels are cleaner, but sometimes we may need to make decisions based on clear conditions, especially when it's not just a simple alternation in cycles, but when a specific style is applied when a condition is met.The most common scenario is to judge odd or even.

<div class="category-items">
    {% for item in categories %}
    <div class="category-card {% if forloop.Counter % 2 == 1 %}is-odd{% else %}is-even{% endif %}">
        <h4><a href="{{ item.Link }}">{{ item.Title }}</a></h4>
        <p>{{ item.Description }}</p>
    </div>
    {% endfor %}
</div>

the corresponding CSS styles:

.category-card.is-odd {
    background-color: #f0f8ff;
}
.category-card.is-even {
    background-color: #f8f8f8;
}

Method three: based onforloop.Countergenerate incremental custom class names

In some designs, we may need to generate a unique class name for each item in the list, such asitem-1,item-2,item-3As. This is very useful when it is necessary to control items at specific positions with fine precision.

<ol class="ordered-list">
    {% for item in navigation %}
    <li class="list-item-{{ forloop.Counter }}">
        <a href="{{ item.Link }}">{{ item.Title }}</a>
    </li>
    {% endfor %}
</ol>

the corresponding CSS styles:

.ordered-list li {
    padding: 10px;
    margin-bottom: 5px;
}
.ordered-list .list-item-1 {
    font-weight: bold;
    color: #dc3545;
}
.ordered-list .list-item-3 {
    border-bottom: 1px dashed #cccccc;
}
/* 甚至可以结合伪类实现更多效果 */
.ordered-list .list-item-{{ forloop.Counter }}:hover {
    background-color: #e9ecef;
}

Method four: Advanced conditional judgment, to implement more complex loops with diverse styles.

When the alternating logic is not just simple even or odd or a few fixed styles, but based on a specific number (for example, every third or fifth item has a special style),forloop.CounterThe conditional judgment ability can take effect.

<div class="gallery">
    {% for image in gallery_images %}
    <div class="gallery-item
        {% if forloop.Counter == 1 %}first-item{% endif %}
        {% if forloop.Counter % 4 == 0 %}last-in-row{% endif %}
        {% if forloop.Counter > 5 and forloop.Counter < 10 %}highlighted{% endif %}">
        <img src="{{ image.src }}" alt="{{ image.alt }}">
        <p>{{ image.caption }}</p>
    </div>
    {% endfor %}
</div>

The corresponding CSS style can be defined as:

.gallery-item {
    float: left;
    width: 24%; /* 假设每行4个 */
    margin-right: 1%;
    margin-bottom: 15px;
    box-sizing: border-box;
    border: 1px solid #eee;
}
.gallery-item.first-item {
    background-color: #ffeb3b;
    border-color: #ff9800;
}
.gallery-item.last-in-row {
    margin-right: 0; /* 清除每行最后一个的右边距 */
}
.gallery-item.highlighted {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

Practical tips and suggestions

  • Semantic class name:Try to use descriptive style purposes instead of specific visual effects class names (such asfeatured-itemAnd

Related articles

How to display the default prompt information when the article list obtained through `archiveList` is empty?

When using Anqi CMS to build a website, we often need to display lists of articles, products, or other content.These lists are usually dynamically retrieved and rendered using such template tags as `archiveList`.}However, if a list is empty for various reasons (such as temporarily no content under a category, or empty search results), the user experience will be greatly reduced if the page is just empty.

2025-11-08

How to implement reverse or custom sorting output of AnQiCMS's `for` loop?

The order of website content listings is crucial for user experience and information delivery.Whether it is news updates, product displays, or article archives, flexibly controlling the output order of lists is a common demand in website operation.AnQiCMS provides a powerful and easy-to-use template engine, allowing us to easily control the arrangement of lists, including reverse order and sorting by specific rules.### AnQiCMS Template Engine Basics The AnQiCMS template system adopts the syntax style of the Django template engine, using concise tags and variable declarations

2025-11-08

How to get the current loop item index or remaining item count in an article?

When using AnQi CMS for website content display, we often need to finely control each item in the list.This may include adding numbers to articles, highlighting the first or last item in a list, or applying different styles based on the position of the item in the list.The AnQi CMS template system uses a syntax similar to the Django template engine, where the key to handling list loops is the `for` loop tag.

2025-11-08

How to loop through and output the article list in AnQiCMS template?

AnQiCMS provides a powerful and flexible template system for website content management, among which, the loop traversal and output of the article list is an indispensable core function for building a dynamic website.Whether you need to display the latest articles, category lists, or implement advanced filtering and pagination, AnQiCMS template tags can help you complete it efficiently.

2025-11-08

How to safely output content containing HTML tags in AnQiCMS templates (e.g., article content)?

Guide to safely output HTML content in AnQiCMS templates When building a website with AnQiCMS, we often need to display content with rich formatting, such as article content, product descriptions, category details, or single-page content.This content is usually entered through the backend rich text editor, which will naturally contain HTML tags such as `<p>`, `<strong>`, `<em>`, `<a>`, and so on.How to correctly and safely output this content with HTML tags in the front-end template is a very important issue.If handled improperly

2025-11-08

How to use the `include` tag to reuse header, footer, and other common code segments in AnQiCMS templates?

Building website templates in AnQiCMS, efficient code reuse is the key to improving development speed and maintenance efficiency.Imagine, the header (Header) and footer (Footer) of a website appear almost on every page. If the same code is written on each page, it is not only time-consuming, but also, once a modification is needed, it has to be searched and updated on each page, which is undoubtedly a huge amount of work.

2025-11-08

How to pass specific variables or data when including a sub-template?

Advanced AnQiCMS Template: `include` Sub-template Data Passing Techniques and Practices In AnQiCMS template development, the `include` tag is undoubtedly a powerful tool for enhancing template reusability and modularization.It allows us to extract common code snippets (such as page headers, footers, sidebars, etc.) and then introduce them where needed, thus avoiding repetition and making the template structure clearer and maintenance more efficient.However, the sub-templates introduced often need to display different content, which raises a core question: how to introduce sub-templates at the time

2025-11-08

How does the `macro` function in AnQiCMS templates help me reduce redundant rendering logic?

In Anqi CMS template development, improving efficiency and maintaining code cleanliness is the goal that every developer is pursuing.web pages often contain many structurally similar but content-wise different areas, such as each article card in the article list, the various features of a product detail page, or each link item in the navigation menu.If each time you have to rewrite this similar rendering logic, it not only takes time and effort, but also, once you need to make modifications, you may face the dilemma of having to make repetitive changes in multiple places.Luckyly, AnQiCMS's powerful template system provides `macro` macro function

2025-11-08