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 fetch data from the backend and present it on the frontend template.AnQiCMS provides a powerful and easy-to-use template engine, allowing us to easily meet these requirements, with 'for loop' being the core tool for displaying list data.
The template engine of AnQiCMS adopts a syntax style similar to Django, which allows users with web development experience to quickly get started.When we talk about 'for loop', it allows us to iterate over the array or collection data passed from the backend to the frontend item by item, and handle and display each item independently.
Start your journey of data traversal:forBasic usage of loops
The most commonforThe loop form is like this:{% for item in your_list %}Here,your_listrepresents the list of data you get from the backend, anditemis a temporary variable that automatically points toyour_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 variable namedarchivesThe list of article 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,articlewhich we define in the loopitemvariable, byarticle.Linkandarticle.TitleWe can then separately obtain the link and title of each article, thereby dynamically generating the list.
In addition, in order to better control the display of the list,forLoops also provide some useful built-in variables, which can be found inforloopobjects:
forloop.Counter: represents the current iteration number of the loop, starting from 1.forloop.RevcounterThe number of remaining iterations of the current loop.
Using these counters, we can easily add special styles to the first or last item in the list, or perform other logical judgments.
Adaptability:forAdvanced usage of loops
In practical applications, the display of list data is often not constant, AnQiCMS'sforLoop provides various modifiers and tags to deal with different scenarios.
Handle empty data:{% empty %}tags
Sometimes, the data list you fetch from the background may be empty.If you loop through an empty list directly, nothing will be displayed on the page, which might confuse the visitor.forLoop support{% empty %}When tags.forthe list being traversed is empty,{% empty %}The content within the block will be displayed instead of 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:reversedandsortedModifiers
You may need to display the list in reverse order or simply sort the list items. AnQiCMS'sforLoop supportreversedandsortedModifier:
{% for item in list reversed %}: Traverse the list in reverse order.{% for item in list sorted %}:Traverse the list after it is sorted by default (usually in dictionary order for numbers or strings).
For example, if you want 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 implement alternating styles:cycletags
In some designs, you may need list items to display alternating styles, such as different colors for odd and even rows.cycleThis provides a perfect solution for labeling. It allows you to define a series of values, which are taken out in order each time the loop runs, and it starts over from the beginning once all values are used up.
{% for item in my_items %}
<div class="{% cycle 'even-row' 'odd-row' %}">
{{ item.Content }}
</div>
{% endfor %}
This is,my_itemsThe first item in the list will useeven-rowa class, the second item will useodd-row, the third item will use againeven-row. Continue in this manner.
combined with the actual application of AnQiCMS built-in tags
AnQiCMS has built-in a variety of practical tags to help you get various types of data lists, and then you can combineforto display them cyclically.
to display article lists (archiveList)
archiveListTags are a powerful tool for obtaining lists of articles or documents. You can filter and retrieve data based on various conditions such as category ID, module ID, recommendation attributes, and sorting methods.
<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 combined withforlooping 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 friend links at the bottom of the website,linkListtags can directly obtain the link data configured in the background, then throughforcyclic presentation.
<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>
Picture processing注意事项
When displaying list items in a loop, especially when it involves images, you may encounter issues with image addresses or thumbnails. The AnQiCMSarchiveListorcategoryListtags return theitemobjects usually containitem.Thumboritem.LogoSuch properties provide the image path directly. If you need to perform additional processing on the image, such as obtaining thumbnails or using lazy loading, you may need to use 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 the maintainability of the code.
- Reasonably name variables:In
forIn the loop, setitemChoose a meaningful name (for examplearticle/category), making the code more readable. - Utilize
|safeFilter:If the content you loop out includes HTML code (such as the article content field), remember to use it to avoid HTML tags from being escaped to plain text.|safeFilter, for example{{ article.Content|safe }}. - Optimize the template structure:Consider using for reusable code blocks
{% include "partial/header.html" %}Extract the auxiliary tags into independent files and then import them where needed, which will make your template structure clearer and easier to maintain. - Performance considerations:Even though the template tags of AnQiCMS have been optimized a lot, but in the design of complex
forWhen looping and nesting, it is still important to avoid unnecessary repeated data queries and maintain concise logic.
By skillfully applyingforLoop and its rich advanced usage, combined with the various data list tags built into AnQiCMS, you will be able to efficiently and flexibly display various dynamic content in templates, building powerful and beautiful websites.
Common Questions (FAQ)
In
forIn a loop, how can you determine if the current loop item is the first or last item in the list?You can useforloopUse the built-in variables provided by the object to judge.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 usually for similar engines. For example:{% if forloop.Counter == 1 %}这是列表的第一项{% endif %}.How can I
forDo images display in the loop, and are they the correct thumbnails?Most list tags of AnQiCMS (such asarchiveList/categoryList)} returned byitemobjects usually containThumb(Thumbnail) orLogo[Cover image] and other fields. You can directly use the values of these fields as<img>tags