In the Anq CMS template,forLoop: More than iteration, advanced techniques help you double your content operation efforts.
As an experienced website operations expert, I am well aware of the importance of an efficient and flexible content management system for enterprises.AnQiCMS (AnQiCMS) provides strong support for our content creation and display with its high-performance architecture based on the Go language and Django template engine syntax.forLoop iteration of tags is undoubtedly our reliable assistant.
However,forThe loop is not just for simple iteration. Delve into the potential of the AnQi CMS template tags, and you will find many advanced usages hidden, such as handling the order of data.reversedandsorted, and elegantly handle empty data,emptycode blocks, even beautiful list display,cycleLabel and control of whitespace in output optimization. These techniques can make your template code more concise and intelligent, thereby providing users with a smoother and more attractive reading experience.
Let's explore together the Anqi CMS template.forLoop through these advanced usages to see how they can be ingeniously integrated into content operation strategies.
Stable foundation:forLoop through the tag's conventional usage
Before delving into advanced usage, let's review firstforThe most basic and core function of loops——traversing data sets. Whether it's an article list, product display, or comment section,forThe loop can display the data extracted from the backend one by one on the front-end page.
For example, if we want to display a list of the latest documents released, we would usually write the template code in this way:
{% archiveList archives with type="list" limit="10" %}
{% for item in archives %}
<li class="article-item">
<a href="{{item.Link}}">{{item.Title}}</a>
<span>发布日期:{{stampToDate(item.CreatedTime, "2006-01-02")}}</span>
</li>
{% endfor %}
{% endarchiveList %}
Here,archivesis a collection of documents,itemis an instance of the current document in each loop. In addition,forthe loop also provides built-inforloop.Counterandforloop.RevcounterVariables that can respectively display the current loop count (starting from 1) and the remaining loop count are very useful when you need to add numbering or special styles to list items:
{% for item in archives %}
<li class="article-item">
<span>第{{ forloop.Counter }}篇 / 剩余{{ forloop.Revcounter }}篇:</span>
<a href="{{item.Link}}">{{item.Title}}</a>
</li>
{% endfor %}
Beyond the ordinary:reversedWithsorteduses
Sometimes, the order in which data is displayed is not always default. For example, you may need to display the list content in reverse order, or sort it based on a certain field. At this time,reversedandsortedit can be very useful.
When we want to traverse the content of a data collection in reverse order, we just need to add in theforloop tag.reversedKeywords. This is particularly convenient when displaying "Latest Comments" or "Latest Activities", if the default data source is in ascending order but the frontend needs it in descending order. For example,archivesThe data is sorted by ID in ascending order by default, and if you want the latest articles (with the largest ID) to be displayed at the top, you can write it like this:
{% for item in archives reversed %}
<div class="card-item latest-first">
<h3><a href="{{item.Link}}">{{item.Title}}</a></h3>
<p>更新时间:{{stampToDate(item.UpdatedTime, "2006-01-02 15:04")}}</p>
</div>
{% endfor %}
whilesortedThe keyword allows us to sort the data set.The template engine of Anqi CMS supports sorting of integer type fields, the default is ascending.This is very helpful for organizing content lists by view count, price, or other numeric custom fields.ViewsView count)of the document list, and I want to display them in ascending order of view count, which can be implemented in this way:
{% archiveList archives with type="list" limit="10" order="views asc" %} {# 注意:这里order="views asc"已在archiveList标签中实现排序,sorted主要针对已获取的数组进行二次排序 #}
{% for item in archives sorted %} {# sorted这里会尝试对item.Id进行排序,如果需要按views排序,通常需要在archiveList标签中指定或通过后端处理 #}
<div class="card-item popular-articles">
<h4><a href="{{item.Link}}">{{item.Title}}</a></h4>
<span>浏览量:{{item.Views}}</span>
</div>
{% endfor %}
It is worth noting that,sortedusually obtained through the background data acquisitionorderParameters specify sorting is more efficient, but in certain specific scenarios, if you need to sort an existing array twice in the frontend (such as sorting a simple field of a complex object array),sortedCan be used as a supplementary means. At the same time,reversedandsortedCan be combined with, for example,{% for item in archives reversed sorted %}This will first sort the data, and then traverse the sorted results in reverse order.
Elegant handling of empty data:emptyStatement block
In content operation, we sometimes encounter situations where the data set is empty.If the situation is not handled properly, blank areas may appear on the page, or unfriendly error messages may be displayed, affecting the user experience.forloop provides aemptyA statement block that can elegantly solve this problem.
emptyA statement block is used inforA loop is executed when there are no items to traverse, which is equivalent to aif...elseThe concise way. It allows you to give friendly hints to users when there is no data, instead of leaving a blank space:
{% archiveList searchResults with type="page" q=urlParams.q limit="10" %}
{% for item in searchResults %}
<div class="search-result-item">
<h3><a href="{{item.Link}}">{{item.Title}}</a></h3>
<p>{{item.Description}}</p>
</div>
{% empty %}
<div class="no-results-message">
很抱歉,没有找到与“{{urlParams.q}}”相关的结果。
</div>
{% endfor %}
{% endarchiveList %}
Compared to first judgeif searchResultsand then loop,emptyThe code block makes the logic clearer and more focused, and also more readable.
Spice up the flowers:cycleFlexible Use of Tags
To make the list display more visually attractive, we often use different styles to distinguish adjacent list items, such as zebra striping. The Anqi CMS'scycleLabels are born for this, they can output the predefined value sequence one by one in the loop.
cycleThe usage of the label is very simple, you can define multiple values in it, each loop will take out a value in order, and after all values have been taken out, it will start from the first value again.
{% for item in archives %}
<li class="article-row {% cycle "odd" "even" %}">
<a href="{{item.Link}}">{{item.Title}}</a>
</li>
{% endfor %}
In this example, list items will alternate useoddandevenThese two CSS classes can easily achieve a zebra-like effect. You can alsocycleThe result is assigned to a variable so that it can be referenced multiple times in the template, making the code cleaner:
{% for item in archives %}
{% cycle "bg-blue" "bg-white" as row_bg %}
<li class="article-row {{ row_bg }}">
<a href="{{item.Link}}">{{item.Title}}</a>
</li>
{% endfor %}
Detail optimization: Techniques for controlling whitespace (-)
During the template rendering process,forlooping,ifThe auto tags may produce unnecessary blank lines in the HTML output, which although it does not affect the page function, may make the final HTML code look less tidy. Anqi CMS provides a small but powerful trick to solve this problem: add a hyphen at the beginning or end of the template tags-.
For example, a commonfora loop may produce additional blank lines:
{% for item in archives %}
<div class="item">{{ item.Title }}</div>
{% endfor %}
Ifarchivescontains data, this code may have an extra blank line before and after eachdivbecause there are blank lines before and after each tag{% for %}and{% endfor %}The label itself will occupy a line. To eliminate these blank lines, we can use-:
{% for item in archives -%}
<div class="item">{{ item.Title }}</div>
{%- endfor %}
By using in{% for %}after-%}and in{% endfor %}before adding{%-It can effectively remove the blank characters brought by template logic tags, generating a tighter HTML output, which is undoubtedly a blessing for operators who pursue ultimate page performance and code cleanliness.
Summary
Anqi CMS'sforto iterate