As an experienced website operations expert, I know how important it is to effectively display dynamic data in daily content management.English CMS (EnglishCMS) provides us with an excellent solution with its powerful performance in Go language and flexible template system.forLoop through an array or slice and elegantly present its content on the website page.
Loop magic in the Anqi CMS template: easily traverse 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.This content is usually organized in the form of an array (Array) or a slice (Slice) on the backend.forLoop tags, making it easy to iterate over these data.
Core syntax: UnderstandforBasic of loops
In the Anq CMS template,forLoop syntax is very intuitive, its basic structure is like this:
{% for item in collection %}
{# 在这里输出每一个 item 的内容 #}
{% endfor %}
Here,collection指代的是你希望遍历的数组或切片变量,而item则是一个临时变量,它在每次循环中会依次代表collection中的每一个元素。你可以通过itemthis variable, combined with the point (.operator, access each element's specific attributes. For example, ifitemrepresents an article, you may need to accessitem.Titleto get 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, operations personnel can quickly get started and achieve dynamic content display.
Deep Application: UnlockforMore Functions of Loops
In addition to basic traversal, the security CMSforThe loop also provides many practical auxiliary functions and advanced features to help us better control loop behavior and data display.
1. Smart handling of empty data:emptyBlock
Imagine if there is no article under a certain category, we do not want the page to be empty but instead display a friendly prompt.forLoopingemptyBlocks are created for this purpose. WhencollectionWhen it is empty or undefined,forThe content within the loop body will not be executed instead ofemptythe content in the block.
{% for item in archives %}
<p>文章标题:{{ item.Title }}</p>
{% empty %}
<p>当前分类下暂无文章,敬请期待!</p>
{% endfor %}
This design makes the template logic more robust and effectively improves the user experience.
2. Master the loop state:.forloopvariable
InforInside the loop, Security CMS provides a specialforloopA variable that contains various status information of the current loop, very suitable for conditional judgment or counting operations:
forloop.Counter: The iteration count of the current loop (counting starts from 1).forloop.Revcounter: How many more iterations until the loop ends.
These counters are very convenient in practical applications. For example, you can add a special style to the first element of a list:
{% for item in navs %}
<li class="{% if forloop.Counter == 1 %}active{% endif %}">
<a href="{{ item.Link }}">{{ item.Title }}</a>
</li>
{% endfor %}
或者在列表中展示当前项的序号:English
{% for item in products %}
<p>{{ forloop.Counter }}. {{ item.Name }}</p>
{% endfor %}
3. 控制遍历顺序:EnglishreversedWithsorted
有时我们希望以特定的顺序遍历数据。EnglishforLoop supportreversedandsortedKeyword:
{% for item in collection reversed %}Replace withcollection倒序遍历。English{% for item in collection sorted %}:尝试对EnglishcollectionSorted traversal (for sortable data types).
For example, if you want to display the latest published articles and hope they are 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 %}
(Although here,archiveListTags themselves supportorderParameter, but if the data has already been loaded into the variable,sortedit can also play a role, but it is usually more efficient to specify sorting directly in the tag.)
4. Alternate display content:cycletags
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'It alternates the output in each loopoddandevenThese two strings can be used as CSS class names.
Flexible data source: Used with filters
The template filters (Filters) of Safe CMS are alsoforThe loop provides 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 %}
PasssplitFilter, we can easily convert a string to an iterable slice, and then throughtrimfilter clean each element, and then useforcycle by one by one. Similarly,make_listFilter can split strings into slices by characters,fieldsFilter can split by spaces.
Practical case: Build a dynamic article list and image gallery
Let us experience through a comprehensive exampleforLoops have charm in AnQi CMS templates. Suppose we want to display a list of articles, each with a title, a brief introduction, and if there is a cover image, it will be displayed. Additionally, each article may contain a photo gallery (this is fromarchiveDetailinImagesField data acquisition).
`twig {# Get the list of articles, 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">很