How to use the `if` tag in combination with `forloop.Counter` to alternate the odd and even row styles of list items?

Calendar 👁️ 56

As an experienced website operation expert, I fully understand how to enhance user experience through meticulous interface design in content display.AnQiCMS (AnQiCMS) provides us with great flexibility with its high-performance architecture based on the Go language and a flexible template engine, allowing us to easily implement various creative and functional features.ifLabel combinationforloop.CounterTo alternate the odd and even row styles of list items.

Improve list readability: Anqi CMSifwith the tag andforloop.CounterImplement alternating row styles

In daily website operations, we often need to display various list data on the page, such as article lists, product lists, user comments, and so on.When the list data volume is large, pure white background or a single style is easy to make visitors feel visually tired, making it difficult to distinguish adjacent rows when reading, thereby affecting the efficiency of information acquisition.At this time, set the background or style of the list items to alternate between odd and even rows, as if adding guiding lines to the list, which can significantly enhance the visual hierarchy and readability, allowing users to browse the content more easily and comfortably.

The Anqi CMS template engine is compatible with Django template syntax, which means we can take advantage of its powerful logic control tags to easily achieve this alternating row effect on the front-end page.The core of realizing this function lies in judging the current iteration number in the loop.

Core tool one:forLoop tags withforloop.Counter

In the template design of Anqi CMS, we usually useforLoop tags to iterate over collection data, such as callingarchiveListTag to get the list of articles:

{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
        <!-- 列表项内容 -->
    {% endfor %}
{% endarchiveList %}

In each timeforDuring the loop iteration, the AnQi CMS template engine will provide some special context variables to help us obtain the current state of the loop. Among them,forloop.CounterIt is a very practical variable, it represents the current number of times the loop is running, starting from1It starts to increase. For example, in the first loop,forloop.CounterThe value is 1; when the loop is executed for the second time, it is 2, and so on. This is the key to achieving alternating row styles.

Core Tool Two: Modulo Operation andifConditional judgment

To determine whether a number is odd or even, we usually use the modulus operation in mathematics (%)。A number modulo 2, if the result is 0, then the number is even; if the result is 1 (or non-zero), then the number is odd.

The AnQi CMS template engine also supports inifusing the modulus operator in conditional judgments.ifTags are the foundation of our logical judgment, they can determine whether to execute a specific code block based on the truth value of a conditional expression.

Combining these two core points makes the思路 very clear: inforIn the loop, we can useforloop.Counter % 2to determine whether the current line is an odd line or an even line, and then throughifApply different CSS classes to different rows.

Practice operation: Implement alternating row styles for odd and even rows.

Next, let's look at a specific example of how to implement alternating row styles in the Anqi CMS template. Suppose we have a list of articles, and we want to apply even row styles toeven-rowStyle, applied to odd rowsodd-rowStyle.

Firstly, we need to define these two styles in the project's CSS file, for example:

/* public/static/css/style.css 或你的自定义样式文件 */
.article-list li {
    padding: 15px;
    margin-bottom: 10px;
    border-radius: 5px;
    transition: background-color 0.3s ease;
}

.article-list li.odd-row {
    background-color: #f9f9f9; /* 浅灰色背景 */
}

.article-list li.even-row {
    background-color: #ffffff; /* 白色背景 */
}

.article-list li:hover {
    box-shadow: 0 2px 10px rgba(0,0,0,0.08);
}

Then, in your Anqi CMS template file (for example,archive/list.htmlorindex.htmlIn the brackets, you can write code to display the article list:

<ul class="article-list">
    {% archiveList archives with type="page" limit="10" %}
        {% for item in archives %}
            {# 使用if标签和forloop.Counter判断奇偶行,并应用不同的CSS类 #}
            {% if forloop.Counter % 2 == 0 %}
                <li class="even-row">
            {% else %}
                <li class="odd-row">
            {% endif %}
                    <a href="{{item.Link}}">
                        <h3>{{item.Title}}</h3>
                        <p>{{item.Description|truncatechars:100}}</p>
                        <div class="meta">
                            <span>分类:{% categoryDetail with name="Title" id=item.CategoryId %}</span>
                            <span>发布日期:{{stampToDate(item.CreatedTime, "2006-01-02")}}</span>
                            <span>阅读量:{{item.Views}}</span>
                        </div>
                    </a>
                </li>
        {% empty %}
            <li>暂无文章可显示。</li>
        {% endfor %}
    {% endarchiveList %}
</ul>

In this code, we first usearchiveListTags get article data, and thenforLoop through each article. Inside the loop, we use{% if forloop.Counter % 2 == 0 %}to determine the currentforloop.CounterIs the value even. If it is even, it will be<li>tagseven-rowclass; otherwise, addodd-rowclass.This way, when the browser renders the page, it will automatically apply different background colors to odd and even rows according to the CSS styles we define, thereby achieving the effect of alternating styles between odd and even rows.

This approach is not only clear and intuitive, but also separates the content logic from the display style, making it convenient for subsequent maintenance and modification.The powerful template engine of AnQi CMS allows us to provide visitors with a flexible and efficient way to enjoy a better reading experience.


Frequently Asked Questions (FAQ)

Q1: How can I not start counting odd and even from 1 or want to apply a special style every N rows?

A1: forloop.CounterStarting from 1, it is very convenient for alternating odd and even rows. If you want to start from 0, you canforloop.CounterPerform simple mathematical operations, such asforloop.Counter|add:-1Make it a 0 base, thenforloop.Counter|add:-1 % 2 == 0It can judge even numbers with 0 base. If you need to apply a special style every N lines, you can useforloop.Counter % N == 0to judge. For example, if you want to apply a special style every three lines, you can in{% if forloop.Counter % 3 == 0 %}Apply a specific style at a certain time. This flexible modulo operation can meet your diverse style needs.

Q2: Will this alternating row style method affect the performance of the website?

A2:This method has a negligible impact on website performance.forloop.CounterIt is a built-in loop variable, modulus operation is also a very basic CPU operation, and they are executed when rendering templates on the server side.The final output to the browser is HTML code with different CSS classes, the browser only needs to render it in the conventional way.Compared to dynamically adding styles with JavaScript, this server-side rendering method is more efficient and friendlier to client performance, without causing significant performance burden.

Q3: Besides odd and even row background colors, what other visual effects can I achieve with this method?

A3:This is based onforloop.CounterThe condition judgment is very flexible, you can implement a variety of visual effects:

  • Adjust font color or size:Odd and even rows use different font colors, weights, or sizes.
  • Icon or decorative element:Add different icons, small images, or border styles at the beginning of odd or even rows.
  • Highlight specific rows:Combineforloop.Counter == Xfor exampleforloop.Counter == 1),can be given to the first line or the last line (combined)forloop.Revcounter == 1)add unique visual effects, such as "Latest Release" or "Hot Recommendation".
  • Card layout changes:If your list is in a card layout, you can try to float the cards on odd rows to the left, the cards on even rows to the right, or adjust their spacing and shadow effects.

Related articles

How to elegantly handle empty list situations in AnQiCMS template using the `{% for ... empty ... %}` syntax?

In AnQiCMS template development, we often need to display a series of content lists, such as article lists, product lists, navigation menus, or friend links.However, these lists are not always filled with data. When the list is empty, how to elegantly inform the user that "there is no content here" instead of displaying a blank page or an error message has become a detail consideration in template design.AnQi CMS is well-versed in this, drawing on the excellent design of Django templates in its powerful template engine developed in Go language, providing us with `{% for ...

2025-11-06

How to use the `IsCurrent` property to mark the currently selected filter condition in the `archiveFilters` filter tag?

As an experienced website operation expert, I deeply understand the critical role of user experience (UX) in the success of a website.A user-friendly, responsive interface can effectively guide users to discover content, and the content filtering feature is an important aspect of improving user experience.In AnQiCMS (AnQiCMS) this efficient and customizable content management system, the `archiveFilters` tag provides strong support for building flexible filtering functions, and its internal `IsCurrent` property is the 'magic wand' that lights up the user experience. Today

2025-11-06

How to determine if a custom field exists or has a value in `archiveParams` before displaying it?

As an experienced website operation expert, I deeply know the powerful potential of AnQiCMS (AnQi CMS) in content management and website optimization.The flexible content model and customizable fields provide great convenience for us to build highly personalized websites.However, how to elegantly handle these dynamically generated custom fields in template design, ensuring that they are displayed only when they exist or have a value, is the key to improving template quality and user experience.

2025-11-06

How to render different input controls (such as text, radio, checkbox) in the `guestbook` form based on the `Type` attribute?

As an experienced website operations expert, I know that a flexible and versatile content management system is the foundation of website success.AnQiCMS (AnQiCMS) with its excellent flexibility and powerful customization capabilities has become an invaluable tool in our hands.Today, let's delve deeply into a very practical topic in actual operation: how to intelligently render different input controls, such as text boxes, radio buttons, or checkboxes, in the `guestbook` form of Anqi CMS according to the preset field types in the background.This is not just an implementation at the technical level

2025-11-06

How to use the `filter-contain` filter in AnQiCMS to check string or array containment in the `if` statement?

As an experienced website operations expert, I fully understand that in an increasingly complex network environment, efficient content management and flexible page display are crucial for improving user experience and SEO effectiveness.AnQiCMS (AnQiCMS) provides a series of practical tools with its high-performance architecture based on the Go language and the powerful features of the Django template engine.

2025-11-06

How to use the `filter-divisibleby` filter to determine the divisibility of a number in an `if` statement?

In AnQiCMS template development, achieving dynamic content display and fine-grained control is a daily challenge for website operation experts.AnQiCMS is highly praised for its concise and efficient template engine, which inherits the elegant style of Django templates, making content display and logical control intuitive.In website operation, we often need to present different content or styles based on the characteristics of numbers, such as displaying an advertisement every few products or setting different background colors for odd and even rows of the list.At this time, the `divisibleby` filter can be perfectly combined with the `if` statement

2025-11-06

How to use the `filter-length_is` filter in AnQiCMS templates for `if` judgment of the exact length of a collection?

## Precise Control and Intelligent Presentation: Efficient Application of the `filter-length_is` Filter in AnQiCMS Templates In the template development practice of AnQiCMS, we often need to finely control the displayed data to ensure the accurate transmission of content and the elegant presentation of the user interface.AnQi CMS provides powerful tools for content operators and developers with its efficient architecture based on the Go language and the flexible syntax of the Django template engine, among which

2025-11-06

What is the difference in handling variable null values between `filter-default` and `filter-default_if_none` in `if` condition judgments?

AnQiCMS (AnQiCMS) is a powerful assistant for our daily content operation, with its flexible template engine syntax making content display diverse and efficient.However, in practice, we often encounter situations where variable values are empty, such as when the article title is not filled in, or when a custom field has no data.How elegantly to handle these 'null' values to ensure that the website front-end display is always professional and friendly has become a topic that content operators must face.

2025-11-06