Master AnQiCMS template: useforThe art of looping through data lists
Hello everyone, partners of AnQiCMS operation
In daily website content operation, we often need to display a series of data, whether it is the latest article list, product classification navigation, or comment details, it is inseparable from the traversal and display of the data set.AnQiCMS as an efficient and flexible content management system, understands the importance of templates in content presentation.Today, let's delve deeply into a core and powerful tag of the AnQiCMS template engine -forLoop and see how to easily handle various data lists to enliven your website content.
AnQiCMS's template engine adopts a syntax style similar to Django, which makes it very quick for partners with other web development experience to get started, and even for beginners, its intuitiveness allows you to quickly master it.forThe loop is the basis for constructing dynamic content display, it can help us present the data obtained from the backend in a structured and customizable way on the front end.
forThe core usage of loops: traversing data sets
Imagine that you have obtained a set of article data from the background, and now you need to display these articles one by one on the web page. At this time,forLoops come into play. Their basic syntax is very concise and clear:
{% for item in collection %}
{# 在这里放置你希望对每个“item”进行的操作和显示逻辑 #}
{% endfor %}
Here, collectionRepresents the data set you want to iterate over, for example, AnQiCMS'sarchiveList(Article list),categoryListData obtained from tags such as (category list) anditemis a temporary variable that representscollectionan item in one. By accessingitemthe different properties (such asitem.TitleGet the title,item.LinkGet the link, and we can display the detailed information of each data item.
Let's take a look at several common data lists to see.forThe charm of loops.
Example 1: Dynamically display the article list.
The article list is one of the most common content forms on a website. Suppose we usearchiveListtags to get the latest articles:
{% archiveList articles with type="list" limit="10" %}
<div class="article-list">
{% for article in articles %}
<article class="article-item">
<a href="{{ article.Link }}" title="{{ article.Title }}">
<h3>{{ article.Title }}</h3>
<p>{{ article.Description }}</p>
<div class="meta-info">
<span>发布时间:{{ stampToDate(article.CreatedTime, "2006年01月02日") }}</span>
<span>阅读量:{{ article.Views }}</span>
</div>
</a>
</article>
{% endfor %}
</div>
{% endarchiveList %}
In this example, we first go througharchiveListtags to store the data toarticlesIn the variable, and limit it to only display 10 list items. Next,{% for article in articles %}It will iterate over these 10 articles one by one inside the loop.article.Link/article.Title/article.Descriptionandarticle.ViewsProperties will respectively display the link, title, introduction, and views of the article. Particularly, for the timestamp fieldCreatedTimeWe rely on the built-in AnQiCMS.stampToDateThe function is formatted to display in a more friendly "2006-01-02" format.
It is worth mentioning that ifarticlesThis collection is empty, we do not want to show blank on the page, but we can give users a friendly prompt. AnQiCMS'sforprovided a loopemptyblock to elegantly handle this situation:
{% archiveList articles with type="list" limit="10" %}
<div class="article-list">
{% for article in articles %}
<article class="article-item">
<a href="{{ article.Link }}" title="{{ article.Title }}">
<h3>{{ article.Title }}</h3>
<p>{{ article.Description }}</p>
</a>
</article>
{% empty %}
<p>抱歉,目前还没有任何文章发布。</p>
{% endfor %}
</div>
{% endarchiveList %}
Whenarticlesis empty,{% empty %}The content within will be rendered, providing a better experience for users.
Example two: Build multi-level category navigation
Website navigation usually needs to display categories, even subcategories.forThe loop can also handle this nested iteration requirement.
<nav class="main-nav">
<ul>
{% navList mainMenu with typeId=1 %} {# 获取ID为1的主导航数据 #}
{% for mainItem in mainMenu %}
<li {% if mainItem.IsCurrent %}class="active"{% endif %}>
<a href="{{ mainItem.Link }}">{{ mainItem.Title }}</a>
{% if mainItem.NavList %} {# 如果有子导航,则进行嵌套循环 #}
<ul class="sub-nav">
{% for subItem in mainItem.NavList %}
<li {% if subItem.IsCurrent %}class="active"{% endif %}>
<a href="{{ subItem.Link }}">{{ subItem.Title }}</a>
</li>
{% endfor %}
</ul>
{% endif %}
</li>
{% endfor %}
{% endnavList %}
</ul>
</nav>
Here, we first go throughnavListGet the main navigation data tomainMenuVariable. OuterforLoop through the main navigation items, and throughmainItem.NavListCheck if there is a sub-navigation. If it exists, use it again in the inner layer.forLoop through the sub-navigation items.mainItem.IsCurrentandsubItem.IsCurrentSuch properties can help us determine whether the current navigation item is selected, thereby addingactivestyles to enhance the user experience.
Example three: Show custom document parameters
In AnQiCMS, you can customize various parameters for articles or product models, such as "author", "source", "product model", etc., and also throughforcyclic unified display.
<div class="product-specs">
<h4>产品参数</h4>
{% archiveParams specs with id=archive.Id %} {# 获取当前文档的所有自定义参数 #}
<ul>
{% for param in specs %}
<li>
<span>{{ param.Name }}:</span>
<span>{{ param.Value | safe }}</span> {# 注意:如果param.Value可能包含HTML,请使用|safe过滤器 #}
</li>
{% endfor %}
</ul>
{% endarchiveParams %}
</div>
here,archiveParamsThe tag will get all custom parameters of the current article (archive.Id) and store them inspecsan array. Loop throughspecsto conveniently display each parameter'sName(parameter name) andValue(Parameter value). Please note thatparam.Valuerich text or HTML code may be included. It is imperative to use|safeA filter to ensure that HTML content is parsed and displayed correctly, rather than being escaped as plain text.
enhancementforadvanced techniques for the iterative experience
In addition to the basic traversal, AnQiCMS also provides some powerful auxiliary functions to make your template more expressive.forThe loop also provides some powerful auxiliary functions to make your template more expressive.
1. UseforloopVariables obtain loop information
InforWithin the loop, AnQiCMS will automatically provide a specialforloopvariable containing some useful loop information:
forloop.Counter: The current loop iteration number, starting from 1.forloop.Revcounter: The reverse sequence number of the current loop, starting from the total count.
This is very useful when you need to add special styles to the first, last, or odd/even items in a list:
{% archiveList articles with type="list" limit="10" %}
<div class="article-list">
{% for article in articles %}
<article class="article-item {% if forloop.Counter == 1 %}first-article{% endif %} {% if forloop.Counter is odd %}odd{% else %}even{% endif %}">
<h3>{{ article.Title }} (第{{ forloop.Counter }}篇,还剩{{ forloop.Revcounter }}篇)</h3>
</article>
{% endfor %}
</div>
{% endarchiveList %}
Byforloop.Counter == 1We can easily identify and style the first article, andforloop.Counter is oddIt can be used to implement the zebra line effect of list items.
2. UsereversedandsortedModifier
Sometimes we want to display the data in a specific order.forLoop supportreversed(Reverse) andsorted(Sort) modifier:
{% for item in collection reversed %}: Reverse traverse the data set.{% for item in collection sorted %}: Traverse the data set after sorting it (default is ascending).
You can even combine them:{% for item in collection reversed sorted %}. This is very flexible when you need to display the same batch of data in different orders.
3. UsecycleLabel to implement style rotation
cycleTags are a very clever tool that can output the multiple values you define in order in a loop. This is very useful when you need to alternate between different background colors, CSS classes, or other variables:
`twig {% archiveList articles with type=“list” limit=“10” %}
<ul class="styled-list">
{% for article in articles %}
<li class="list-item {% cycle