How to use the `add` filter in a loop to implement alternating row colors or dynamically concatenate different CSS class names?

Calendar 👁️ 62

In modern web design, the visual presentation of list content has an important impact on user experience.Whether it is an article list, product display, or comment area, by giving list items different styles, such as alternate row coloring or applying different class names based on specific conditions, it can significantly enhance the readability and aesthetics of the page.AnQiCMS's powerful template engine provides flexible tools to implement these dynamic style requirements, among whichforin the loopcycleTags andaddThe filter is our powerful assistant.

Understanding the dynamic style needs in the loop.

Imagine browsing through a long list of articles when each article has the same background color; it's easy for the eyes to tire and difficult to distinguish between adjacent entries.At this time, if the list can implement 'alternating row colors', that is, one row is light and the next row is dark, the reading experience will immediately become smooth many times.

In addition to simple alternate line coloring, sometimes we also need more fine-grained control.For example, add a special "first-item" class name to the first item in the list, or dynamically generate a class name containing a number based on some data (such as an article ID, read count), like "post-id-123".These requirements all point to a core feature: to be able to flexibly concatenate a unique or specific regular CSS class name for each list item in a loop.

AnQiCMS's template language borrows the syntax of the Django template engine, allowing us to easily embed logic control and data output in the HTML structure. Next, let's take a look at how toforImplement these dynamic styles in the loop.

Loop base in AnQiCMS template

We usually use in AnQiCMS template,{% for item in list %}Tags to traverse the dataset, for example, an article list(archiveList) or a category list(categoryListIn this loop, the system provides several very useful special variables to help us obtain the current state of the loop:

  • forloop.Counter: The current iteration number, starting from1start counting.
  • forloop.Revcounter: The number of remaining elements in the current loop, counted from the total in reverse order.

A simple article list loop might look like this:

{% archiveList archives with type="list" limit="5" %}
    {% for item in archives %}
    <li>
        <span>这是第 {{ forloop.Counter }} 篇文章</span>
        <a href="{{item.Link}}">{{item.Title}}</a>
    </li>
    {% endfor %}
{% endarchiveList %}

Hereforloop.CounterWill output 1, 2, 3, 4, 5, providing the basic numerical basis for dynamic style control.

UsecycleTags implement alternating row coloring.

For the most common alternating row color requirement, AnQiCMS providescyclea tag that allows you to repeat a set of values in a loop according to a preset order. This is better than manual judgmentforloop.CounterThe parity is much more concise.

Suppose we define two CSS class namesevenandoddto represent the styles of odd and even rows. UsecycleLabel, we can implement it like this:

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
    <li class="{% cycle 'even' 'odd' %}">
        <a href="{{item.Link}}">{{item.Title}}</a>
        <span>发布日期:{{stampToDate(item.CreatedTime, "2006-01-02")}}</span>
    </li>
    {% endfor %}
{% endarchiveList %}

In this code block,{% cycle 'even' 'odd' %}This will output alternately in each loop'even'and'odd'strings. The first article will getevenCategory, the second one isodd, the third one is againeven, proceeding in this manner, it perfectly achieves the effect of alternating colors between rows. You can even provide more values tocycle, so that it repeats in a longer sequence:{% cycle 'class-a' 'class-b' 'class-c' %}.

Use cleverlyaddFilter for dynamic class name concatenation

cycleThe tag is very suitable for repeated patterns, but when we need more flexible, numeric or mixed content-based class names,addThe filter comes into play.addThe filter is mainly used for adding (appending) numbers or strings.In the template, it can concatenate different values (including numbers and strings) to generate a new string.This is very useful for dynamically concatenating CSS class names.

addusing a filter{{ obj|add:obj2 }}format, you can convertobjandobj2The value is appended. If they are numbers, perform mathematical addition; if one or both are strings, perform string concatenation.

Scenario one: Generate class names with serial numbers for list items

For example, we want to generate a similar one for each articlepost-item-1/post-item-2The class name, to facilitate JavaScript or more refined CSS control.

{% archiveList archives with type="list" limit="5" %}
    {% for item in archives %}
    <li class="post-item-{{ forloop.Counter|add:'' }}">
        <a href="{{item.Link}}">{{item.Title}}</a>
    </li>
    {% endfor %}
{% endarchiveList %}

here,forloop.CounterIt will output numbers (1, 2, 3…), which we will combine with an empty string''performaddOperation is to ensureforloop.CounterTreated as a string for concatenation, thus generatedpost-item-1/post-item-2Class names such as. Of course, according to AnQiCMSaddThe flexibility of the filter, even if directly{{ 'post-item-'|add:forloop.Counter }}It will also automatically convert numbers to strings for concatenation, the effect is the same.

Scenario two: Combine multiple conditions and data to concatenate complex class names

We can also useaddthe filter meetsifLogical judgment andcycleCombine labels to create more complex dynamic class names.

Assuming our requirement is:

  1. All list items have a base classlist-item.
  2. The first item in the list has an extrais-firstClass.
  3. List item alternate row coloring, usingdarkandlightClass.
  4. Each item also has a class based on its position in the loop, such asitem-num-1.

We can write the template code like this:

`twig {% archive

Related articles

The `add` filter performs mathematical calculations in the AnQiCMS template, what is the difference from the arithmetic operation tag in `tag-calc.md`?

During the template development process of AnQiCMS, we often encounter scenarios where numerical calculations or logical judgments are required.The system provides us with various processing methods, among which the `add` filter and the arithmetic operation capabilities introduced in `tag-calc.md` are two commonly used tools.Although they all involve numerical processing, they have significant differences in functional positioning, usage, and complexity.First, let's understand the `add` filter.As the name implies, the `add` filter is mainly used to perform **addition operations or string concatenation**

2025-11-07

How to use the `add` filter to dynamically add a brand name or fixed suffix to the `Title` of the page `TDK`?

In website content operation, the page's "Title", "Keywords", and "Description", which is what we often call TDK, plays a crucial role in search engine optimization (SEO).A well-structured and brand-recognizable page title that not only helps search engines better understand the page content but also attracts users' attention in search results.AnQiCMS provides a flexible template engine, allowing us to finely control these key information

2025-11-07

When handling floating-point number addition with the `add` filter, should special attention be paid to its calculation accuracy?

When using AnQi CMS for website content management, template tags and filters are tools we often use, greatly enhancing the flexibility of content presentation.Among them, the `add` filter allows us to perform addition operations of numbers or strings in the template, which is very convenient in many scenarios.However, when it comes to adding floating-point numbers (which are decimal numbers), some users may wonder: Does the `add` filter need to pay special attention to its calculation accuracy when handling such calculations?

2025-11-07

How to concatenate the area code and phone number in the contact (`contact` tag) using the `add` filter?

It is crucial to clearly and effectively display contact information when operating your website.AnQiCMS (AnQiCMS) with its flexible template engine and powerful tag system, allows you to easily achieve various complex display needs.Today, let's talk about a common but somewhat tricky requirement: how to concatenate the area code and phone number in the contact information using the `add` filter to make your phone number clear at a glance.Why do you need to concatenate the area code and phone number?

2025-11-07

What is the final concatenation result when one operand of the `add` filter is a number and the other is a string that cannot be converted to a number?

AnQi CMS is an enterprise-level content management system developed based on the Go language, dedicated to providing users with efficient and customizable content management solutions.In daily content operation and template development, we often use various template tags and filters to process data, where the `add` filter is a very practical feature that can help us conveniently perform numerical addition or string concatenation.However, when operands of mixed types are involved, the logic of their behavior becomes particularly important.

2025-11-07

How to use the `add` filter to dynamically add 'Published on:' before the blog post's publish time?

When operating a blog, we often hope that the publication time of the articles can be presented in a more intuitive and brand style compliant manner.For example, adding 'Published on:' before the date can make it clear to the reader that this is a published article.AnQiCMS (AnQiCMS) with its flexible template engine makes such customization very simple.Today, let's discuss how to cleverly use the built-in `add` filter of AnQiCMS to dynamically add the phrase 'Published on:' before the publication time of blog posts.

2025-11-07

Does the `add` filter support chained calls, such as `{{ var1|add:var2|add:var3 }}` to concatenate multiple variables?

When developing templates in Anq CMS, we often encounter situations where we need to combine, concatenate, or sum multiple variables.Among them, the `add` filter is a very practical tool that allows us to perform addition operations on numbers or concatenate strings.However, some users may be curious whether the `add` filter supports a chain-like call like `{{ var1|add:var2|add:var3 }}` to concatenate multiple variables at once?Familiarize yourself with the template syntax of AnQi CMS after deep study

2025-11-07

How does the `add` filter flexibly combine fixed text with variable content when building dynamic prompt information?

In Anqi CMS template design, building dynamic prompts with real-time interactive features is the key to improving user experience.Whether it is to display product inventory, user welcome messages, or article reading volume, we hope to seamlessly combine fixed text with continuously changing variable content.At this point, the `add` filter becomes a very practical and flexible tool.The `add` filter in the Anqi CMS template is very intuitive: it can add or concatenate two values.This process has high intelligence. If the two values being operated on are of numeric type, it will perform mathematical addition.

2025-11-07