As an experienced website operation expert, I know how important it is to efficiently display dynamic data in daily content management.AnQiCMS (AnQiCMS) leverages the powerful performance of the Go language and its flexible template system, providing us with an excellent solution.Today, let's delve deeply into a very practical and common scenario in Anqi CMS template development: how to useforLoop through an array or slice and elegantly present its content on a web page.
Loop magic in AnQi CMS template: easily loop through array and slice content.
When building dynamic websites, we often encounter the need to display a series of similar content, such as article lists, product image galleries, navigation menus, or custom parameters, etc.This content is usually organized in the form of an array (Array) or a slice (Slice).The template engine of Anqi CMS, drawing on the syntax features of mainstream templates like Django, provides us with a powerful and intuitiveforLoop tags make it easy to iterate over these data.
Core grammar: understandforThe basics of looping
The AnQi CMS template includesforLoop syntax is very intuitive, its basic structure is as follows:
{% for item in collection %}
{# 在这里输出每一个 item 的内容 #}
{% endfor %}
Here, collectionIt refers to the array or slice variable you want to traverse, anditemis a temporary variable that representscollectioneach element in it. You can use it toitemThis variable, combined with the dot (.) operator, accesses the specific properties of each element. For example, ifitemrepresents an article, you may need to accessitem.Titleget the article title, oritem.LinkGet the article link.
This concise syntax design greatly reduces the threshold for template development, even without a strong programming background, operation personnel can quickly get started and realize the dynamic display of content.
In-depth Application: UnlockforMore Features of Loops
In addition to the basic traversal, Anqi CMS'sforThe loop also provides many practical auxiliary functions and advanced features to help us better control loop behavior and data display.
1. Smart handling of null data:emptyblock
Imagine if there is no article under a certain category temporarily, we do not want the page to be empty, but instead display a friendly prompt message.forrepeatedlyemptyThe block is born for this purpose. WhencollectionWhen it is empty or undefined,forThe content within the loop body will not be executed, instead,emptyBlock content.
{% for item in archives %}
<p>文章标题:{{ item.Title }}</p>
{% empty %}
<p>当前分类下暂无文章,敬请期待!</p>
{% endfor %}
This design makes the template logic more robust, effectively improving the user experience.
2. Master the loop state:forloopVariable
InforInside the loop, Anqi CMS provides a specialforloopA variable that contains various status information of the current loop, very suitable for performing some conditional judgments or counting operations:
forloop.Counter: The iteration count of the current loop (starting from 1).forloop.RevcounterHow many iterations are left before the loop ends.
These counters are very convenient in practical applications. For example, you can add a special style to the first element of the list:
{% for item in navs %}
<li class="{% if forloop.Counter == 1 %}active{% endif %}">
<a href="{{ item.Link }}">{{ item.Title }}</a>
</li>
{% endfor %}
Or display the current item number in the list:
{% for item in products %}
<p>{{ forloop.Counter }}. {{ item.Name }}</p>
{% endfor %}
3. Control the traversal order:reversedwithsorted
Sometimes we want to traverse the data in a specific order.forLoop supportreversedandsortedKeyword:
{% for item in collection reversed %}: TocollectionReverse traversal.{% for item in collection sorted %}: Try tocollectionTraverse after sorting (for sortable data types).
For example, if you want to display the latest published articles and you want them to be arranged from newest to oldest:
{% archiveList archives with type="list" order="CreatedTime desc" limit="5" %}
{% for item in archives %}
<p>{{ item.Title }} - {{ stampToDate(item.CreatedTime, "2006-01-02") }}</p>
{% endfor %}
{% endarchiveList %}
(Here althougharchiveListThe tag itself supportsorderParameter, but if the data has already been loaded into a variable,sortedit can also play a role, although it is usually more efficient to specify sorting directly in the tag.)
4. Alternate display content:cycleTag
When designing list styles, we may want odd rows and even rows to have different background colors, or switch styles every few elements.cycleTags can help us achieve this alternating output requirement:
{% for item in products %}
<div class="product-item {% cycle 'odd' 'even' %}">
<h3>{{ item.Title }}</h3>
{# ... 其他产品信息 ... #}
</div>
{% endfor %}
Herecycle 'odd' 'even'They will alternate in each loopoddandevenThese strings, we can use them as CSS class names.
Flexible data source: used with filters
Anqi CMS template filters (Filters) alsoforLoops provide a rich source of data. For example, we often need to convert a comma-separated string into a list for iteration:
{% set tagsString = "SEO优化,内容营销,网站建设,Go语言" %}
{% set tagList = tagsString|split:"," %} {# 使用 split 过滤器将字符串切割成数组 #}
{% for tag in tagList %}
<span class="tag-badge">{{ tag|trim }}</span> {# 使用 trim 过滤器去除空格 #}
{% endfor %}
BysplitA filter, we can easily convert a string into an iterable slice, and then pass throughtrimThe filter cleans each element, and finally usesforLoop through each one by one. Similarly,make_listThe filter can split a string into slices by characters,fieldsThe filter can split by spaces.
Practical case: Build a dynamic article list and image gallery
Let us experience through a comprehensive exampleforThe charm of loops in Anqi CMS templates. Suppose we want to display a list of articles, each article includes a title, a brief introduction, and if there is a cover image, it will be displayed. And each article may contain a photo gallery (this is fromarchiveDetailinImagesThe data obtained from the field).
"twig {# Retrieve article list, here using the archiveList tag, type="page" indicates support for pagination #} {% archiveList articles with type="page" moduleId="1" limit="10" %}"}
{% for article in articles %}
<div class="article-card">
<a href="{{ article.Link }}" class="article-link">
<h3 class="article-title">{{ forloop.Counter }}. {{ article.Title }}</h3>
{% if article.Thumb %}
<img src="{{ article.Thumb }}" alt="{{ article.Title }}" class="article-thumb">
{% endif %}
<p class="article-description">{{ article.Description }}</p>
</a>
{# 获取文章详情,以获取其内部的图片列表 #}
{% archiveDetail articleFullData with id=article.Id %}
{% if articleFullData.Images %}
<div class="image-gallery">
<h4>文章图片集:</h4>
<div class="gallery-inner">
{% for imgUrl in articleFullData.Images %} {# 遍历 Images 切片 #}
<img src="{{ imgUrl }}" alt="图片 {{ forloop.Counter }}" class="gallery-img">
{% endfor %}
</div>
</div>
{% endif %}
{% endarchiveDetail %}
</div>
{% empty %}
<p class="no-content-message">很