Can the `divisibleby` filter be used to implement alternating row colors or other conditional styles in a loop?

Calendar 👁️ 74

In the daily operation of website content, how to make the list data more readable and visually attractive is a key factor in improving user experience.AnQiCMS (AnQiCMS) provides rich possibilities for content display with its flexible template engine.Today, let's talk about a very practical template filter -divisiblebyLook at how it helps us achieve alternating row coloring or other conditional styles in a loop.

Get to knowdivisiblebyFilter

The Anqi CMS template system adopts a template engine syntax similar to Django, making the creation and customization of templates very intuitive and powerful.Among them, Filters are a very practical feature of the template engine, allowing us to process or transform variables when outputting them.

divisiblebyIt is such a filter, its main function isCheck if a number can be divided by another number evenly. This filter will return a boolean value (i.e.TrueorFalse), clearly telling us the result of the division.

Its syntax is very concise:

{{ 数值 | divisibleby: 除数 }}

For example, if we want to determine whether the number 21 is divisible by 3, we can write it like this:

{{ 21 | divisibleby:3 }}
{# 输出结果:True #}

And if we want to determine whether 22 is divisible by 3:

{{ 22 | divisibleby:3 }}
{# 输出结果:False #}

UnderstooddivisiblebyThis feature allows us to cleverly apply it in loops to achieve various conditional styles.

Practice 1: Implement alternating row coloring in loops

When displaying data in a table or list, alternating row coloring is a common technique to enhance user experience, which helps users easily distinguish and read each line of data. In the template loop of AnQi CMS, we can take advantage ofdivisiblebyFilters andforloop.Counter(Loop counter) easily achieve this effect.

Of Security CMSforThe loop tag built-in included aforloopwithin the object,forloop.Counterstarts from 1, providing the current iteration number for each loop.

Combineforloop.Counteranddivisibleby:2We can then determine whether the current line is an odd line or an even line:

  • Ifforloop.CounterIf it is divisible by 2, it means it is an even line.
  • If it is not divisible by 2, it means it is an odd line.

Here is an example of a row alternation code implemented in the document list (usually usingarchiveListtags to obtain

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
    {# forloop.Counter | divisibleby:2 检查当前循环次数是否能被2整除 #}
    <li class="list-item {% if forloop.Counter | divisibleby:2 %}even-row{% else %}odd-row{% endif %}">
        <h4>{{ item.Title }}</h4>
        <p>{{ item.Description }}</p>
        <span>发布时间:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
    </li>
    {% endfor %}
{% endarchiveList %}

In this code, we set up each<li>Elements are dynamically addedeven-roworodd-rowThese CSS classes. You only need to define the styles for these classes in your CSS file, for example:

.even-row {
    background-color: #f9f9f9; /* 浅灰色背景 */
}
.odd-row {
    background-color: #ffffff; /* 白色背景 */
}
.list-item {
    padding: 10px;
    border-bottom: 1px solid #eee;
}

Such that, each line in the list will display a different background color according to its parity, greatly enhancing the visual effects.

Practice Two: Implementing more flexible conditional styles

divisiblebyThe purpose of the filter is not just to alternate row colors. It can also be used to apply styles based on specific numerical conditions in a loop.

Imagine that you might want a special promotional tag for every third product item, or highlight every fifth news title with striking colors.divisiblebyIt can easily help you achieve these.

Here is an example of how to highlight every third list item:

{% archiveList products with type="list" limit="15" %}
    {% for product in products %}
    {# 检查当前循环次数是否能被3整除,如果是,则添加highlight-promo类 #}
    <div class="product-card {% if forloop.Counter | divisibleby:3 %}highlight-promo{% endif %}">
        <h3>{{ product.Title }}</h3>
        <img src="{{ product.Thumb }}" alt="{{ product.Title }}">
        <p class="price">¥{{ product.Price }}</p>
        {% if forloop.Counter | divisibleby:3 %}
            <span class="promo-tag">特别推荐!</span>
        {% endif %}
    </div>
    {% endfor %}
{% endarchiveList %}

With the corresponding CSS style:

.product-card {
    border: 1px solid #eee;
    padding: 15px;
    margin-bottom: 10px;
    text-align: center;
}
.highlight-promo {
    border: 2px solid #ff6600; /* 突出边框 */
    box-shadow: 0 0 8px rgba(255, 102, 0, 0.3); /* 阴影效果 */
}
.promo-tag {
    display: inline-block;
    background-color: #ff6600;
    color: #fff;
    padding: 3px 8px;
    font-size: 0.8em;
    margin-top: 5px;
    border-radius: 3px;
}

By this method, you can according toforloop.Counteranddivisiblebyfilter, combinedifLabel, implement any conditional judgment based on numerical divisibility, adding more personalization and interactivity to your website content. Whether it's alternating row coloring, special marking, grouped display, or other creative styles,divisiblebyIt is a very powerful and practical tool.

Frequently Asked Questions (FAQ)

  1. **In the AnQiCMS template, `forloop

Related articles

How to determine if a number can be evenly divided by another number in AnQiCMS templates?

In web content display, we often encounter situations where we need to adjust the layout or display logic of content based on the characteristics of some numbers.For example, we may need to insert an advertisement every few articles, or make even and odd rows of the table display different background colors, or perform special operations when the list loops to a specific position.In the AnQiCMS template system, based on the Django template engine syntax, it provides a very practical filter that can easily meet this requirement.This filter is `divisibleby`

2025-11-08

What will the `get_digit` filter return when processing non-numeric strings?

In AnQiCMS template development, we often use various filters to process data, where the `get_digit` filter is a convenient tool for extracting specific digits from numbers.However, when we turn our attention to a more common but potentially misunderstood scenario - that is, when the `get_digit` filter encounters a **non-numeric string**, its behavior becomes less obvious.Let's review the performance of the `get_digit` filter when dealing with pure numbers.When the data is of a standard numeric type

2025-11-08

How to extract a number at a specified position from a numeric string (e.g., extract the batch number from the product code)?

In the daily operation of websites, we often encounter situations where we need to handle various encodings or IDs, such as product codes, order numbers, batch numbers, etc., which often contain multiple segments of information, and we may only need to extract a part of the numbers.For example, from the complex product code “PROD20230815BATCH007”, we only want to quickly obtain the batch number “007”.The Anqi CMS, with its flexible content model and powerful template tag system, can easily meet such demands.Next, we will discuss how to use Anqi CMS

2025-11-08

What type of result will be obtained when the `add` filter processes addition of different data types?

In AnQi CMS template development, we often encounter scenarios where we need to process and transform data.(Filter) is a powerful feature that was born for this purpose, which can help us format, modify, or calculate variables with concise syntax.Today, let's delve deeply into one very practical filter: `add`, especially its specific performance in handling the addition of different data types.### `add` filter: Simplifies the combination of numbers and text The core function of the `add` filter, as the name implies, is to add two values together

2025-11-08

How to format a Unix timestamp into a readable date and time string?

In website content management, the way time is presented is crucial to user experience.Although the system may prefer a unified and efficient Unix timestamp format for background data processing, for visitors, a string of random numbers is obviously not as intuitive and easy to understand as AnQi CMS knows this and provides a simple and powerful tool to solve this problem.### Unix timestamp: The 'time language' in the database Unix timestamp, in short

2025-11-08

What are the similarities and differences between the `stampToDate` and `date` filters in handling time formatting and their applicable scenarios?

In Anqi CMS template development, we often need to display time data in a user-friendly format.The system provides two very practical tools for handling time: the `stampToDate` function and the `date` filter.Although they can all help us format time, there are some key similarities and differences as well as applicable scenarios, understanding these can make our template development more efficient and accurate.## `stampToDate`: A timestamp handler In AnQi CMS

2025-11-08

How to truncate a long string and automatically add an ellipsis (...)?

In website operation, we often encounter situations where we need to display a piece of text, but we cannot let it be too long to avoid affecting the page layout or reading experience.Whether it is the title, abstract, or product description of an article, if the content exceeds the expected length, the usual practice is to truncate a part of it and add an ellipsis at the end to indicate that the content has not yet ended.For AnQiCMS users, achieving such an effect is not complicated, thanks to its flexible and powerful template engine, we have a variety of built-in filters (Filters) that can easily handle it

2025-11-08

How does the `truncatechars_html` filter safely truncate HTML content without breaking the tag structure?

In website operation, we often need to display an abstract of a large amount of content on a page, such as the article list on the homepage, a brief introduction on the product details page, or recommended content for a module.These summaries must be able to attract readers to click and maintain the neat and beautiful layout of the page.However, when the content itself contains rich HTML formatting (such as bold, italic, images, links, etc.), simply truncating the character length often leads to a headache: the HTML tag structure is destroyed, causing the page to display incorrectly and even affecting the overall style.Imagine

2025-11-08