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.