In AnQi CMS template design, we often encounter situations where we need to define and iterate over some fixed or small array data. Although most dynamic content is displayed through built-in tags likearchiveList/categoryListObtain, but for some localization configurations, custom options, or static lists, processing the array directly in the template will be more convenient. Anqi CMS provideslistfilter, in conjunction withforLoop tags can easily achieve this requirement.
Get to knowlistFilter: The array constructor in the template.
listThe filter is a practical tool in Anqi CMS template engine, it allows us to directly convert a string literal array into an iterable array object.This is very useful for defining a fixed set of options, navigation item identifiers, or other short data lists in a template.
Its basic usage is to pass a string that conforms to the JSON array format to it, then through|listthe filter for conversion. Usually, we would combinesetThe transformed array will be assigned to a variable for subsequent use.
For example, if we want to define an array containing several keywords in a template:
{% set myKeywords = '["安企CMS","模板","内容管理","GoLang"]'|list %}
In this code block,'["安企CMS","模板","内容管理","GoLang"]'is a string, whereas|listThe filter is responsible for parsing this string into a real array object and assigning it to a variable namedmyKeywords. It is worth noting that even if the array contains values that look like numbers (such as'["item", 123, "another"]')listThe filter will also treat all its internal elements as string types during parsing.
UseforLoop: The general method to traverse an array.
Once we pass throughlistThe filter successfully defined an array variable, which can then utilize the built-in template engine'sforloop tags to iterate over each element.forLoops play a core role in Anqi CMS templates, they can iterate over any traversable object, including the array we just created.
A typicalforThe loop structure is as follows:
{% for item in myKeywords %}
<!-- 在这里处理每一个 item -->
{% endfor %}
In each loop,itemThe variable will hold one element of the array at a time. You can use it directly to{{ item }}output the value of the current element.
To better control and display the traversal process,forThe loop also provides some practical auxiliary variables:
forloop.Counter: The current loop iteration number, starting from 1.forloop.Revcounter: The number of remaining elements to be looped over.
In addition, when the array may be empty,forThe loop also has an elegant way of doing things.emptyThe clause is used to display specific content when the array is empty, to avoid blank pages or errors:
{% for item in myKeywords %}
<li class="keyword-item">第{{ forloop.Counter }}个关键词:{{ item }}</li>
{% empty %}
<li>当前没有关键词可显示。</li>
{% endfor %}
Combine actual scenarios: Make the template more flexible
UnderstoodlistFilters andforAfter the basic use of loops, we can apply them in various practical scenarios, enhancing the flexibility and maintainability of templates.
For example, on a product detail page, you may need to display a list of fixed product features, which vary slightly between different product models but are not suitable for management through backend custom fields (because they are fixed options rather than input values). In this case, you can define a feature array in the template:
{% set productFeatures = '["防水防尘", "超长续航", "高清显示屏"]'|list %}
<div class="product-features">
<h3>核心功能</h3>
<ul>
{% for feature in productFeatures %}
<li><i class="icon-check"></i> {{ feature }}</li>
{% empty %}
<li>暂无核心功能介绍。</li>
{% endfor %}
</ul>
</div>
Another common scenario is displaying social media link icons in the footer or sidebar of a web page. If you want the icons to be fixed in order and type, and easy to adjust in the template,listThe filter is very suitable:
{% set socialIcons = '["facebook", "twitter", "linkedin", "youtube"]'|list %}
<div class="social-media">
{% for platform in socialIcons %}
<a href="/{{ platform }}" target="_blank" title="访问我们的{{ platform }}主页">
<i class="fab fa-{{ platform }}"></i>
</a>
{% endfor %}
</div>
In this way, we can directly embed some lightweight, static data into the template, which improves the template's self-sufficiency and reduces the dependency on backend dynamic data requests.
Tip
- Data types are unified:As mentioned before,
listThe filter will parse all elements into strings. If you need to perform mathematical operations on the "numbers" in the array, you need to use|integeror|floatThe filter performs type conversion. - Scope of application:
listThe filter is most suitable for defining lists with relatively fixed content and a small number of items. For large or frequently changing data, it is still recommended to use the Anqi CMS backend content management function to publish and manage, and to use the corresponding tags (such asarchiveList) to obtain. - Debugging tips:During development, if you are not sure
listWhether the filter correctly converts a string to an array or want to view the actual content of the array, you can use|stringformat:"%#v"or|dumpA filter to print variable details, for example:{{ myKeywords|stringformat:"%#v" }}This will output the detailed structure of the array internally in Go language, helping you debug.
MasterlistFilters andforThe combination of loops can help us build safe CMS templates more efficiently and flexibly, handling various simple list data display needs.
Frequently Asked Questions (FAQ)
Question: Through
listCan the array defined by the filter be directly used for mathematical operations if the elements are numbers? Answer:No.listThe filter will treat all array elements as string types. Even if you define like'["10", "20"]'|list,The "10" and "20" in the array are still strings. If you need to perform mathematical operations on these elements in a loop (such as addition or comparison), you need to use|integeror|floatThe filter explicitly converts them to numeric type, for example{{ item|integer }}.Question:
listCan the filter be used to define nested arrays or more complex object structures? Answer:listThe filter is mainly used to convert simple string array literals to string arrays (i.e.),[]string{}). It does not support defining nested arrays directly (such as),[['a','b'],['c','d']])or a complex object structure containing key-value pairs. For scenarios requiring the processing of more complex data structures, it is usually recommended to pass the data as an object or array to the template through a controller (backend).Question: If through
listDoes the array defined by the filter end up being empty, will the page report an error? How can it be handled elegantly? Answer:If it passeslistThe filter defines an empty array, for example'[]'|list),and useforLoop through, the page will not report an error. In order to provide a better user experience,forA loop tag provides a{% empty %}sentence. Whenforthe array to be looped through is empty,{% empty %}and{% endfor %}The content between the brackets will be rendered, you can use it to display prompts such as 'No data available' or 'List is empty'.