Master AnQiCMS template: useforThe art of looping through data lists

Hello, all operation partners of AnQiCMS!

In the daily operation of website content, we often need to display a series of data, whether it is the latest article list, product category navigation, or comment details, it is inseparable from the traversal and display of the data set.AnQiCMS as an efficient and flexible content management system, deeply understands the importance of templates in content presentation.forLoop through it and see how it can easily handle various data lists, bringing vitality to your website content.

AnQiCMS's template engine adopts a syntax style similar to Django, which makes it very easy for partners with other web development experience to get started quickly, and even for beginners, its intuitiveness allows you to grasp it quickly.forLoops are the foundation for building dynamic content displays, which help us present data obtained from the backend in a structured and customizable manner on the front-end page.

forThe core usage of loops: traversing data sets

Imagine that you have retrieved a set of article data from the backend, and now you need to display these articles one by one on the webpage. At this time,forThe loop comes into play. Its basic syntax structure is very concise and clear:

{% for item in collection %}
    {# 在这里放置你希望对每个“item”进行的操作和显示逻辑 #}
{% endfor %}

Here,collectionrepresents the data set you want to iterate over, for example, AnQiCMS'sarchiveList(article list),categoryList(分类列表)English tags get the data.itemis a temporary variable, which represents in turn in each loop.collectionone of the data items. By accessingitemdifferent properties (such asitem.Titleto get the title,item.LinkGet the link), we can display the detailed information of each data item.

Let's take a look at several common data lists to see it in detail.forThe charm of loops.

Example one: dynamically display the list of articles.

The article list is one of the most common content forms on a website. Suppose we usearchiveListtags to get the latest articles:

{% archiveList articles with type="list" limit="10" %}
    <div class="article-list">
    {% for article in articles %}
        <article class="article-item">
            <a href="{{ article.Link }}" title="{{ article.Title }}">
                <h3>{{ article.Title }}</h3>
                <p>{{ article.Description }}</p>
                <div class="meta-info">
                    <span>发布时间:{{ stampToDate(article.CreatedTime, "2006年01月02日") }}</span>
                    <span>阅读量:{{ article.Views }}</span>
                </div>
            </a>
        </article>
    {% endfor %}
    </div>
{% endarchiveList %}

In this example, we first store the data througharchiveListtags to store the data intoarticlesIn the variable, and limit it to only display 10 list items. Next,{% for article in articles %}We will iterate over these 10 articles one by one. In the loop body,article.Link/article.Title/article.Descriptionandarticle.ViewsThe link, title, introduction, and page views of the article will be displayed respectively. Particularly, for the timestamp fieldCreatedTimeWe have used the built-in AnQiCMS.stampToDateThe function formats it to a more user-friendly form such as '2006-01-02'.

It is worth mentioning that ifarticlesThis collection is empty, we do not want to display blank pages on the site, but rather provide a friendly prompt to the user. The AnQiCMS uses a block to elegantly handle this situation:forloop provides aemptyblock to elegantly handle this situation:

{% archiveList articles with type="list" limit="10" %}
    <div class="article-list">
    {% for article in articles %}
        <article class="article-item">
            <a href="{{ article.Link }}" title="{{ article.Title }}">
                <h3>{{ article.Title }}</h3>
                <p>{{ article.Description }}</p>
            </a>
        </article>
    {% empty %}
        <p>抱歉,目前还没有任何文章发布。</p>
    {% endfor %}
    </div>
{% endarchiveList %}

Whenarticlesis empty{% empty %}The content inside will be rendered, providing a better experience for users.

Example two: Build multi-level category navigation

Website navigation usually requires displaying categories, even subcategories.forLoop can also handle such nested traversal requirements.

<nav class="main-nav">
    <ul>
    {% navList mainMenu with typeId=1 %} {# 获取ID为1的主导航数据 #}
        {% for mainItem in mainMenu %}
            <li {% if mainItem.IsCurrent %}class="active"{% endif %}>
                <a href="{{ mainItem.Link }}">{{ mainItem.Title }}</a>
                {% if mainItem.NavList %} {# 如果有子导航,则进行嵌套循环 #}
                    <ul class="sub-nav">
                    {% for subItem in mainItem.NavList %}
                        <li {% if subItem.IsCurrent %}class="active"{% endif %}>
                            <a href="{{ subItem.Link }}">{{ subItem.Title }}</a>
                        </li>
                    {% endfor %}
                    </ul>
                {% endif %}
            </li>
        {% endfor %}
    {% endnavList %}
    </ul>
</nav>

Here, we first go throughnavListGet the main navigation data tomainMenuVariables. Outer layerforLoop through the main navigation items, and throughmainItem.NavListCheck if there is a child navigation. If it exists, use it again in the inner layer.forLoop through child navigation items.mainItem.IsCurrentandsubItem.IsCurrentThis property can help us determine whether the current navigation item is selected, thereby addingactivestyle to enhance the user experience.

Example three: display custom document parameters

In AnQiCMS, all the various parameters you customize for articles or product models, such as 'author', 'source', 'product model', etc., can also be displayed in a unified manner through circulation.forLoop unified display.

<div class="product-specs">
    <h4>产品参数</h4>
    {% archiveParams specs with id=archive.Id %} {# 获取当前文档的所有自定义参数 #}
        <ul>
        {% for param in specs %}
            <li>
                <span>{{ param.Name }}:</span>
                <span>{{ param.Value | safe }}</span> {# 注意:如果param.Value可能包含HTML,请使用|safe过滤器 #}
            </li>
        {% endfor %}
        </ul>
    {% endarchiveParams %}
</div>

Here,archiveParams标签会获取当前文章(archive.Id)的所有自定义参数,并将其存入specs数组。循环遍历specs,可以方便地展示每个参数的Name(参数名称)和Value(Parameter value). It is especially reminded that,param.Valueit may contain rich text or HTML code, be sure to use|safeFilter, to ensure that HTML content can be correctly parsed and displayed, rather than being escaped into plain text.

EnhancementforAdvanced techniques for the loop experience

In addition to basic traversal, AnQiCMS'sforLoop also provides some powerful auxiliary functions to make your template more expressive.

1. UtilizeforloopVariable gets loop information

InforInside the loop, AnQiCMS will automatically provide a specialforloopVariables that contain some useful loop information:

  • forloop.Counter: The current loop number, starting from 1.
  • forloop.Revcounter: The reverse number of the current loop, starting from the total count.

This is very useful when you need to add special styles to the first, last, or odd/even items in a list:

{% archiveList articles with type="list" limit="10" %}
    <div class="article-list">
    {% for article in articles %}
        <article class="article-item {% if forloop.Counter == 1 %}first-article{% endif %} {% if forloop.Counter is odd %}odd{% else %}even{% endif %}">
            <h3>{{ article.Title }} (第{{ forloop.Counter }}篇,还剩{{ forloop.Revcounter }}篇)</h3>
        </article>
    {% endfor %}
    </div>
{% endarchiveList %}

Passforloop.Counter == 1We can easily identify and style the first articleforloop.Counter is oddwhich can be used to implement the zebra line effect of list items

2. ApplyreversedandsortedModifiers

Sometimes we want the data to be displayed in a specific order.forLoop supportreversed(Reverse)andsorted(Sorted) modifier:

  • {% for item in collection reversed %}: Traverse the data set in reverse.
  • {% for item in collection sorted %}: Traverse the sorted data set (default ascending).

You can even combine them:{% for item in collection reversed sorted %}This is very flexible when it is necessary to display the same batch of data in different orders.

3. UsecycleStyle cycling implemented by tags

cycleLabels are a very clever tool, they can output in order the multiple values you define in a loop. This is very useful when you need to alternate between different background colors, CSS classes, or other variables.

auto

<ul class="styled-list">
{% for article in articles %}
    <li class="list-item {% cycle