The `for` loop tag can iterate over arrays, but it also supports advanced usages like `reversed` or `empty`?
The AnQi CMS template includesforLoop: More than just iteration, advanced techniques help you double your content operation efforts
As an experienced website operations expert, I fully understand the importance of an efficient and flexible content management system for a company.AnQiCMS (AnQiCMS) leverages its high-performance architecture based on the Go language and Django template engine syntax to provide strong support for our content creation and display.In daily operations, we often need to present data sets in list form on the website, at this time,forThe loop iteration tag is undoubtedly our powerful assistant.
However,forLoops are not just for simple iteration. Delve deeper into the potential of the Anqi CMS template tags, and you will find many advanced uses, such as handling data order.reversedandsortedand elegantly handling empty data,emptyeven with beautiful list display statements,cycleLabel and control of white space for optimized output. These techniques make the template code more concise and intelligent, thereby providing users with a smoother and more attractive reading experience.
Let's explore the Anqi CMS template togetherforThese advanced loop usages, see how to ingeniously integrate them into content operation strategies.
Solid foundation:forThe conventional application of looping through tags
Before delving into advanced usage, let's review firstforThe most basic and core function of looping is to traverse data sets. Whether it is an article list, product display or comment section,forLoops can present 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 released documents, we would usually write the template code like this:
{% 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 the instance of the current document in each iteration. Moreover,forthe loop also provides built-inforloop.Counterandforloop.RevcounterVariables, they can display the current loop count (starting from 1) and the remaining loop count, which is 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 norm:reversedwithsortedusefulness
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 you may want to sort it based on a field. At this point,reversedandsortedIt can be put to use.
When we want to iterate over the contents of a data set in reverse order, we just need to add in theforloop tag.reversedKeywords. This is especially convenient when displaying "latest comments" or "latest activities", if the data source is in default ascending order but the front-end needs to be in reverse order. For example, ifarchivesData is sorted by ID in ascending order by default, but if you want the latest articles (with the largest ID) to be displayed at the top, you can do 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 %}
AndsortedKeywords allow us to sort data sets. The Anqi CMS template engine supports sorting of integer fields, with the default being ascending.This is very helpful in organizing content lists by view count, price, or other numeric custom fields.For example, if you have a parameter that contains numeric values such asViewsThe document list of views) and you want to display it from low to high by views, you can implement it like this:
{% 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,sortedIt is usually passed through data acquisition in the backgroundorderParameters specify sorting more efficiently, but in certain specific scenarios, if you need to sort an existing array twice on the front end (for example, sorting a simple field of a complex object array),sortedCan be used as a supplementary means. At the same time,reversedandsortedCan be used together, for example,{% for item in archives reversed sorted %}This will first sort the data, and then traverse the sorted results in reverse order.
Elegantly handle empty data:emptyStatement block
In content operation, we sometimes encounter the situation where the data set is empty.If this situation is not handled, a blank area may appear on the page, or even unfriendly error messages may be displayed, affecting the user experience.AnQi CMS offorprovided a loopemptyThis can solve the problem elegantly. Statement block
emptyStatement block inforThe loop is executed when there are no items to iterate over, which is equivalent to aif...elseA concise way. It allows you to提示用户 without data, rather than 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判断 firstif searchResultsThen loop,emptyCode blocks make the logic clearer and more focused, and also more readable.
To add luster to the situation:cycleFlexible use of tags
To make the list display more visually appealing, we often use different styles to distinguish adjacent list items, such as the zebra striping effect. Anqi CMS'scycleThe label is born for this, it can output the predefined value sequence one by one in a loop.
cycleThe usage of labels is very simple, you can define multiple values in it, and a value will be taken out in order each time the loop runs, and it will start from the first value again after all the values have been taken out.
{% 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 usingoddandevenThese CSS classes can easily achieve a zebra pattern. You can also usecycleAssign the result 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 template rendering,forloop,ifSentences and logical tags may produce unnecessary blank lines in HTML output, which does not affect the page function, but may make the final HTML code look less neat. AnQi CMS provides a small but powerful trick to solve this problem: add a hyphen at the beginning or end of the template tag-.
For example, a regularforA loop may produce additional blank lines:
{% for item in archives %}
<div class="item">{{ item.Title }}</div>
{% endfor %}
IfarchivesThere is data, this code may have extra blank lines in eachdivBecause there are blank lines before and after the tags{% for %}and{% endfor %}The tag 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 adding in{% for %}added afterwards-%}and before{% endfor %}added before{%-Effectively remove these blank characters brought by template logic tags, generate a tighter HTML output, which is undoubtedly a blessing for operators who pursue ultimate page performance and code perfectionism.
Summary
Of Security CMSforLoop through