How to control the display of different styles for odd and even rows in a table or list loop?

Calendar 👁️ 89

In web design and content display, in order to enhance the user reading experience and make the information presentation clearer, we often need to apply different styles to the odd and even rows in tables or lists.This visual distinction not only breaks the monotony of the content but also significantly improves the readability of the data.In AnQiCMS, achieving this effect with its flexible and powerful template engine is quite direct and convenient.

Core Concept:forLoop and Row Counter

AnQiCMS's template system uses a syntax similar to Django's template engine, which allows us to easily obtain the current loop index when iterating over data. The key to implementing odd/even row differentiation styles lies in utilizingforNested in the loopforloop.CounterVariable.

When we use sucharchiveList/categoryList/pageListetc. tags to get the data list, and then through{% for item in archives %}such a structure to iterate, forloop.CounterIt will automatically record the number of times the current loop is running, and its count starts from 1.

With this counter, we can determine whether each line is an odd or even line, and then apply different styles to them.

Implement different styles for odd and even lines.

The most common method to determine if a number is odd or even is to use the modulo (Modulo) operator%A number divided by 2, if the remainder is 1, then the number is odd; if the remainder is 0, then the number is even.

In AnQiCMS templates, we can use it like this:

  • Whenforloop.Counter % 2 == 1means it is an odd row.
  • Whenforloop.Counter % 2 == 0means it is an even row.

Next, we can use this judgment result to dynamically add different CSS classes to list items (such as<li>labels or table cells'<tr>labels).

The following is an example of aarchiveListAdd an example of odd and even row styling to the list items:

Suppose we want to display an article list and make the odd and even row backgrounds different.

<ul class="article-list">
    {% archiveList archives with type="list" limit="10" %}
        {% for item in archives %}
        {# 根据 forloop.Counter 的奇偶性,动态添加 CSS 类 #}
        <li class="article-item {% if forloop.Counter % 2 == 1 %}odd-row{% else %}even-row{% endif %}">
            <a href="{{item.Link}}">
                <h3>{{item.Title}}</h3>
                <p>{{item.Description}}</p>
                <span>发布日期:{{stampToDate(item.CreatedTime, "2006-01-02")}}</span>
            </a>
            {% if item.Thumb %}
                <img src="{{item.Thumb}}" alt="{{item.Title}}">
            {% endif %}
        </li>
        {% empty %}
        <li>暂无文章内容</li>
        {% endfor %}
    {% endarchiveList %}
</ul>

Then, in your CSS file (usually)/public/static/你的模板目录/css/style.cssOr specify the style files you reference, define the styles of these classes:

/* article-list 样式(可选,根据你的布局需求) */
.article-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

/* 奇数行样式 */
.odd-row {
    background-color: #f9f9f9; /* 浅灰色背景 */
    padding: 15px;
    margin-bottom: 10px;
    border-radius: 5px;
}

/* 偶数行样式 */
.even-row {
    background-color: #ffffff; /* 白色背景 */
    padding: 15px;
    margin-bottom: 10px;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05); /* 添加一点阴影增加区分度 */
}

/* 列表项内部链接和文本样式(可选) */
.article-item a {
    text-decoration: none;
    color: #333;
    display: block;
}
.article-item h3 {
    color: #0056b3;
    margin-top: 0;
    margin-bottom: 5px;
}
.article-item p {
    font-size: 0.95em;
    color: #666;
    line-height: 1.6;
    margin-bottom: 10px;
}
.article-item span {
    font-size: 0.85em;
    color: #999;
}
.article-item img {
    max-width: 100px;
    height: auto;
    float: right;
    margin-left: 15px;
    border-radius: 3px;
}

This will make your article list display clear odd and even line differentiation styles, greatly enhancing the visual effects and user experience.

Actual application scenarios and extension ideas

This method is not limited to simple<ul><li>lists, it also applies to:

  • tables (<table>) data:In<tr>apply odd and even row styles on the tag to make the table data clear at a glance.
  • Card layout:Each card as a cyclic item, the background and border can be adjusted according to odd and even numbers.
  • Comment list:Make it easier for users to distinguish different comment entries.

Besides odd and even rows,forloop.CounterCan also help us achieve more flexible style control, for example:

  • Highlight the first element: {% if forloop.Counter == 1 %}first-item{% endif %}
  • Group elements of a specific number: {% if forloop.Counter % 3 == 0 %}third-item-group-end{% endif %}

By using these techniques, you can better utilize the powerful functions of the AnQiCMS template engine to create a beautiful, easy-to-use, and feature-rich website interface.

Frequently Asked Questions (FAQ)

  1. This odd-even row style method is only applicable to lists (<ul>) right?No, this method is applicable to all the AnQiCMS templates that use{% for ... in ... %}HTML elements traversed in a loop. Whether it's a table row (<tr>) or a card layout constructed usingdiv, you can make use of it inside the loop.forloop.CounterTo determine the odd or even line and apply different styles.

  2. How can I add a special style to the first line of the list instead of the odd or even line style?You can useforloop.CounterTo determine if the current loop is the first iteration. For example, in your<li>tag, you can judge like this:

    <li class="{% if forloop.Counter == 1 %}first-item-style{% elif forloop.Counter % 2 == 1 %}odd-row{% else %}even-row{% endif %}">
        <!-- 内容 -->
    </li>
    

    Then definefirst-item-stylethe CSS style.

  3. Where should I put these CSS styles in the AnQiCMS template file?According to the AnQiCMS template creation conventions, the static resources such as styles, JS scripts, images, and so on used by the template are usually stored in/public/static/In the directory. So, you can add these CSS rules in your template folder, for exampletemplates/your_template_name/public/static/css/style.cssIn the file, add these CSS rules. Make sure your HTML template file correctly references these CSS files.

Related articles

How can you determine if a variable exists in a template and dynamically display content based on the result?

Build an energetic website on AnQiCMS, content management is not just about publishing information, but also about how to intelligently present these information.Imagine if your website could flexibly adjust the display style based on the actual data, for example, showing an image if there is one, and displaying alternative text if there isn't;If there is relevant content, recommend it; if not, kindly prompt The key to realizing this intelligent dynamic display lies in how to determine whether a variable exists in the template

2025-11-09

How to implement showing or hiding part of the content based on user group permissions (such as VIP exclusive content)?

In website operation, providing differentiated content services based on user identity is a common strategy to enhance user experience and achieve content monetization.AnQiCMS (AnQiCMS) with its flexible user group management and VIP system, can help us easily implement content display or hide based on user permissions.This article will delve into how to use this feature of Anqi CMS to create exclusive VIP content for your website or display different information based on user level.

2025-11-09

How to use the `archiveList` tag to sort and display the article list by views or publication time?

How to efficiently display and organize content in website operation often directly relates to user experience and the effectiveness of content dissemination.AnQiCMS provides a series of powerful and flexible template tags that allow content managers to easily control the display of articles.Today, let's talk about how to use the `archiveList` tag to sort and display the article list by views or publishing time.### Understanding the `archiveList` tag The `archiveList` tag is AnQiCMS

2025-11-09

How to include external static resource files (CSS, JS, images) in a template?

When using AnQiCMS to build a website, introducing styles (CSS), interactive scripts (JS), and images as static resources is the foundation for the website's aesthetics and functionality.Understand how to correctly introduce these files in the template, so that your website not only looks professional but also has rich functions and maintains efficient and stable operation.AnQi CMS with its concise and efficient architecture and flexible template engine makes it very intuitive to manage and introduce these resources.The AnQiCMS template system, especially in handling static resources, is very thoughtful

2025-11-09

How can you format a timestamp to display the publication date in a friendly date and time format?

In website operation, the content publication date is not just a time mark, it is also an important basis for visitors to obtain information timeliness.A clear and readable date format that can significantly improve user experience and make your website content appear more professional and considerate.However, in a powerful content management system like AnQiCMS, the publication date is usually stored in the database in the form of a "timestamp", which is usually a string of numbers that is difficult to understand directly.For example, you might see a number like `1609470335`

2025-11-09

How to customize the display of Banner Carousel images on the website homepage?

In website operation, the homepage Banner carousel image is an important component to attract visitors' attention and convey core information.AnQiCMS (AnQiCMS) understands this need and provides a flexible and convenient way for you to easily customize and display these key visual elements on the homepage of your website. ### Prepare: Manage Your Banner Image in the Background First, we need to make sure that the images used for the carousel have been uploaded and properly managed.The AnQi CMS usually provides a special "Banner Management" area in the background

2025-11-09

How to display a list of friendship links on the front page of the website?

In website operation, friendship links have always been an important means to enhance website authority, increase external traffic, and enhance user trust.If you are using AnQiCMS to manage your website and want to display a list of friend links on the frontend page, you will find that this process is surprisingly simple and efficient.AnQi CMS, with its simple design and powerful features, makes content management easy, and the display of friendship links is no exception.Next, let's take a look at how to display friend links in Anqi CMS.

2025-11-09

How to use breadcrumb navigation tags to display the current page path at the top of the page?

In website operation, a clear navigation path is crucial for user experience and search engine optimization.When a user is browsing deep pages on a website, a straightforward 'You are here' prompt can help them quickly locate and easily return to the parent directory.This is a kind of auxiliary navigation method, which we call breadcrumb navigation.AnQiCMS (AnQiCMS) is built-in with powerful breadcrumb navigation tags, allowing developers and content operators to easily display the current location path at the top of the page.What is breadcrumb navigation and why is it important?

2025-11-09