In website content management, dynamically displaying list data is a very basic and important feature.Whether it is a news list, product display, category navigation, or friend links, we need to be able to flexibly retrieve data from the backend and present it on the front-end template.AnQiCMS (AnQiCMS) provides a powerful and easy-to-use template engine, allowing us to easily meet these requirements, among which the "for loop" is the core tool for displaying list data.
AnQiCMS's template engine adopts a syntax style similar to Django, which allows users with web development experience to quickly get started.When we talk about a "for loop", it allows us to iterate over the array or collection data passed from the backend to the frontend item by item, and to process and display each item independently.
Start the journey of data traversal:forBasic usage of the loop
The most commonforA loop form, it looks like this:{% for item in your_list %}. Here,your_listIt represents the list data you get from the backend, whileitemit is a temporary variable that automatically points to in each loopyour_listThe current item of data. When the loop ends, we need to use{% endfor %}to close the loop block.
For example, if we have a file namedarchivesThe article list data, if you want to display their titles and links on the web page, we can write the template code like this:
<ul>
{% for article in archives %}
<li><a href="{{ article.Link }}">{{ article.Title }}</a></li>
{% endfor %}
</ul>
In this example,articleIt is the one we define in the loopitemby using the form of the variable,article.Linkandarticle.TitleWe can then get the link and title of each article, thus dynamically generating a list.
In addition, to better control the display of the list,forLoops also provide some practical built-in variables, which can be found inforloopthe object:
forloop.Counter: indicates the current iteration number of the loop, starting from 1.forloop.Revcounter: Indicates the remaining number of iterations in the current loop.
Using these counters, we can easily add special styles to the first or last item in the list, or make other logical judgments.
Adaptability:forAdvanced use of loops
In practical applications, the display of list data is often not immutable, AnQiCMS providesfora variety of modifiers and tags to deal with different scenarios.
Handle empty data:{% empty %}Tag
Sometimes, the data list you get from the background may be empty.If you loop an empty list directly, nothing will be displayed on the page, which may confuse the visitor.To provide a more friendly user experience,forLoop support{% empty %}tags. Whenforthe list being traversed by a loop is empty,{% empty %}The content within the block will be displayed, not the loop itself.
<ul>
{% for product in products %}
<li>
<img src="{{ product.Thumb }}" alt="{{ product.Title }}">
<h3>{{ product.Title }}</h3>
</li>
{% empty %}
<li>抱歉,暂时没有产品信息可供显示。</li>
{% endfor %}
</ul>
Change the order of the loop:reversedandsortedModifier
You may need to display the list in reverse order or simply sort the list items. AnQiCMSforLoop supportreversedandsortedmodifier:
{% for item in list reversed %}: Traverse the list in reverse.{% for item in list sorted %}Translate the list to default sort and traverse (usually in dictionary order of numbers or strings).
For example, to display the latest published articles at the top of the list, but the background data is stored in ascending order by ID, you can usereversed:
{% for news in news_list reversed %}
<p>{{ news.Title }} - {{ stampToDate(news.CreatedTime, "2006-01-02") }}</p>
{% endfor %}
to achieve alternating styles:cycleTag
In some designs, you may need list items to display alternating styles, such as different colors for odd and even rows.cycleThe label provides a perfect solution. It allows you to define a series of values, each time looping through and using a value in order, until all values are exhausted and then starting over from the beginning.
{% for item in my_items %}
<div class="{% cycle 'even-row' 'odd-row' %}">
{{ item.Content }}
</div>
{% endfor %}
Thus,my_itemsThe first item in the list will be usedeven-rowThe second item will be usedodd-rowThe third item will be used againeven-rowand so on.
Combined with the actual application of AnQiCMS built-in tags
AnQiCMS built-in a variety of practical tags to help you get various types of data lists, and then you can combineforto display them in a loop.
to display the article list(archiveList)
archiveListTags are powerful tools for obtaining lists of articles or documents. You can filter and retrieve data according to various conditions such as category ID, module ID, recommended attributes, sorting methods, and more.
<h3>最新文章</h3>
<ul>
{% archiveList latest_articles with type="list" limit="5" order="id desc" %}
{% for article in latest_articles %}
<li>
<a href="{{ article.Link }}">{{ article.Title }}</a>
<span>发布于:{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
<span>阅读量:{{ article.Views }}</span>
</li>
{% empty %}
<li>暂无最新文章。</li>
{% endfor %}
{% endarchiveList %}
</ul>
Display category list(categoryList)
If you need to build a navigation menu or sidebar category,categoryListLabel collaborationforLooping will be very convenient. It even supports nested looping display for multi-level categories.
<nav>
<ul class="main-nav">
{% categoryList top_categories with moduleId="1" parentId="0" %} {# 获取文章模块的顶级分类 #}
{% for category in top_categories %}
<li class="nav-item">
<a href="{{ category.Link }}">{{ category.Title }}</a>
{% if category.HasChildren %} {# 判断是否有子分类 #}
<ul class="sub-nav">
{% categoryList sub_categories with parentId=category.Id %} {# 获取当前分类的子分类 #}
{% for sub_category in sub_categories %}
<li><a href="{{ sub_category.Link }}">{{ sub_category.Title }}</a></li>
{% endfor %}
{% endcategoryList %}
</ul>
{% endif %}
</li>
{% endfor %}
{% endcategoryList %}
</ul>
</nav>
Display friend links(linkList)
For the link at the bottom of the website,linkListthe tag can directly obtain the link data configured in the background, and thenfordisplay in a loop.
<div class="friend-links">
<h4>友情链接</h4>
{% linkList friends %}
{% if friends %}
<ul>
{% for link in friends %}
<li><a href="{{ link.Link }}" {% if link.Nofollow == 1 %}rel="nofollow"{% endif %} target="_blank">{{ link.Title }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>暂无友情链接。</p>
{% endif %}
{% endlinkList %}
</div>
Note on image processing
When displaying list items in a loop, especially when it involves images, you may encounter issues with image addresses or thumbnails. From AnQiCMS'sarchiveListorcategoryListtags returned byitemObjects usually containitem.Thumboritem.LogoSuch properties directly provide the image path. If you need to perform additional processing on the image, such as obtaining thumbnails or using lazy loading, you may need to work with other filters or HTML attributes, such aslazy="data-src"Set the image lazy loading attribute.
Keep the template tidy and efficient: **Practice
Good habits in template development can greatly improve efficiency and code maintainability.
- Reasonably name variables:In
forIn the loop, assign aitemChoose a meaningful name (for examplearticle/category), which makes the code more readable. - Utilize
|safeFilter:If the content you loop to output contains HTML code (such as the article content field), in order to prevent HTML tags from being escaped into plain text, remember to use|safeFilter, for example{{ article.Content|safe }}. - Optimize the template structure:Consider using for code blocks that are reused
{% include "partial/header.html" %}Translate auxiliary labels into separate files and then import them where needed, which will make your template structure clearer and easier to maintain. - Performance consideration: Although AnQiCMS's template tags have been optimized a lot, but in designing complex
forWhen looping and nesting, it is still necessary to avoid unnecessary repeated data queries and keep the logic concise.
By mastering the use offorThe advanced usage of loops, combined with the various data list tags built into AnQiCMS, allows you to efficiently and flexibly display various dynamic content in templates, building powerful and aesthetically pleasing websites.
Frequently Asked Questions (FAQ)
In
forHow to determine if the current item in a loop is the first or last item in a list?You can useforloopUsing the built-in variables provided by the object.forloop.Counter == 1You can determine if it is the first item,forloop.Revcounter == 0(or determine)forloop.LastAlthough it is not explicitly mentioned in the document, it can be judged whether it is the last item if similar engines have{% if forloop.Counter == 1 %}这是列表的第一项{% endif %}.How can I
forDisplay images in a loop and ensure they are the correct thumbnails?Most list tags of AnQiCMS, such asarchiveList/categoryList) returned byitemObjects usually containThumb(thumbnail) orLogo(Cover image) and fields. You can directly use the values of these fields as<img>Tag