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

When building a website, we often need to finely control the elements in a list, especially when displaying list data. It is a common requirement to set a unique style for the first or last item in the list.For example, you may want the first product image in the list to be larger, or not to display a separator on the last item in the news list.AnQiCMS powerful template system provides an intuitive and flexible way to meet such 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 quick for web development colleagues to get started. When dealing with list data, forLoops are our powerful assistants.

AnQiCMSforLoop basics

In AnQiCMS templates,forThe loop is used to iterate over an array, slice (slice), or other iterable objects, rendering each element one by one. The basic loop structure is usually as follows:

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

IfcollectionIt is empty, you can still useemptylabels to define the content displayed when the list has no data, which can avoid blank pages or errors.

{% 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'sforLoop built-in some very practical variables, which automatically track the state of the loop. One of them,forloop.Counterandforloop.Revcounteris the key to achieving this goal.

  • forloop.Counter: It represents the number of times the current loop has run,1Start counting. Whenforloop.Counterhas a value of1it means that the current element being processed is the first element in the list.
  • forloop.Revcounter: It indicates how many elements are left after the current loop, just like from1Start counting. Whenforloop.Revcounterhas a value of1When, it means that the current process is the last element in the list.

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

Add a special style to the first item in the list

The most common requirement is that the first element in the list needs to have a special display effect.This may be to attract users' attention, or simply for visual design consistency.forloop.Counter, you can easily achieve this.

Suppose you want to add a special style to the first article in the latest article list,featured-itemThe CSS class, and display a "Latest" 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.Counterequals 1, we not only give<li>Element was addedfeatured-itemclass, but also insert a "Latest" badge before 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 may want to remove the separator to the right of the last item in a horizontally aligned navigation menu, or give it a different background color.forloop.Revcounterit comes into play.

Here is an example of a categorized list, and we hope to separate each item with a vertical line, but not display a vertical line 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 separator will only be output when the current item is not the last item|.

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 list of document containing images, you can make the first image particularly large, the last image have special borders, and the middle images maintain the 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 %}

Through this method, you can create a rich and diverse visual effect for different list areas of the website according to your business needs, enhancing the user experience.

Advanced techniques and precautions.

  • {% empty %}The good use of blocks:Always consider the case where the list is empty, and make use of{% empty %}blocks to provide friendly prompt information.
  • limitParameters: When usingarchiveListorcategoryListto obtain data with tags such aslimitThe parameter can control the length of the loop, thereby indirectly affectingforloop.RevcounterEnglish calculation.
  • cycletags: Besides the special style of the first and last items, if you need to apply alternating styles to list items (such as different background colors for odd and even rows), you can use{% cycle 'odd-row' 'even-row' %}SuchcycleLabel, it will output predefined values in order each time the loop runs.
  • Content securityWhen you output a field like this in a loop,{{ item.Content|safe }}which may contain HTML or JS code, be sure to use|safeFilter and ensure that the content source is trustworthy to prevent potential XSS attacks. AnQiCMS templates are set to escape content by default,|safeIt explicitly informs the system that the content is safe and does not require escaping.

By using flexibilityforLoop through these built-in variables and tag features, and you will be able to control the display style of AnQiCMS website content more efficiently and accurately, bringing users an even better browsing experience.


Common Questions (FAQ)