How to use the loop (for) tag to traverse and display data lists in AnQiCMS templates?

In AnQiCMS template development, mastering how to effectively display dynamic data lists is the key to building a feature-rich website.Whether it is the latest article, product display, or classification navigation, all of these rely on the loop mechanism in the template.AnQiCMS's template system draws on the simplicity and power of the Django template engine, among which theforThe loop tag is the core tool for implementing data iteration.

UnderstandingforThe basic of loop tag

When we need to repeatedly display a series of similar structures on the page,forLoops come in handy. Their basic syntax is very intuitive:{% for item in collection %} ... {% endfor %}. Here,collectionrepresents the collection of data you want to iterate over, which can be various data lists provided by the system (such as article lists, product lists), anditemIt is a temporary variable that points tocollectionone of the data items. Byitemwe can access the various properties of the data item and present it on the page.

Core data retrieval: usingarchiveListas an example

In AnQiCMS, to retrieve a list of data, specific tags are usually used, the most commonly used and comprehensive of which isarchiveListThe tag can help us retrieve various types of documents (articles, products, etc.) and supports flexible filtering and sorting.

UsearchiveListWhen, we usually combine multiple parameters to accurately control the required data:

  • moduleIdThis parameter is used to specify which content model document you want to retrieve. For example, if you want to get a list of articles, you may setmoduleId="1"(Assuming the article model ID is 1); if it is a product list, set the corresponding product model ID.
  • categoryIdIf you only want to display documents under a specific category, you can use this parameter to specify the category ID.You can also enter multiple IDs separated by commas to retrieve documents of multiple categories.Especially, if you do not specifycategoryIdIt will try to get the category ID of the current page, and if you want to set it explicitly not to read automatically, you can set it tocategoryId="0".
  • typeThis parameter is very important, it determines the type of the list.type="list"It is usually used to obtain a list of fixed number of data (such as the hot recommendations on the homepage); whiletype="page"it is used for large lists that require pagination display, which will work with subsequent pagination tagspaginationtogether.
  • limit: Used to control the number of data displayed. When you usetype="list"you can directly set a number, such aslimit="10". More flexible is that it also supportsoffsetpatterns such aslimit="2,10"Indicates starting from the 3rd data item and fetching 10 items.
  • order: How should the data be sorted? You can chooseorder="id desc"Sorted by ID in descending order (newest release),order="views desc"Sort by views in descending order (most popular), ororder="sort desc"Sort by custom sorting set in the background.

When we usearchiveListWhen a tag fetches data, it will usually assign the result to a variable, for examplearchives:{% archiveList archives with moduleId="1" type="list" limit="5" order="id desc" %}

CombineforTag traverses and displays data

With the dataset in place, the next step is to useforLoop it to display on the page. Let's look at a typical article list example:

<div class="article-list">
    {% archiveList articles with moduleId="1" type="list" limit="5" order="id desc" %}
        {% for item in articles %}
        <div class="article-item">
            <a href="{{ item.Link }}" class="article-title">{{ item.Title }}</a>
            <div class="article-meta">
                <span>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
                <span>浏览量:{{ item.Views }}</span>
            </div>
            {% if item.Thumb %}
            <div class="article-thumb">
                <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
            </div>
            {% endif %}
            <p class="article-description">{{ item.Description }}</p>
        </div>
        {% empty %}
        <p>暂时没有文章发布。</p>
        {% endfor %}
    {% endarchiveList %}
</div>

In this example:

  1. We first usearchiveListGot the latest 5 articles (moduleId="1",limit="5",order="id desc"), and store the results inarticlesthe variable.
  2. Then,{% for item in articles %}Start traversingarticlesThis list. Each loop,itemrepresents all the information of an article.
  3. Inside the loop, we notice the{{ item.Link }}get the article link,{{ item.Title }}Get the article title,{{ item.Views }}View the number of page views.
  4. publish date{{ stampToDate(item.CreatedTime, "2006-01-02") }}and here we usestampToDateA filter to format the original timestamp into a more readable 'Year-Month-Day' format.
  5. {% if item.Thumb %}This is a simple conditional judgment, the image will be displayed only when the article has a thumbnail.
  6. Most importantly{% empty %}tag, which provides whenarticlesWhen the list is empty, the content displayed on the page avoids the embarrassment of a blank page and improves the user experience.

Auxiliary information in the loop: forloopobject

InforInside the loop, AnQiCMS also provides a specialforloopobject that can provide the context information of the current loop, which is very useful for implementing some special styles or logic:

  • forloop.Counter: Indicates the current loop index, starting from 1.
  • forloop.RevcounterIt indicates the reverse index of the current loop, starting from the total number of the list and ending at 1. For example, you may want to add a CSS class to the first element of the list.activeof the CSS class:{% for item in articles %} <li class="{% if forloop.Counter == 1 %}active{% endif %}">...</li> {% endfor %}

The universality of other list tags

exceptarchiveList, AnQiCMS also provides many other tags for obtaining data lists, their usage is similar toarchiveListVery similar, both are by assigning a variable, and combiningfora loop to iterate:

  • categoryListUsed to get the classification list of articles or products.
  • pageListGet a single page list (such as "About Us",
  • tagDataListGet the document list under a specific Tag.
  • navListGet the website navigation menu list, usually used to build top or bottom navigation.
  • bannerListGet the website's Banner image list, commonly used for carousel.
  • linkListGet the list of friend links.

MasteredarchiveListandforThe use of loops, you can easily display the data generated by these tags in all corners of the website, thus building dynamic and rich content pages.The powerful template function of AnQiCMS is precisely through this intuitive label combination, making the operation and display of website content efficient and flexible.


Frequently Asked Questions (FAQ)

Q1: Why myforThe loop did not output anything and did not display{% empty %}What is the backup text?

A1: IfforThe loop did not output any data and did not displayemptytext, which usually means that you are{% archiveList ... %}In the definition of any other list label{% for item in ... %}The variable name used does not match. For example, you may have defined{% archiveList documents ... %}But when looping, you wrote it as{% for item in archives %}Please make sure that the variable names match exactly.

Q2: How toforIn a loop, based on the value of a certain attribute of a data item, different content or style is displayed?

A2: You can useifLogical judgment tags are used inforImplement conditional rendering inside the loop. For example, if you want to add an ellipsis to a long article title or add a "top" tag to an article with a specific ID, you can do this:

{% for item in articles %}
    <div class="article-item">
        {% if item.Title|length > 30 %}
            <h3 class="long-title">{{ item.Title|truncatechars(30) }}...</h3>
        {% else %}
            <h3>{{ item.Title }}</h3>
        {% endif %}

        {% if item.Id == 123 %} {# 假设ID为123的文章是置顶文章 #}
            <span class="sticky-tag">置顶</span>
        {% endif %}
        {# 其他内容 #}
    </div>
{% endfor %}

Hereitem.Title|lengthanditem.Title|truncatechars(30)Is using AnQiCMS built-in string filter to get length and truncate strings.

Q3:archiveListoflimitParameter and pagination tagspaginationWhat are the differences, and how should I choose?

A3:limitThe parameter is used to limit the number of data obtained at a time. It is suitable when you want to display a fixed number of data on a page, such as 'Latest recommendations for 5 articles', 'Top 10 products'.limitcooperatetype="list"HoweverpaginationLabels are used to handle situations where a large amount of data needs to be displayed on multiple pages. When you setarchiveListoftype="page"the system will automatically calculate the total number of pages and the current page number,paginationTags use this information to generate page link, allowing users to jump between pages. In short,limitIt is a quantity limit,paginationIt is page navigation, both used together(type="page"Must be matched withpagination) To enable full pagination functionality.