How to use a for loop in AnQiCMS template and control the special display style of the first or last item in the loop?

When building a website, we often need to fine-tune the elements in the list, especially when displaying list data, setting a unique style for the first or last item in the list is a common requirement.For example, you may want the first product image in the list to be larger, or not to display a separator in the last item of the news list.The powerful template system of AnQiCMS provides an intuitive and flexible way to meet these needs.

AnQiCMS's template system is based on Go language, but its syntax style is very similar to Django template engine, which makes it very easy for colleagues familiar with web development to get started quickly. When dealing with list data,forLoops are our powerful assistant.

AnQiCMS'forLoop basics

In AnQiCMS template,forUsed for traversing arrays, slices (slices) or other iterable objects, rendering each element one by one. The basic loop structure is usually this:

{% for item in collection %}
    {# 在这里处理每个item的数据 #}
{% endfor %}

Ifcollectionis empty, you can also useemptytags to define the content displayed when the list is empty, which can prevent the page from appearing blank or error.

{% for item in someList %}
    <p>{{ item.Title }}</p>
{% empty %}
    <p>当前没有任何内容。</p>
{% endfor %}

To implement special style control for the first or last item in the loop, AnQiCMS'sforLoops have built-in variables that are very useful, which automatically track the state of the loop. Among them,forloop.Counterandforloop.Revcounteris the key to achieving your goal.

  • forloop.Counter: indicates the current number of times the loop has iterated from1Start counting. Whenforloop.CounterThe value is1it means that the current element being processed is the first element in the list.
  • forloop.Revcounter: It indicates how many elements remain after the current loop, starting from1Start counting. Whenforloop.RevcounterThe value is1When, it means that the current item being processed is the last one in the list.

With these two variables, we can very conveniently add special styles to the first and last items of the list.

Add a special style to the first item in the list

The most common requirement is that the first element in the list needs special display effects.This may be to attract the attention of users, or simply for visual design consistency. Utilizeforloop.CounterYou can easily achieve this goal

Suppose you want to add a special style to the first article in the latest article listfeatured-itemof the CSS class and display a 'new' badge:

{% archiveList latestArticles with type="list" limit="5" %}
    <ul class="article-list">
        {% for article in latestArticles %}
            <li class="article-item {% if forloop.Counter == 1 %}featured-item{% endif %}">
                {% if forloop.Counter == 1 %}<span class="badge new-badge">最新</span>{% endif %}
                <a href="{{ article.Link }}">{{ article.Title }}</a>
                <p>{{ article.Description|truncatechars:100 }}</p>
            </li>
        {% empty %}
            <li>暂无最新文章。</li>
        {% endfor %}
    </ul>
{% endarchiveList %}

In this example, whenforloop.Counteris equal to 1, we not only add<li>to the elementfeatured-itemClass, also inserted a "new" badge in front of the article title.

Add special style to the last item in the list.

The last element of the list often needs to be different. For example, you might want to remove the separator on the right of the last item in a horizontally arranged navigation menu, or give it a different background color. At this time,forloop.Revcounterit comes in handy.

The following is an example of a categorized list, and we hope to separate each item with a vertical bar, but not display a vertical bar for the last item:

{% categoryList mainCategories with moduleId="1" parentId="0" limit="3" %}
    <nav class="main-nav">
        <ul>
            {% for category in mainCategories %}
                <li class="nav-item">
                    <a href="{{ category.Link }}">{{ category.Title }}</a>
                </li>
                {% if forloop.Revcounter != 1 %}
                    <span class="separator">|</span>
                {% endif %}
            {% empty %}
                <li>暂无分类。</li>
            {% endfor %}
        </ul>
    </nav>
{% endcategoryList %}

Here, {% if forloop.Revcounter != 1 %}The condition judgment ensures that the delimiter will only be output when the current item is not the last one|.

Actual application and deeper control

The combination of these variables allows you to control the display of the list very flexibly.For example, in a document list containing images, you can make the first image particularly large, the last image have special borders, and the middle images maintain a regular style.

{% archiveList productGallery with type="list" categoryId="10" limit="6" %}
    <div class="product-gallery">
        {% for product in productGallery %}
            <div class="product-card {% if forloop.Counter == 1 %}large-image{% elif forloop.Revcounter == 1 %}special-border{% endif %}">
                <a href="{{ product.Link }}">
                    <img src="{{ product.Thumb }}" alt="{{ product.Title }}">
                    <h3>{{ product.Title }}</h3>
                </a>
            </div>
        {% empty %}
            <p>暂无产品展示。</p>
        {% endfor %}
    </div>
{% endarchiveList %}

In this way, you can create a variety of visual effects for different list areas of the website according to your business needs, thereby improving the user experience.

Advanced techniques and precautions

  • {% empty %}The proper use of blocks.Always consider the case where the list is empty and utilize{% empty %}blocks to provide friendly prompt information.
  • limitParameter: In usearchiveListorcategoryListSet reasonable settings when using tags such aslimitParameters can control the length of the loop, thus indirectly affectingforloop.RevcounterThe calculation.
  • cycleTag: Besides the special style of the first and last items, if you need to alternate the styles of the list items (such as different background colors for odd and even rows), you can use{% cycle 'odd-row' 'even-row' %}such as this.cycleLabel, it will output predefined values in order every time the loop runs.
  • Content security: When you output like in the loop,{{ item.Content|safe }}When such a field may contain HTML or JS code, please use it must be|safeA filter should be used to ensure that the content source is trustworthy to prevent potential XSS attacks. AnQiCMS templates are set to escape content by default, |safeIt is explicitly告知系统the content is safe, no need to escape.

By flexible applicationforLoop these built-in variables and tag features, you will be able to control the display of AnQiCMS website content more efficiently and accurately, bringing users a more excellent browsing experience.


Frequently Asked Questions (FAQ)