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 articles, product displays, or category navigation, all of these rely on the loop mechanism in the template.forLoop tags are the core tools for data traversal.
UnderstandingforThe basics of loop tags
When we need to repeatedly display a series of structurally similar data on the page,forLoop comes into play. Its basic syntax is very intuitive:{% for item in collection %} ... {% endfor %}Here,collectionRepresents the data collection 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, which points tocollectionan item in. Throughitem, we can access the various attributes of the data item and present it on the page.
Core data acquisition: witharchiveListfor example
In AnQiCMS, to get the data list, specific tags are usually used, of which the most commonly used and most comprehensive isarchiveList标签。它能够帮助我们从数据库中检索出各种类型的文档(文章、产品等),并支持灵活的筛选和排序。
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 retrieve 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.Also, multiple IDs can be passed separated by commas to retrieve documents of multiple categories.categoryIdIt will try to get the current page's category ID. If you want to explicitly not read it automatically, you can set it tocategoryId="0".type: This parameter is very important, it determines the type of the list.type="list"Used to obtain a list of fixed number of data (such as the hot recommendations on the homepage); whiletype="page"is used for large lists that need to be displayed in pages, it will work协同 with subsequent pagination tagspaginationtogether.limit:Used to control the number of displayed data. When you usetype="list"you can directly set a number, such aslimit="10". It is also more flexible as it supportsoffsetpatterns likelimit="2,10"Represents starting from the 3rd data item, retrieving 10 data items.orderWhat is the sorting method of the data? You can choose.order="id desc"Sorted by ID in descending order (newest released),order="views desc"Sorted by view count in descending order (most popular), ororder="sort desc"Sorted by custom sorting set by the backend.
When we usearchiveListWhen fetching data with a tag, the result is usually assigned to a variable, such asarchives:{% archiveList archives with moduleId="1" type="list" limit="5" order="id desc" %}
CombineforTag traversal and data display
With a dataset, the next step is to useforto display it on the page in a loop. 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:
- We first use
archiveListGot the latest 5 articles (moduleId="1",limit="5",order="id desc"),and the result is stored inarticlesthe variable. - Next,
{% for item in articles %}Start traversingarticlesThis list. Each loop,itemrepresents all the information of an article. - In the loop, we use
{{ item.Link }}Get article link,{{ item.Title }}To get the article title,{{ item.Views }}Get the number of views. - Noticed the release date
{{ stampToDate(item.CreatedTime, "2006-01-02") }}Here,stampToDateThe filter is used to format the original timestamp into a more readable "year-month-day" format. {% if item.Thumb %}It is a simple conditional judgment, and the image will be displayed only when there is a thumbnail in the article.- The most important thing is
{% empty %}tags, it provides whenarticlesThe content displayed on the page when the list is empty, avoiding the embarrassment of a blank page, and enhancing the user experience.
Auxiliary information in the loop:forloopObject
InforLoop inside, 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.CounterIt represents the current loop index, starting from 1.forloop.RevcounterThe value indicates the reverse index of the current loop, starting from the total number of the list and ending at 1. For example, you might want to add a CSS class to the first element of the list.activeto the CSS class:{% for item in articles %}<li class="{% if forloop.Counter == 1 %}active{% endif %}">...</li>{% endfor %}
Other list labels' versatility
ExceptarchiveListAnQiCMS also provides many other tags for retrieving data lists, their usage is similar toarchiveListVery similar, both involve assigning a variable and combiningforto traverse in a loop:
categoryList: Used to get the classification list of articles or products.pageList:Get single-page list (such as "About UstagDataList:Get the document list under a specific Tag.navList:Retrieve the website navigation menu list, usually used to build top or bottom navigation.bannerList:Retrieve the website Banner image list, commonly used for carousel images.linkList:Retrieve the list of friend links.
MasteredarchiveListandforThe usage of loops, you can easily display the data generated by these tags in various corners of the website, thus building dynamic and content-rich pages.AnQiCMS powerful template function, it is through this intuitive tag combination, making the operation and display of website content efficient and flexible.
Common Questions (FAQ)
Q1: Why myforThe loop did not output any content, nor did it display{% empty %}What is the backup text?
A1: IfforThere was no output or display inside the loopemptyThis usually means you are{% archiveList ... %}Indefined variables{% for item in ... %}used variables do not match. For example, you may have defined{% archiveList documents ... %},but wrote it as{% for item in archives %}Please make sure that the variable name matches completely.
Q2: How toforDo you want to display different content or styles based on the value of a certain attribute in the loop?
A2: You can useifLogical judgment tags inforLoop internal implementation of conditional rendering. For example, if you want to add an ellipsis to a particularly long article title or add a "pin" mark to an article with a specific ID, you can do it like 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)It uses the built-in string filter of AnQiCMS to get the length and truncate the string.
Q3:archiveListoflimitParameters and pagination tagspaginationWhat are the differences, and how should they be chosen?
A3:limitThe parameter is used to limit the number of data fetched at a time. It is suitable to use when you want to display a fixed number of data on a page, such as 'Latest Recommendations 5 Articles', 'Hot Products 10' etc.limitwithtype="list".paginationThe label is used to handle situations where a large amount of data needs to be displayed across multiple pages. When you setarchiveListoftype="page", the system will automatically calculate the total number of pages and the current page number.paginationLabels will use this information to generate page link, allowing users to jump between different pages. In short,limitIt is a quantity limit,paginationIt is page navigation, both are used together (type="page"It must be paired withpaginationIt can only realize the complete pagination function.